livedesk 0.1.476 → 0.1.477

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,186 +0,0 @@
1
- import{r as RC,a as d,M as Hf,S as Aa,R as hd,B as jC,P as Yh,X as vr,b as Vf,C as qi,F as ib,L as Ui,A as xx,c as EC,d as ob,E as lb,T as DC,D as mv,e as Oa,f as IC,g as Sx,h as LC,i as _C,j as Wi,k as Ba,l as Rp,m as zf,n as pv,o as Gc,p as Cx,q as Vc,s as kx,t as Mx,u as cb,v as FC,w as PC,H as qc,W as zp,x as OC,y as BC,z as dd,K as HC,G as Ax,I as Ig,J as zl,N as Nx,O as zC,Q as $C,U as UC,V as hv,Y as qC,Z as gv,_ as Tx,$ as WC,a0 as yi,a1 as ub,a2 as vv,a3 as $p,a4 as Kf,a5 as xp,a6 as Rx,a7 as GC,a8 as jx,a9 as VC,aa as Ex,ab as KC,ac as Lg,ad as QC,ae as _g,af as Dx,ag as YC,ah as XC,ai as ZC,aj as JC,ak as ek,al as tk,am as db,an as nk,ao as ak,ap as rk,aq as sk,ar as Fg,as as Pg,at as ik,au as ok,av as fb,aw as Xh,ax as lk,ay as mb,az as Ix,aA as ck,aB as uk,aC as dk}from"./icons-CpeZfjFK.js";import{r as Lx}from"./react-CSxCfTKV.js";import{c as fk}from"./supabase-C7qjtLN3.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const c of document.querySelectorAll('link[rel="modulepreload"]'))o(c);new MutationObserver(c=>{for(const u of c)if(u.type==="childList")for(const f of u.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&o(f)}).observe(document,{childList:!0,subtree:!0});function r(c){const u={};return c.integrity&&(u.integrity=c.integrity),c.referrerPolicy&&(u.referrerPolicy=c.referrerPolicy),c.crossOrigin==="use-credentials"?u.credentials="include":c.crossOrigin==="anonymous"?u.credentials="omit":u.credentials="same-origin",u}function o(c){if(c.ep)return;c.ep=!0;const u=r(c);fetch(c.href,u)}})();var Zh={exports:{}},Nf={};var pb;function mk(){if(pb)return Nf;pb=1;var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function r(o,c,u){var f=null;if(u!==void 0&&(f=""+u),c.key!==void 0&&(f=""+c.key),"key"in c){u={};for(var h in c)h!=="key"&&(u[h]=c[h])}else u=c;return c=u.ref,{$$typeof:t,type:o,key:f,ref:c!==void 0?c:null,props:u}}return Nf.Fragment=n,Nf.jsx=r,Nf.jsxs=r,Nf}var hb;function pk(){return hb||(hb=1,Zh.exports=mk()),Zh.exports}var i=pk(),Jh={exports:{}},Tf={},eg={exports:{}},tg={};var gb;function hk(){return gb||(gb=1,(function(t){function n($,_){var ie=$.length;$.push(_);e:for(;0<ie;){var be=ie-1>>>1,H=$[be];if(0<c(H,_))$[be]=_,$[ie]=H,ie=be;else break e}}function r($){return $.length===0?null:$[0]}function o($){if($.length===0)return null;var _=$[0],ie=$.pop();if(ie!==_){$[0]=ie;e:for(var be=0,H=$.length,te=H>>>1;be<te;){var le=2*(be+1)-1,Ce=$[le],Ae=le+1,_e=$[Ae];if(0>c(Ce,ie))Ae<H&&0>c(_e,Ce)?($[be]=_e,$[Ae]=ie,be=Ae):($[be]=Ce,$[le]=ie,be=le);else if(Ae<H&&0>c(_e,ie))$[be]=_e,$[Ae]=ie,be=Ae;else break e}}return _}function c($,_){var ie=$.sortIndex-_.sortIndex;return ie!==0?ie:$.id-_.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,x=3,A=!1,k=!1,N=!1,E=!1,D=typeof setTimeout=="function"?setTimeout:null,T=typeof clearTimeout=="function"?clearTimeout:null,F=typeof setImmediate<"u"?setImmediate:null;function O($){for(var _=r(y);_!==null;){if(_.callback===null)o(y);else if(_.startTime<=$)o(y),_.sortIndex=_.expirationTime,n(g,_);else break;_=r(y)}}function P($){if(N=!1,O($),!k)if(r(g)!==null)k=!0,z||(z=!0,K());else{var _=r(y);_!==null&&ne(P,_.startTime-$)}}var z=!1,I=-1,X=5,se=-1;function Z(){return E?!0:!(t.unstable_now()-se<X)}function G(){if(E=!1,z){var $=t.unstable_now();se=$;var _=!0;try{e:{k=!1,N&&(N=!1,T(I),I=-1),A=!0;var ie=x;try{t:{for(O($),b=r(g);b!==null&&!(b.expirationTime>$&&Z());){var be=b.callback;if(typeof be=="function"){b.callback=null,x=b.priorityLevel;var H=be(b.expirationTime<=$);if($=t.unstable_now(),typeof H=="function"){b.callback=H,O($),_=!0;break t}b===r(g)&&o(g),O($)}else o(g);b=r(g)}if(b!==null)_=!0;else{var te=r(y);te!==null&&ne(P,te.startTime-$),_=!1}}break e}finally{b=null,x=ie,A=!1}_=void 0}}finally{_?K():z=!1}}}var K;if(typeof F=="function")K=function(){F(G)};else if(typeof MessageChannel<"u"){var me=new MessageChannel,V=me.port2;me.port1.onmessage=G,K=function(){V.postMessage(null)}}else K=function(){D(G,0)};function ne($,_){I=D(function(){$(t.unstable_now())},_)}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($){$.callback=null},t.unstable_forceFrameRate=function($){0>$||125<$?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):X=0<$?Math.floor(1e3/$):5},t.unstable_getCurrentPriorityLevel=function(){return x},t.unstable_next=function($){switch(x){case 1:case 2:case 3:var _=3;break;default:_=x}var ie=x;x=_;try{return $()}finally{x=ie}},t.unstable_requestPaint=function(){E=!0},t.unstable_runWithPriority=function($,_){switch($){case 1:case 2:case 3:case 4:case 5:break;default:$=3}var ie=x;x=$;try{return _()}finally{x=ie}},t.unstable_scheduleCallback=function($,_,ie){var be=t.unstable_now();switch(typeof ie=="object"&&ie!==null?(ie=ie.delay,ie=typeof ie=="number"&&0<ie?be+ie:be):ie=be,$){case 1:var H=-1;break;case 2:H=250;break;case 5:H=1073741823;break;case 4:H=1e4;break;default:H=5e3}return H=ie+H,$={id:w++,callback:_,priorityLevel:$,startTime:ie,expirationTime:H,sortIndex:-1},ie>be?($.sortIndex=ie,n(y,$),r(g)===null&&$===r(y)&&(N?(T(I),I=-1):N=!0,ne(P,ie-be))):($.sortIndex=H,n(g,$),k||A||(k=!0,z||(z=!0,K()))),$},t.unstable_shouldYield=Z,t.unstable_wrapCallback=function($){var _=x;return function(){var ie=x;x=_;try{return $.apply(this,arguments)}finally{x=ie}}}})(tg)),tg}var vb;function gk(){return vb||(vb=1,eg.exports=hk()),eg.exports}var yb;function vk(){if(yb)return Tf;yb=1;var t=gk(),n=RC(),r=Lx();function o(e){var a="https://react.dev/errors/"+e;if(1<arguments.length){a+="?args[]="+encodeURIComponent(arguments[1]);for(var s=2;s<arguments.length;s++)a+="&args[]="+encodeURIComponent(arguments[s])}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 c(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function u(e){var a=e,s=e;if(e.alternate)for(;a.return;)a=a.return;else{e=a;do a=e,(a.flags&4098)!==0&&(s=a.return),e=a.return;while(e)}return a.tag===3?s: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(o(188))}function y(e){var a=e.alternate;if(!a){if(a=u(e),a===null)throw Error(o(188));return a!==e?null:e}for(var s=e,l=a;;){var m=s.return;if(m===null)break;var v=m.alternate;if(v===null){if(l=m.return,l!==null){s=l;continue}break}if(m.child===v.child){for(v=m.child;v;){if(v===s)return g(m),e;if(v===l)return g(m),a;v=v.sibling}throw Error(o(188))}if(s.return!==l.return)s=m,l=v;else{for(var M=!1,L=m.child;L;){if(L===s){M=!0,s=m,l=v;break}if(L===l){M=!0,l=m,s=v;break}L=L.sibling}if(!M){for(L=v.child;L;){if(L===s){M=!0,s=v,l=m;break}if(L===l){M=!0,l=v,s=m;break}L=L.sibling}if(!M)throw Error(o(189))}}if(s.alternate!==l)throw Error(o(190))}if(s.tag!==3)throw Error(o(188));return s.stateNode.current===s?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,x=Symbol.for("react.element"),A=Symbol.for("react.transitional.element"),k=Symbol.for("react.portal"),N=Symbol.for("react.fragment"),E=Symbol.for("react.strict_mode"),D=Symbol.for("react.profiler"),T=Symbol.for("react.consumer"),F=Symbol.for("react.context"),O=Symbol.for("react.forward_ref"),P=Symbol.for("react.suspense"),z=Symbol.for("react.suspense_list"),I=Symbol.for("react.memo"),X=Symbol.for("react.lazy"),se=Symbol.for("react.activity"),Z=Symbol.for("react.memo_cache_sentinel"),G=Symbol.iterator;function K(e){return e===null||typeof e!="object"?null:(e=G&&e[G]||e["@@iterator"],typeof e=="function"?e:null)}var me=Symbol.for("react.client.reference");function V(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===me?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case N:return"Fragment";case D:return"Profiler";case E:return"StrictMode";case P:return"Suspense";case z:return"SuspenseList";case se:return"Activity"}if(typeof e=="object")switch(e.$$typeof){case k:return"Portal";case F:return e.displayName||"Context";case T:return(e._context.displayName||"Context")+".Consumer";case O:var a=e.render;return e=e.displayName,e||(e=a.displayName||a.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case I:return a=e.displayName||null,a!==null?a:V(e.type)||"Memo";case X:a=e._payload,e=e._init;try{return V(e(a))}catch{}}return null}var ne=Array.isArray,$=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,_=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ie={pending:!1,data:null,method:null,action:null},be=[],H=-1;function te(e){return{current:e}}function le(e){0>H||(e.current=be[H],be[H]=null,H--)}function Ce(e,a){H++,be[H]=e.current,e.current=a}var Ae=te(null),_e=te(null),ue=te(null),He=te(null);function ze(e,a){switch(Ce(ue,a),Ce(_e,e),Ce(Ae,null),a.nodeType){case 9:case 11:e=(e=a.documentElement)&&(e=e.namespaceURI)?Ry(e):0;break;default:if(e=a.tagName,a=a.namespaceURI)a=Ry(a),e=jy(a,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}le(Ae),Ce(Ae,e)}function et(){le(Ae),le(_e),le(ue)}function Xe(e){e.memoizedState!==null&&Ce(He,e);var a=Ae.current,s=jy(a,e.type);a!==s&&(Ce(_e,e),Ce(Ae,s))}function Ze(e){_e.current===e&&(le(Ae),le(_e)),He.current===e&&(le(He),Cf._currentValue=ie)}var Ue,Y;function Se(e){if(Ue===void 0)try{throw Error()}catch(s){var a=s.stack.trim().match(/\n( *(at )?)/);Ue=a&&a[1]||"",Y=-1<s.stack.indexOf(`
2
- at`)?" (<anonymous>)":-1<s.stack.indexOf("@")?"@unknown:0:0":""}return`
3
- `+Ue+e+Y}var ye=!1;function je(e,a){if(!e||ye)return"";ye=!0;var s=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var l={DetermineComponentFrameRoot:function(){try{if(a){var Ee=function(){throw Error()};if(Object.defineProperty(Ee.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Ee,[])}catch(Me){var we=Me}Reflect.construct(e,[],Ee)}else{try{Ee.call()}catch(Me){we=Me}e.call(Ee.prototype)}}else{try{throw Error()}catch(Me){we=Me}(Ee=e())&&typeof Ee.catch=="function"&&Ee.catch(function(){})}}catch(Me){if(Me&&we&&typeof Me.stack=="string")return[Me.stack,we.stack]}return[null,null]}};l.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var m=Object.getOwnPropertyDescriptor(l.DetermineComponentFrameRoot,"name");m&&m.configurable&&Object.defineProperty(l.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var v=l.DetermineComponentFrameRoot(),M=v[0],L=v[1];if(M&&L){var Q=M.split(`
4
- `),ve=L.split(`
5
- `);for(m=l=0;l<Q.length&&!Q[l].includes("DetermineComponentFrameRoot");)l++;for(;m<ve.length&&!ve[m].includes("DetermineComponentFrameRoot");)m++;if(l===Q.length||m===ve.length)for(l=Q.length-1,m=ve.length-1;1<=l&&0<=m&&Q[l]!==ve[m];)m--;for(;1<=l&&0<=m;l--,m--)if(Q[l]!==ve[m]){if(l!==1||m!==1)do if(l--,m--,0>m||Q[l]!==ve[m]){var Te=`
6
- `+Q[l].replace(" at new "," at ");return e.displayName&&Te.includes("<anonymous>")&&(Te=Te.replace("<anonymous>",e.displayName)),Te}while(1<=l&&0<=m);break}}}finally{ye=!1,Error.prepareStackTrace=s}return(s=e?e.displayName||e.name:"")?Se(s):""}function $e(e,a){switch(e.tag){case 26:case 27:case 5:return Se(e.type);case 16:return Se("Lazy");case 13:return e.child!==a&&a!==null?Se("Suspense Fallback"):Se("Suspense");case 19:return Se("SuspenseList");case 0:case 15:return je(e.type,!1);case 11:return je(e.type.render,!1);case 1:return je(e.type,!0);case 31:return Se("Activity");default:return""}}function B(e){try{var a="",s=null;do a+=$e(e,s),s=e,e=e.return;while(e);return a}catch(l){return`
7
- Error generating stack: `+l.message+`
8
- `+l.stack}}var lt=Object.prototype.hasOwnProperty,Nt=t.unstable_scheduleCallback,Ht=t.unstable_cancelCallback,ke=t.unstable_shouldYield,qe=t.unstable_requestPaint,Ye=t.unstable_now,_t=t.unstable_getCurrentPriorityLevel,tt=t.unstable_ImmediatePriority,pe=t.unstable_UserBlockingPriority,Ne=t.unstable_NormalPriority,Be=t.unstable_LowPriority,Oe=t.unstable_IdlePriority,We=t.log,Rt=t.unstable_setDisableYieldValue,ee=null,he=null;function Fe(e){if(typeof We=="function"&&Rt(e),he&&typeof he.setStrictMode=="function")try{he.setStrictMode(ee,e)}catch{}}var fe=Math.clz32?Math.clz32:ct,xe=Math.log,nt=Math.LN2;function ct(e){return e>>>=0,e===0?32:31-(xe(e)/nt|0)|0}var ft=256,dt=262144,Dt=4194304;function Yt(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 cn(e,a,s){var l=e.pendingLanes;if(l===0)return 0;var m=0,v=e.suspendedLanes,M=e.pingedLanes;e=e.warmLanes;var L=l&134217727;return L!==0?(l=L&~v,l!==0?m=Yt(l):(M&=L,M!==0?m=Yt(M):s||(s=L&~e,s!==0&&(m=Yt(s))))):(L=l&~v,L!==0?m=Yt(L):M!==0?m=Yt(M):s||(s=l&~e,s!==0&&(m=Yt(s)))),m===0?0:a!==0&&a!==m&&(a&v)===0&&(v=m&-m,s=a&-a,v>=s||v===32&&(s&4194048)!==0)?a:m}function Xt(e,a){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&a)===0}function oa(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 Na(){var e=Dt;return Dt<<=1,(Dt&62914560)===0&&(Dt=4194304),e}function Pn(e){for(var a=[],s=0;31>s;s++)a.push(e);return a}function Wn(e,a){e.pendingLanes|=a,a!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function la(e,a,s,l,m,v){var M=e.pendingLanes;e.pendingLanes=s,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=s,e.entangledLanes&=s,e.errorRecoveryDisabledLanes&=s,e.shellSuspendCounter=0;var L=e.entanglements,Q=e.expirationTimes,ve=e.hiddenUpdates;for(s=M&~s;0<s;){var Te=31-fe(s),Ee=1<<Te;L[Te]=0,Q[Te]=-1;var we=ve[Te];if(we!==null)for(ve[Te]=null,Te=0;Te<we.length;Te++){var Me=we[Te];Me!==null&&(Me.lane&=-536870913)}s&=~Ee}l!==0&&Pe(e,l,0),v!==0&&m===0&&e.tag!==0&&(e.suspendedLanes|=v&~(M&~a))}function Pe(e,a,s){e.pendingLanes|=a,e.suspendedLanes&=~a;var l=31-fe(a);e.entangledLanes|=a,e.entanglements[l]=e.entanglements[l]|1073741824|s&261930}function q(e,a){var s=e.entangledLanes|=a;for(e=e.entanglements;s;){var l=31-fe(s),m=1<<l;m&a|e[l]&a&&(e[l]|=a),s&=~m}}function at(e,a){var s=a&-a;return s=(s&42)!==0?1:ht(s),(s&(e.suspendedLanes|a))!==0?0:s}function ht(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 Zt(e){return e&=-e,2<e?8<e?(e&134217727)!==0?32:268435456:8:2}function bn(){var e=_.p;return e!==0?e:(e=window.event,e===void 0?32:Jy(e.type))}function Es(e,a){var s=_.p;try{return _.p=e,a()}finally{_.p=s}}var Ua=Math.random().toString(36).slice(2),de="__reactFiber$"+Ua,De="__reactProps$"+Ua,Ke="__reactContainer$"+Ua,wt="__reactEvents$"+Ua,Jt="__reactListeners$"+Ua,Ft="__reactHandles$"+Ua,mt="__reactResources$"+Ua,Pt="__reactMarker$"+Ua;function xt(e){delete e[de],delete e[De],delete e[wt],delete e[Jt],delete e[Ft]}function mn(e){var a=e[de];if(a)return a;for(var s=e.parentNode;s;){if(a=s[Ke]||s[de]){if(s=a.alternate,a.child!==null||s!==null&&s.child!==null)for(e=Py(e);e!==null;){if(s=e[de])return s;e=Py(e)}return a}e=s,s=e.parentNode}return null}function na(e){if(e=e[de]||e[Ke]){var a=e.tag;if(a===5||a===6||a===13||a===31||a===26||a===27||a===3)return e}return null}function wn(e){var a=e.tag;if(a===5||a===26||a===27||a===6)return e.stateNode;throw Error(o(33))}function On(e){var a=e[mt];return a||(a=e[mt]={hoistableStyles:new Map,hoistableScripts:new Map}),a}function rn(e){e[Pt]=!0}var br=new Set,wr={};function Ot(e,a){Rn(e,a),Rn(e+"Capture",a)}function Rn(e,a){for(wr[e]=a,e=0;e<a.length;e++)br.add(a[e])}var Bn=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]*$"),Za={},va={};function xr(e){return lt.call(va,e)?!0:lt.call(Za,e)?!1:Bn.test(e)?va[e]=!0:(Za[e]=!0,!1)}function Ja(e,a,s){if(xr(a))if(s===null)e.removeAttribute(a);else{switch(typeof s){case"undefined":case"function":case"symbol":e.removeAttribute(a);return;case"boolean":var l=a.toLowerCase().slice(0,5);if(l!=="data-"&&l!=="aria-"){e.removeAttribute(a);return}}e.setAttribute(a,""+s)}}function is(e,a,s){if(s===null)e.removeAttribute(a);else{switch(typeof s){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(a);return}e.setAttribute(a,""+s)}}function Ta(e,a,s,l){if(l===null)e.removeAttribute(s);else{switch(typeof l){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(s);return}e.setAttributeNS(a,s,""+l)}}function un(e){switch(typeof e){case"bigint":case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function er(e){var a=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(a==="checkbox"||a==="radio")}function Ds(e,a,s){var l=Object.getOwnPropertyDescriptor(e.constructor.prototype,a);if(!e.hasOwnProperty(a)&&typeof l<"u"&&typeof l.get=="function"&&typeof l.set=="function"){var m=l.get,v=l.set;return Object.defineProperty(e,a,{configurable:!0,get:function(){return m.call(this)},set:function(M){s=""+M,v.call(this,M)}}),Object.defineProperty(e,a,{enumerable:l.enumerable}),{getValue:function(){return s},setValue:function(M){s=""+M},stopTracking:function(){e._valueTracker=null,delete e[a]}}}}function _o(e){if(!e._valueTracker){var a=er(e)?"checked":"value";e._valueTracker=Ds(e,a,""+e[a])}}function os(e){if(!e)return!1;var a=e._valueTracker;if(!a)return!0;var s=a.getValue(),l="";return e&&(l=er(e)?e.checked?"true":"false":e.value),e=l,e!==s?(a.setValue(e),!0):!1}function Js(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 Ki=/[\n"\\]/g;function Ln(e){return e.replace(Ki,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Fo(e,a,s,l,m,v,M,L){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=""+un(a)):e.value!==""+un(a)&&(e.value=""+un(a)):M!=="submit"&&M!=="reset"||e.removeAttribute("value"),a!=null?Wr(e,M,un(a)):s!=null?Wr(e,M,un(s)):l!=null&&e.removeAttribute("value"),m==null&&v!=null&&(e.defaultChecked=!!v),m!=null&&(e.checked=m&&typeof m!="function"&&typeof m!="symbol"),L!=null&&typeof L!="function"&&typeof L!="symbol"&&typeof L!="boolean"?e.name=""+un(L):e.removeAttribute("name")}function Jc(e,a,s,l,m,v,M,L){if(v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"&&(e.type=v),a!=null||s!=null){if(!(v!=="submit"&&v!=="reset"||a!=null)){_o(e);return}s=s!=null?""+un(s):"",a=a!=null?""+un(a):s,L||a===e.value||(e.value=a),e.defaultValue=a}l=l??m,l=typeof l!="function"&&typeof l!="symbol"&&!!l,e.checked=L?e.checked:!!l,e.defaultChecked=!!l,M!=null&&typeof M!="function"&&typeof M!="symbol"&&typeof M!="boolean"&&(e.name=M),_o(e)}function Wr(e,a,s){a==="number"&&Js(e.ownerDocument)===e||e.defaultValue===""+s||(e.defaultValue=""+s)}function ei(e,a,s,l){if(e=e.options,a){a={};for(var m=0;m<s.length;m++)a["$"+s[m]]=!0;for(s=0;s<e.length;s++)m=a.hasOwnProperty("$"+e[s].value),e[s].selected!==m&&(e[s].selected=m),m&&l&&(e[s].defaultSelected=!0)}else{for(s=""+un(s),a=null,m=0;m<e.length;m++){if(e[m].value===s){e[m].selected=!0,l&&(e[m].defaultSelected=!0);return}a!==null||e[m].disabled||(a=e[m])}a!==null&&(a.selected=!0)}}function St(e,a,s){if(a!=null&&(a=""+un(a),a!==e.value&&(e.value=a),s==null)){e.defaultValue!==a&&(e.defaultValue=a);return}e.defaultValue=s!=null?""+un(s):""}function Gn(e,a,s,l){if(a==null){if(l!=null){if(s!=null)throw Error(o(92));if(ne(l)){if(1<l.length)throw Error(o(93));l=l[0]}s=l}s==null&&(s=""),a=s}s=un(a),e.defaultValue=s,l=e.textContent,l===s&&l!==""&&l!==null&&(e.value=l),_o(e)}function ls(e,a){if(a){var s=e.firstChild;if(s&&s===e.lastChild&&s.nodeType===3){s.nodeValue=a;return}}e.textContent=a}var en=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 Qi(e,a,s){var l=a.indexOf("--")===0;s==null||typeof s=="boolean"||s===""?l?e.setProperty(a,""):a==="float"?e.cssFloat="":e[a]="":l?e.setProperty(a,s):typeof s!="number"||s===0||en.has(a)?a==="float"?e.cssFloat=s:e[a]=(""+s).trim():e[a]=s+"px"}function Po(e,a,s){if(a!=null&&typeof a!="object")throw Error(o(62));if(e=e.style,s!=null){for(var l in s)!s.hasOwnProperty(l)||a!=null&&a.hasOwnProperty(l)||(l.indexOf("--")===0?e.setProperty(l,""):l==="float"?e.cssFloat="":e[l]="");for(var m in a)l=a[m],a.hasOwnProperty(m)&&s[m]!==l&&Qi(e,m,l)}else for(var v in a)a.hasOwnProperty(v)&&Qi(e,v,a[v])}function ti(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 Kl=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"]]),Wt=/^[\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 Ra(e){return Wt.test(""+e)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":e}function tr(){}var ni=null;function Vn(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Sr=null,qa=null;function Ql(e){var a=na(e);if(a&&(e=a.stateNode)){var s=e[De]||null;e:switch(e=a.stateNode,a.type){case"input":if(Fo(e,s.value,s.defaultValue,s.defaultValue,s.checked,s.defaultChecked,s.type,s.name),a=s.name,s.type==="radio"&&a!=null){for(s=e;s.parentNode;)s=s.parentNode;for(s=s.querySelectorAll('input[name="'+Ln(""+a)+'"][type="radio"]'),a=0;a<s.length;a++){var l=s[a];if(l!==e&&l.form===e.form){var m=l[De]||null;if(!m)throw Error(o(90));Fo(l,m.value,m.defaultValue,m.defaultValue,m.checked,m.defaultChecked,m.type,m.name)}}for(a=0;a<s.length;a++)l=s[a],l.form===e.form&&os(l)}break e;case"textarea":St(e,s.value,s.defaultValue);break e;case"select":a=s.value,a!=null&&ei(e,!!s.multiple,a,!1)}}}var Oo=!1;function Yl(e,a,s){if(Oo)return e(a,s);Oo=!0;try{var l=e(a);return l}finally{if(Oo=!1,(Sr!==null||qa!==null)&&(Rm(),Sr&&(a=Sr,e=qa,qa=Sr=null,Ql(a),e)))for(a=0;a<e.length;a++)Ql(e[a])}}function Yi(e,a){var s=e.stateNode;if(s===null)return null;var l=s[De]||null;if(l===null)return null;s=l[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":(l=!l.disabled)||(e=e.type,l=!(e==="button"||e==="input"||e==="select"||e==="textarea")),e=!l;break e;default:e=!1}if(e)return null;if(s&&typeof s!="function")throw Error(o(231,a,typeof s));return s}var Cr=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),cs=!1;if(Cr)try{var Xi={};Object.defineProperty(Xi,"passive",{get:function(){cs=!0}}),window.addEventListener("test",Xi,Xi),window.removeEventListener("test",Xi,Xi)}catch{cs=!1}var us=null,ai=null,Gt=null;function ja(){if(Gt)return Gt;var e,a=ai,s=a.length,l,m="value"in us?us.value:us.textContent,v=m.length;for(e=0;e<s&&a[e]===m[e];e++);var M=s-e;for(l=1;l<=M&&a[s-l]===m[v-l];l++);return Gt=m.slice(e,1<l?1-l:void 0)}function nr(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 pn(){return!0}function ds(){return!1}function xn(e){function a(s,l,m,v,M){this._reactName=s,this._targetInst=m,this.type=l,this.nativeEvent=v,this.target=M,this.currentTarget=null;for(var L in e)e.hasOwnProperty(L)&&(s=e[L],this[L]=s?s(v):v[L]);return this.isDefaultPrevented=(v.defaultPrevented!=null?v.defaultPrevented:v.returnValue===!1)?pn:ds,this.isPropagationStopped=ds,this}return b(a.prototype,{preventDefault:function(){this.defaultPrevented=!0;var s=this.nativeEvent;s&&(s.preventDefault?s.preventDefault():typeof s.returnValue!="unknown"&&(s.returnValue=!1),this.isDefaultPrevented=pn)},stopPropagation:function(){var s=this.nativeEvent;s&&(s.stopPropagation?s.stopPropagation():typeof s.cancelBubble!="unknown"&&(s.cancelBubble=!0),this.isPropagationStopped=pn)},persist:function(){},isPersistent:pn}),a}var kr={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Wa=xn(kr),fs=b({},kr,{view:0,detail:0}),Zi=xn(fs),Ea,Da,Bo,Ji=b({},fs,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Ho,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!==Bo&&(Bo&&e.type==="mousemove"?(Ea=e.screenX-Bo.screenX,Da=e.screenY-Bo.screenY):Da=Ea=0,Bo=e),Ea)},movementY:function(e){return"movementY"in e?e.movementY:Da}}),eo=xn(Ji),Mr=b({},Ji,{dataTransfer:0}),Xl=xn(Mr),Ar=b({},fs,{relatedTarget:0}),Si=xn(Ar),Zl=b({},kr,{animationName:0,elapsedTime:0,pseudoElement:0}),ri=xn(Zl),bd=b({},kr,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),eu=xn(bd),wd=b({},kr,{data:0}),xd=xn(wd),tu={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Sd={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"},Ci={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function nu(e){var a=this.nativeEvent;return a.getModifierState?a.getModifierState(e):(e=Ci[e])?!!a[e]:!1}function Ho(){return nu}var au=b({},fs,{key:function(e){if(e.key){var a=tu[e.key]||e.key;if(a!=="Unidentified")return a}return e.type==="keypress"?(e=nr(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?Sd[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Ho,charCode:function(e){return e.type==="keypress"?nr(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?nr(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),Cd=xn(au),Ga=b({},Ji,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Jl=xn(Ga),th=b({},fs,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Ho}),si=xn(th),am=b({},kr,{propertyName:0,elapsedTime:0,pseudoElement:0}),ms=xn(am),Gr=b({},Ji,{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}),Nr=xn(Gr),ec=b({},kr,{newState:0,oldState:0}),rm=xn(ec),Kn=[9,13,27,32],ca=Cr&&"CompositionEvent"in window,zo=null;Cr&&"documentMode"in document&&(zo=document.documentMode);var $o=Cr&&"TextEvent"in window&&!zo,yt=Cr&&(!ca||zo&&8<zo&&11>=zo),Tr=" ",ki=!1;function to(e,a){switch(e){case"keyup":return Kn.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Uo(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Rr=!1;function no(e,a){switch(e){case"compositionend":return Uo(a);case"keypress":return a.which!==32?null:(ki=!0,Tr);case"textInput":return e=a.data,e===Tr&&ki?null:e;default:return null}}function ru(e,a){if(Rr)return e==="compositionend"||!ca&&to(e,a)?(e=ja(),Gt=ai=us=null,Rr=!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 yt&&a.locale!=="ko"?null:a.data;default:return null}}var qo={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 Mi(e){var a=e&&e.nodeName&&e.nodeName.toLowerCase();return a==="input"?!!qo[e.type]:a==="textarea"}function Ai(e,a,s,l){Sr?qa?qa.push(l):qa=[l]:Sr=l,a=Fm(a,"onChange"),0<a.length&&(s=new Wa("onChange","change",null,s,l),e.push({event:s,listeners:a}))}var Is=null,Ni=null;function ps(e){Cy(e,0)}function jr(e){var a=wn(e);if(os(a))return e}function su(e,a){if(e==="change")return a}var Va=!1;if(Cr){var kd;if(Cr){var Ti="oninput"in document;if(!Ti){var sm=document.createElement("div");sm.setAttribute("oninput","return;"),Ti=typeof sm.oninput=="function"}kd=Ti}else kd=!1;Va=kd&&(!document.documentMode||9<document.documentMode)}function Wo(){Is&&(Is.detachEvent("onpropertychange",tc),Ni=Is=null)}function tc(e){if(e.propertyName==="value"&&jr(Ni)){var a=[];Ai(a,Ni,e,Vn(e)),Yl(ps,a)}}function iu(e,a,s){e==="focusin"?(Wo(),Is=a,Ni=s,Is.attachEvent("onpropertychange",tc)):e==="focusout"&&Wo()}function ou(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return jr(Ni)}function Md(e,a){if(e==="click")return jr(a)}function Ad(e,a){if(e==="input"||e==="change")return jr(a)}function lu(e,a){return e===a&&(e!==0||1/e===1/a)||e!==e&&a!==a}var ar=typeof Object.is=="function"?Object.is:lu;function Go(e,a){if(ar(e,a))return!0;if(typeof e!="object"||e===null||typeof a!="object"||a===null)return!1;var s=Object.keys(e),l=Object.keys(a);if(s.length!==l.length)return!1;for(l=0;l<s.length;l++){var m=s[l];if(!lt.call(a,m)||!ar(e[m],a[m]))return!1}return!0}function Ls(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function nc(e,a){var s=Ls(e);e=0;for(var l;s;){if(s.nodeType===3){if(l=e+s.textContent.length,e<=a&&l>=a)return{node:s,offset:a-e};e=l}e:{for(;s;){if(s.nextSibling){s=s.nextSibling;break e}s=s.parentNode}s=void 0}s=Ls(s)}}function ao(e,a){return e&&a?e===a?!0:e&&e.nodeType===3?!1:a&&a.nodeType===3?ao(e,a.parentNode):"contains"in e?e.contains(a):e.compareDocumentPosition?!!(e.compareDocumentPosition(a)&16):!1:!1}function ro(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var a=Js(e.document);a instanceof e.HTMLIFrameElement;){try{var s=typeof a.contentWindow.location.href=="string"}catch{s=!1}if(s)e=a.contentWindow;else break;a=Js(e.document)}return a}function ii(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 aa=Cr&&"documentMode"in document&&11>=document.documentMode,hs=null,cu=null,Qn=null,rr=!1;function Nd(e,a,s){var l=s.window===s?s.document:s.nodeType===9?s:s.ownerDocument;rr||hs==null||hs!==Js(l)||(l=hs,"selectionStart"in l&&ii(l)?l={start:l.selectionStart,end:l.selectionEnd}:(l=(l.ownerDocument&&l.ownerDocument.defaultView||window).getSelection(),l={anchorNode:l.anchorNode,anchorOffset:l.anchorOffset,focusNode:l.focusNode,focusOffset:l.focusOffset}),Qn&&Go(Qn,l)||(Qn=l,l=Fm(cu,"onSelect"),0<l.length&&(a=new Wa("onSelect","select",null,a,s),e.push({event:a,listeners:l}),a.target=hs)))}function jn(e,a){var s={};return s[e.toLowerCase()]=a.toLowerCase(),s["Webkit"+e]="webkit"+a,s["Moz"+e]="moz"+a,s}var Vr={animationend:jn("Animation","AnimationEnd"),animationiteration:jn("Animation","AnimationIteration"),animationstart:jn("Animation","AnimationStart"),transitionrun:jn("Transition","TransitionRun"),transitionstart:jn("Transition","TransitionStart"),transitioncancel:jn("Transition","TransitionCancel"),transitionend:jn("Transition","TransitionEnd")},_s={},im={};Cr&&(im=document.createElement("div").style,"AnimationEvent"in window||(delete Vr.animationend.animation,delete Vr.animationiteration.animation,delete Vr.animationstart.animation),"TransitionEvent"in window||delete Vr.transitionend.transition);function oi(e){if(_s[e])return _s[e];if(!Vr[e])return e;var a=Vr[e],s;for(s in a)if(a.hasOwnProperty(s)&&s in im)return _s[e]=a[s];return e}var nh=oi("animationend"),om=oi("animationiteration"),so=oi("animationstart"),ah=oi("transitionrun"),Vo=oi("transitionstart"),Td=oi("transitioncancel"),rh=oi("transitionend"),sh=new Map,lm="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(" ");lm.push("scrollEnd");function gs(e,a){sh.set(e,a),Ot(a,[e])}var ac=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)},Er=[],Ko=0,Rd=0;function uu(){for(var e=Ko,a=Rd=Ko=0;a<e;){var s=Er[a];Er[a++]=null;var l=Er[a];Er[a++]=null;var m=Er[a];Er[a++]=null;var v=Er[a];if(Er[a++]=null,l!==null&&m!==null){var M=l.pending;M===null?m.next=m:(m.next=M.next,M.next=m),l.pending=m}v!==0&&Ps(s,m,v)}}function Qo(e,a,s,l){Er[Ko++]=e,Er[Ko++]=a,Er[Ko++]=s,Er[Ko++]=l,Rd|=l,e.lanes|=l,e=e.alternate,e!==null&&(e.lanes|=l)}function rc(e,a,s,l){return Qo(e,a,s,l),Kr(e)}function Fs(e,a){return Qo(e,null,null,a),Kr(e)}function Ps(e,a,s){e.lanes|=s;var l=e.alternate;l!==null&&(l.lanes|=s);for(var m=!1,v=e.return;v!==null;)v.childLanes|=s,l=v.alternate,l!==null&&(l.childLanes|=s),v.tag===22&&(e=v.stateNode,e===null||e._visibility&1||(m=!0)),e=v,v=v.return;return e.tag===3?(v=e.stateNode,m&&a!==null&&(m=31-fe(s),e=v.hiddenUpdates,l=e[m],l===null?e[m]=[a]:l.push(a),a.lane=s|536870912),v):null}function Kr(e){if(50<gf)throw gf=0,wh=null,Error(o(185));for(var a=e.return;a!==null;)e=a,a=e.return;return e.tag===3?e.stateNode:null}var Ka={};function du(e,a,s,l){this.tag=e,this.key=s,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=l,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ia(e,a,s,l){return new du(e,a,s,l)}function Yo(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Os(e,a){var s=e.alternate;return s===null?(s=Ia(e.tag,a,e.key,e.mode),s.elementType=e.elementType,s.type=e.type,s.stateNode=e.stateNode,s.alternate=e,e.alternate=s):(s.pendingProps=a,s.type=e.type,s.flags=0,s.subtreeFlags=0,s.deletions=null),s.flags=e.flags&65011712,s.childLanes=e.childLanes,s.lanes=e.lanes,s.child=e.child,s.memoizedProps=e.memoizedProps,s.memoizedState=e.memoizedState,s.updateQueue=e.updateQueue,a=e.dependencies,s.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext},s.sibling=e.sibling,s.index=e.index,s.ref=e.ref,s.refCleanup=e.refCleanup,s}function jd(e,a){e.flags&=65011714;var s=e.alternate;return s===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=s.childLanes,e.lanes=s.lanes,e.child=s.child,e.subtreeFlags=0,e.deletions=null,e.memoizedProps=s.memoizedProps,e.memoizedState=s.memoizedState,e.updateQueue=s.updateQueue,e.type=s.type,a=s.dependencies,e.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext}),e}function sc(e,a,s,l,m,v){var M=0;if(l=e,typeof e=="function")Yo(e)&&(M=1);else if(typeof e=="string")M=vC(e,s,Ae.current)?26:e==="html"||e==="head"||e==="body"?27:5;else e:switch(e){case se:return e=Ia(31,s,a,m),e.elementType=se,e.lanes=v,e;case N:return vs(s.children,m,v,a);case E:M=8,m|=24;break;case D:return e=Ia(12,s,a,m|2),e.elementType=D,e.lanes=v,e;case P:return e=Ia(13,s,a,m),e.elementType=P,e.lanes=v,e;case z:return e=Ia(19,s,a,m),e.elementType=z,e.lanes=v,e;default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case F:M=10;break e;case T:M=9;break e;case O:M=11;break e;case I:M=14;break e;case X:M=16,l=null;break e}M=29,s=Error(o(130,e===null?"null":typeof e,"")),l=null}return a=Ia(M,s,a,m),a.elementType=e,a.type=l,a.lanes=v,a}function vs(e,a,s,l){return e=Ia(7,e,l,a),e.lanes=s,e}function ic(e,a,s){return e=Ia(6,e,null,a),e.lanes=s,e}function Xo(e){var a=Ia(18,null,null,0);return a.stateNode=e,a}function Ct(e,a,s){return a=Ia(4,e.children!==null?e.children:[],e.key,a),a.lanes=s,a.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},a}var Bs=new WeakMap;function Dr(e,a){if(typeof e=="object"&&e!==null){var s=Bs.get(e);return s!==void 0?s:(a={value:e,source:a,stack:B(a)},Bs.set(e,a),a)}return{value:e,source:a,stack:B(a)}}var Qr=[],ys=0,bs=null,io=0,Mt=[],En=0,ws=null,Qa=1,Hs="";function li(e,a){Qr[ys++]=io,Qr[ys++]=bs,bs=e,io=a}function oc(e,a,s){Mt[En++]=Qa,Mt[En++]=Hs,Mt[En++]=ws,ws=e;var l=Qa;e=Hs;var m=32-fe(l)-1;l&=~(1<<m),s+=1;var v=32-fe(a)+m;if(30<v){var M=m-m%5;v=(l&(1<<M)-1).toString(32),l>>=M,m-=M,Qa=1<<32-fe(a)+m|s<<m|l,Hs=v+e}else Qa=1<<v|s<<m|l,Hs=e}function fu(e){e.return!==null&&(li(e,1),oc(e,1,0))}function mu(e){for(;e===bs;)bs=Qr[--ys],Qr[ys]=null,io=Qr[--ys],Qr[ys]=null;for(;e===ws;)ws=Mt[--En],Mt[En]=null,Hs=Mt[--En],Mt[En]=null,Qa=Mt[--En],Mt[En]=null}function lc(e,a){Mt[En++]=Qa,Mt[En++]=Hs,Mt[En++]=ws,Qa=a.id,Hs=a.overflow,ws=e}var _n=null,Je=null,Bt=!1,Ri=null,ya=!1,Zo=Error(o(519));function La(e){var a=Error(o(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw ji(Dr(a,e)),Zo}function pu(e){var a=e.stateNode,s=e.type,l=e.memoizedProps;switch(a[de]=e,a[De]=l,s){case"dialog":qt("cancel",a),qt("close",a);break;case"iframe":case"object":case"embed":qt("load",a);break;case"video":case"audio":for(s=0;s<yf.length;s++)qt(yf[s],a);break;case"source":qt("error",a);break;case"img":case"image":case"link":qt("error",a),qt("load",a);break;case"details":qt("toggle",a);break;case"input":qt("invalid",a),Jc(a,l.value,l.defaultValue,l.checked,l.defaultChecked,l.type,l.name,!0);break;case"select":qt("invalid",a);break;case"textarea":qt("invalid",a),Gn(a,l.value,l.defaultValue,l.children)}s=l.children,typeof s!="string"&&typeof s!="number"&&typeof s!="bigint"||a.textContent===""+s||l.suppressHydrationWarning===!0||Ny(a.textContent,s)?(l.popover!=null&&(qt("beforetoggle",a),qt("toggle",a)),l.onScroll!=null&&qt("scroll",a),l.onScrollEnd!=null&&qt("scrollend",a),l.onClick!=null&&(a.onclick=tr),a=!0):a=!1,a||La(e,!0)}function Ed(e){for(_n=e.return;_n;)switch(_n.tag){case 5:case 31:case 13:ya=!1;return;case 27:case 3:ya=!0;return;default:_n=_n.return}}function Jo(e){if(e!==_n)return!1;if(!Bt)return Ed(e),Bt=!0,!1;var a=e.tag,s;if((s=a!==3&&a!==27)&&((s=a===5)&&(s=e.type,s=!(s!=="form"&&s!=="button")||_h(e.type,e.memoizedProps)),s=!s),s&&Je&&La(e),Ed(e),a===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(o(317));Je=Fy(e)}else if(a===31){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(o(317));Je=Fy(e)}else a===27?(a=Je,Tl(e.type)?(e=Hh,Hh=null,Je=e):Je=a):Je=_n?Ks(e.stateNode.nextSibling):null;return!0}function oo(){Je=_n=null,Bt=!1}function Dd(){var e=Ri;return e!==null&&(ns===null?ns=e:ns.push.apply(ns,e),Ri=null),e}function ji(e){Ri===null?Ri=[e]:Ri.push(e)}var Id=te(null),zs=null,sr=null;function Dn(e,a,s){Ce(Id,a._currentValue),a._currentValue=s}function ir(e){e._currentValue=Id.current,le(Id)}function ba(e,a,s){for(;e!==null;){var l=e.alternate;if((e.childLanes&a)!==a?(e.childLanes|=a,l!==null&&(l.childLanes|=a)):l!==null&&(l.childLanes&a)!==a&&(l.childLanes|=a),e===s)break;e=e.return}}function or(e,a,s,l){var m=e.child;for(m!==null&&(m.return=e);m!==null;){var v=m.dependencies;if(v!==null){var M=m.child;v=v.firstContext;e:for(;v!==null;){var L=v;v=m;for(var Q=0;Q<a.length;Q++)if(L.context===a[Q]){v.lanes|=s,L=v.alternate,L!==null&&(L.lanes|=s),ba(v.return,s,e),l||(M=null);break e}v=L.next}}else if(m.tag===18){if(M=m.return,M===null)throw Error(o(341));M.lanes|=s,v=M.alternate,v!==null&&(v.lanes|=s),ba(M,s,e),M=null}else M=m.child;if(M!==null)M.return=m;else for(M=m;M!==null;){if(M===e){M=null;break}if(m=M.sibling,m!==null){m.return=M.return,M=m;break}M=M.return}m=M}}function Ie(e,a,s,l){e=null;for(var m=a,v=!1;m!==null;){if(!v){if((m.flags&524288)!==0)v=!0;else if((m.flags&262144)!==0)break}if(m.tag===10){var M=m.alternate;if(M===null)throw Error(o(387));if(M=M.memoizedProps,M!==null){var L=m.type;ar(m.pendingProps.value,M.value)||(e!==null?e.push(L):e=[L])}}else if(m===He.current){if(M=m.alternate,M===null)throw Error(o(387));M.memoizedState.memoizedState!==m.memoizedState.memoizedState&&(e!==null?e.push(Cf):e=[Cf])}m=m.return}e!==null&&or(a,e,s,l),a.flags|=262144}function cc(e){for(e=e.firstContext;e!==null;){if(!ar(e.context._currentValue,e.memoizedValue))return!0;e=e.next}return!1}function lo(e){zs=e,sr=null,e=e.dependencies,e!==null&&(e.firstContext=null)}function wa(e){return Yr(zs,e)}function el(e,a){return zs===null&&lo(e),Yr(e,a)}function Yr(e,a){var s=a._currentValue;if(a={context:a,memoizedValue:s,next:null},sr===null){if(e===null)throw Error(o(308));sr=a,e.dependencies={lanes:0,firstContext:a},e.flags|=524288}else sr=sr.next=a;return s}var Wv=typeof AbortController<"u"?AbortController:function(){var e=[],a=this.signal={aborted:!1,addEventListener:function(s,l){e.push(l)}};this.abort=function(){a.aborted=!0,e.forEach(function(s){return s()})}},tl=t.unstable_scheduleCallback,Yn=t.unstable_NormalPriority,Hn={$$typeof:F,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function uc(){return{controller:new Wv,data:new Map,refCount:0}}function lr(e){e.refCount--,e.refCount===0&&tl(Yn,function(){e.controller.abort()})}var dc=null,Ld=0,Vt=0,xs=null;function ih(e,a){if(dc===null){var s=dc=[];Ld=0,Vt=Ah(),xs={status:"pending",value:void 0,then:function(l){s.push(l)}}}return Ld++,a.then($s,$s),a}function $s(){if(--Ld===0&&dc!==null){xs!==null&&(xs.status="fulfilled");var e=dc;dc=null,Vt=0,xs=null;for(var a=0;a<e.length;a++)(0,e[a])()}}function cm(e,a){var s=[],l={status:"pending",value:null,reason:null,then:function(m){s.push(m)}};return e.then(function(){l.status="fulfilled",l.value=a;for(var m=0;m<s.length;m++)(0,s[m])(a)},function(m){for(l.status="rejected",l.reason=m,m=0;m<s.length;m++)(0,s[m])(void 0)}),l}var nl=$.S;$.S=function(e,a){Xv=Ye(),typeof a=="object"&&a!==null&&typeof a.then=="function"&&ih(e,a),nl!==null&&nl(e,a)};var ra=te(null);function al(){var e=ra.current;return e!==null?e:Mn.pooledCache}function _d(e,a){a===null?Ce(ra,ra.current):Ce(ra,a.pool)}function rl(){var e=al();return e===null?null:{parent:Hn._currentValue,pool:e}}var ci=Error(o(460)),sl=Error(o(474)),Ir=Error(o(542)),Lr={then:function(){}};function fc(e){return e=e.status,e==="fulfilled"||e==="rejected"}function il(e,a,s){switch(s=e[s],s===void 0?e.push(a):s!==a&&(a.then(tr,tr),a=s),a.status){case"fulfilled":return a.value;case"rejected":throw e=a.reason,Fd(e),e;default:if(typeof a.status=="string")a.then(tr,tr);else{if(e=Mn,e!==null&&100<e.shellSuspendCounter)throw Error(o(482));e=a,e.status="pending",e.then(function(l){if(a.status==="pending"){var m=a;m.status="fulfilled",m.value=l}},function(l){if(a.status==="pending"){var m=a;m.status="rejected",m.reason=l}})}switch(a.status){case"fulfilled":return a.value;case"rejected":throw e=a.reason,Fd(e),e}throw Xn=a,ci}}function _a(e){try{var a=e._init;return a(e._payload)}catch(s){throw s!==null&&typeof s=="object"&&typeof s.then=="function"?(Xn=s,ci):s}}var Xn=null;function cr(){if(Xn===null)throw Error(o(459));var e=Xn;return Xn=null,e}function Fd(e){if(e===ci||e===Ir)throw Error(o(483))}var ol=null,ll=0;function ui(e){var a=ll;return ll+=1,ol===null&&(ol=[]),il(ol,e,a)}function co(e,a){a=a.props.ref,e.ref=a!==void 0?a:null}function uo(e,a){throw a.$$typeof===x?Error(o(525)):(e=Object.prototype.toString.call(a),Error(o(31,e==="[object Object]"?"object with keys {"+Object.keys(a).join(", ")+"}":e)))}function Us(e){function a(ce,re){if(e){var ge=ce.deletions;ge===null?(ce.deletions=[re],ce.flags|=16):ge.push(re)}}function s(ce,re){if(!e)return null;for(;re!==null;)a(ce,re),re=re.sibling;return null}function l(ce){for(var re=new Map;ce!==null;)ce.key!==null?re.set(ce.key,ce):re.set(ce.index,ce),ce=ce.sibling;return re}function m(ce,re){return ce=Os(ce,re),ce.index=0,ce.sibling=null,ce}function v(ce,re,ge){return ce.index=ge,e?(ge=ce.alternate,ge!==null?(ge=ge.index,ge<re?(ce.flags|=67108866,re):ge):(ce.flags|=67108866,re)):(ce.flags|=1048576,re)}function M(ce){return e&&ce.alternate===null&&(ce.flags|=67108866),ce}function L(ce,re,ge,Re){return re===null||re.tag!==6?(re=ic(ge,ce.mode,Re),re.return=ce,re):(re=m(re,ge),re.return=ce,re)}function Q(ce,re,ge,Re){var vt=ge.type;return vt===N?Te(ce,re,ge.props.children,Re,ge.key):re!==null&&(re.elementType===vt||typeof vt=="object"&&vt!==null&&vt.$$typeof===X&&_a(vt)===re.type)?(re=m(re,ge.props),co(re,ge),re.return=ce,re):(re=sc(ge.type,ge.key,ge.props,null,ce.mode,Re),co(re,ge),re.return=ce,re)}function ve(ce,re,ge,Re){return re===null||re.tag!==4||re.stateNode.containerInfo!==ge.containerInfo||re.stateNode.implementation!==ge.implementation?(re=Ct(ge,ce.mode,Re),re.return=ce,re):(re=m(re,ge.children||[]),re.return=ce,re)}function Te(ce,re,ge,Re,vt){return re===null||re.tag!==7?(re=vs(ge,ce.mode,Re,vt),re.return=ce,re):(re=m(re,ge),re.return=ce,re)}function Ee(ce,re,ge){if(typeof re=="string"&&re!==""||typeof re=="number"||typeof re=="bigint")return re=ic(""+re,ce.mode,ge),re.return=ce,re;if(typeof re=="object"&&re!==null){switch(re.$$typeof){case A:return ge=sc(re.type,re.key,re.props,null,ce.mode,ge),co(ge,re),ge.return=ce,ge;case k:return re=Ct(re,ce.mode,ge),re.return=ce,re;case X:return re=_a(re),Ee(ce,re,ge)}if(ne(re)||K(re))return re=vs(re,ce.mode,ge,null),re.return=ce,re;if(typeof re.then=="function")return Ee(ce,ui(re),ge);if(re.$$typeof===F)return Ee(ce,el(ce,re),ge);uo(ce,re)}return null}function we(ce,re,ge,Re){var vt=re!==null?re.key:null;if(typeof ge=="string"&&ge!==""||typeof ge=="number"||typeof ge=="bigint")return vt!==null?null:L(ce,re,""+ge,Re);if(typeof ge=="object"&&ge!==null){switch(ge.$$typeof){case A:return ge.key===vt?Q(ce,re,ge,Re):null;case k:return ge.key===vt?ve(ce,re,ge,Re):null;case X:return ge=_a(ge),we(ce,re,ge,Re)}if(ne(ge)||K(ge))return vt!==null?null:Te(ce,re,ge,Re,null);if(typeof ge.then=="function")return we(ce,re,ui(ge),Re);if(ge.$$typeof===F)return we(ce,re,el(ce,ge),Re);uo(ce,ge)}return null}function Me(ce,re,ge,Re,vt){if(typeof Re=="string"&&Re!==""||typeof Re=="number"||typeof Re=="bigint")return ce=ce.get(ge)||null,L(re,ce,""+Re,vt);if(typeof Re=="object"&&Re!==null){switch(Re.$$typeof){case A:return ce=ce.get(Re.key===null?ge:Re.key)||null,Q(re,ce,Re,vt);case k:return ce=ce.get(Re.key===null?ge:Re.key)||null,ve(re,ce,Re,vt);case X:return Re=_a(Re),Me(ce,re,ge,Re,vt)}if(ne(Re)||K(Re))return ce=ce.get(ge)||null,Te(re,ce,Re,vt,null);if(typeof Re.then=="function")return Me(ce,re,ge,ui(Re),vt);if(Re.$$typeof===F)return Me(ce,re,ge,el(re,Re),vt);uo(re,Re)}return null}function it(ce,re,ge,Re){for(var vt=null,tn=null,ut=re,Lt=re=0,Qt=null;ut!==null&&Lt<ge.length;Lt++){ut.index>Lt?(Qt=ut,ut=null):Qt=ut.sibling;var nn=we(ce,ut,ge[Lt],Re);if(nn===null){ut===null&&(ut=Qt);break}e&&ut&&nn.alternate===null&&a(ce,ut),re=v(nn,re,Lt),tn===null?vt=nn:tn.sibling=nn,tn=nn,ut=Qt}if(Lt===ge.length)return s(ce,ut),Bt&&li(ce,Lt),vt;if(ut===null){for(;Lt<ge.length;Lt++)ut=Ee(ce,ge[Lt],Re),ut!==null&&(re=v(ut,re,Lt),tn===null?vt=ut:tn.sibling=ut,tn=ut);return Bt&&li(ce,Lt),vt}for(ut=l(ut);Lt<ge.length;Lt++)Qt=Me(ut,ce,Lt,ge[Lt],Re),Qt!==null&&(e&&Qt.alternate!==null&&ut.delete(Qt.key===null?Lt:Qt.key),re=v(Qt,re,Lt),tn===null?vt=Qt:tn.sibling=Qt,tn=Qt);return e&&ut.forEach(function(Il){return a(ce,Il)}),Bt&&li(ce,Lt),vt}function kt(ce,re,ge,Re){if(ge==null)throw Error(o(151));for(var vt=null,tn=null,ut=re,Lt=re=0,Qt=null,nn=ge.next();ut!==null&&!nn.done;Lt++,nn=ge.next()){ut.index>Lt?(Qt=ut,ut=null):Qt=ut.sibling;var Il=we(ce,ut,nn.value,Re);if(Il===null){ut===null&&(ut=Qt);break}e&&ut&&Il.alternate===null&&a(ce,ut),re=v(Il,re,Lt),tn===null?vt=Il:tn.sibling=Il,tn=Il,ut=Qt}if(nn.done)return s(ce,ut),Bt&&li(ce,Lt),vt;if(ut===null){for(;!nn.done;Lt++,nn=ge.next())nn=Ee(ce,nn.value,Re),nn!==null&&(re=v(nn,re,Lt),tn===null?vt=nn:tn.sibling=nn,tn=nn);return Bt&&li(ce,Lt),vt}for(ut=l(ut);!nn.done;Lt++,nn=ge.next())nn=Me(ut,ce,Lt,nn.value,Re),nn!==null&&(e&&nn.alternate!==null&&ut.delete(nn.key===null?Lt:nn.key),re=v(nn,re,Lt),tn===null?vt=nn:tn.sibling=nn,tn=nn);return e&&ut.forEach(function(TC){return a(ce,TC)}),Bt&&li(ce,Lt),vt}function vn(ce,re,ge,Re){if(typeof ge=="object"&&ge!==null&&ge.type===N&&ge.key===null&&(ge=ge.props.children),typeof ge=="object"&&ge!==null){switch(ge.$$typeof){case A:e:{for(var vt=ge.key;re!==null;){if(re.key===vt){if(vt=ge.type,vt===N){if(re.tag===7){s(ce,re.sibling),Re=m(re,ge.props.children),Re.return=ce,ce=Re;break e}}else if(re.elementType===vt||typeof vt=="object"&&vt!==null&&vt.$$typeof===X&&_a(vt)===re.type){s(ce,re.sibling),Re=m(re,ge.props),co(Re,ge),Re.return=ce,ce=Re;break e}s(ce,re);break}else a(ce,re);re=re.sibling}ge.type===N?(Re=vs(ge.props.children,ce.mode,Re,ge.key),Re.return=ce,ce=Re):(Re=sc(ge.type,ge.key,ge.props,null,ce.mode,Re),co(Re,ge),Re.return=ce,ce=Re)}return M(ce);case k:e:{for(vt=ge.key;re!==null;){if(re.key===vt)if(re.tag===4&&re.stateNode.containerInfo===ge.containerInfo&&re.stateNode.implementation===ge.implementation){s(ce,re.sibling),Re=m(re,ge.children||[]),Re.return=ce,ce=Re;break e}else{s(ce,re);break}else a(ce,re);re=re.sibling}Re=Ct(ge,ce.mode,Re),Re.return=ce,ce=Re}return M(ce);case X:return ge=_a(ge),vn(ce,re,ge,Re)}if(ne(ge))return it(ce,re,ge,Re);if(K(ge)){if(vt=K(ge),typeof vt!="function")throw Error(o(150));return ge=vt.call(ge),kt(ce,re,ge,Re)}if(typeof ge.then=="function")return vn(ce,re,ui(ge),Re);if(ge.$$typeof===F)return vn(ce,re,el(ce,ge),Re);uo(ce,ge)}return typeof ge=="string"&&ge!==""||typeof ge=="number"||typeof ge=="bigint"?(ge=""+ge,re!==null&&re.tag===6?(s(ce,re.sibling),Re=m(re,ge),Re.return=ce,ce=Re):(s(ce,re),Re=ic(ge,ce.mode,Re),Re.return=ce,ce=Re),M(ce)):s(ce,re)}return function(ce,re,ge,Re){try{ll=0;var vt=vn(ce,re,ge,Re);return ol=null,vt}catch(ut){if(ut===ci||ut===Ir)throw ut;var tn=Ia(29,ut,null,ce.mode);return tn.lanes=Re,tn.return=ce,tn}}}var _r=Us(!0),hu=Us(!1),Fa=!1;function cl(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function ul(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 xa(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Sa(e,a,s){var l=e.updateQueue;if(l===null)return null;if(l=l.shared,(on&2)!==0){var m=l.pending;return m===null?a.next=a:(a.next=m.next,m.next=a),l.pending=a,a=Kr(e),Ps(e,null,s),a}return Qo(e,l,a,s),Kr(e)}function Ss(e,a,s){if(a=a.updateQueue,a!==null&&(a=a.shared,(s&4194048)!==0)){var l=a.lanes;l&=e.pendingLanes,s|=l,a.lanes=s,q(e,s)}}function Zn(e,a){var s=e.updateQueue,l=e.alternate;if(l!==null&&(l=l.updateQueue,s===l)){var m=null,v=null;if(s=s.firstBaseUpdate,s!==null){do{var M={lane:s.lane,tag:s.tag,payload:s.payload,callback:null,next:null};v===null?m=v=M:v=v.next=M,s=s.next}while(s!==null);v===null?m=v=a:v=v.next=a}else m=v=a;s={baseState:l.baseState,firstBaseUpdate:m,lastBaseUpdate:v,shared:l.shared,callbacks:l.callbacks},e.updateQueue=s;return}e=s.lastBaseUpdate,e===null?s.firstBaseUpdate=a:e.next=a,s.lastBaseUpdate=a}var dl=!1;function Fr(){if(dl){var e=xs;if(e!==null)throw e}}function Ei(e,a,s,l){dl=!1;var m=e.updateQueue;Fa=!1;var v=m.firstBaseUpdate,M=m.lastBaseUpdate,L=m.shared.pending;if(L!==null){m.shared.pending=null;var Q=L,ve=Q.next;Q.next=null,M===null?v=ve:M.next=ve,M=Q;var Te=e.alternate;Te!==null&&(Te=Te.updateQueue,L=Te.lastBaseUpdate,L!==M&&(L===null?Te.firstBaseUpdate=ve:L.next=ve,Te.lastBaseUpdate=Q))}if(v!==null){var Ee=m.baseState;M=0,Te=ve=Q=null,L=v;do{var we=L.lane&-536870913,Me=we!==L.lane;if(Me?(Kt&we)===we:(l&we)===we){we!==0&&we===Vt&&(dl=!0),Te!==null&&(Te=Te.next={lane:0,tag:L.tag,payload:L.payload,callback:null,next:null});e:{var it=e,kt=L;we=a;var vn=s;switch(kt.tag){case 1:if(it=kt.payload,typeof it=="function"){Ee=it.call(vn,Ee,we);break e}Ee=it;break e;case 3:it.flags=it.flags&-65537|128;case 0:if(it=kt.payload,we=typeof it=="function"?it.call(vn,Ee,we):it,we==null)break e;Ee=b({},Ee,we);break e;case 2:Fa=!0}}we=L.callback,we!==null&&(e.flags|=64,Me&&(e.flags|=8192),Me=m.callbacks,Me===null?m.callbacks=[we]:Me.push(we))}else Me={lane:we,tag:L.tag,payload:L.payload,callback:L.callback,next:null},Te===null?(ve=Te=Me,Q=Ee):Te=Te.next=Me,M|=we;if(L=L.next,L===null){if(L=m.shared.pending,L===null)break;Me=L,L=Me.next,Me.next=null,m.lastBaseUpdate=Me,m.shared.pending=null}}while(!0);Te===null&&(Q=Ee),m.baseState=Q,m.firstBaseUpdate=ve,m.lastBaseUpdate=Te,v===null&&(m.shared.lanes=0),Cl|=M,e.lanes=M,e.memoizedState=Ee}}function um(e,a){if(typeof e!="function")throw Error(o(191,e));e.call(a)}function dm(e,a){var s=e.callbacks;if(s!==null)for(e.callbacks=null,e=0;e<s.length;e++)um(s[e],a)}var di=te(null),fo=te(0);function Pd(e,a){e=To,Ce(fo,e),Ce(di,a),To=e|a.baseLanes}function Di(){Ce(fo,To),Ce(di,di.current)}function gu(){To=fo.current,le(di),le(fo)}var ur=te(null),Xr=null;function Pr(e){var a=e.alternate;Ce(zn,zn.current&1),Ce(ur,e),Xr===null&&(a===null||di.current!==null||a.memoizedState!==null)&&(Xr=e)}function Od(e){Ce(zn,zn.current),Ce(ur,e),Xr===null&&(Xr=e)}function Bd(e){e.tag===22?(Ce(zn,zn.current),Ce(ur,e),Xr===null&&(Xr=e)):Ii()}function Ii(){Ce(zn,zn.current),Ce(ur,ur.current)}function dr(e){le(ur),Xr===e&&(Xr=null),le(zn)}var zn=te(0);function mc(e){for(var a=e;a!==null;){if(a.tag===13){var s=a.memoizedState;if(s!==null&&(s=s.dehydrated,s===null||Oh(s)||Bh(s)))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 Zr=0,jt=null,sn=null,An=null,pc=!1,Jr=!1,qs=!1,fi=0,Cs=0,Li=null,oh=0;function In(){throw Error(o(321))}function mo(e,a){if(a===null)return!1;for(var s=0;s<a.length&&s<e.length;s++)if(!ar(e[s],a[s]))return!1;return!0}function hc(e,a,s,l,m,v){return Zr=v,jt=a,a.memoizedState=null,a.updateQueue=null,a.lanes=0,$.H=e===null||e.memoizedState===null?xl:ju,qs=!1,v=s(l,m),qs=!1,Jr&&(v=fm(a,s,l,m)),fl(e),v}function fl(e){$.H=wl;var a=sn!==null&&sn.next!==null;if(Zr=0,An=sn=jt=null,pc=!1,Cs=0,Li=null,a)throw Error(o(300));e===null||Fn||(e=e.dependencies,e!==null&&cc(e)&&(Fn=!0))}function fm(e,a,s,l){jt=e;var m=0;do{if(Jr&&(Li=null),Cs=0,Jr=!1,25<=m)throw Error(o(301));if(m+=1,An=sn=null,e.updateQueue!=null){var v=e.updateQueue;v.lastEffect=null,v.events=null,v.stores=null,v.memoCache!=null&&(v.memoCache.index=0)}$.H=Yd,v=a(s,l)}while(Jr);return v}function vu(){var e=$.H,a=e.useState()[0];return a=typeof a.then=="function"?ml(a):a,e=e.useState()[0],(sn!==null?sn.memoizedState:null)!==e&&(jt.flags|=1024),a}function yu(){var e=fi!==0;return fi=0,e}function po(e,a,s){a.updateQueue=e.updateQueue,a.flags&=-2053,e.lanes&=~s}function gc(e){if(pc){for(e=e.memoizedState;e!==null;){var a=e.queue;a!==null&&(a.pending=null),e=e.next}pc=!1}Zr=0,An=sn=jt=null,Jr=!1,Cs=fi=0,Li=null}function ua(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return An===null?jt.memoizedState=An=e:An=An.next=e,An}function Nn(){if(sn===null){var e=jt.alternate;e=e!==null?e.memoizedState:null}else e=sn.next;var a=An===null?jt.memoizedState:An.next;if(a!==null)An=a,sn=e;else{if(e===null)throw jt.alternate===null?Error(o(467)):Error(o(310));sn=e,e={memoizedState:sn.memoizedState,baseState:sn.baseState,baseQueue:sn.baseQueue,queue:sn.queue,next:null},An===null?jt.memoizedState=An=e:An=An.next=e}return An}function ho(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function ml(e){var a=Cs;return Cs+=1,Li===null&&(Li=[]),e=il(Li,e,a),a=jt,(An===null?a.memoizedState:An.next)===null&&(a=a.alternate,$.H=a===null||a.memoizedState===null?xl:ju),e}function Ws(e){if(e!==null&&typeof e=="object"){if(typeof e.then=="function")return ml(e);if(e.$$typeof===F)return wa(e)}throw Error(o(438,String(e)))}function bu(e){var a=null,s=jt.updateQueue;if(s!==null&&(a=s.memoCache),a==null){var l=jt.alternate;l!==null&&(l=l.updateQueue,l!==null&&(l=l.memoCache,l!=null&&(a={data:l.data.map(function(m){return m.slice()}),index:0})))}if(a==null&&(a={data:[],index:0}),s===null&&(s=ho(),jt.updateQueue=s),s.memoCache=a,s=a.data[a.index],s===void 0)for(s=a.data[a.index]=Array(e),l=0;l<e;l++)s[l]=Z;return a.index++,s}function Gs(e,a){return typeof a=="function"?a(e):a}function Ca(e){var a=Nn();return pl(a,sn,e)}function pl(e,a,s){var l=e.queue;if(l===null)throw Error(o(311));l.lastRenderedReducer=s;var m=e.baseQueue,v=l.pending;if(v!==null){if(m!==null){var M=m.next;m.next=v.next,v.next=M}a.baseQueue=m=v,l.pending=null}if(v=e.baseState,m===null)e.memoizedState=v;else{a=m.next;var L=M=null,Q=null,ve=a,Te=!1;do{var Ee=ve.lane&-536870913;if(Ee!==ve.lane?(Kt&Ee)===Ee:(Zr&Ee)===Ee){var we=ve.revertLane;if(we===0)Q!==null&&(Q=Q.next={lane:0,revertLane:0,gesture:null,action:ve.action,hasEagerState:ve.hasEagerState,eagerState:ve.eagerState,next:null}),Ee===Vt&&(Te=!0);else if((Zr&we)===we){ve=ve.next,we===Vt&&(Te=!0);continue}else Ee={lane:0,revertLane:ve.revertLane,gesture:null,action:ve.action,hasEagerState:ve.hasEagerState,eagerState:ve.eagerState,next:null},Q===null?(L=Q=Ee,M=v):Q=Q.next=Ee,jt.lanes|=we,Cl|=we;Ee=ve.action,qs&&s(v,Ee),v=ve.hasEagerState?ve.eagerState:s(v,Ee)}else we={lane:Ee,revertLane:ve.revertLane,gesture:ve.gesture,action:ve.action,hasEagerState:ve.hasEagerState,eagerState:ve.eagerState,next:null},Q===null?(L=Q=we,M=v):Q=Q.next=we,jt.lanes|=Ee,Cl|=Ee;ve=ve.next}while(ve!==null&&ve!==a);if(Q===null?M=v:Q.next=L,!ar(v,e.memoizedState)&&(Fn=!0,Te&&(s=xs,s!==null)))throw s;e.memoizedState=v,e.baseState=M,e.baseQueue=Q,l.lastRenderedState=v}return m===null&&(l.lanes=0),[e.memoizedState,l.dispatch]}function vc(e){var a=Nn(),s=a.queue;if(s===null)throw Error(o(311));s.lastRenderedReducer=e;var l=s.dispatch,m=s.pending,v=a.memoizedState;if(m!==null){s.pending=null;var M=m=m.next;do v=e(v,M.action),M=M.next;while(M!==m);ar(v,a.memoizedState)||(Fn=!0),a.memoizedState=v,a.baseQueue===null&&(a.baseState=v),s.lastRenderedState=v}return[v,l]}function go(e,a,s){var l=jt,m=Nn(),v=Bt;if(v){if(s===void 0)throw Error(o(407));s=s()}else s=a();var M=!ar((sn||m).memoizedState,s);if(M&&(m.memoizedState=s,Fn=!0),m=m.queue,zr(vo.bind(null,l,m,e),[e]),m.getSnapshot!==a||M||An!==null&&An.memoizedState.tag&1){if(l.flags|=2048,_i(9,{destroy:void 0},Br.bind(null,l,m,s,a),null),Mn===null)throw Error(o(349));v||(Zr&127)!==0||Or(l,a,s)}return s}function Or(e,a,s){e.flags|=16384,e={getSnapshot:a,value:s},a=jt.updateQueue,a===null?(a=ho(),jt.updateQueue=a,a.stores=[e]):(s=a.stores,s===null?a.stores=[e]:s.push(e))}function Br(e,a,s,l){a.value=s,a.getSnapshot=l,Hd(a)&&yc(e)}function vo(e,a,s){return s(function(){Hd(a)&&yc(e)})}function Hd(e){var a=e.getSnapshot;e=e.value;try{var s=a();return!ar(e,s)}catch{return!0}}function yc(e){var a=Fs(e,2);a!==null&&as(a,e,2)}function fr(e){var a=ua();if(typeof e=="function"){var s=e;if(e=s(),qs){Fe(!0);try{s()}finally{Fe(!1)}}}return a.memoizedState=a.baseState=e,a.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Gs,lastRenderedState:e},a}function lh(e,a,s,l){return e.baseState=s,pl(e,sn,typeof l=="function"?l:Gs)}function mm(e,a,s,l,m){if(Ru(e))throw Error(o(485));if(e=a.action,e!==null){var v={payload:m,action:e,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(M){v.listeners.push(M)}};$.T!==null?s(!0):v.isTransition=!1,l(v),s=a.pending,s===null?(v.next=a.pending=v,bc(a,v)):(v.next=s.next,a.pending=s.next=v)}}function bc(e,a){var s=a.action,l=a.payload,m=e.state;if(a.isTransition){var v=$.T,M={};$.T=M;try{var L=s(m,l),Q=$.S;Q!==null&&Q(M,L),wc(e,a,L)}catch(ve){gl(e,a,ve)}finally{v!==null&&M.types!==null&&(v.types=M.types),$.T=v}}else try{v=s(m,l),wc(e,a,v)}catch(ve){gl(e,a,ve)}}function wc(e,a,s){s!==null&&typeof s=="object"&&typeof s.then=="function"?s.then(function(l){hl(e,a,l)},function(l){return gl(e,a,l)}):hl(e,a,s)}function hl(e,a,s){a.status="fulfilled",a.value=s,wu(a),e.state=s,a=e.pending,a!==null&&(s=a.next,s===a?e.pending=null:(s=s.next,a.next=s,bc(e,s)))}function gl(e,a,s){var l=e.pending;if(e.pending=null,l!==null){l=l.next;do a.status="rejected",a.reason=s,wu(a),a=a.next;while(a!==l)}e.action=null}function wu(e){e=e.listeners;for(var a=0;a<e.length;a++)(0,e[a])()}function zd(e,a){return a}function ks(e,a){if(Bt){var s=Mn.formState;if(s!==null){e:{var l=jt;if(Bt){if(Je){t:{for(var m=Je,v=ya;m.nodeType!==8;){if(!v){m=null;break t}if(m=Ks(m.nextSibling),m===null){m=null;break t}}v=m.data,m=v==="F!"||v==="F"?m:null}if(m){Je=Ks(m.nextSibling),l=m.data==="F!";break e}}La(l)}l=!1}l&&(a=s[0])}}return s=ua(),s.memoizedState=s.baseState=a,l={pending:null,lanes:0,dispatch:null,lastRenderedReducer:zd,lastRenderedState:a},s.queue=l,s=bl.bind(null,jt,l),l.dispatch=s,l=fr(!1),v=Kd.bind(null,jt,!1,l.queue),l=ua(),m={state:a,dispatch:null,action:e,pending:null},l.queue=m,s=mm.bind(null,jt,m,v,s),m.dispatch=s,l.memoizedState=e,[a,s,!1]}function $d(e){var a=Nn();return xu(a,sn,e)}function xu(e,a,s){if(a=pl(e,a,zd)[0],e=Ca(Gs)[0],typeof a=="object"&&a!==null&&typeof a.then=="function")try{var l=ml(a)}catch(M){throw M===ci?Ir:M}else l=a;a=Nn();var m=a.queue,v=m.dispatch;return s!==a.memoizedState&&(jt.flags|=2048,_i(9,{destroy:void 0},Ud.bind(null,m,s),null)),[l,v,e]}function Ud(e,a){e.action=a}function Su(e){var a=Nn(),s=sn;if(s!==null)return xu(a,s,e);Nn(),a=a.memoizedState,s=Nn();var l=s.queue.dispatch;return s.memoizedState=e,[a,l,!1]}function _i(e,a,s,l){return e={tag:e,create:s,deps:l,inst:a,next:null},a=jt.updateQueue,a===null&&(a=ho(),jt.updateQueue=a),s=a.lastEffect,s===null?a.lastEffect=e.next=e:(l=s.next,s.next=e,e.next=l,a.lastEffect=e),e}function qd(){return Nn().memoizedState}function yo(e,a,s,l){var m=ua();jt.flags|=e,m.memoizedState=_i(1|a,{destroy:void 0},s,l===void 0?null:l)}function Hr(e,a,s,l){var m=Nn();l=l===void 0?null:l;var v=m.memoizedState.inst;sn!==null&&l!==null&&mo(l,sn.memoizedState.deps)?m.memoizedState=_i(a,v,s,l):(jt.flags|=e,m.memoizedState=_i(1|a,v,s,l))}function Wd(e,a){yo(8390656,8,e,a)}function zr(e,a){Hr(2048,8,e,a)}function bo(e){jt.flags|=4;var a=jt.updateQueue;if(a===null)a=ho(),jt.updateQueue=a,a.events=[e];else{var s=a.events;s===null?a.events=[e]:s.push(e)}}function ka(e){var a=Nn().memoizedState;return bo({ref:a,nextImpl:e}),function(){if((on&2)!==0)throw Error(o(440));return a.impl.apply(void 0,arguments)}}function es(e,a){return Hr(4,2,e,a)}function $r(e,a){return Hr(4,4,e,a)}function Cu(e,a){if(typeof a=="function"){e=e();var s=a(e);return function(){typeof s=="function"?s():a(null)}}if(a!=null)return e=e(),a.current=e,function(){a.current=null}}function pm(e,a,s){s=s!=null?s.concat([e]):null,Hr(4,4,Cu.bind(null,a,e),s)}function ku(){}function hm(e,a){var s=Nn();a=a===void 0?null:a;var l=s.memoizedState;return a!==null&&mo(a,l[1])?l[0]:(s.memoizedState=[e,a],e)}function Mu(e,a){var s=Nn();a=a===void 0?null:a;var l=s.memoizedState;if(a!==null&&mo(a,l[1]))return l[0];if(l=e(),qs){Fe(!0);try{e()}finally{Fe(!1)}}return s.memoizedState=[l,a],l}function xc(e,a,s){return s===void 0||(Zr&1073741824)!==0&&(Kt&261930)===0?e.memoizedState=a:(e.memoizedState=s,e=Jv(),jt.lanes|=e,Cl|=e,s)}function Sn(e,a,s,l){return ar(s,a)?s:di.current!==null?(e=xc(e,s,l),ar(e,a)||(Fn=!0),e):(Zr&42)===0||(Zr&1073741824)!==0&&(Kt&261930)===0?(Fn=!0,e.memoizedState=s):(e=Jv(),jt.lanes|=e,Cl|=e,a)}function Au(e,a,s,l,m){var v=_.p;_.p=v!==0&&8>v?v:8;var M=$.T,L={};$.T=L,Kd(e,!1,a,s);try{var Q=m(),ve=$.S;if(ve!==null&&ve(L,Q),Q!==null&&typeof Q=="object"&&typeof Q.then=="function"){var Te=cm(Q,l);Sc(e,a,Te,Ts(e))}else Sc(e,a,l,Ts(e))}catch(Ee){Sc(e,a,{then:function(){},status:"rejected",reason:Ee},Ts())}finally{_.p=v,M!==null&&L.types!==null&&(M.types=L.types),$.T=M}}function Nu(){}function vl(e,a,s,l){if(e.tag!==5)throw Error(o(476));var m=Gd(e).queue;Au(e,m,a,ie,s===null?Nu:function(){return Vd(e),s(l)})}function Gd(e){var a=e.memoizedState;if(a!==null)return a;a={memoizedState:ie,baseState:ie,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Gs,lastRenderedState:ie},next:null};var s={};return a.next={memoizedState:s,baseState:s,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Gs,lastRenderedState:s},next:null},e.memoizedState=a,e=e.alternate,e!==null&&(e.memoizedState=a),a}function Vd(e){var a=Gd(e);a.next===null&&(a=e.alternate.memoizedState),Sc(e,a.next.queue,{},Ts())}function wo(){return wa(Cf)}function Tu(){return Nn().memoizedState}function yl(){return Nn().memoizedState}function ch(e){for(var a=e.return;a!==null;){switch(a.tag){case 24:case 3:var s=Ts();e=xa(s);var l=Sa(a,e,s);l!==null&&(as(l,a,s),Ss(l,a,s)),a={cache:uc()},e.payload=a;return}a=a.return}}function gm(e,a,s){var l=Ts();s={lane:l,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null},Ru(e)?vm(a,s):(s=rc(e,a,s,l),s!==null&&(as(s,e,l),Qd(s,a,l)))}function bl(e,a,s){var l=Ts();Sc(e,a,s,l)}function Sc(e,a,s,l){var m={lane:l,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null};if(Ru(e))vm(a,m);else{var v=e.alternate;if(e.lanes===0&&(v===null||v.lanes===0)&&(v=a.lastRenderedReducer,v!==null))try{var M=a.lastRenderedState,L=v(M,s);if(m.hasEagerState=!0,m.eagerState=L,ar(L,M))return Qo(e,a,m,0),Mn===null&&uu(),!1}catch{}if(s=rc(e,a,m,l),s!==null)return as(s,e,l),Qd(s,a,l),!0}return!1}function Kd(e,a,s,l){if(l={lane:2,revertLane:Ah(),gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},Ru(e)){if(a)throw Error(o(479))}else a=rc(e,s,l,2),a!==null&&as(a,e,2)}function Ru(e){var a=e.alternate;return e===jt||a!==null&&a===jt}function vm(e,a){Jr=pc=!0;var s=e.pending;s===null?a.next=a:(a.next=s.next,s.next=a),e.pending=a}function Qd(e,a,s){if((s&4194048)!==0){var l=a.lanes;l&=e.pendingLanes,s|=l,a.lanes=s,q(e,s)}}var wl={readContext:wa,use:Ws,useCallback:In,useContext:In,useEffect:In,useImperativeHandle:In,useLayoutEffect:In,useInsertionEffect:In,useMemo:In,useReducer:In,useRef:In,useState:In,useDebugValue:In,useDeferredValue:In,useTransition:In,useSyncExternalStore:In,useId:In,useHostTransitionStatus:In,useFormState:In,useActionState:In,useOptimistic:In,useMemoCache:In,useCacheRefresh:In};wl.useEffectEvent=In;var xl={readContext:wa,use:Ws,useCallback:function(e,a){return ua().memoizedState=[e,a===void 0?null:a],e},useContext:wa,useEffect:Wd,useImperativeHandle:function(e,a,s){s=s!=null?s.concat([e]):null,yo(4194308,4,Cu.bind(null,a,e),s)},useLayoutEffect:function(e,a){return yo(4194308,4,e,a)},useInsertionEffect:function(e,a){yo(4,2,e,a)},useMemo:function(e,a){var s=ua();a=a===void 0?null:a;var l=e();if(qs){Fe(!0);try{e()}finally{Fe(!1)}}return s.memoizedState=[l,a],l},useReducer:function(e,a,s){var l=ua();if(s!==void 0){var m=s(a);if(qs){Fe(!0);try{s(a)}finally{Fe(!1)}}}else m=a;return l.memoizedState=l.baseState=m,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:m},l.queue=e,e=e.dispatch=gm.bind(null,jt,e),[l.memoizedState,e]},useRef:function(e){var a=ua();return e={current:e},a.memoizedState=e},useState:function(e){e=fr(e);var a=e.queue,s=bl.bind(null,jt,a);return a.dispatch=s,[e.memoizedState,s]},useDebugValue:ku,useDeferredValue:function(e,a){var s=ua();return xc(s,e,a)},useTransition:function(){var e=fr(!1);return e=Au.bind(null,jt,e.queue,!0,!1),ua().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,a,s){var l=jt,m=ua();if(Bt){if(s===void 0)throw Error(o(407));s=s()}else{if(s=a(),Mn===null)throw Error(o(349));(Kt&127)!==0||Or(l,a,s)}m.memoizedState=s;var v={value:s,getSnapshot:a};return m.queue=v,Wd(vo.bind(null,l,v,e),[e]),l.flags|=2048,_i(9,{destroy:void 0},Br.bind(null,l,v,s,a),null),s},useId:function(){var e=ua(),a=Mn.identifierPrefix;if(Bt){var s=Hs,l=Qa;s=(l&~(1<<32-fe(l)-1)).toString(32)+s,a="_"+a+"R_"+s,s=fi++,0<s&&(a+="H"+s.toString(32)),a+="_"}else s=oh++,a="_"+a+"r_"+s.toString(32)+"_";return e.memoizedState=a},useHostTransitionStatus:wo,useFormState:ks,useActionState:ks,useOptimistic:function(e){var a=ua();a.memoizedState=a.baseState=e;var s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return a.queue=s,a=Kd.bind(null,jt,!0,s),s.dispatch=a,[e,a]},useMemoCache:bu,useCacheRefresh:function(){return ua().memoizedState=ch.bind(null,jt)},useEffectEvent:function(e){var a=ua(),s={impl:e};return a.memoizedState=s,function(){if((on&2)!==0)throw Error(o(440));return s.impl.apply(void 0,arguments)}}},ju={readContext:wa,use:Ws,useCallback:hm,useContext:wa,useEffect:zr,useImperativeHandle:pm,useInsertionEffect:es,useLayoutEffect:$r,useMemo:Mu,useReducer:Ca,useRef:qd,useState:function(){return Ca(Gs)},useDebugValue:ku,useDeferredValue:function(e,a){var s=Nn();return Sn(s,sn.memoizedState,e,a)},useTransition:function(){var e=Ca(Gs)[0],a=Nn().memoizedState;return[typeof e=="boolean"?e:ml(e),a]},useSyncExternalStore:go,useId:Tu,useHostTransitionStatus:wo,useFormState:$d,useActionState:$d,useOptimistic:function(e,a){var s=Nn();return lh(s,sn,e,a)},useMemoCache:bu,useCacheRefresh:yl};ju.useEffectEvent=ka;var Yd={readContext:wa,use:Ws,useCallback:hm,useContext:wa,useEffect:zr,useImperativeHandle:pm,useInsertionEffect:es,useLayoutEffect:$r,useMemo:Mu,useReducer:vc,useRef:qd,useState:function(){return vc(Gs)},useDebugValue:ku,useDeferredValue:function(e,a){var s=Nn();return sn===null?xc(s,e,a):Sn(s,sn.memoizedState,e,a)},useTransition:function(){var e=vc(Gs)[0],a=Nn().memoizedState;return[typeof e=="boolean"?e:ml(e),a]},useSyncExternalStore:go,useId:Tu,useHostTransitionStatus:wo,useFormState:Su,useActionState:Su,useOptimistic:function(e,a){var s=Nn();return sn!==null?lh(s,sn,e,a):(s.baseState=e,[e,s.queue.dispatch])},useMemoCache:bu,useCacheRefresh:yl};Yd.useEffectEvent=ka;function Xd(e,a,s,l){a=e.memoizedState,s=s(l,a),s=s==null?a:b({},a,s),e.memoizedState=s,e.lanes===0&&(e.updateQueue.baseState=s)}var Zd={enqueueSetState:function(e,a,s){e=e._reactInternals;var l=Ts(),m=xa(l);m.payload=a,s!=null&&(m.callback=s),a=Sa(e,m,l),a!==null&&(as(a,e,l),Ss(a,e,l))},enqueueReplaceState:function(e,a,s){e=e._reactInternals;var l=Ts(),m=xa(l);m.tag=1,m.payload=a,s!=null&&(m.callback=s),a=Sa(e,m,l),a!==null&&(as(a,e,l),Ss(a,e,l))},enqueueForceUpdate:function(e,a){e=e._reactInternals;var s=Ts(),l=xa(s);l.tag=2,a!=null&&(l.callback=a),a=Sa(e,l,s),a!==null&&(as(a,e,s),Ss(a,e,s))}};function Cc(e,a,s,l,m,v,M){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(l,v,M):a.prototype&&a.prototype.isPureReactComponent?!Go(s,l)||!Go(m,v):!0}function ym(e,a,s,l){e=a.state,typeof a.componentWillReceiveProps=="function"&&a.componentWillReceiveProps(s,l),typeof a.UNSAFE_componentWillReceiveProps=="function"&&a.UNSAFE_componentWillReceiveProps(s,l),a.state!==e&&Zd.enqueueReplaceState(a,a.state,null)}function xo(e,a){var s=a;if("ref"in a){s={};for(var l in a)l!=="ref"&&(s[l]=a[l])}if(e=e.defaultProps){s===a&&(s=b({},s));for(var m in e)s[m]===void 0&&(s[m]=e[m])}return s}function bm(e){ac(e)}function wm(e){console.error(e)}function Eu(e){ac(e)}function kc(e,a){try{var s=e.onUncaughtError;s(a.value,{componentStack:a.stack})}catch(l){setTimeout(function(){throw l})}}function Jd(e,a,s){try{var l=e.onCaughtError;l(s.value,{componentStack:s.stack,errorBoundary:a.tag===1?a.stateNode:null})}catch(m){setTimeout(function(){throw m})}}function Du(e,a,s){return s=xa(s),s.tag=3,s.payload={element:null},s.callback=function(){kc(e,a)},s}function xm(e){return e=xa(e),e.tag=3,e}function Iu(e,a,s,l){var m=s.type.getDerivedStateFromError;if(typeof m=="function"){var v=l.value;e.payload=function(){return m(v)},e.callback=function(){Jd(a,s,l)}}var M=s.stateNode;M!==null&&typeof M.componentDidCatch=="function"&&(e.callback=function(){Jd(a,s,l),typeof m!="function"&&(kl===null?kl=new Set([this]):kl.add(this));var L=l.stack;this.componentDidCatch(l.value,{componentStack:L!==null?L:""})})}function Lu(e,a,s,l,m){if(s.flags|=32768,l!==null&&typeof l=="object"&&typeof l.then=="function"){if(a=s.alternate,a!==null&&Ie(a,s,m,!0),s=ur.current,s!==null){switch(s.tag){case 31:case 13:return Xr===null?jm():s.alternate===null&&Jn===0&&(Jn=3),s.flags&=-257,s.flags|=65536,s.lanes=m,l===Lr?s.flags|=16384:(a=s.updateQueue,a===null?s.updateQueue=new Set([l]):a.add(l),Ch(e,l,m)),!1;case 22:return s.flags|=65536,l===Lr?s.flags|=16384:(a=s.updateQueue,a===null?(a={transitions:null,markerInstances:null,retryQueue:new Set([l])},s.updateQueue=a):(s=a.retryQueue,s===null?a.retryQueue=new Set([l]):s.add(l)),Ch(e,l,m)),!1}throw Error(o(435,s.tag))}return Ch(e,l,m),jm(),!1}if(Bt)return a=ur.current,a!==null?((a.flags&65536)===0&&(a.flags|=256),a.flags|=65536,a.lanes=m,l!==Zo&&(e=Error(o(422),{cause:l}),ji(Dr(e,s)))):(l!==Zo&&(a=Error(o(423),{cause:l}),ji(Dr(a,s))),e=e.current.alternate,e.flags|=65536,m&=-m,e.lanes|=m,l=Dr(l,s),m=Du(e.stateNode,l,m),Zn(e,m),Jn!==4&&(Jn=2)),!1;var v=Error(o(520),{cause:l});if(v=Dr(v,s),hf===null?hf=[v]:hf.push(v),Jn!==4&&(Jn=2),a===null)return!0;l=Dr(l,s),s=a;do{switch(s.tag){case 3:return s.flags|=65536,e=m&-m,s.lanes|=e,e=Du(s.stateNode,l,e),Zn(s,e),!1;case 1:if(a=s.type,v=s.stateNode,(s.flags&128)===0&&(typeof a.getDerivedStateFromError=="function"||v!==null&&typeof v.componentDidCatch=="function"&&(kl===null||!kl.has(v))))return s.flags|=65536,m&=-m,s.lanes|=m,m=xm(m),Iu(m,e,s,l),Zn(s,m),!1}s=s.return}while(s!==null);return!1}var _u=Error(o(461)),Fn=!1;function sa(e,a,s,l){a.child=e===null?hu(a,null,s,l):_r(a,e.child,s,l)}function Ve(e,a,s,l,m){s=s.render;var v=a.ref;if("ref"in l){var M={};for(var L in l)L!=="ref"&&(M[L]=l[L])}else M=l;return lo(a),l=hc(e,a,s,M,v,m),L=yu(),e!==null&&!Fn?(po(e,a,m),Ms(e,a,m)):(Bt&&L&&fu(a),a.flags|=1,sa(e,a,l,m),a.child)}function Mc(e,a,s,l,m){if(e===null){var v=s.type;return typeof v=="function"&&!Yo(v)&&v.defaultProps===void 0&&s.compare===null?(a.tag=15,a.type=v,ef(e,a,v,l,m)):(e=sc(s.type,null,l,a,a.mode,m),e.ref=a.ref,e.return=a,a.child=e)}if(v=e.child,!lf(e,m)){var M=v.memoizedProps;if(s=s.compare,s=s!==null?s:Go,s(M,l)&&e.ref===a.ref)return Ms(e,a,m)}return a.flags|=1,e=Os(v,l),e.ref=a.ref,e.return=a,a.child=e}function ef(e,a,s,l,m){if(e!==null){var v=e.memoizedProps;if(Go(v,l)&&e.ref===a.ref)if(Fn=!1,a.pendingProps=l=v,lf(e,m))(e.flags&131072)!==0&&(Fn=!0);else return a.lanes=e.lanes,Ms(e,a,m)}return tf(e,a,s,l,m)}function Sm(e,a,s,l){var m=l.children,v=e!==null?e.memoizedState:null;if(e===null&&a.stateNode===null&&(a.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),l.mode==="hidden"){if((a.flags&128)!==0){if(v=v!==null?v.baseLanes|s:s,e!==null){for(l=a.child=e.child,m=0;l!==null;)m=m|l.lanes|l.childLanes,l=l.sibling;l=m&~v}else l=0,a.child=null;return Pu(e,a,v,s,l)}if((s&536870912)!==0)a.memoizedState={baseLanes:0,cachePool:null},e!==null&&_d(a,v!==null?v.cachePool:null),v!==null?Pd(a,v):Di(),Bd(a);else return l=a.lanes=536870912,Pu(e,a,v!==null?v.baseLanes|s:s,s,l)}else v!==null?(_d(a,v.cachePool),Pd(a,v),Ii(),a.memoizedState=null):(e!==null&&_d(a,null),Di(),Ii());return sa(e,a,m,s),a.child}function Fu(e,a){return e!==null&&e.tag===22||a.stateNode!==null||(a.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),a.sibling}function Pu(e,a,s,l,m){var v=al();return v=v===null?null:{parent:Hn._currentValue,pool:v},a.memoizedState={baseLanes:s,cachePool:v},e!==null&&_d(a,null),Di(),Bd(a),e!==null&&Ie(e,a,l,!0),a.childLanes=m,null}function So(e,a){return a=Ac({mode:a.mode,children:a.children},e.mode),a.ref=e.ref,e.child=a,a.return=e,a}function da(e,a,s){return _r(a,e.child,null,s),e=So(a,a.pendingProps),e.flags|=2,dr(a),a.memoizedState=null,e}function Ur(e,a,s){var l=a.pendingProps,m=(a.flags&128)!==0;if(a.flags&=-129,e===null){if(Bt){if(l.mode==="hidden")return e=So(a,l),a.lanes=536870912,Fu(null,e);if(Od(a),(e=Je)?(e=_y(e,ya),e=e!==null&&e.data==="&"?e:null,e!==null&&(a.memoizedState={dehydrated:e,treeContext:ws!==null?{id:Qa,overflow:Hs}:null,retryLane:536870912,hydrationErrors:null},s=Xo(e),s.return=a,a.child=s,_n=a,Je=null)):e=null,e===null)throw La(a);return a.lanes=536870912,null}return So(a,l)}var v=e.memoizedState;if(v!==null){var M=v.dehydrated;if(Od(a),m)if(a.flags&256)a.flags&=-257,a=da(e,a,s);else if(a.memoizedState!==null)a.child=e.child,a.flags|=128,a=null;else throw Error(o(558));else if(Fn||Ie(e,a,s,!1),m=(s&e.childLanes)!==0,Fn||m){if(l=Mn,l!==null&&(M=at(l,s),M!==0&&M!==v.retryLane))throw v.retryLane=M,Fs(e,M),as(l,e,M),_u;jm(),a=da(e,a,s)}else e=v.treeContext,Je=Ks(M.nextSibling),_n=a,Bt=!0,Ri=null,ya=!1,e!==null&&lc(a,e),a=So(a,l),a.flags|=4096;return a}return e=Os(e.child,{mode:l.mode,children:l.children}),e.ref=a.ref,a.child=e,e.return=a,e}function gt(e,a){var s=a.ref;if(s===null)e!==null&&e.ref!==null&&(a.flags|=4194816);else{if(typeof s!="function"&&typeof s!="object")throw Error(o(284));(e===null||e.ref!==s)&&(a.flags|=4194816)}}function tf(e,a,s,l,m){return lo(a),s=hc(e,a,s,l,void 0,m),l=yu(),e!==null&&!Fn?(po(e,a,m),Ms(e,a,m)):(Bt&&l&&fu(a),a.flags|=1,sa(e,a,s,m),a.child)}function Co(e,a,s,l,m,v){return lo(a),a.updateQueue=null,s=fm(a,l,s,m),fl(e),l=yu(),e!==null&&!Fn?(po(e,a,v),Ms(e,a,v)):(Bt&&l&&fu(a),a.flags|=1,sa(e,a,s,v),a.child)}function nf(e,a,s,l,m){if(lo(a),a.stateNode===null){var v=Ka,M=s.contextType;typeof M=="object"&&M!==null&&(v=wa(M)),v=new s(l,v),a.memoizedState=v.state!==null&&v.state!==void 0?v.state:null,v.updater=Zd,a.stateNode=v,v._reactInternals=a,v=a.stateNode,v.props=l,v.state=a.memoizedState,v.refs={},cl(a),M=s.contextType,v.context=typeof M=="object"&&M!==null?wa(M):Ka,v.state=a.memoizedState,M=s.getDerivedStateFromProps,typeof M=="function"&&(Xd(a,s,M,l),v.state=a.memoizedState),typeof s.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&&Zd.enqueueReplaceState(v,v.state,null),Ei(a,l,v,m),Fr(),v.state=a.memoizedState),typeof v.componentDidMount=="function"&&(a.flags|=4194308),l=!0}else if(e===null){v=a.stateNode;var L=a.memoizedProps,Q=xo(s,L);v.props=Q;var ve=v.context,Te=s.contextType;M=Ka,typeof Te=="object"&&Te!==null&&(M=wa(Te));var Ee=s.getDerivedStateFromProps;Te=typeof Ee=="function"||typeof v.getSnapshotBeforeUpdate=="function",L=a.pendingProps!==L,Te||typeof v.UNSAFE_componentWillReceiveProps!="function"&&typeof v.componentWillReceiveProps!="function"||(L||ve!==M)&&ym(a,v,l,M),Fa=!1;var we=a.memoizedState;v.state=we,Ei(a,l,v,m),Fr(),ve=a.memoizedState,L||we!==ve||Fa?(typeof Ee=="function"&&(Xd(a,s,Ee,l),ve=a.memoizedState),(Q=Fa||Cc(a,s,Q,l,we,ve,M))?(Te||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=l,a.memoizedState=ve),v.props=l,v.state=ve,v.context=M,l=Q):(typeof v.componentDidMount=="function"&&(a.flags|=4194308),l=!1)}else{v=a.stateNode,ul(e,a),M=a.memoizedProps,Te=xo(s,M),v.props=Te,Ee=a.pendingProps,we=v.context,ve=s.contextType,Q=Ka,typeof ve=="object"&&ve!==null&&(Q=wa(ve)),L=s.getDerivedStateFromProps,(ve=typeof L=="function"||typeof v.getSnapshotBeforeUpdate=="function")||typeof v.UNSAFE_componentWillReceiveProps!="function"&&typeof v.componentWillReceiveProps!="function"||(M!==Ee||we!==Q)&&ym(a,v,l,Q),Fa=!1,we=a.memoizedState,v.state=we,Ei(a,l,v,m),Fr();var Me=a.memoizedState;M!==Ee||we!==Me||Fa||e!==null&&e.dependencies!==null&&cc(e.dependencies)?(typeof L=="function"&&(Xd(a,s,L,l),Me=a.memoizedState),(Te=Fa||Cc(a,s,Te,l,we,Me,Q)||e!==null&&e.dependencies!==null&&cc(e.dependencies))?(ve||typeof v.UNSAFE_componentWillUpdate!="function"&&typeof v.componentWillUpdate!="function"||(typeof v.componentWillUpdate=="function"&&v.componentWillUpdate(l,Me,Q),typeof v.UNSAFE_componentWillUpdate=="function"&&v.UNSAFE_componentWillUpdate(l,Me,Q)),typeof v.componentDidUpdate=="function"&&(a.flags|=4),typeof v.getSnapshotBeforeUpdate=="function"&&(a.flags|=1024)):(typeof v.componentDidUpdate!="function"||M===e.memoizedProps&&we===e.memoizedState||(a.flags|=4),typeof v.getSnapshotBeforeUpdate!="function"||M===e.memoizedProps&&we===e.memoizedState||(a.flags|=1024),a.memoizedProps=l,a.memoizedState=Me),v.props=l,v.state=Me,v.context=Q,l=Te):(typeof v.componentDidUpdate!="function"||M===e.memoizedProps&&we===e.memoizedState||(a.flags|=4),typeof v.getSnapshotBeforeUpdate!="function"||M===e.memoizedProps&&we===e.memoizedState||(a.flags|=1024),l=!1)}return v=l,gt(e,a),l=(a.flags&128)!==0,v||l?(v=a.stateNode,s=l&&typeof s.getDerivedStateFromError!="function"?null:v.render(),a.flags|=1,e!==null&&l?(a.child=_r(a,e.child,null,m),a.child=_r(a,null,s,m)):sa(e,a,s,m),a.memoizedState=v.state,e=a.child):e=Ms(e,a,m),e}function af(e,a,s,l){return oo(),a.flags|=256,sa(e,a,s,l),a.child}var Fi={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function Ou(e){return{baseLanes:e,cachePool:rl()}}function Bu(e,a,s){return e=e!==null?e.childLanes&~s:0,a&&(e|=Ns),e}function rf(e,a,s){var l=a.pendingProps,m=!1,v=(a.flags&128)!==0,M;if((M=v)||(M=e!==null&&e.memoizedState===null?!1:(zn.current&2)!==0),M&&(m=!0,a.flags&=-129),M=(a.flags&32)!==0,a.flags&=-33,e===null){if(Bt){if(m?Pr(a):Ii(),(e=Je)?(e=_y(e,ya),e=e!==null&&e.data!=="&"?e:null,e!==null&&(a.memoizedState={dehydrated:e,treeContext:ws!==null?{id:Qa,overflow:Hs}:null,retryLane:536870912,hydrationErrors:null},s=Xo(e),s.return=a,a.child=s,_n=a,Je=null)):e=null,e===null)throw La(a);return Bh(e)?a.lanes=32:a.lanes=536870912,null}var L=l.children;return l=l.fallback,m?(Ii(),m=a.mode,L=Ac({mode:"hidden",children:L},m),l=vs(l,m,s,null),L.return=a,l.return=a,L.sibling=l,a.child=L,l=a.child,l.memoizedState=Ou(s),l.childLanes=Bu(e,M,s),a.memoizedState=Fi,Fu(null,l)):(Pr(a),Hu(a,L))}var Q=e.memoizedState;if(Q!==null&&(L=Q.dehydrated,L!==null)){if(v)a.flags&256?(Pr(a),a.flags&=-257,a=ko(e,a,s)):a.memoizedState!==null?(Ii(),a.child=e.child,a.flags|=128,a=null):(Ii(),L=l.fallback,m=a.mode,l=Ac({mode:"visible",children:l.children},m),L=vs(L,m,s,null),L.flags|=2,l.return=a,L.return=a,l.sibling=L,a.child=l,_r(a,e.child,null,s),l=a.child,l.memoizedState=Ou(s),l.childLanes=Bu(e,M,s),a.memoizedState=Fi,a=Fu(null,l));else if(Pr(a),Bh(L)){if(M=L.nextSibling&&L.nextSibling.dataset,M)var ve=M.dgst;M=ve,l=Error(o(419)),l.stack="",l.digest=M,ji({value:l,source:null,stack:null}),a=ko(e,a,s)}else if(Fn||Ie(e,a,s,!1),M=(s&e.childLanes)!==0,Fn||M){if(M=Mn,M!==null&&(l=at(M,s),l!==0&&l!==Q.retryLane))throw Q.retryLane=l,Fs(e,l),as(M,e,l),_u;Oh(L)||jm(),a=ko(e,a,s)}else Oh(L)?(a.flags|=192,a.child=e.child,a=null):(e=Q.treeContext,Je=Ks(L.nextSibling),_n=a,Bt=!0,Ri=null,ya=!1,e!==null&&lc(a,e),a=Hu(a,l.children),a.flags|=4096);return a}return m?(Ii(),L=l.fallback,m=a.mode,Q=e.child,ve=Q.sibling,l=Os(Q,{mode:"hidden",children:l.children}),l.subtreeFlags=Q.subtreeFlags&65011712,ve!==null?L=Os(ve,L):(L=vs(L,m,s,null),L.flags|=2),L.return=a,l.return=a,l.sibling=L,a.child=l,Fu(null,l),l=a.child,L=e.child.memoizedState,L===null?L=Ou(s):(m=L.cachePool,m!==null?(Q=Hn._currentValue,m=m.parent!==Q?{parent:Q,pool:Q}:m):m=rl(),L={baseLanes:L.baseLanes|s,cachePool:m}),l.memoizedState=L,l.childLanes=Bu(e,M,s),a.memoizedState=Fi,Fu(e.child,l)):(Pr(a),s=e.child,e=s.sibling,s=Os(s,{mode:"visible",children:l.children}),s.return=a,s.sibling=null,e!==null&&(M=a.deletions,M===null?(a.deletions=[e],a.flags|=16):M.push(e)),a.child=s,a.memoizedState=null,s)}function Hu(e,a){return a=Ac({mode:"visible",children:a},e.mode),a.return=e,e.child=a}function Ac(e,a){return e=Ia(22,e,null,a),e.lanes=0,e}function ko(e,a,s){return _r(a,e.child,null,s),e=Hu(a,a.pendingProps.children),e.flags|=2,a.memoizedState=null,e}function Nc(e,a,s){e.lanes|=a;var l=e.alternate;l!==null&&(l.lanes|=a),ba(e.return,a,s)}function sf(e,a,s,l,m,v){var M=e.memoizedState;M===null?e.memoizedState={isBackwards:a,rendering:null,renderingStartTime:0,last:l,tail:s,tailMode:m,treeForkCount:v}:(M.isBackwards=a,M.rendering=null,M.renderingStartTime=0,M.last=l,M.tail=s,M.tailMode=m,M.treeForkCount=v)}function of(e,a,s){var l=a.pendingProps,m=l.revealOrder,v=l.tail;l=l.children;var M=zn.current,L=(M&2)!==0;if(L?(M=M&1|2,a.flags|=128):M&=1,Ce(zn,M),sa(e,a,l,s),l=Bt?io:0,!L&&e!==null&&(e.flags&128)!==0)e:for(e=a.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&Nc(e,s,a);else if(e.tag===19)Nc(e,s,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(m){case"forwards":for(s=a.child,m=null;s!==null;)e=s.alternate,e!==null&&mc(e)===null&&(m=s),s=s.sibling;s=m,s===null?(m=a.child,a.child=null):(m=s.sibling,s.sibling=null),sf(a,!1,m,s,v,l);break;case"backwards":case"unstable_legacy-backwards":for(s=null,m=a.child,a.child=null;m!==null;){if(e=m.alternate,e!==null&&mc(e)===null){a.child=m;break}e=m.sibling,m.sibling=s,s=m,m=e}sf(a,!0,s,null,v,l);break;case"together":sf(a,!1,null,null,void 0,l);break;default:a.memoizedState=null}return a.child}function Ms(e,a,s){if(e!==null&&(a.dependencies=e.dependencies),Cl|=a.lanes,(s&a.childLanes)===0)if(e!==null){if(Ie(e,a,s,!1),(s&a.childLanes)===0)return null}else return null;if(e!==null&&a.child!==e.child)throw Error(o(153));if(a.child!==null){for(e=a.child,s=Os(e,e.pendingProps),a.child=s,s.return=a;e.sibling!==null;)e=e.sibling,s=s.sibling=Os(e,e.pendingProps),s.return=a;s.sibling=null}return a.child}function lf(e,a){return(e.lanes&a)!==0?!0:(e=e.dependencies,!!(e!==null&&cc(e)))}function uh(e,a,s){switch(a.tag){case 3:ze(a,a.stateNode.containerInfo),Dn(a,Hn,e.memoizedState.cache),oo();break;case 27:case 5:Xe(a);break;case 4:ze(a,a.stateNode.containerInfo);break;case 10:Dn(a,a.type,a.memoizedProps.value);break;case 31:if(a.memoizedState!==null)return a.flags|=128,Od(a),null;break;case 13:var l=a.memoizedState;if(l!==null)return l.dehydrated!==null?(Pr(a),a.flags|=128,null):(s&a.child.childLanes)!==0?rf(e,a,s):(Pr(a),e=Ms(e,a,s),e!==null?e.sibling:null);Pr(a);break;case 19:var m=(e.flags&128)!==0;if(l=(s&a.childLanes)!==0,l||(Ie(e,a,s,!1),l=(s&a.childLanes)!==0),m){if(l)return of(e,a,s);a.flags|=128}if(m=a.memoizedState,m!==null&&(m.rendering=null,m.tail=null,m.lastEffect=null),Ce(zn,zn.current),l)break;return null;case 22:return a.lanes=0,Sm(e,a,s,a.pendingProps);case 24:Dn(a,Hn,e.memoizedState.cache)}return Ms(e,a,s)}function zu(e,a,s){if(e!==null)if(e.memoizedProps!==a.pendingProps)Fn=!0;else{if(!lf(e,s)&&(a.flags&128)===0)return Fn=!1,uh(e,a,s);Fn=(e.flags&131072)!==0}else Fn=!1,Bt&&(a.flags&1048576)!==0&&oc(a,io,a.index);switch(a.lanes=0,a.tag){case 16:e:{var l=a.pendingProps;if(e=_a(a.elementType),a.type=e,typeof e=="function")Yo(e)?(l=xo(e,l),a.tag=1,a=nf(null,a,e,l,s)):(a.tag=0,a=tf(null,a,e,l,s));else{if(e!=null){var m=e.$$typeof;if(m===O){a.tag=11,a=Ve(null,a,e,l,s);break e}else if(m===I){a.tag=14,a=Mc(null,a,e,l,s);break e}}throw a=V(e)||e,Error(o(306,a,""))}}return a;case 0:return tf(e,a,a.type,a.pendingProps,s);case 1:return l=a.type,m=xo(l,a.pendingProps),nf(e,a,l,m,s);case 3:e:{if(ze(a,a.stateNode.containerInfo),e===null)throw Error(o(387));l=a.pendingProps;var v=a.memoizedState;m=v.element,ul(e,a),Ei(a,l,null,s);var M=a.memoizedState;if(l=M.cache,Dn(a,Hn,l),l!==v.cache&&or(a,[Hn],s,!0),Fr(),l=M.element,v.isDehydrated)if(v={element:l,isDehydrated:!1,cache:M.cache},a.updateQueue.baseState=v,a.memoizedState=v,a.flags&256){a=af(e,a,l,s);break e}else if(l!==m){m=Dr(Error(o(424)),a),ji(m),a=af(e,a,l,s);break e}else for(e=a.stateNode.containerInfo,e.nodeType===9?e=e.body:e=e.nodeName==="HTML"?e.ownerDocument.body:e,Je=Ks(e.firstChild),_n=a,Bt=!0,Ri=null,ya=!0,s=hu(a,null,l,s),a.child=s;s;)s.flags=s.flags&-3|4096,s=s.sibling;else{if(oo(),l===m){a=Ms(e,a,s);break e}sa(e,a,l,s)}a=a.child}return a;case 26:return gt(e,a),e===null?(s=zy(a.type,null,a.pendingProps,null))?a.memoizedState=s:Bt||(s=a.type,e=a.pendingProps,l=Pm(ue.current).createElement(s),l[de]=a,l[De]=e,Ya(l,s,e),rn(l),a.stateNode=l):a.memoizedState=zy(a.type,e.memoizedProps,a.pendingProps,e.memoizedState),null;case 27:return Xe(a),e===null&&Bt&&(l=a.stateNode=Oy(a.type,a.pendingProps,ue.current),_n=a,ya=!0,m=Je,Tl(a.type)?(Hh=m,Je=Ks(l.firstChild)):Je=m),sa(e,a,a.pendingProps.children,s),gt(e,a),e===null&&(a.flags|=4194304),a.child;case 5:return e===null&&Bt&&((m=l=Je)&&(l=rC(l,a.type,a.pendingProps,ya),l!==null?(a.stateNode=l,_n=a,Je=Ks(l.firstChild),ya=!1,m=!0):m=!1),m||La(a)),Xe(a),m=a.type,v=a.pendingProps,M=e!==null?e.memoizedProps:null,l=v.children,_h(m,v)?l=null:M!==null&&_h(m,M)&&(a.flags|=32),a.memoizedState!==null&&(m=hc(e,a,vu,null,null,s),Cf._currentValue=m),gt(e,a),sa(e,a,l,s),a.child;case 6:return e===null&&Bt&&((e=s=Je)&&(s=sC(s,a.pendingProps,ya),s!==null?(a.stateNode=s,_n=a,Je=null,e=!0):e=!1),e||La(a)),null;case 13:return rf(e,a,s);case 4:return ze(a,a.stateNode.containerInfo),l=a.pendingProps,e===null?a.child=_r(a,null,l,s):sa(e,a,l,s),a.child;case 11:return Ve(e,a,a.type,a.pendingProps,s);case 7:return sa(e,a,a.pendingProps,s),a.child;case 8:return sa(e,a,a.pendingProps.children,s),a.child;case 12:return sa(e,a,a.pendingProps.children,s),a.child;case 10:return l=a.pendingProps,Dn(a,a.type,l.value),sa(e,a,l.children,s),a.child;case 9:return m=a.type._context,l=a.pendingProps.children,lo(a),m=wa(m),l=l(m),a.flags|=1,sa(e,a,l,s),a.child;case 14:return Mc(e,a,a.type,a.pendingProps,s);case 15:return ef(e,a,a.type,a.pendingProps,s);case 19:return of(e,a,s);case 31:return Ur(e,a,s);case 22:return Sm(e,a,s,a.pendingProps);case 24:return lo(a),l=wa(Hn),e===null?(m=al(),m===null&&(m=Mn,v=uc(),m.pooledCache=v,v.refCount++,v!==null&&(m.pooledCacheLanes|=s),m=v),a.memoizedState={parent:l,cache:m},cl(a),Dn(a,Hn,m)):((e.lanes&s)!==0&&(ul(e,a),Ei(a,null,null,s),Fr()),m=e.memoizedState,v=a.memoizedState,m.parent!==l?(m={parent:l,cache:l},a.memoizedState=m,a.lanes===0&&(a.memoizedState=a.updateQueue.baseState=m),Dn(a,Hn,l)):(l=v.cache,Dn(a,Hn,l),l!==m.cache&&or(a,[Hn],s,!0))),sa(e,a,a.pendingProps.children,s),a.child;case 29:throw a.pendingProps}throw Error(o(156,a.tag))}function mi(e){e.flags|=4}function cf(e,a,s,l,m){if((a=(e.mode&32)!==0)&&(a=!1),a){if(e.flags|=16777216,(m&335544128)===m)if(e.stateNode.complete)e.flags|=8192;else if(ay())e.flags|=8192;else throw Xn=Lr,sl}else e.flags&=-16777217}function Pa(e,a){if(a.type!=="stylesheet"||(a.state.loading&4)!==0)e.flags&=-16777217;else if(e.flags|=16777216,!Gy(a))if(ay())e.flags|=8192;else throw Xn=Lr,sl}function Mo(e,a){a!==null&&(e.flags|=4),e.flags&16384&&(a=e.tag!==22?Na():536870912,e.lanes|=a,Ku|=a)}function Tc(e,a){if(!Bt)switch(e.tailMode){case"hidden":a=e.tail;for(var s=null;a!==null;)a.alternate!==null&&(s=a),a=a.sibling;s===null?e.tail=null:s.sibling=null;break;case"collapsed":s=e.tail;for(var l=null;s!==null;)s.alternate!==null&&(l=s),s=s.sibling;l===null?a||e.tail===null?e.tail=null:e.tail.sibling=null:l.sibling=null}}function Tn(e){var a=e.alternate!==null&&e.alternate.child===e.child,s=0,l=0;if(a)for(var m=e.child;m!==null;)s|=m.lanes|m.childLanes,l|=m.subtreeFlags&65011712,l|=m.flags&65011712,m.return=e,m=m.sibling;else for(m=e.child;m!==null;)s|=m.lanes|m.childLanes,l|=m.subtreeFlags,l|=m.flags,m.return=e,m=m.sibling;return e.subtreeFlags|=l,e.childLanes=s,a}function dh(e,a,s){var l=a.pendingProps;switch(mu(a),a.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Tn(a),null;case 1:return Tn(a),null;case 3:return s=a.stateNode,l=null,e!==null&&(l=e.memoizedState.cache),a.memoizedState.cache!==l&&(a.flags|=2048),ir(Hn),et(),s.pendingContext&&(s.context=s.pendingContext,s.pendingContext=null),(e===null||e.child===null)&&(Jo(a)?mi(a):e===null||e.memoizedState.isDehydrated&&(a.flags&256)===0||(a.flags|=1024,Dd())),Tn(a),null;case 26:var m=a.type,v=a.memoizedState;return e===null?(mi(a),v!==null?(Tn(a),Pa(a,v)):(Tn(a),cf(a,m,null,l,s))):v?v!==e.memoizedState?(mi(a),Tn(a),Pa(a,v)):(Tn(a),a.flags&=-16777217):(e=e.memoizedProps,e!==l&&mi(a),Tn(a),cf(a,m,e,l,s)),null;case 27:if(Ze(a),s=ue.current,m=a.type,e!==null&&a.stateNode!=null)e.memoizedProps!==l&&mi(a);else{if(!l){if(a.stateNode===null)throw Error(o(166));return Tn(a),null}e=Ae.current,Jo(a)?pu(a):(e=Oy(m,l,s),a.stateNode=e,mi(a))}return Tn(a),null;case 5:if(Ze(a),m=a.type,e!==null&&a.stateNode!=null)e.memoizedProps!==l&&mi(a);else{if(!l){if(a.stateNode===null)throw Error(o(166));return Tn(a),null}if(v=Ae.current,Jo(a))pu(a);else{var M=Pm(ue.current);switch(v){case 1:v=M.createElementNS("http://www.w3.org/2000/svg",m);break;case 2:v=M.createElementNS("http://www.w3.org/1998/Math/MathML",m);break;default:switch(m){case"svg":v=M.createElementNS("http://www.w3.org/2000/svg",m);break;case"math":v=M.createElementNS("http://www.w3.org/1998/Math/MathML",m);break;case"script":v=M.createElement("div"),v.innerHTML="<script><\/script>",v=v.removeChild(v.firstChild);break;case"select":v=typeof l.is=="string"?M.createElement("select",{is:l.is}):M.createElement("select"),l.multiple?v.multiple=!0:l.size&&(v.size=l.size);break;default:v=typeof l.is=="string"?M.createElement(m,{is:l.is}):M.createElement(m)}}v[de]=a,v[De]=l;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(Ya(v,m,l),m){case"button":case"input":case"select":case"textarea":l=!!l.autoFocus;break e;case"img":l=!0;break e;default:l=!1}l&&mi(a)}}return Tn(a),cf(a,a.type,e===null?null:e.memoizedProps,a.pendingProps,s),null;case 6:if(e&&a.stateNode!=null)e.memoizedProps!==l&&mi(a);else{if(typeof l!="string"&&a.stateNode===null)throw Error(o(166));if(e=ue.current,Jo(a)){if(e=a.stateNode,s=a.memoizedProps,l=null,m=_n,m!==null)switch(m.tag){case 27:case 5:l=m.memoizedProps}e[de]=a,e=!!(e.nodeValue===s||l!==null&&l.suppressHydrationWarning===!0||Ny(e.nodeValue,s)),e||La(a,!0)}else e=Pm(e).createTextNode(l),e[de]=a,a.stateNode=e}return Tn(a),null;case 31:if(s=a.memoizedState,e===null||e.memoizedState!==null){if(l=Jo(a),s!==null){if(e===null){if(!l)throw Error(o(318));if(e=a.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(o(557));e[de]=a}else oo(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Tn(a),e=!1}else s=Dd(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=s),e=!0;if(!e)return a.flags&256?(dr(a),a):(dr(a),null);if((a.flags&128)!==0)throw Error(o(558))}return Tn(a),null;case 13:if(l=a.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(m=Jo(a),l!==null&&l.dehydrated!==null){if(e===null){if(!m)throw Error(o(318));if(m=a.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(o(317));m[de]=a}else oo(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Tn(a),m=!1}else m=Dd(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=m),m=!0;if(!m)return a.flags&256?(dr(a),a):(dr(a),null)}return dr(a),(a.flags&128)!==0?(a.lanes=s,a):(s=l!==null,e=e!==null&&e.memoizedState!==null,s&&(l=a.child,m=null,l.alternate!==null&&l.alternate.memoizedState!==null&&l.alternate.memoizedState.cachePool!==null&&(m=l.alternate.memoizedState.cachePool.pool),v=null,l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(v=l.memoizedState.cachePool.pool),v!==m&&(l.flags|=2048)),s!==e&&s&&(a.child.flags|=8192),Mo(a,a.updateQueue),Tn(a),null);case 4:return et(),e===null&&jh(a.stateNode.containerInfo),Tn(a),null;case 10:return ir(a.type),Tn(a),null;case 19:if(le(zn),l=a.memoizedState,l===null)return Tn(a),null;if(m=(a.flags&128)!==0,v=l.rendering,v===null)if(m)Tc(l,!1);else{if(Jn!==0||e!==null&&(e.flags&128)!==0)for(e=a.child;e!==null;){if(v=mc(e),v!==null){for(a.flags|=128,Tc(l,!1),e=v.updateQueue,a.updateQueue=e,Mo(a,e),a.subtreeFlags=0,e=s,s=a.child;s!==null;)jd(s,e),s=s.sibling;return Ce(zn,zn.current&1|2),Bt&&li(a,l.treeForkCount),a.child}e=e.sibling}l.tail!==null&&Ye()>Nm&&(a.flags|=128,m=!0,Tc(l,!1),a.lanes=4194304)}else{if(!m)if(e=mc(v),e!==null){if(a.flags|=128,m=!0,e=e.updateQueue,a.updateQueue=e,Mo(a,e),Tc(l,!0),l.tail===null&&l.tailMode==="hidden"&&!v.alternate&&!Bt)return Tn(a),null}else 2*Ye()-l.renderingStartTime>Nm&&s!==536870912&&(a.flags|=128,m=!0,Tc(l,!1),a.lanes=4194304);l.isBackwards?(v.sibling=a.child,a.child=v):(e=l.last,e!==null?e.sibling=v:a.child=v,l.last=v)}return l.tail!==null?(e=l.tail,l.rendering=e,l.tail=e.sibling,l.renderingStartTime=Ye(),e.sibling=null,s=zn.current,Ce(zn,m?s&1|2:s&1),Bt&&li(a,l.treeForkCount),e):(Tn(a),null);case 22:case 23:return dr(a),gu(),l=a.memoizedState!==null,e!==null?e.memoizedState!==null!==l&&(a.flags|=8192):l&&(a.flags|=8192),l?(s&536870912)!==0&&(a.flags&128)===0&&(Tn(a),a.subtreeFlags&6&&(a.flags|=8192)):Tn(a),s=a.updateQueue,s!==null&&Mo(a,s.retryQueue),s=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(s=e.memoizedState.cachePool.pool),l=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(l=a.memoizedState.cachePool.pool),l!==s&&(a.flags|=2048),e!==null&&le(ra),null;case 24:return s=null,e!==null&&(s=e.memoizedState.cache),a.memoizedState.cache!==s&&(a.flags|=2048),ir(Hn),Tn(a),null;case 25:return null;case 30:return null}throw Error(o(156,a.tag))}function fh(e,a){switch(mu(a),a.tag){case 1:return e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 3:return ir(Hn),et(),e=a.flags,(e&65536)!==0&&(e&128)===0?(a.flags=e&-65537|128,a):null;case 26:case 27:case 5:return Ze(a),null;case 31:if(a.memoizedState!==null){if(dr(a),a.alternate===null)throw Error(o(340));oo()}return e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 13:if(dr(a),e=a.memoizedState,e!==null&&e.dehydrated!==null){if(a.alternate===null)throw Error(o(340));oo()}return e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 19:return le(zn),null;case 4:return et(),null;case 10:return ir(a.type),null;case 22:case 23:return dr(a),gu(),e!==null&&le(ra),e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 24:return ir(Hn),null;case 25:return null;default:return null}}function uf(e,a){switch(mu(a),a.tag){case 3:ir(Hn),et();break;case 26:case 27:case 5:Ze(a);break;case 4:et();break;case 31:a.memoizedState!==null&&dr(a);break;case 13:dr(a);break;case 19:le(zn);break;case 10:ir(a.type);break;case 22:case 23:dr(a),gu(),e!==null&&le(ra);break;case 24:ir(Hn)}}function Pi(e,a){try{var s=a.updateQueue,l=s!==null?s.lastEffect:null;if(l!==null){var m=l.next;s=m;do{if((s.tag&e)===e){l=void 0;var v=s.create,M=s.inst;l=v(),M.destroy=l}s=s.next}while(s!==m)}}catch(L){fn(a,a.return,L)}}function ts(e,a,s){try{var l=a.updateQueue,m=l!==null?l.lastEffect:null;if(m!==null){var v=m.next;l=v;do{if((l.tag&e)===e){var M=l.inst,L=M.destroy;if(L!==void 0){M.destroy=void 0,m=a;var Q=s,ve=L;try{ve()}catch(Te){fn(m,Q,Te)}}}l=l.next}while(l!==v)}}catch(Te){fn(a,a.return,Te)}}function df(e){var a=e.updateQueue;if(a!==null){var s=e.stateNode;try{dm(a,s)}catch(l){fn(e,e.return,l)}}}function Cm(e,a,s){s.props=xo(e.type,e.memoizedProps),s.state=e.memoizedState;try{s.componentWillUnmount()}catch(l){fn(e,a,l)}}function Rc(e,a){try{var s=e.ref;if(s!==null){switch(e.tag){case 26:case 27:case 5:var l=e.stateNode;break;case 30:l=e.stateNode;break;default:l=e.stateNode}typeof s=="function"?e.refCleanup=s(l):s.current=l}}catch(m){fn(e,a,m)}}function Vs(e,a){var s=e.ref,l=e.refCleanup;if(s!==null)if(typeof l=="function")try{l()}catch(m){fn(e,a,m)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof s=="function")try{s(null)}catch(m){fn(e,a,m)}else s.current=null}function $u(e){var a=e.type,s=e.memoizedProps,l=e.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":s.autoFocus&&l.focus();break e;case"img":s.src?l.src=s.src:s.srcSet&&(l.srcset=s.srcSet)}}catch(m){fn(e,e.return,m)}}function Oi(e,a,s){try{var l=e.stateNode;Z0(l,e.type,s,a),l[De]=a}catch(m){fn(e,e.return,m)}}function km(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&Tl(e.type)||e.tag===4}function pi(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||km(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&&Tl(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 Uu(e,a,s){var l=e.tag;if(l===5||l===6)e=e.stateNode,a?(s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s).insertBefore(e,a):(a=s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s,a.appendChild(e),s=s._reactRootContainer,s!=null||a.onclick!==null||(a.onclick=tr));else if(l!==4&&(l===27&&Tl(e.type)&&(s=e.stateNode,a=null),e=e.child,e!==null))for(Uu(e,a,s),e=e.sibling;e!==null;)Uu(e,a,s),e=e.sibling}function jc(e,a,s){var l=e.tag;if(l===5||l===6)e=e.stateNode,a?s.insertBefore(e,a):s.appendChild(e);else if(l!==4&&(l===27&&Tl(e.type)&&(s=e.stateNode),e=e.child,e!==null))for(jc(e,a,s),e=e.sibling;e!==null;)jc(e,a,s),e=e.sibling}function p(e){var a=e.stateNode,s=e.memoizedProps;try{for(var l=e.type,m=a.attributes;m.length;)a.removeAttributeNode(m[0]);Ya(a,l,s),a[de]=e,a[De]=s}catch(v){fn(e,e.return,v)}}var S=!1,C=!1,R=!1,j=typeof WeakSet=="function"?WeakSet:Set,U=null;function W(e,a){if(e=e.containerInfo,Ih=qm,e=ro(e),ii(e)){if("selectionStart"in e)var s={start:e.selectionStart,end:e.selectionEnd};else e:{s=(s=e.ownerDocument)&&s.defaultView||window;var l=s.getSelection&&s.getSelection();if(l&&l.rangeCount!==0){s=l.anchorNode;var m=l.anchorOffset,v=l.focusNode;l=l.focusOffset;try{s.nodeType,v.nodeType}catch{s=null;break e}var M=0,L=-1,Q=-1,ve=0,Te=0,Ee=e,we=null;t:for(;;){for(var Me;Ee!==s||m!==0&&Ee.nodeType!==3||(L=M+m),Ee!==v||l!==0&&Ee.nodeType!==3||(Q=M+l),Ee.nodeType===3&&(M+=Ee.nodeValue.length),(Me=Ee.firstChild)!==null;)we=Ee,Ee=Me;for(;;){if(Ee===e)break t;if(we===s&&++ve===m&&(L=M),we===v&&++Te===l&&(Q=M),(Me=Ee.nextSibling)!==null)break;Ee=we,we=Ee.parentNode}Ee=Me}s=L===-1||Q===-1?null:{start:L,end:Q}}else s=null}s=s||{start:0,end:0}}else s=null;for(Lh={focusedElem:e,selectionRange:s},qm=!1,U=a;U!==null;)if(a=U,e=a.child,(a.subtreeFlags&1028)!==0&&e!==null)e.return=a,U=e;else for(;U!==null;){switch(a=U,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(s=0;s<e.length;s++)m=e[s],m.ref.impl=m.nextImpl;break;case 11:case 15:break;case 1:if((e&1024)!==0&&v!==null){e=void 0,s=a,m=v.memoizedProps,v=v.memoizedState,l=s.stateNode;try{var it=xo(s.type,m);e=l.getSnapshotBeforeUpdate(it,v),l.__reactInternalSnapshotBeforeUpdate=e}catch(kt){fn(s,s.return,kt)}}break;case 3:if((e&1024)!==0){if(e=a.stateNode.containerInfo,s=e.nodeType,s===9)Ph(e);else if(s===1)switch(e.nodeName){case"HEAD":case"HTML":case"BODY":Ph(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(o(163))}if(e=a.sibling,e!==null){e.return=a.return,U=e;break}U=a.return}}function oe(e,a,s){var l=s.flags;switch(s.tag){case 0:case 11:case 15:Ao(e,s),l&4&&Pi(5,s);break;case 1:if(Ao(e,s),l&4)if(e=s.stateNode,a===null)try{e.componentDidMount()}catch(M){fn(s,s.return,M)}else{var m=xo(s.type,a.memoizedProps);a=a.memoizedState;try{e.componentDidUpdate(m,a,e.__reactInternalSnapshotBeforeUpdate)}catch(M){fn(s,s.return,M)}}l&64&&df(s),l&512&&Rc(s,s.return);break;case 3:if(Ao(e,s),l&64&&(e=s.updateQueue,e!==null)){if(a=null,s.child!==null)switch(s.child.tag){case 27:case 5:a=s.child.stateNode;break;case 1:a=s.child.stateNode}try{dm(e,a)}catch(M){fn(s,s.return,M)}}break;case 27:a===null&&l&4&&p(s);case 26:case 5:Ao(e,s),a===null&&l&4&&$u(s),l&512&&Rc(s,s.return);break;case 12:Ao(e,s);break;case 31:Ao(e,s),l&4&&zt(e,s);break;case 13:Ao(e,s),l&4&&Cn(e,s),l&64&&(e=s.memoizedState,e!==null&&(e=e.dehydrated,e!==null&&(s=H0.bind(null,s),iC(e,s))));break;case 22:if(l=s.memoizedState!==null||S,!l){a=a!==null&&a.memoizedState!==null||C,m=S;var v=C;S=l,(C=a)&&!v?No(e,s,(s.subtreeFlags&8772)!==0):Ao(e,s),S=m,C=v}break;case 30:break;default:Ao(e,s)}}function ae(e){var a=e.alternate;a!==null&&(e.alternate=null,ae(a)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(a=e.stateNode,a!==null&&xt(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 J=null,Ge=!1;function Le(e,a,s){for(s=s.child;s!==null;)st(e,a,s),s=s.sibling}function st(e,a,s){if(he&&typeof he.onCommitFiberUnmount=="function")try{he.onCommitFiberUnmount(ee,s)}catch{}switch(s.tag){case 26:C||Vs(s,a),Le(e,a,s),s.memoizedState?s.memoizedState.count--:s.stateNode&&(s=s.stateNode,s.parentNode.removeChild(s));break;case 27:C||Vs(s,a);var l=J,m=Ge;Tl(s.type)&&(J=s.stateNode,Ge=!1),Le(e,a,s),wf(s.stateNode),J=l,Ge=m;break;case 5:C||Vs(s,a);case 6:if(l=J,m=Ge,J=null,Le(e,a,s),J=l,Ge=m,J!==null)if(Ge)try{(J.nodeType===9?J.body:J.nodeName==="HTML"?J.ownerDocument.body:J).removeChild(s.stateNode)}catch(v){fn(s,a,v)}else try{J.removeChild(s.stateNode)}catch(v){fn(s,a,v)}break;case 18:J!==null&&(Ge?(e=J,Iy(e.nodeType===9?e.body:e.nodeName==="HTML"?e.ownerDocument.body:e,s.stateNode),nd(e)):Iy(J,s.stateNode));break;case 4:l=J,m=Ge,J=s.stateNode.containerInfo,Ge=!0,Le(e,a,s),J=l,Ge=m;break;case 0:case 11:case 14:case 15:ts(2,s,a),C||ts(4,s,a),Le(e,a,s);break;case 1:C||(Vs(s,a),l=s.stateNode,typeof l.componentWillUnmount=="function"&&Cm(s,a,l)),Le(e,a,s);break;case 21:Le(e,a,s);break;case 22:C=(l=C)||s.memoizedState!==null,Le(e,a,s),C=l;break;default:Le(e,a,s)}}function zt(e,a){if(a.memoizedState===null&&(e=a.alternate,e!==null&&(e=e.memoizedState,e!==null))){e=e.dehydrated;try{nd(e)}catch(s){fn(a,a.return,s)}}}function Cn(e,a){if(a.memoizedState===null&&(e=a.alternate,e!==null&&(e=e.memoizedState,e!==null&&(e=e.dehydrated,e!==null))))try{nd(e)}catch(s){fn(a,a.return,s)}}function $t(e){switch(e.tag){case 31:case 13:case 19:var a=e.stateNode;return a===null&&(a=e.stateNode=new j),a;case 22:return e=e.stateNode,a=e._retryCache,a===null&&(a=e._retryCache=new j),a;default:throw Error(o(435,e.tag))}}function ln(e,a){var s=$t(e);a.forEach(function(l){if(!s.has(l)){s.add(l);var m=z0.bind(null,e,l);l.then(m,m)}})}function hn(e,a){var s=a.deletions;if(s!==null)for(var l=0;l<s.length;l++){var m=s[l],v=e,M=a,L=M;e:for(;L!==null;){switch(L.tag){case 27:if(Tl(L.type)){J=L.stateNode,Ge=!1;break e}break;case 5:J=L.stateNode,Ge=!1;break e;case 3:case 4:J=L.stateNode.containerInfo,Ge=!0;break e}L=L.return}if(J===null)throw Error(o(160));st(v,M,m),J=null,Ge=!1,v=m.alternate,v!==null&&(v.return=null),m.return=null}if(a.subtreeFlags&13886)for(a=a.child;a!==null;)Ec(a,e),a=a.sibling}var fa=null;function Ec(e,a){var s=e.alternate,l=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:hn(a,e),kn(e),l&4&&(ts(3,e,e.return),Pi(3,e),ts(5,e,e.return));break;case 1:hn(a,e),kn(e),l&512&&(C||s===null||Vs(s,s.return)),l&64&&S&&(e=e.updateQueue,e!==null&&(l=e.callbacks,l!==null&&(s=e.shared.hiddenCallbacks,e.shared.hiddenCallbacks=s===null?l:s.concat(l))));break;case 26:var m=fa;if(hn(a,e),kn(e),l&512&&(C||s===null||Vs(s,s.return)),l&4){var v=s!==null?s.memoizedState:null;if(l=e.memoizedState,s===null)if(l===null)if(e.stateNode===null){e:{l=e.type,s=e.memoizedProps,m=m.ownerDocument||m;t:switch(l){case"title":v=m.getElementsByTagName("title")[0],(!v||v[Pt]||v[de]||v.namespaceURI==="http://www.w3.org/2000/svg"||v.hasAttribute("itemprop"))&&(v=m.createElement(l),m.head.insertBefore(v,m.querySelector("head > title"))),Ya(v,l,s),v[de]=e,rn(v),l=v;break e;case"link":var M=qy("link","href",m).get(l+(s.href||""));if(M){for(var L=0;L<M.length;L++)if(v=M[L],v.getAttribute("href")===(s.href==null||s.href===""?null:s.href)&&v.getAttribute("rel")===(s.rel==null?null:s.rel)&&v.getAttribute("title")===(s.title==null?null:s.title)&&v.getAttribute("crossorigin")===(s.crossOrigin==null?null:s.crossOrigin)){M.splice(L,1);break t}}v=m.createElement(l),Ya(v,l,s),m.head.appendChild(v);break;case"meta":if(M=qy("meta","content",m).get(l+(s.content||""))){for(L=0;L<M.length;L++)if(v=M[L],v.getAttribute("content")===(s.content==null?null:""+s.content)&&v.getAttribute("name")===(s.name==null?null:s.name)&&v.getAttribute("property")===(s.property==null?null:s.property)&&v.getAttribute("http-equiv")===(s.httpEquiv==null?null:s.httpEquiv)&&v.getAttribute("charset")===(s.charSet==null?null:s.charSet)){M.splice(L,1);break t}}v=m.createElement(l),Ya(v,l,s),m.head.appendChild(v);break;default:throw Error(o(468,l))}v[de]=e,rn(v),l=v}e.stateNode=l}else Wy(m,e.type,e.stateNode);else e.stateNode=Uy(m,l,e.memoizedProps);else v!==l?(v===null?s.stateNode!==null&&(s=s.stateNode,s.parentNode.removeChild(s)):v.count--,l===null?Wy(m,e.type,e.stateNode):Uy(m,l,e.memoizedProps)):l===null&&e.stateNode!==null&&Oi(e,e.memoizedProps,s.memoizedProps)}break;case 27:hn(a,e),kn(e),l&512&&(C||s===null||Vs(s,s.return)),s!==null&&l&4&&Oi(e,e.memoizedProps,s.memoizedProps);break;case 5:if(hn(a,e),kn(e),l&512&&(C||s===null||Vs(s,s.return)),e.flags&32){m=e.stateNode;try{ls(m,"")}catch(it){fn(e,e.return,it)}}l&4&&e.stateNode!=null&&(m=e.memoizedProps,Oi(e,m,s!==null?s.memoizedProps:m)),l&1024&&(R=!0);break;case 6:if(hn(a,e),kn(e),l&4){if(e.stateNode===null)throw Error(o(162));l=e.memoizedProps,s=e.stateNode;try{s.nodeValue=l}catch(it){fn(e,e.return,it)}}break;case 3:if(Hm=null,m=fa,fa=Om(a.containerInfo),hn(a,e),fa=m,kn(e),l&4&&s!==null&&s.memoizedState.isDehydrated)try{nd(a.containerInfo)}catch(it){fn(e,e.return,it)}R&&(R=!1,qu(e));break;case 4:l=fa,fa=Om(e.stateNode.containerInfo),hn(a,e),kn(e),fa=l;break;case 12:hn(a,e),kn(e);break;case 31:hn(a,e),kn(e),l&4&&(l=e.updateQueue,l!==null&&(e.updateQueue=null,ln(e,l)));break;case 13:hn(a,e),kn(e),e.child.flags&8192&&e.memoizedState!==null!=(s!==null&&s.memoizedState!==null)&&(Am=Ye()),l&4&&(l=e.updateQueue,l!==null&&(e.updateQueue=null,ln(e,l)));break;case 22:m=e.memoizedState!==null;var Q=s!==null&&s.memoizedState!==null,ve=S,Te=C;if(S=ve||m,C=Te||Q,hn(a,e),C=Te,S=ve,kn(e),l&8192)e:for(a=e.stateNode,a._visibility=m?a._visibility&-2:a._visibility|1,m&&(s===null||Q||S||C||Dc(e)),s=null,a=e;;){if(a.tag===5||a.tag===26){if(s===null){Q=s=a;try{if(v=Q.stateNode,m)M=v.style,typeof M.setProperty=="function"?M.setProperty("display","none","important"):M.display="none";else{L=Q.stateNode;var Ee=Q.memoizedProps.style,we=Ee!=null&&Ee.hasOwnProperty("display")?Ee.display:null;L.style.display=we==null||typeof we=="boolean"?"":(""+we).trim()}}catch(it){fn(Q,Q.return,it)}}}else if(a.tag===6){if(s===null){Q=a;try{Q.stateNode.nodeValue=m?"":Q.memoizedProps}catch(it){fn(Q,Q.return,it)}}}else if(a.tag===18){if(s===null){Q=a;try{var Me=Q.stateNode;m?Ly(Me,!0):Ly(Q.stateNode,!1)}catch(it){fn(Q,Q.return,it)}}}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;s===a&&(s=null),a=a.return}s===a&&(s=null),a.sibling.return=a.return,a=a.sibling}l&4&&(l=e.updateQueue,l!==null&&(s=l.retryQueue,s!==null&&(l.retryQueue=null,ln(e,s))));break;case 19:hn(a,e),kn(e),l&4&&(l=e.updateQueue,l!==null&&(e.updateQueue=null,ln(e,l)));break;case 30:break;case 21:break;default:hn(a,e),kn(e)}}function kn(e){var a=e.flags;if(a&2){try{for(var s,l=e.return;l!==null;){if(km(l)){s=l;break}l=l.return}if(s==null)throw Error(o(160));switch(s.tag){case 27:var m=s.stateNode,v=pi(e);jc(e,v,m);break;case 5:var M=s.stateNode;s.flags&32&&(ls(M,""),s.flags&=-33);var L=pi(e);jc(e,L,M);break;case 3:case 4:var Q=s.stateNode.containerInfo,ve=pi(e);Uu(e,ve,Q);break;default:throw Error(o(161))}}catch(Te){fn(e,e.return,Te)}e.flags&=-3}a&4096&&(e.flags&=-4097)}function qu(e){if(e.subtreeFlags&1024)for(e=e.child;e!==null;){var a=e;qu(a),a.tag===5&&a.flags&1024&&a.stateNode.reset(),e=e.sibling}}function Ao(e,a){if(a.subtreeFlags&8772)for(a=a.child;a!==null;)oe(e,a.alternate,a),a=a.sibling}function Dc(e){for(e=e.child;e!==null;){var a=e;switch(a.tag){case 0:case 11:case 14:case 15:ts(4,a,a.return),Dc(a);break;case 1:Vs(a,a.return);var s=a.stateNode;typeof s.componentWillUnmount=="function"&&Cm(a,a.return,s),Dc(a);break;case 27:wf(a.stateNode);case 26:case 5:Vs(a,a.return),Dc(a);break;case 22:a.memoizedState===null&&Dc(a);break;case 30:Dc(a);break;default:Dc(a)}e=e.sibling}}function No(e,a,s){for(s=s&&(a.subtreeFlags&8772)!==0,a=a.child;a!==null;){var l=a.alternate,m=e,v=a,M=v.flags;switch(v.tag){case 0:case 11:case 15:No(m,v,s),Pi(4,v);break;case 1:if(No(m,v,s),l=v,m=l.stateNode,typeof m.componentDidMount=="function")try{m.componentDidMount()}catch(ve){fn(l,l.return,ve)}if(l=v,m=l.updateQueue,m!==null){var L=l.stateNode;try{var Q=m.shared.hiddenCallbacks;if(Q!==null)for(m.shared.hiddenCallbacks=null,m=0;m<Q.length;m++)um(Q[m],L)}catch(ve){fn(l,l.return,ve)}}s&&M&64&&df(v),Rc(v,v.return);break;case 27:p(v);case 26:case 5:No(m,v,s),s&&l===null&&M&4&&$u(v),Rc(v,v.return);break;case 12:No(m,v,s);break;case 31:No(m,v,s),s&&M&4&&zt(m,v);break;case 13:No(m,v,s),s&&M&4&&Cn(m,v);break;case 22:v.memoizedState===null&&No(m,v,s),Rc(v,v.return);break;case 30:break;default:No(m,v,s)}a=a.sibling}}function mh(e,a){var s=null;e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(s=e.memoizedState.cachePool.pool),e=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(e=a.memoizedState.cachePool.pool),e!==s&&(e!=null&&e.refCount++,s!=null&&lr(s))}function ph(e,a){e=null,a.alternate!==null&&(e=a.alternate.memoizedState.cache),a=a.memoizedState.cache,a!==e&&(a.refCount++,e!=null&&lr(e))}function hi(e,a,s,l){if(a.subtreeFlags&10256)for(a=a.child;a!==null;)Gv(e,a,s,l),a=a.sibling}function Gv(e,a,s,l){var m=a.flags;switch(a.tag){case 0:case 11:case 15:hi(e,a,s,l),m&2048&&Pi(9,a);break;case 1:hi(e,a,s,l);break;case 3:hi(e,a,s,l),m&2048&&(e=null,a.alternate!==null&&(e=a.alternate.memoizedState.cache),a=a.memoizedState.cache,a!==e&&(a.refCount++,e!=null&&lr(e)));break;case 12:if(m&2048){hi(e,a,s,l),e=a.stateNode;try{var v=a.memoizedProps,M=v.id,L=v.onPostCommit;typeof L=="function"&&L(M,a.alternate===null?"mount":"update",e.passiveEffectDuration,-0)}catch(Q){fn(a,a.return,Q)}}else hi(e,a,s,l);break;case 31:hi(e,a,s,l);break;case 13:hi(e,a,s,l);break;case 23:break;case 22:v=a.stateNode,M=a.alternate,a.memoizedState!==null?v._visibility&2?hi(e,a,s,l):ff(e,a):v._visibility&2?hi(e,a,s,l):(v._visibility|=2,Wu(e,a,s,l,(a.subtreeFlags&10256)!==0||!1)),m&2048&&mh(M,a);break;case 24:hi(e,a,s,l),m&2048&&ph(a.alternate,a);break;default:hi(e,a,s,l)}}function Wu(e,a,s,l,m){for(m=m&&((a.subtreeFlags&10256)!==0||!1),a=a.child;a!==null;){var v=e,M=a,L=s,Q=l,ve=M.flags;switch(M.tag){case 0:case 11:case 15:Wu(v,M,L,Q,m),Pi(8,M);break;case 23:break;case 22:var Te=M.stateNode;M.memoizedState!==null?Te._visibility&2?Wu(v,M,L,Q,m):ff(v,M):(Te._visibility|=2,Wu(v,M,L,Q,m)),m&&ve&2048&&mh(M.alternate,M);break;case 24:Wu(v,M,L,Q,m),m&&ve&2048&&ph(M.alternate,M);break;default:Wu(v,M,L,Q,m)}a=a.sibling}}function ff(e,a){if(a.subtreeFlags&10256)for(a=a.child;a!==null;){var s=e,l=a,m=l.flags;switch(l.tag){case 22:ff(s,l),m&2048&&mh(l.alternate,l);break;case 24:ff(s,l),m&2048&&ph(l.alternate,l);break;default:ff(s,l)}a=a.sibling}}var mf=8192;function Gu(e,a,s){if(e.subtreeFlags&mf)for(e=e.child;e!==null;)Vv(e,a,s),e=e.sibling}function Vv(e,a,s){switch(e.tag){case 26:Gu(e,a,s),e.flags&mf&&e.memoizedState!==null&&yC(s,fa,e.memoizedState,e.memoizedProps);break;case 5:Gu(e,a,s);break;case 3:case 4:var l=fa;fa=Om(e.stateNode.containerInfo),Gu(e,a,s),fa=l;break;case 22:e.memoizedState===null&&(l=e.alternate,l!==null&&l.memoizedState!==null?(l=mf,mf=16777216,Gu(e,a,s),mf=l):Gu(e,a,s));break;default:Gu(e,a,s)}}function Kv(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 pf(e){var a=e.deletions;if((e.flags&16)!==0){if(a!==null)for(var s=0;s<a.length;s++){var l=a[s];U=l,Yv(l,e)}Kv(e)}if(e.subtreeFlags&10256)for(e=e.child;e!==null;)Qv(e),e=e.sibling}function Qv(e){switch(e.tag){case 0:case 11:case 15:pf(e),e.flags&2048&&ts(9,e,e.return);break;case 3:pf(e);break;case 12:pf(e);break;case 22:var a=e.stateNode;e.memoizedState!==null&&a._visibility&2&&(e.return===null||e.return.tag!==13)?(a._visibility&=-3,Mm(e)):pf(e);break;default:pf(e)}}function Mm(e){var a=e.deletions;if((e.flags&16)!==0){if(a!==null)for(var s=0;s<a.length;s++){var l=a[s];U=l,Yv(l,e)}Kv(e)}for(e=e.child;e!==null;){switch(a=e,a.tag){case 0:case 11:case 15:ts(8,a,a.return),Mm(a);break;case 22:s=a.stateNode,s._visibility&2&&(s._visibility&=-3,Mm(a));break;default:Mm(a)}e=e.sibling}}function Yv(e,a){for(;U!==null;){var s=U;switch(s.tag){case 0:case 11:case 15:ts(8,s,a);break;case 23:case 22:if(s.memoizedState!==null&&s.memoizedState.cachePool!==null){var l=s.memoizedState.cachePool.pool;l!=null&&l.refCount++}break;case 24:lr(s.memoizedState.cache)}if(l=s.child,l!==null)l.return=s,U=l;else e:for(s=e;U!==null;){l=U;var m=l.sibling,v=l.return;if(ae(l),l===s){U=null;break e}if(m!==null){m.return=v,U=m;break e}U=v}}}var I0={getCacheForType:function(e){var a=wa(Hn),s=a.data.get(e);return s===void 0&&(s=e(),a.data.set(e,s)),s},cacheSignal:function(){return wa(Hn).controller.signal}},L0=typeof WeakMap=="function"?WeakMap:Map,on=0,Mn=null,Ut=null,Kt=0,dn=0,As=null,Sl=!1,Vu=!1,hh=!1,To=0,Jn=0,Cl=0,Ic=0,gh=0,Ns=0,Ku=0,hf=null,ns=null,vh=!1,Am=0,Xv=0,Nm=1/0,Tm=null,kl=null,Ma=0,Ml=null,Qu=null,Ro=0,yh=0,bh=null,Zv=null,gf=0,wh=null;function Ts(){return(on&2)!==0&&Kt!==0?Kt&-Kt:$.T!==null?Ah():bn()}function Jv(){if(Ns===0)if((Kt&536870912)===0||Bt){var e=dt;dt<<=1,(dt&3932160)===0&&(dt=262144),Ns=e}else Ns=536870912;return e=ur.current,e!==null&&(e.flags|=32),Ns}function as(e,a,s){(e===Mn&&(dn===2||dn===9)||e.cancelPendingCommit!==null)&&(Yu(e,0),Al(e,Kt,Ns,!1)),Wn(e,s),((on&2)===0||e!==Mn)&&(e===Mn&&((on&2)===0&&(Ic|=s),Jn===4&&Al(e,Kt,Ns,!1)),Bi(e))}function ey(e,a,s){if((on&6)!==0)throw Error(o(327));var l=!s&&(a&127)===0&&(a&e.expiredLanes)===0||Xt(e,a),m=l?P0(e,a):Sh(e,a,!0),v=l;do{if(m===0){Vu&&!l&&Al(e,a,0,!1);break}else{if(s=e.current.alternate,v&&!_0(s)){m=Sh(e,a,!1),v=!1;continue}if(m===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 L=e;m=hf;var Q=L.current.memoizedState.isDehydrated;if(Q&&(Yu(L,M).flags|=256),M=Sh(L,M,!1),M!==2){if(hh&&!Q){L.errorRecoveryDisabledLanes|=v,Ic|=v,m=4;break e}v=ns,ns=m,v!==null&&(ns===null?ns=v:ns.push.apply(ns,v))}m=M}if(v=!1,m!==2)continue}}if(m===1){Yu(e,0),Al(e,a,0,!0);break}e:{switch(l=e,v=m,v){case 0:case 1:throw Error(o(345));case 4:if((a&4194048)!==a)break;case 6:Al(l,a,Ns,!Sl);break e;case 2:ns=null;break;case 3:case 5:break;default:throw Error(o(329))}if((a&62914560)===a&&(m=Am+300-Ye(),10<m)){if(Al(l,a,Ns,!Sl),cn(l,0,!0)!==0)break e;Ro=a,l.timeoutHandle=Ey(ty.bind(null,l,s,ns,Tm,vh,a,Ns,Ic,Ku,Sl,v,"Throttled",-0,0),m);break e}ty(l,s,ns,Tm,vh,a,Ns,Ic,Ku,Sl,v,null,-0,0)}}break}while(!0);Bi(e)}function ty(e,a,s,l,m,v,M,L,Q,ve,Te,Ee,we,Me){if(e.timeoutHandle=-1,Ee=a.subtreeFlags,Ee&8192||(Ee&16785408)===16785408){Ee={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:tr},Vv(a,v,Ee);var it=(v&62914560)===v?Am-Ye():(v&4194048)===v?Xv-Ye():0;if(it=bC(Ee,it),it!==null){Ro=v,e.cancelPendingCommit=it(cy.bind(null,e,a,v,s,l,m,M,L,Q,Te,Ee,null,we,Me)),Al(e,v,M,!ve);return}}cy(e,a,v,s,l,m,M,L,Q)}function _0(e){for(var a=e;;){var s=a.tag;if((s===0||s===11||s===15)&&a.flags&16384&&(s=a.updateQueue,s!==null&&(s=s.stores,s!==null)))for(var l=0;l<s.length;l++){var m=s[l],v=m.getSnapshot;m=m.value;try{if(!ar(v(),m))return!1}catch{return!1}}if(s=a.child,a.subtreeFlags&16384&&s!==null)s.return=a,a=s;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 Al(e,a,s,l){a&=~gh,a&=~Ic,e.suspendedLanes|=a,e.pingedLanes&=~a,l&&(e.warmLanes|=a),l=e.expirationTimes;for(var m=a;0<m;){var v=31-fe(m),M=1<<v;l[v]=-1,m&=~M}s!==0&&Pe(e,s,a)}function Rm(){return(on&6)===0?(vf(0),!1):!0}function xh(){if(Ut!==null){if(dn===0)var e=Ut.return;else e=Ut,sr=zs=null,gc(e),ol=null,ll=0,e=Ut;for(;e!==null;)uf(e.alternate,e),e=e.return;Ut=null}}function Yu(e,a){var s=e.timeoutHandle;s!==-1&&(e.timeoutHandle=-1,tC(s)),s=e.cancelPendingCommit,s!==null&&(e.cancelPendingCommit=null,s()),Ro=0,xh(),Mn=e,Ut=s=Os(e.current,null),Kt=a,dn=0,As=null,Sl=!1,Vu=Xt(e,a),hh=!1,Ku=Ns=gh=Ic=Cl=Jn=0,ns=hf=null,vh=!1,(a&8)!==0&&(a|=a&32);var l=e.entangledLanes;if(l!==0)for(e=e.entanglements,l&=a;0<l;){var m=31-fe(l),v=1<<m;a|=e[m],l&=~v}return To=a,uu(),s}function ny(e,a){jt=null,$.H=wl,a===ci||a===Ir?(a=cr(),dn=3):a===sl?(a=cr(),dn=4):dn=a===_u?8:a!==null&&typeof a=="object"&&typeof a.then=="function"?6:1,As=a,Ut===null&&(Jn=1,kc(e,Dr(a,e.current)))}function ay(){var e=ur.current;return e===null?!0:(Kt&4194048)===Kt?Xr===null:(Kt&62914560)===Kt||(Kt&536870912)!==0?e===Xr:!1}function ry(){var e=$.H;return $.H=wl,e===null?wl:e}function sy(){var e=$.A;return $.A=I0,e}function jm(){Jn=4,Sl||(Kt&4194048)!==Kt&&ur.current!==null||(Vu=!0),(Cl&134217727)===0&&(Ic&134217727)===0||Mn===null||Al(Mn,Kt,Ns,!1)}function Sh(e,a,s){var l=on;on|=2;var m=ry(),v=sy();(Mn!==e||Kt!==a)&&(Tm=null,Yu(e,a)),a=!1;var M=Jn;e:do try{if(dn!==0&&Ut!==null){var L=Ut,Q=As;switch(dn){case 8:xh(),M=6;break e;case 3:case 2:case 9:case 6:ur.current===null&&(a=!0);var ve=dn;if(dn=0,As=null,Xu(e,L,Q,ve),s&&Vu){M=0;break e}break;default:ve=dn,dn=0,As=null,Xu(e,L,Q,ve)}}F0(),M=Jn;break}catch(Te){ny(e,Te)}while(!0);return a&&e.shellSuspendCounter++,sr=zs=null,on=l,$.H=m,$.A=v,Ut===null&&(Mn=null,Kt=0,uu()),M}function F0(){for(;Ut!==null;)iy(Ut)}function P0(e,a){var s=on;on|=2;var l=ry(),m=sy();Mn!==e||Kt!==a?(Tm=null,Nm=Ye()+500,Yu(e,a)):Vu=Xt(e,a);e:do try{if(dn!==0&&Ut!==null){a=Ut;var v=As;t:switch(dn){case 1:dn=0,As=null,Xu(e,a,v,1);break;case 2:case 9:if(fc(v)){dn=0,As=null,oy(a);break}a=function(){dn!==2&&dn!==9||Mn!==e||(dn=7),Bi(e)},v.then(a,a);break e;case 3:dn=7;break e;case 4:dn=5;break e;case 7:fc(v)?(dn=0,As=null,oy(a)):(dn=0,As=null,Xu(e,a,v,7));break;case 5:var M=null;switch(Ut.tag){case 26:M=Ut.memoizedState;case 5:case 27:var L=Ut;if(M?Gy(M):L.stateNode.complete){dn=0,As=null;var Q=L.sibling;if(Q!==null)Ut=Q;else{var ve=L.return;ve!==null?(Ut=ve,Em(ve)):Ut=null}break t}}dn=0,As=null,Xu(e,a,v,5);break;case 6:dn=0,As=null,Xu(e,a,v,6);break;case 8:xh(),Jn=6;break e;default:throw Error(o(462))}}O0();break}catch(Te){ny(e,Te)}while(!0);return sr=zs=null,$.H=l,$.A=m,on=s,Ut!==null?0:(Mn=null,Kt=0,uu(),Jn)}function O0(){for(;Ut!==null&&!ke();)iy(Ut)}function iy(e){var a=zu(e.alternate,e,To);e.memoizedProps=e.pendingProps,a===null?Em(e):Ut=a}function oy(e){var a=e,s=a.alternate;switch(a.tag){case 15:case 0:a=Co(s,a,a.pendingProps,a.type,void 0,Kt);break;case 11:a=Co(s,a,a.pendingProps,a.type.render,a.ref,Kt);break;case 5:gc(a);default:uf(s,a),a=Ut=jd(a,To),a=zu(s,a,To)}e.memoizedProps=e.pendingProps,a===null?Em(e):Ut=a}function Xu(e,a,s,l){sr=zs=null,gc(a),ol=null,ll=0;var m=a.return;try{if(Lu(e,m,a,s,Kt)){Jn=1,kc(e,Dr(s,e.current)),Ut=null;return}}catch(v){if(m!==null)throw Ut=m,v;Jn=1,kc(e,Dr(s,e.current)),Ut=null;return}a.flags&32768?(Bt||l===1?e=!0:Vu||(Kt&536870912)!==0?e=!1:(Sl=e=!0,(l===2||l===9||l===3||l===6)&&(l=ur.current,l!==null&&l.tag===13&&(l.flags|=16384))),ly(a,e)):Em(a)}function Em(e){var a=e;do{if((a.flags&32768)!==0){ly(a,Sl);return}e=a.return;var s=dh(a.alternate,a,To);if(s!==null){Ut=s;return}if(a=a.sibling,a!==null){Ut=a;return}Ut=a=e}while(a!==null);Jn===0&&(Jn=5)}function ly(e,a){do{var s=fh(e.alternate,e);if(s!==null){s.flags&=32767,Ut=s;return}if(s=e.return,s!==null&&(s.flags|=32768,s.subtreeFlags=0,s.deletions=null),!a&&(e=e.sibling,e!==null)){Ut=e;return}Ut=e=s}while(e!==null);Jn=6,Ut=null}function cy(e,a,s,l,m,v,M,L,Q){e.cancelPendingCommit=null;do Dm();while(Ma!==0);if((on&6)!==0)throw Error(o(327));if(a!==null){if(a===e.current)throw Error(o(177));if(v=a.lanes|a.childLanes,v|=Rd,la(e,s,v,M,L,Q),e===Mn&&(Ut=Mn=null,Kt=0),Qu=a,Ml=e,Ro=s,yh=v,bh=m,Zv=l,(a.subtreeFlags&10256)!==0||(a.flags&10256)!==0?(e.callbackNode=null,e.callbackPriority=0,$0(Ne,function(){return py(),null})):(e.callbackNode=null,e.callbackPriority=0),l=(a.flags&13878)!==0,(a.subtreeFlags&13878)!==0||l){l=$.T,$.T=null,m=_.p,_.p=2,M=on,on|=4;try{W(e,a,s)}finally{on=M,_.p=m,$.T=l}}Ma=1,uy(),dy(),fy()}}function uy(){if(Ma===1){Ma=0;var e=Ml,a=Qu,s=(a.flags&13878)!==0;if((a.subtreeFlags&13878)!==0||s){s=$.T,$.T=null;var l=_.p;_.p=2;var m=on;on|=4;try{Ec(a,e);var v=Lh,M=ro(e.containerInfo),L=v.focusedElem,Q=v.selectionRange;if(M!==L&&L&&L.ownerDocument&&ao(L.ownerDocument.documentElement,L)){if(Q!==null&&ii(L)){var ve=Q.start,Te=Q.end;if(Te===void 0&&(Te=ve),"selectionStart"in L)L.selectionStart=ve,L.selectionEnd=Math.min(Te,L.value.length);else{var Ee=L.ownerDocument||document,we=Ee&&Ee.defaultView||window;if(we.getSelection){var Me=we.getSelection(),it=L.textContent.length,kt=Math.min(Q.start,it),vn=Q.end===void 0?kt:Math.min(Q.end,it);!Me.extend&&kt>vn&&(M=vn,vn=kt,kt=M);var ce=nc(L,kt),re=nc(L,vn);if(ce&&re&&(Me.rangeCount!==1||Me.anchorNode!==ce.node||Me.anchorOffset!==ce.offset||Me.focusNode!==re.node||Me.focusOffset!==re.offset)){var ge=Ee.createRange();ge.setStart(ce.node,ce.offset),Me.removeAllRanges(),kt>vn?(Me.addRange(ge),Me.extend(re.node,re.offset)):(ge.setEnd(re.node,re.offset),Me.addRange(ge))}}}}for(Ee=[],Me=L;Me=Me.parentNode;)Me.nodeType===1&&Ee.push({element:Me,left:Me.scrollLeft,top:Me.scrollTop});for(typeof L.focus=="function"&&L.focus(),L=0;L<Ee.length;L++){var Re=Ee[L];Re.element.scrollLeft=Re.left,Re.element.scrollTop=Re.top}}qm=!!Ih,Lh=Ih=null}finally{on=m,_.p=l,$.T=s}}e.current=a,Ma=2}}function dy(){if(Ma===2){Ma=0;var e=Ml,a=Qu,s=(a.flags&8772)!==0;if((a.subtreeFlags&8772)!==0||s){s=$.T,$.T=null;var l=_.p;_.p=2;var m=on;on|=4;try{oe(e,a.alternate,a)}finally{on=m,_.p=l,$.T=s}}Ma=3}}function fy(){if(Ma===4||Ma===3){Ma=0,qe();var e=Ml,a=Qu,s=Ro,l=Zv;(a.subtreeFlags&10256)!==0||(a.flags&10256)!==0?Ma=5:(Ma=0,Qu=Ml=null,my(e,e.pendingLanes));var m=e.pendingLanes;if(m===0&&(kl=null),Zt(s),a=a.stateNode,he&&typeof he.onCommitFiberRoot=="function")try{he.onCommitFiberRoot(ee,a,void 0,(a.current.flags&128)===128)}catch{}if(l!==null){a=$.T,m=_.p,_.p=2,$.T=null;try{for(var v=e.onRecoverableError,M=0;M<l.length;M++){var L=l[M];v(L.value,{componentStack:L.stack})}}finally{$.T=a,_.p=m}}(Ro&3)!==0&&Dm(),Bi(e),m=e.pendingLanes,(s&261930)!==0&&(m&42)!==0?e===wh?gf++:(gf=0,wh=e):gf=0,vf(0)}}function my(e,a){(e.pooledCacheLanes&=a)===0&&(a=e.pooledCache,a!=null&&(e.pooledCache=null,lr(a)))}function Dm(){return uy(),dy(),fy(),py()}function py(){if(Ma!==5)return!1;var e=Ml,a=yh;yh=0;var s=Zt(Ro),l=$.T,m=_.p;try{_.p=32>s?32:s,$.T=null,s=bh,bh=null;var v=Ml,M=Ro;if(Ma=0,Qu=Ml=null,Ro=0,(on&6)!==0)throw Error(o(331));var L=on;if(on|=4,Qv(v.current),Gv(v,v.current,M,s),on=L,vf(0,!1),he&&typeof he.onPostCommitFiberRoot=="function")try{he.onPostCommitFiberRoot(ee,v)}catch{}return!0}finally{_.p=m,$.T=l,my(e,a)}}function hy(e,a,s){a=Dr(s,a),a=Du(e.stateNode,a,2),e=Sa(e,a,2),e!==null&&(Wn(e,2),Bi(e))}function fn(e,a,s){if(e.tag===3)hy(e,e,s);else for(;a!==null;){if(a.tag===3){hy(a,e,s);break}else if(a.tag===1){var l=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof l.componentDidCatch=="function"&&(kl===null||!kl.has(l))){e=Dr(s,e),s=xm(2),l=Sa(a,s,2),l!==null&&(Iu(s,l,a,e),Wn(l,2),Bi(l));break}}a=a.return}}function Ch(e,a,s){var l=e.pingCache;if(l===null){l=e.pingCache=new L0;var m=new Set;l.set(a,m)}else m=l.get(a),m===void 0&&(m=new Set,l.set(a,m));m.has(s)||(hh=!0,m.add(s),e=B0.bind(null,e,a,s),a.then(e,e))}function B0(e,a,s){var l=e.pingCache;l!==null&&l.delete(a),e.pingedLanes|=e.suspendedLanes&s,e.warmLanes&=~s,Mn===e&&(Kt&s)===s&&(Jn===4||Jn===3&&(Kt&62914560)===Kt&&300>Ye()-Am?(on&2)===0&&Yu(e,0):gh|=s,Ku===Kt&&(Ku=0)),Bi(e)}function gy(e,a){a===0&&(a=Na()),e=Fs(e,a),e!==null&&(Wn(e,a),Bi(e))}function H0(e){var a=e.memoizedState,s=0;a!==null&&(s=a.retryLane),gy(e,s)}function z0(e,a){var s=0;switch(e.tag){case 31:case 13:var l=e.stateNode,m=e.memoizedState;m!==null&&(s=m.retryLane);break;case 19:l=e.stateNode;break;case 22:l=e.stateNode._retryCache;break;default:throw Error(o(314))}l!==null&&l.delete(a),gy(e,s)}function $0(e,a){return Nt(e,a)}var Im=null,Zu=null,kh=!1,Lm=!1,Mh=!1,Nl=0;function Bi(e){e!==Zu&&e.next===null&&(Zu===null?Im=Zu=e:Zu=Zu.next=e),Lm=!0,kh||(kh=!0,q0())}function vf(e,a){if(!Mh&&Lm){Mh=!0;do for(var s=!1,l=Im;l!==null;){if(e!==0){var m=l.pendingLanes;if(m===0)var v=0;else{var M=l.suspendedLanes,L=l.pingedLanes;v=(1<<31-fe(42|e)+1)-1,v&=m&~(M&~L),v=v&201326741?v&201326741|1:v?v|2:0}v!==0&&(s=!0,wy(l,v))}else v=Kt,v=cn(l,l===Mn?v:0,l.cancelPendingCommit!==null||l.timeoutHandle!==-1),(v&3)===0||Xt(l,v)||(s=!0,wy(l,v));l=l.next}while(s);Mh=!1}}function U0(){vy()}function vy(){Lm=kh=!1;var e=0;Nl!==0&&eC()&&(e=Nl);for(var a=Ye(),s=null,l=Im;l!==null;){var m=l.next,v=yy(l,a);v===0?(l.next=null,s===null?Im=m:s.next=m,m===null&&(Zu=s)):(s=l,(e!==0||(v&3)!==0)&&(Lm=!0)),l=m}Ma!==0&&Ma!==5||vf(e),Nl!==0&&(Nl=0)}function yy(e,a){for(var s=e.suspendedLanes,l=e.pingedLanes,m=e.expirationTimes,v=e.pendingLanes&-62914561;0<v;){var M=31-fe(v),L=1<<M,Q=m[M];Q===-1?((L&s)===0||(L&l)!==0)&&(m[M]=oa(L,a)):Q<=a&&(e.expiredLanes|=L),v&=~L}if(a=Mn,s=Kt,s=cn(e,e===a?s:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),l=e.callbackNode,s===0||e===a&&(dn===2||dn===9)||e.cancelPendingCommit!==null)return l!==null&&l!==null&&Ht(l),e.callbackNode=null,e.callbackPriority=0;if((s&3)===0||Xt(e,s)){if(a=s&-s,a===e.callbackPriority)return a;switch(l!==null&&Ht(l),Zt(s)){case 2:case 8:s=pe;break;case 32:s=Ne;break;case 268435456:s=Oe;break;default:s=Ne}return l=by.bind(null,e),s=Nt(s,l),e.callbackPriority=a,e.callbackNode=s,a}return l!==null&&l!==null&&Ht(l),e.callbackPriority=2,e.callbackNode=null,2}function by(e,a){if(Ma!==0&&Ma!==5)return e.callbackNode=null,e.callbackPriority=0,null;var s=e.callbackNode;if(Dm()&&e.callbackNode!==s)return null;var l=Kt;return l=cn(e,e===Mn?l:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),l===0?null:(ey(e,l,a),yy(e,Ye()),e.callbackNode!=null&&e.callbackNode===s?by.bind(null,e):null)}function wy(e,a){if(Dm())return null;ey(e,a,!0)}function q0(){nC(function(){(on&6)!==0?Nt(tt,U0):vy()})}function Ah(){if(Nl===0){var e=Vt;e===0&&(e=ft,ft<<=1,(ft&261888)===0&&(ft=256)),Nl=e}return Nl}function xy(e){return e==null||typeof e=="symbol"||typeof e=="boolean"?null:typeof e=="function"?e:Ra(""+e)}function Sy(e,a){var s=a.ownerDocument.createElement("input");return s.name=a.name,s.value=a.value,e.id&&s.setAttribute("form",e.id),a.parentNode.insertBefore(s,a),e=new FormData(e),s.parentNode.removeChild(s),e}function W0(e,a,s,l,m){if(a==="submit"&&s&&s.stateNode===m){var v=xy((m[De]||null).action),M=l.submitter;M&&(a=(a=M[De]||null)?xy(a.formAction):M.getAttribute("formAction"),a!==null&&(v=a,M=null));var L=new Wa("action","action",null,l,m);e.push({event:L,listeners:[{instance:null,listener:function(){if(l.defaultPrevented){if(Nl!==0){var Q=M?Sy(m,M):new FormData(m);vl(s,{pending:!0,data:Q,method:m.method,action:v},null,Q)}}else typeof v=="function"&&(L.preventDefault(),Q=M?Sy(m,M):new FormData(m),vl(s,{pending:!0,data:Q,method:m.method,action:v},v,Q))},currentTarget:m}]})}}for(var Nh=0;Nh<lm.length;Nh++){var Th=lm[Nh],G0=Th.toLowerCase(),V0=Th[0].toUpperCase()+Th.slice(1);gs(G0,"on"+V0)}gs(nh,"onAnimationEnd"),gs(om,"onAnimationIteration"),gs(so,"onAnimationStart"),gs("dblclick","onDoubleClick"),gs("focusin","onFocus"),gs("focusout","onBlur"),gs(ah,"onTransitionRun"),gs(Vo,"onTransitionStart"),gs(Td,"onTransitionCancel"),gs(rh,"onTransitionEnd"),Rn("onMouseEnter",["mouseout","mouseover"]),Rn("onMouseLeave",["mouseout","mouseover"]),Rn("onPointerEnter",["pointerout","pointerover"]),Rn("onPointerLeave",["pointerout","pointerover"]),Ot("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),Ot("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),Ot("onBeforeInput",["compositionend","keypress","textInput","paste"]),Ot("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),Ot("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),Ot("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var yf="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(" "),K0=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(yf));function Cy(e,a){a=(a&4)!==0;for(var s=0;s<e.length;s++){var l=e[s],m=l.event;l=l.listeners;e:{var v=void 0;if(a)for(var M=l.length-1;0<=M;M--){var L=l[M],Q=L.instance,ve=L.currentTarget;if(L=L.listener,Q!==v&&m.isPropagationStopped())break e;v=L,m.currentTarget=ve;try{v(m)}catch(Te){ac(Te)}m.currentTarget=null,v=Q}else for(M=0;M<l.length;M++){if(L=l[M],Q=L.instance,ve=L.currentTarget,L=L.listener,Q!==v&&m.isPropagationStopped())break e;v=L,m.currentTarget=ve;try{v(m)}catch(Te){ac(Te)}m.currentTarget=null,v=Q}}}}function qt(e,a){var s=a[wt];s===void 0&&(s=a[wt]=new Set);var l=e+"__bubble";s.has(l)||(ky(a,e,2,!1),s.add(l))}function Rh(e,a,s){var l=0;a&&(l|=4),ky(s,e,l,a)}var _m="_reactListening"+Math.random().toString(36).slice(2);function jh(e){if(!e[_m]){e[_m]=!0,br.forEach(function(s){s!=="selectionchange"&&(K0.has(s)||Rh(s,!1,e),Rh(s,!0,e))});var a=e.nodeType===9?e:e.ownerDocument;a===null||a[_m]||(a[_m]=!0,Rh("selectionchange",!1,a))}}function ky(e,a,s,l){switch(Jy(a)){case 2:var m=SC;break;case 8:m=CC;break;default:m=Wh}s=m.bind(null,a,s,e),m=void 0,!cs||a!=="touchstart"&&a!=="touchmove"&&a!=="wheel"||(m=!0),l?m!==void 0?e.addEventListener(a,s,{capture:!0,passive:m}):e.addEventListener(a,s,!0):m!==void 0?e.addEventListener(a,s,{passive:m}):e.addEventListener(a,s,!1)}function Eh(e,a,s,l,m){var v=l;if((a&1)===0&&(a&2)===0&&l!==null)e:for(;;){if(l===null)return;var M=l.tag;if(M===3||M===4){var L=l.stateNode.containerInfo;if(L===m)break;if(M===4)for(M=l.return;M!==null;){var Q=M.tag;if((Q===3||Q===4)&&M.stateNode.containerInfo===m)return;M=M.return}for(;L!==null;){if(M=mn(L),M===null)return;if(Q=M.tag,Q===5||Q===6||Q===26||Q===27){l=v=M;continue e}L=L.parentNode}}l=l.return}Yl(function(){var ve=v,Te=Vn(s),Ee=[];e:{var we=sh.get(e);if(we!==void 0){var Me=Wa,it=e;switch(e){case"keypress":if(nr(s)===0)break e;case"keydown":case"keyup":Me=Cd;break;case"focusin":it="focus",Me=Si;break;case"focusout":it="blur",Me=Si;break;case"beforeblur":case"afterblur":Me=Si;break;case"click":if(s.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":Me=eo;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":Me=Xl;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":Me=si;break;case nh:case om:case so:Me=ri;break;case rh:Me=ms;break;case"scroll":case"scrollend":Me=Zi;break;case"wheel":Me=Nr;break;case"copy":case"cut":case"paste":Me=eu;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":Me=Jl;break;case"toggle":case"beforetoggle":Me=rm}var kt=(a&4)!==0,vn=!kt&&(e==="scroll"||e==="scrollend"),ce=kt?we!==null?we+"Capture":null:we;kt=[];for(var re=ve,ge;re!==null;){var Re=re;if(ge=Re.stateNode,Re=Re.tag,Re!==5&&Re!==26&&Re!==27||ge===null||ce===null||(Re=Yi(re,ce),Re!=null&&kt.push(bf(re,Re,ge))),vn)break;re=re.return}0<kt.length&&(we=new Me(we,it,null,s,Te),Ee.push({event:we,listeners:kt}))}}if((a&7)===0){e:{if(we=e==="mouseover"||e==="pointerover",Me=e==="mouseout"||e==="pointerout",we&&s!==ni&&(it=s.relatedTarget||s.fromElement)&&(mn(it)||it[Ke]))break e;if((Me||we)&&(we=Te.window===Te?Te:(we=Te.ownerDocument)?we.defaultView||we.parentWindow:window,Me?(it=s.relatedTarget||s.toElement,Me=ve,it=it?mn(it):null,it!==null&&(vn=u(it),kt=it.tag,it!==vn||kt!==5&&kt!==27&&kt!==6)&&(it=null)):(Me=null,it=ve),Me!==it)){if(kt=eo,Re="onMouseLeave",ce="onMouseEnter",re="mouse",(e==="pointerout"||e==="pointerover")&&(kt=Jl,Re="onPointerLeave",ce="onPointerEnter",re="pointer"),vn=Me==null?we:wn(Me),ge=it==null?we:wn(it),we=new kt(Re,re+"leave",Me,s,Te),we.target=vn,we.relatedTarget=ge,Re=null,mn(Te)===ve&&(kt=new kt(ce,re+"enter",it,s,Te),kt.target=ge,kt.relatedTarget=vn,Re=kt),vn=Re,Me&&it)t:{for(kt=Q0,ce=Me,re=it,ge=0,Re=ce;Re;Re=kt(Re))ge++;Re=0;for(var vt=re;vt;vt=kt(vt))Re++;for(;0<ge-Re;)ce=kt(ce),ge--;for(;0<Re-ge;)re=kt(re),Re--;for(;ge--;){if(ce===re||re!==null&&ce===re.alternate){kt=ce;break t}ce=kt(ce),re=kt(re)}kt=null}else kt=null;Me!==null&&My(Ee,we,Me,kt,!1),it!==null&&vn!==null&&My(Ee,vn,it,kt,!0)}}e:{if(we=ve?wn(ve):window,Me=we.nodeName&&we.nodeName.toLowerCase(),Me==="select"||Me==="input"&&we.type==="file")var tn=su;else if(Mi(we))if(Va)tn=Ad;else{tn=ou;var ut=iu}else Me=we.nodeName,!Me||Me.toLowerCase()!=="input"||we.type!=="checkbox"&&we.type!=="radio"?ve&&ti(ve.elementType)&&(tn=su):tn=Md;if(tn&&(tn=tn(e,ve))){Ai(Ee,tn,s,Te);break e}ut&&ut(e,we,ve),e==="focusout"&&ve&&we.type==="number"&&ve.memoizedProps.value!=null&&Wr(we,"number",we.value)}switch(ut=ve?wn(ve):window,e){case"focusin":(Mi(ut)||ut.contentEditable==="true")&&(hs=ut,cu=ve,Qn=null);break;case"focusout":Qn=cu=hs=null;break;case"mousedown":rr=!0;break;case"contextmenu":case"mouseup":case"dragend":rr=!1,Nd(Ee,s,Te);break;case"selectionchange":if(aa)break;case"keydown":case"keyup":Nd(Ee,s,Te)}var Lt;if(ca)e:{switch(e){case"compositionstart":var Qt="onCompositionStart";break e;case"compositionend":Qt="onCompositionEnd";break e;case"compositionupdate":Qt="onCompositionUpdate";break e}Qt=void 0}else Rr?to(e,s)&&(Qt="onCompositionEnd"):e==="keydown"&&s.keyCode===229&&(Qt="onCompositionStart");Qt&&(yt&&s.locale!=="ko"&&(Rr||Qt!=="onCompositionStart"?Qt==="onCompositionEnd"&&Rr&&(Lt=ja()):(us=Te,ai="value"in us?us.value:us.textContent,Rr=!0)),ut=Fm(ve,Qt),0<ut.length&&(Qt=new xd(Qt,e,null,s,Te),Ee.push({event:Qt,listeners:ut}),Lt?Qt.data=Lt:(Lt=Uo(s),Lt!==null&&(Qt.data=Lt)))),(Lt=$o?no(e,s):ru(e,s))&&(Qt=Fm(ve,"onBeforeInput"),0<Qt.length&&(ut=new xd("onBeforeInput","beforeinput",null,s,Te),Ee.push({event:ut,listeners:Qt}),ut.data=Lt)),W0(Ee,e,ve,s,Te)}Cy(Ee,a)})}function bf(e,a,s){return{instance:e,listener:a,currentTarget:s}}function Fm(e,a){for(var s=a+"Capture",l=[];e!==null;){var m=e,v=m.stateNode;if(m=m.tag,m!==5&&m!==26&&m!==27||v===null||(m=Yi(e,s),m!=null&&l.unshift(bf(e,m,v)),m=Yi(e,a),m!=null&&l.push(bf(e,m,v))),e.tag===3)return l;e=e.return}return[]}function Q0(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5&&e.tag!==27);return e||null}function My(e,a,s,l,m){for(var v=a._reactName,M=[];s!==null&&s!==l;){var L=s,Q=L.alternate,ve=L.stateNode;if(L=L.tag,Q!==null&&Q===l)break;L!==5&&L!==26&&L!==27||ve===null||(Q=ve,m?(ve=Yi(s,v),ve!=null&&M.unshift(bf(s,ve,Q))):m||(ve=Yi(s,v),ve!=null&&M.push(bf(s,ve,Q)))),s=s.return}M.length!==0&&e.push({event:a,listeners:M})}var Y0=/\r\n?/g,X0=/\u0000|\uFFFD/g;function Ay(e){return(typeof e=="string"?e:""+e).replace(Y0,`
9
- `).replace(X0,"")}function Ny(e,a){return a=Ay(a),Ay(e)===a}function gn(e,a,s,l,m,v){switch(s){case"children":typeof l=="string"?a==="body"||a==="textarea"&&l===""||ls(e,l):(typeof l=="number"||typeof l=="bigint")&&a!=="body"&&ls(e,""+l);break;case"className":is(e,"class",l);break;case"tabIndex":is(e,"tabindex",l);break;case"dir":case"role":case"viewBox":case"width":case"height":is(e,s,l);break;case"style":Po(e,l,v);break;case"data":if(a!=="object"){is(e,"data",l);break}case"src":case"href":if(l===""&&(a!=="a"||s!=="href")){e.removeAttribute(s);break}if(l==null||typeof l=="function"||typeof l=="symbol"||typeof l=="boolean"){e.removeAttribute(s);break}l=Ra(""+l),e.setAttribute(s,l);break;case"action":case"formAction":if(typeof l=="function"){e.setAttribute(s,"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"&&(s==="formAction"?(a!=="input"&&gn(e,a,"name",m.name,m,null),gn(e,a,"formEncType",m.formEncType,m,null),gn(e,a,"formMethod",m.formMethod,m,null),gn(e,a,"formTarget",m.formTarget,m,null)):(gn(e,a,"encType",m.encType,m,null),gn(e,a,"method",m.method,m,null),gn(e,a,"target",m.target,m,null)));if(l==null||typeof l=="symbol"||typeof l=="boolean"){e.removeAttribute(s);break}l=Ra(""+l),e.setAttribute(s,l);break;case"onClick":l!=null&&(e.onclick=tr);break;case"onScroll":l!=null&&qt("scroll",e);break;case"onScrollEnd":l!=null&&qt("scrollend",e);break;case"dangerouslySetInnerHTML":if(l!=null){if(typeof l!="object"||!("__html"in l))throw Error(o(61));if(s=l.__html,s!=null){if(m.children!=null)throw Error(o(60));e.innerHTML=s}}break;case"multiple":e.multiple=l&&typeof l!="function"&&typeof l!="symbol";break;case"muted":e.muted=l&&typeof l!="function"&&typeof l!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(l==null||typeof l=="function"||typeof l=="boolean"||typeof l=="symbol"){e.removeAttribute("xlink:href");break}s=Ra(""+l),e.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",s);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":l!=null&&typeof l!="function"&&typeof l!="symbol"?e.setAttribute(s,""+l):e.removeAttribute(s);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":l&&typeof l!="function"&&typeof l!="symbol"?e.setAttribute(s,""):e.removeAttribute(s);break;case"capture":case"download":l===!0?e.setAttribute(s,""):l!==!1&&l!=null&&typeof l!="function"&&typeof l!="symbol"?e.setAttribute(s,l):e.removeAttribute(s);break;case"cols":case"rows":case"size":case"span":l!=null&&typeof l!="function"&&typeof l!="symbol"&&!isNaN(l)&&1<=l?e.setAttribute(s,l):e.removeAttribute(s);break;case"rowSpan":case"start":l==null||typeof l=="function"||typeof l=="symbol"||isNaN(l)?e.removeAttribute(s):e.setAttribute(s,l);break;case"popover":qt("beforetoggle",e),qt("toggle",e),Ja(e,"popover",l);break;case"xlinkActuate":Ta(e,"http://www.w3.org/1999/xlink","xlink:actuate",l);break;case"xlinkArcrole":Ta(e,"http://www.w3.org/1999/xlink","xlink:arcrole",l);break;case"xlinkRole":Ta(e,"http://www.w3.org/1999/xlink","xlink:role",l);break;case"xlinkShow":Ta(e,"http://www.w3.org/1999/xlink","xlink:show",l);break;case"xlinkTitle":Ta(e,"http://www.w3.org/1999/xlink","xlink:title",l);break;case"xlinkType":Ta(e,"http://www.w3.org/1999/xlink","xlink:type",l);break;case"xmlBase":Ta(e,"http://www.w3.org/XML/1998/namespace","xml:base",l);break;case"xmlLang":Ta(e,"http://www.w3.org/XML/1998/namespace","xml:lang",l);break;case"xmlSpace":Ta(e,"http://www.w3.org/XML/1998/namespace","xml:space",l);break;case"is":Ja(e,"is",l);break;case"innerText":case"textContent":break;default:(!(2<s.length)||s[0]!=="o"&&s[0]!=="O"||s[1]!=="n"&&s[1]!=="N")&&(s=Kl.get(s)||s,Ja(e,s,l))}}function Dh(e,a,s,l,m,v){switch(s){case"style":Po(e,l,v);break;case"dangerouslySetInnerHTML":if(l!=null){if(typeof l!="object"||!("__html"in l))throw Error(o(61));if(s=l.__html,s!=null){if(m.children!=null)throw Error(o(60));e.innerHTML=s}}break;case"children":typeof l=="string"?ls(e,l):(typeof l=="number"||typeof l=="bigint")&&ls(e,""+l);break;case"onScroll":l!=null&&qt("scroll",e);break;case"onScrollEnd":l!=null&&qt("scrollend",e);break;case"onClick":l!=null&&(e.onclick=tr);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!wr.hasOwnProperty(s))e:{if(s[0]==="o"&&s[1]==="n"&&(m=s.endsWith("Capture"),a=s.slice(2,m?s.length-7:void 0),v=e[De]||null,v=v!=null?v[s]:null,typeof v=="function"&&e.removeEventListener(a,v,m),typeof l=="function")){typeof v!="function"&&v!==null&&(s in e?e[s]=null:e.hasAttribute(s)&&e.removeAttribute(s)),e.addEventListener(a,l,m);break e}s in e?e[s]=l:l===!0?e.setAttribute(s,""):Ja(e,s,l)}}}function Ya(e,a,s){switch(a){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":qt("error",e),qt("load",e);var l=!1,m=!1,v;for(v in s)if(s.hasOwnProperty(v)){var M=s[v];if(M!=null)switch(v){case"src":l=!0;break;case"srcSet":m=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(o(137,a));default:gn(e,a,v,M,s,null)}}m&&gn(e,a,"srcSet",s.srcSet,s,null),l&&gn(e,a,"src",s.src,s,null);return;case"input":qt("invalid",e);var L=v=M=m=null,Q=null,ve=null;for(l in s)if(s.hasOwnProperty(l)){var Te=s[l];if(Te!=null)switch(l){case"name":m=Te;break;case"type":M=Te;break;case"checked":Q=Te;break;case"defaultChecked":ve=Te;break;case"value":v=Te;break;case"defaultValue":L=Te;break;case"children":case"dangerouslySetInnerHTML":if(Te!=null)throw Error(o(137,a));break;default:gn(e,a,l,Te,s,null)}}Jc(e,v,L,Q,ve,M,m,!1);return;case"select":qt("invalid",e),l=M=v=null;for(m in s)if(s.hasOwnProperty(m)&&(L=s[m],L!=null))switch(m){case"value":v=L;break;case"defaultValue":M=L;break;case"multiple":l=L;default:gn(e,a,m,L,s,null)}a=v,s=M,e.multiple=!!l,a!=null?ei(e,!!l,a,!1):s!=null&&ei(e,!!l,s,!0);return;case"textarea":qt("invalid",e),v=m=l=null;for(M in s)if(s.hasOwnProperty(M)&&(L=s[M],L!=null))switch(M){case"value":l=L;break;case"defaultValue":m=L;break;case"children":v=L;break;case"dangerouslySetInnerHTML":if(L!=null)throw Error(o(91));break;default:gn(e,a,M,L,s,null)}Gn(e,l,m,v);return;case"option":for(Q in s)s.hasOwnProperty(Q)&&(l=s[Q],l!=null)&&(Q==="selected"?e.selected=l&&typeof l!="function"&&typeof l!="symbol":gn(e,a,Q,l,s,null));return;case"dialog":qt("beforetoggle",e),qt("toggle",e),qt("cancel",e),qt("close",e);break;case"iframe":case"object":qt("load",e);break;case"video":case"audio":for(l=0;l<yf.length;l++)qt(yf[l],e);break;case"image":qt("error",e),qt("load",e);break;case"details":qt("toggle",e);break;case"embed":case"source":case"link":qt("error",e),qt("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(ve in s)if(s.hasOwnProperty(ve)&&(l=s[ve],l!=null))switch(ve){case"children":case"dangerouslySetInnerHTML":throw Error(o(137,a));default:gn(e,a,ve,l,s,null)}return;default:if(ti(a)){for(Te in s)s.hasOwnProperty(Te)&&(l=s[Te],l!==void 0&&Dh(e,a,Te,l,s,void 0));return}}for(L in s)s.hasOwnProperty(L)&&(l=s[L],l!=null&&gn(e,a,L,l,s,null))}function Z0(e,a,s,l){switch(a){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var m=null,v=null,M=null,L=null,Q=null,ve=null,Te=null;for(Me in s){var Ee=s[Me];if(s.hasOwnProperty(Me)&&Ee!=null)switch(Me){case"checked":break;case"value":break;case"defaultValue":Q=Ee;default:l.hasOwnProperty(Me)||gn(e,a,Me,null,l,Ee)}}for(var we in l){var Me=l[we];if(Ee=s[we],l.hasOwnProperty(we)&&(Me!=null||Ee!=null))switch(we){case"type":v=Me;break;case"name":m=Me;break;case"checked":ve=Me;break;case"defaultChecked":Te=Me;break;case"value":M=Me;break;case"defaultValue":L=Me;break;case"children":case"dangerouslySetInnerHTML":if(Me!=null)throw Error(o(137,a));break;default:Me!==Ee&&gn(e,a,we,Me,l,Ee)}}Fo(e,M,L,Q,ve,Te,v,m);return;case"select":Me=M=L=we=null;for(v in s)if(Q=s[v],s.hasOwnProperty(v)&&Q!=null)switch(v){case"value":break;case"multiple":Me=Q;default:l.hasOwnProperty(v)||gn(e,a,v,null,l,Q)}for(m in l)if(v=l[m],Q=s[m],l.hasOwnProperty(m)&&(v!=null||Q!=null))switch(m){case"value":we=v;break;case"defaultValue":L=v;break;case"multiple":M=v;default:v!==Q&&gn(e,a,m,v,l,Q)}a=L,s=M,l=Me,we!=null?ei(e,!!s,we,!1):!!l!=!!s&&(a!=null?ei(e,!!s,a,!0):ei(e,!!s,s?[]:"",!1));return;case"textarea":Me=we=null;for(L in s)if(m=s[L],s.hasOwnProperty(L)&&m!=null&&!l.hasOwnProperty(L))switch(L){case"value":break;case"children":break;default:gn(e,a,L,null,l,m)}for(M in l)if(m=l[M],v=s[M],l.hasOwnProperty(M)&&(m!=null||v!=null))switch(M){case"value":we=m;break;case"defaultValue":Me=m;break;case"children":break;case"dangerouslySetInnerHTML":if(m!=null)throw Error(o(91));break;default:m!==v&&gn(e,a,M,m,l,v)}St(e,we,Me);return;case"option":for(var it in s)we=s[it],s.hasOwnProperty(it)&&we!=null&&!l.hasOwnProperty(it)&&(it==="selected"?e.selected=!1:gn(e,a,it,null,l,we));for(Q in l)we=l[Q],Me=s[Q],l.hasOwnProperty(Q)&&we!==Me&&(we!=null||Me!=null)&&(Q==="selected"?e.selected=we&&typeof we!="function"&&typeof we!="symbol":gn(e,a,Q,we,l,Me));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 kt in s)we=s[kt],s.hasOwnProperty(kt)&&we!=null&&!l.hasOwnProperty(kt)&&gn(e,a,kt,null,l,we);for(ve in l)if(we=l[ve],Me=s[ve],l.hasOwnProperty(ve)&&we!==Me&&(we!=null||Me!=null))switch(ve){case"children":case"dangerouslySetInnerHTML":if(we!=null)throw Error(o(137,a));break;default:gn(e,a,ve,we,l,Me)}return;default:if(ti(a)){for(var vn in s)we=s[vn],s.hasOwnProperty(vn)&&we!==void 0&&!l.hasOwnProperty(vn)&&Dh(e,a,vn,void 0,l,we);for(Te in l)we=l[Te],Me=s[Te],!l.hasOwnProperty(Te)||we===Me||we===void 0&&Me===void 0||Dh(e,a,Te,we,l,Me);return}}for(var ce in s)we=s[ce],s.hasOwnProperty(ce)&&we!=null&&!l.hasOwnProperty(ce)&&gn(e,a,ce,null,l,we);for(Ee in l)we=l[Ee],Me=s[Ee],!l.hasOwnProperty(Ee)||we===Me||we==null&&Me==null||gn(e,a,Ee,we,l,Me)}function Ty(e){switch(e){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function J0(){if(typeof performance.getEntriesByType=="function"){for(var e=0,a=0,s=performance.getEntriesByType("resource"),l=0;l<s.length;l++){var m=s[l],v=m.transferSize,M=m.initiatorType,L=m.duration;if(v&&L&&Ty(M)){for(M=0,L=m.responseEnd,l+=1;l<s.length;l++){var Q=s[l],ve=Q.startTime;if(ve>L)break;var Te=Q.transferSize,Ee=Q.initiatorType;Te&&Ty(Ee)&&(Q=Q.responseEnd,M+=Te*(Q<L?1:(L-ve)/(Q-ve)))}if(--l,a+=8*(v+M)/(m.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 Ih=null,Lh=null;function Pm(e){return e.nodeType===9?e:e.ownerDocument}function Ry(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 jy(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 _h(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 Fh=null;function eC(){var e=window.event;return e&&e.type==="popstate"?e===Fh?!1:(Fh=e,!0):(Fh=null,!1)}var Ey=typeof setTimeout=="function"?setTimeout:void 0,tC=typeof clearTimeout=="function"?clearTimeout:void 0,Dy=typeof Promise=="function"?Promise:void 0,nC=typeof queueMicrotask=="function"?queueMicrotask:typeof Dy<"u"?function(e){return Dy.resolve(null).then(e).catch(aC)}:Ey;function aC(e){setTimeout(function(){throw e})}function Tl(e){return e==="head"}function Iy(e,a){var s=a,l=0;do{var m=s.nextSibling;if(e.removeChild(s),m&&m.nodeType===8)if(s=m.data,s==="/$"||s==="/&"){if(l===0){e.removeChild(m),nd(a);return}l--}else if(s==="$"||s==="$?"||s==="$~"||s==="$!"||s==="&")l++;else if(s==="html")wf(e.ownerDocument.documentElement);else if(s==="head"){s=e.ownerDocument.head,wf(s);for(var v=s.firstChild;v;){var M=v.nextSibling,L=v.nodeName;v[Pt]||L==="SCRIPT"||L==="STYLE"||L==="LINK"&&v.rel.toLowerCase()==="stylesheet"||s.removeChild(v),v=M}}else s==="body"&&wf(e.ownerDocument.body);s=m}while(s);nd(a)}function Ly(e,a){var s=e;e=0;do{var l=s.nextSibling;if(s.nodeType===1?a?(s._stashedDisplay=s.style.display,s.style.display="none"):(s.style.display=s._stashedDisplay||"",s.getAttribute("style")===""&&s.removeAttribute("style")):s.nodeType===3&&(a?(s._stashedText=s.nodeValue,s.nodeValue=""):s.nodeValue=s._stashedText||""),l&&l.nodeType===8)if(s=l.data,s==="/$"){if(e===0)break;e--}else s!=="$"&&s!=="$?"&&s!=="$~"&&s!=="$!"||e++;s=l}while(s)}function Ph(e){var a=e.firstChild;for(a&&a.nodeType===10&&(a=a.nextSibling);a;){var s=a;switch(a=a.nextSibling,s.nodeName){case"HTML":case"HEAD":case"BODY":Ph(s),xt(s);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(s.rel.toLowerCase()==="stylesheet")continue}e.removeChild(s)}}function rC(e,a,s,l){for(;e.nodeType===1;){var m=s;if(e.nodeName.toLowerCase()!==a.toLowerCase()){if(!l&&(e.nodeName!=="INPUT"||e.type!=="hidden"))break}else if(l){if(!e[Pt])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!==m.rel||e.getAttribute("href")!==(m.href==null||m.href===""?null:m.href)||e.getAttribute("crossorigin")!==(m.crossOrigin==null?null:m.crossOrigin)||e.getAttribute("title")!==(m.title==null?null:m.title))break;return e;case"style":if(e.hasAttribute("data-precedence"))break;return e;case"script":if(v=e.getAttribute("src"),(v!==(m.src==null?null:m.src)||e.getAttribute("type")!==(m.type==null?null:m.type)||e.getAttribute("crossorigin")!==(m.crossOrigin==null?null:m.crossOrigin))&&v&&e.hasAttribute("async")&&!e.hasAttribute("itemprop"))break;return e;default:return e}}else if(a==="input"&&e.type==="hidden"){var v=m.name==null?null:""+m.name;if(m.type==="hidden"&&e.getAttribute("name")===v)return e}else return e;if(e=Ks(e.nextSibling),e===null)break}return null}function sC(e,a,s){if(a==="")return null;for(;e.nodeType!==3;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!s||(e=Ks(e.nextSibling),e===null))return null;return e}function _y(e,a){for(;e.nodeType!==8;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!a||(e=Ks(e.nextSibling),e===null))return null;return e}function Oh(e){return e.data==="$?"||e.data==="$~"}function Bh(e){return e.data==="$!"||e.data==="$?"&&e.ownerDocument.readyState!=="loading"}function iC(e,a){var s=e.ownerDocument;if(e.data==="$~")e._reactRetry=a;else if(e.data!=="$?"||s.readyState!=="loading")a();else{var l=function(){a(),s.removeEventListener("DOMContentLoaded",l)};s.addEventListener("DOMContentLoaded",l),e._reactRetry=l}}function Ks(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 Hh=null;function Fy(e){e=e.nextSibling;for(var a=0;e;){if(e.nodeType===8){var s=e.data;if(s==="/$"||s==="/&"){if(a===0)return Ks(e.nextSibling);a--}else s!=="$"&&s!=="$!"&&s!=="$?"&&s!=="$~"&&s!=="&"||a++}e=e.nextSibling}return null}function Py(e){e=e.previousSibling;for(var a=0;e;){if(e.nodeType===8){var s=e.data;if(s==="$"||s==="$!"||s==="$?"||s==="$~"||s==="&"){if(a===0)return e;a--}else s!=="/$"&&s!=="/&"||a++}e=e.previousSibling}return null}function Oy(e,a,s){switch(a=Pm(s),e){case"html":if(e=a.documentElement,!e)throw Error(o(452));return e;case"head":if(e=a.head,!e)throw Error(o(453));return e;case"body":if(e=a.body,!e)throw Error(o(454));return e;default:throw Error(o(451))}}function wf(e){for(var a=e.attributes;a.length;)e.removeAttributeNode(a[0]);xt(e)}var Qs=new Map,By=new Set;function Om(e){return typeof e.getRootNode=="function"?e.getRootNode():e.nodeType===9?e:e.ownerDocument}var jo=_.d;_.d={f:oC,r:lC,D:cC,C:uC,L:dC,m:fC,X:pC,S:mC,M:hC};function oC(){var e=jo.f(),a=Rm();return e||a}function lC(e){var a=na(e);a!==null&&a.tag===5&&a.type==="form"?Vd(a):jo.r(e)}var Ju=typeof document>"u"?null:document;function Hy(e,a,s){var l=Ju;if(l&&typeof a=="string"&&a){var m=Ln(a);m='link[rel="'+e+'"][href="'+m+'"]',typeof s=="string"&&(m+='[crossorigin="'+s+'"]'),By.has(m)||(By.add(m),e={rel:e,crossOrigin:s,href:a},l.querySelector(m)===null&&(a=l.createElement("link"),Ya(a,"link",e),rn(a),l.head.appendChild(a)))}}function cC(e){jo.D(e),Hy("dns-prefetch",e,null)}function uC(e,a){jo.C(e,a),Hy("preconnect",e,a)}function dC(e,a,s){jo.L(e,a,s);var l=Ju;if(l&&e&&a){var m='link[rel="preload"][as="'+Ln(a)+'"]';a==="image"&&s&&s.imageSrcSet?(m+='[imagesrcset="'+Ln(s.imageSrcSet)+'"]',typeof s.imageSizes=="string"&&(m+='[imagesizes="'+Ln(s.imageSizes)+'"]')):m+='[href="'+Ln(e)+'"]';var v=m;switch(a){case"style":v=ed(e);break;case"script":v=td(e)}Qs.has(v)||(e=b({rel:"preload",href:a==="image"&&s&&s.imageSrcSet?void 0:e,as:a},s),Qs.set(v,e),l.querySelector(m)!==null||a==="style"&&l.querySelector(xf(v))||a==="script"&&l.querySelector(Sf(v))||(a=l.createElement("link"),Ya(a,"link",e),rn(a),l.head.appendChild(a)))}}function fC(e,a){jo.m(e,a);var s=Ju;if(s&&e){var l=a&&typeof a.as=="string"?a.as:"script",m='link[rel="modulepreload"][as="'+Ln(l)+'"][href="'+Ln(e)+'"]',v=m;switch(l){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":v=td(e)}if(!Qs.has(v)&&(e=b({rel:"modulepreload",href:e},a),Qs.set(v,e),s.querySelector(m)===null)){switch(l){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(s.querySelector(Sf(v)))return}l=s.createElement("link"),Ya(l,"link",e),rn(l),s.head.appendChild(l)}}}function mC(e,a,s){jo.S(e,a,s);var l=Ju;if(l&&e){var m=On(l).hoistableStyles,v=ed(e);a=a||"default";var M=m.get(v);if(!M){var L={loading:0,preload:null};if(M=l.querySelector(xf(v)))L.loading=5;else{e=b({rel:"stylesheet",href:e,"data-precedence":a},s),(s=Qs.get(v))&&zh(e,s);var Q=M=l.createElement("link");rn(Q),Ya(Q,"link",e),Q._p=new Promise(function(ve,Te){Q.onload=ve,Q.onerror=Te}),Q.addEventListener("load",function(){L.loading|=1}),Q.addEventListener("error",function(){L.loading|=2}),L.loading|=4,Bm(M,a,l)}M={type:"stylesheet",instance:M,count:1,state:L},m.set(v,M)}}}function pC(e,a){jo.X(e,a);var s=Ju;if(s&&e){var l=On(s).hoistableScripts,m=td(e),v=l.get(m);v||(v=s.querySelector(Sf(m)),v||(e=b({src:e,async:!0},a),(a=Qs.get(m))&&$h(e,a),v=s.createElement("script"),rn(v),Ya(v,"link",e),s.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},l.set(m,v))}}function hC(e,a){jo.M(e,a);var s=Ju;if(s&&e){var l=On(s).hoistableScripts,m=td(e),v=l.get(m);v||(v=s.querySelector(Sf(m)),v||(e=b({src:e,async:!0,type:"module"},a),(a=Qs.get(m))&&$h(e,a),v=s.createElement("script"),rn(v),Ya(v,"link",e),s.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},l.set(m,v))}}function zy(e,a,s,l){var m=(m=ue.current)?Om(m):null;if(!m)throw Error(o(446));switch(e){case"meta":case"title":return null;case"style":return typeof s.precedence=="string"&&typeof s.href=="string"?(a=ed(s.href),s=On(m).hoistableStyles,l=s.get(a),l||(l={type:"style",instance:null,count:0,state:null},s.set(a,l)),l):{type:"void",instance:null,count:0,state:null};case"link":if(s.rel==="stylesheet"&&typeof s.href=="string"&&typeof s.precedence=="string"){e=ed(s.href);var v=On(m).hoistableStyles,M=v.get(e);if(M||(m=m.ownerDocument||m,M={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},v.set(e,M),(v=m.querySelector(xf(e)))&&!v._p&&(M.instance=v,M.state.loading=5),Qs.has(e)||(s={rel:"preload",as:"style",href:s.href,crossOrigin:s.crossOrigin,integrity:s.integrity,media:s.media,hrefLang:s.hrefLang,referrerPolicy:s.referrerPolicy},Qs.set(e,s),v||gC(m,e,s,M.state))),a&&l===null)throw Error(o(528,""));return M}if(a&&l!==null)throw Error(o(529,""));return null;case"script":return a=s.async,s=s.src,typeof s=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=td(s),s=On(m).hoistableScripts,l=s.get(a),l||(l={type:"script",instance:null,count:0,state:null},s.set(a,l)),l):{type:"void",instance:null,count:0,state:null};default:throw Error(o(444,e))}}function ed(e){return'href="'+Ln(e)+'"'}function xf(e){return'link[rel="stylesheet"]['+e+"]"}function $y(e){return b({},e,{"data-precedence":e.precedence,precedence:null})}function gC(e,a,s,l){e.querySelector('link[rel="preload"][as="style"]['+a+"]")?l.loading=1:(a=e.createElement("link"),l.preload=a,a.addEventListener("load",function(){return l.loading|=1}),a.addEventListener("error",function(){return l.loading|=2}),Ya(a,"link",s),rn(a),e.head.appendChild(a))}function td(e){return'[src="'+Ln(e)+'"]'}function Sf(e){return"script[async]"+e}function Uy(e,a,s){if(a.count++,a.instance===null)switch(a.type){case"style":var l=e.querySelector('style[data-href~="'+Ln(s.href)+'"]');if(l)return a.instance=l,rn(l),l;var m=b({},s,{"data-href":s.href,"data-precedence":s.precedence,href:null,precedence:null});return l=(e.ownerDocument||e).createElement("style"),rn(l),Ya(l,"style",m),Bm(l,s.precedence,e),a.instance=l;case"stylesheet":m=ed(s.href);var v=e.querySelector(xf(m));if(v)return a.state.loading|=4,a.instance=v,rn(v),v;l=$y(s),(m=Qs.get(m))&&zh(l,m),v=(e.ownerDocument||e).createElement("link"),rn(v);var M=v;return M._p=new Promise(function(L,Q){M.onload=L,M.onerror=Q}),Ya(v,"link",l),a.state.loading|=4,Bm(v,s.precedence,e),a.instance=v;case"script":return v=td(s.src),(m=e.querySelector(Sf(v)))?(a.instance=m,rn(m),m):(l=s,(m=Qs.get(v))&&(l=b({},s),$h(l,m)),e=e.ownerDocument||e,m=e.createElement("script"),rn(m),Ya(m,"link",l),e.head.appendChild(m),a.instance=m);case"void":return null;default:throw Error(o(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(l=a.instance,a.state.loading|=4,Bm(l,s.precedence,e));return a.instance}function Bm(e,a,s){for(var l=s.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),m=l.length?l[l.length-1]:null,v=m,M=0;M<l.length;M++){var L=l[M];if(L.dataset.precedence===a)v=L;else if(v!==m)break}v?v.parentNode.insertBefore(e,v.nextSibling):(a=s.nodeType===9?s.head:s,a.insertBefore(e,a.firstChild))}function zh(e,a){e.crossOrigin==null&&(e.crossOrigin=a.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=a.referrerPolicy),e.title==null&&(e.title=a.title)}function $h(e,a){e.crossOrigin==null&&(e.crossOrigin=a.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=a.referrerPolicy),e.integrity==null&&(e.integrity=a.integrity)}var Hm=null;function qy(e,a,s){if(Hm===null){var l=new Map,m=Hm=new Map;m.set(s,l)}else m=Hm,l=m.get(s),l||(l=new Map,m.set(s,l));if(l.has(e))return l;for(l.set(e,null),s=s.getElementsByTagName(e),m=0;m<s.length;m++){var v=s[m];if(!(v[Pt]||v[de]||e==="link"&&v.getAttribute("rel")==="stylesheet")&&v.namespaceURI!=="http://www.w3.org/2000/svg"){var M=v.getAttribute(a)||"";M=e+M;var L=l.get(M);L?L.push(v):l.set(M,[v])}}return l}function Wy(e,a,s){e=e.ownerDocument||e,e.head.insertBefore(s,a==="title"?e.querySelector("head > title"):null)}function vC(e,a,s){if(s===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 Gy(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function yC(e,a,s,l){if(s.type==="stylesheet"&&(typeof l.media!="string"||matchMedia(l.media).matches!==!1)&&(s.state.loading&4)===0){if(s.instance===null){var m=ed(l.href),v=a.querySelector(xf(m));if(v){a=v._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(e.count++,e=zm.bind(e),a.then(e,e)),s.state.loading|=4,s.instance=v,rn(v);return}v=a.ownerDocument||a,l=$y(l),(m=Qs.get(m))&&zh(l,m),v=v.createElement("link"),rn(v);var M=v;M._p=new Promise(function(L,Q){M.onload=L,M.onerror=Q}),Ya(v,"link",l),s.instance=v}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(s,a),(a=s.state.preload)&&(s.state.loading&3)===0&&(e.count++,s=zm.bind(e),a.addEventListener("load",s),a.addEventListener("error",s))}}var Uh=0;function bC(e,a){return e.stylesheets&&e.count===0&&Um(e,e.stylesheets),0<e.count||0<e.imgCount?function(s){var l=setTimeout(function(){if(e.stylesheets&&Um(e,e.stylesheets),e.unsuspend){var v=e.unsuspend;e.unsuspend=null,v()}},6e4+a);0<e.imgBytes&&Uh===0&&(Uh=62500*J0());var m=setTimeout(function(){if(e.waitingForImages=!1,e.count===0&&(e.stylesheets&&Um(e,e.stylesheets),e.unsuspend)){var v=e.unsuspend;e.unsuspend=null,v()}},(e.imgBytes>Uh?50:800)+a);return e.unsuspend=s,function(){e.unsuspend=null,clearTimeout(l),clearTimeout(m)}}:null}function zm(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Um(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var $m=null;function Um(e,a){e.stylesheets=null,e.unsuspend!==null&&(e.count++,$m=new Map,a.forEach(wC,e),$m=null,zm.call(e))}function wC(e,a){if(!(a.state.loading&4)){var s=$m.get(e);if(s)var l=s.get(null);else{s=new Map,$m.set(e,s);for(var m=e.querySelectorAll("link[data-precedence],style[data-precedence]"),v=0;v<m.length;v++){var M=m[v];(M.nodeName==="LINK"||M.getAttribute("media")!=="not all")&&(s.set(M.dataset.precedence,M),l=M)}l&&s.set(null,l)}m=a.instance,M=m.getAttribute("data-precedence"),v=s.get(M)||l,v===l&&s.set(null,m),s.set(M,m),this.count++,l=zm.bind(this),m.addEventListener("load",l),m.addEventListener("error",l),v?v.parentNode.insertBefore(m,v.nextSibling):(e=e.nodeType===9?e.head:e,e.insertBefore(m,e.firstChild)),a.state.loading|=4}}var Cf={$$typeof:F,Provider:null,Consumer:null,_currentValue:ie,_currentValue2:ie,_threadCount:0};function xC(e,a,s,l,m,v,M,L,Q){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=Pn(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Pn(0),this.hiddenUpdates=Pn(null),this.identifierPrefix=l,this.onUncaughtError=m,this.onCaughtError=v,this.onRecoverableError=M,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=Q,this.incompleteTransitions=new Map}function Vy(e,a,s,l,m,v,M,L,Q,ve,Te,Ee){return e=new xC(e,a,s,M,Q,ve,Te,Ee,L),a=1,v===!0&&(a|=24),v=Ia(3,null,null,a),e.current=v,v.stateNode=e,a=uc(),a.refCount++,e.pooledCache=a,a.refCount++,v.memoizedState={element:l,isDehydrated:s,cache:a},cl(v),e}function Ky(e){return e?(e=Ka,e):Ka}function Qy(e,a,s,l,m,v){m=Ky(m),l.context===null?l.context=m:l.pendingContext=m,l=xa(a),l.payload={element:s},v=v===void 0?null:v,v!==null&&(l.callback=v),s=Sa(e,l,a),s!==null&&(as(s,e,a),Ss(s,e,a))}function Yy(e,a){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var s=e.retryLane;e.retryLane=s!==0&&s<a?s:a}}function qh(e,a){Yy(e,a),(e=e.alternate)&&Yy(e,a)}function Xy(e){if(e.tag===13||e.tag===31){var a=Fs(e,67108864);a!==null&&as(a,e,67108864),qh(e,67108864)}}function Zy(e){if(e.tag===13||e.tag===31){var a=Ts();a=ht(a);var s=Fs(e,a);s!==null&&as(s,e,a),qh(e,a)}}var qm=!0;function SC(e,a,s,l){var m=$.T;$.T=null;var v=_.p;try{_.p=2,Wh(e,a,s,l)}finally{_.p=v,$.T=m}}function CC(e,a,s,l){var m=$.T;$.T=null;var v=_.p;try{_.p=8,Wh(e,a,s,l)}finally{_.p=v,$.T=m}}function Wh(e,a,s,l){if(qm){var m=Gh(l);if(m===null)Eh(e,a,l,Wm,s),eb(e,l);else if(MC(m,e,a,s,l))l.stopPropagation();else if(eb(e,l),a&4&&-1<kC.indexOf(e)){for(;m!==null;){var v=na(m);if(v!==null)switch(v.tag){case 3:if(v=v.stateNode,v.current.memoizedState.isDehydrated){var M=Yt(v.pendingLanes);if(M!==0){var L=v;for(L.pendingLanes|=2,L.entangledLanes|=2;M;){var Q=1<<31-fe(M);L.entanglements[1]|=Q,M&=~Q}Bi(v),(on&6)===0&&(Nm=Ye()+500,vf(0))}}break;case 31:case 13:L=Fs(v,2),L!==null&&as(L,v,2),Rm(),qh(v,2)}if(v=Gh(l),v===null&&Eh(e,a,l,Wm,s),v===m)break;m=v}m!==null&&l.stopPropagation()}else Eh(e,a,l,null,s)}}function Gh(e){return e=Vn(e),Vh(e)}var Wm=null;function Vh(e){if(Wm=null,e=mn(e),e!==null){var a=u(e);if(a===null)e=null;else{var s=a.tag;if(s===13){if(e=f(a),e!==null)return e;e=null}else if(s===31){if(e=h(a),e!==null)return e;e=null}else if(s===3){if(a.stateNode.current.memoizedState.isDehydrated)return a.tag===3?a.stateNode.containerInfo:null;e=null}else a!==e&&(e=null)}}return Wm=e,null}function Jy(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(_t()){case tt:return 2;case pe:return 8;case Ne:case Be:return 32;case Oe:return 268435456;default:return 32}default:return 32}}var Kh=!1,Rl=null,jl=null,El=null,kf=new Map,Mf=new Map,Dl=[],kC="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 eb(e,a){switch(e){case"focusin":case"focusout":Rl=null;break;case"dragenter":case"dragleave":jl=null;break;case"mouseover":case"mouseout":El=null;break;case"pointerover":case"pointerout":kf.delete(a.pointerId);break;case"gotpointercapture":case"lostpointercapture":Mf.delete(a.pointerId)}}function Af(e,a,s,l,m,v){return e===null||e.nativeEvent!==v?(e={blockedOn:a,domEventName:s,eventSystemFlags:l,nativeEvent:v,targetContainers:[m]},a!==null&&(a=na(a),a!==null&&Xy(a)),e):(e.eventSystemFlags|=l,a=e.targetContainers,m!==null&&a.indexOf(m)===-1&&a.push(m),e)}function MC(e,a,s,l,m){switch(a){case"focusin":return Rl=Af(Rl,e,a,s,l,m),!0;case"dragenter":return jl=Af(jl,e,a,s,l,m),!0;case"mouseover":return El=Af(El,e,a,s,l,m),!0;case"pointerover":var v=m.pointerId;return kf.set(v,Af(kf.get(v)||null,e,a,s,l,m)),!0;case"gotpointercapture":return v=m.pointerId,Mf.set(v,Af(Mf.get(v)||null,e,a,s,l,m)),!0}return!1}function tb(e){var a=mn(e.target);if(a!==null){var s=u(a);if(s!==null){if(a=s.tag,a===13){if(a=f(s),a!==null){e.blockedOn=a,Es(e.priority,function(){Zy(s)});return}}else if(a===31){if(a=h(s),a!==null){e.blockedOn=a,Es(e.priority,function(){Zy(s)});return}}else if(a===3&&s.stateNode.current.memoizedState.isDehydrated){e.blockedOn=s.tag===3?s.stateNode.containerInfo:null;return}}}e.blockedOn=null}function Gm(e){if(e.blockedOn!==null)return!1;for(var a=e.targetContainers;0<a.length;){var s=Gh(e.nativeEvent);if(s===null){s=e.nativeEvent;var l=new s.constructor(s.type,s);ni=l,s.target.dispatchEvent(l),ni=null}else return a=na(s),a!==null&&Xy(a),e.blockedOn=s,!1;a.shift()}return!0}function nb(e,a,s){Gm(e)&&s.delete(a)}function AC(){Kh=!1,Rl!==null&&Gm(Rl)&&(Rl=null),jl!==null&&Gm(jl)&&(jl=null),El!==null&&Gm(El)&&(El=null),kf.forEach(nb),Mf.forEach(nb)}function Vm(e,a){e.blockedOn===a&&(e.blockedOn=null,Kh||(Kh=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,AC)))}var Km=null;function ab(e){Km!==e&&(Km=e,t.unstable_scheduleCallback(t.unstable_NormalPriority,function(){Km===e&&(Km=null);for(var a=0;a<e.length;a+=3){var s=e[a],l=e[a+1],m=e[a+2];if(typeof l!="function"){if(Vh(l||s)===null)continue;break}var v=na(s);v!==null&&(e.splice(a,3),a-=3,vl(v,{pending:!0,data:m,method:s.method,action:l},l,m))}}))}function nd(e){function a(Q){return Vm(Q,e)}Rl!==null&&Vm(Rl,e),jl!==null&&Vm(jl,e),El!==null&&Vm(El,e),kf.forEach(a),Mf.forEach(a);for(var s=0;s<Dl.length;s++){var l=Dl[s];l.blockedOn===e&&(l.blockedOn=null)}for(;0<Dl.length&&(s=Dl[0],s.blockedOn===null);)tb(s),s.blockedOn===null&&Dl.shift();if(s=(e.ownerDocument||e).$$reactFormReplay,s!=null)for(l=0;l<s.length;l+=3){var m=s[l],v=s[l+1],M=m[De]||null;if(typeof v=="function")M||ab(s);else if(M){var L=null;if(v&&v.hasAttribute("formAction")){if(m=v,M=v[De]||null)L=M.formAction;else if(Vh(m)!==null)continue}else L=M.action;typeof L=="function"?s[l+1]=L:(s.splice(l,3),l-=3),ab(s)}}}function rb(){function e(v){v.canIntercept&&v.info==="react-transition"&&v.intercept({handler:function(){return new Promise(function(M){return m=M})},focusReset:"manual",scroll:"manual"})}function a(){m!==null&&(m(),m=null),l||setTimeout(s,20)}function s(){if(!l&&!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 l=!1,m=null;return navigation.addEventListener("navigate",e),navigation.addEventListener("navigatesuccess",a),navigation.addEventListener("navigateerror",a),setTimeout(s,100),function(){l=!0,navigation.removeEventListener("navigate",e),navigation.removeEventListener("navigatesuccess",a),navigation.removeEventListener("navigateerror",a),m!==null&&(m(),m=null)}}}function Qh(e){this._internalRoot=e}Qm.prototype.render=Qh.prototype.render=function(e){var a=this._internalRoot;if(a===null)throw Error(o(409));var s=a.current,l=Ts();Qy(s,l,e,a,null,null)},Qm.prototype.unmount=Qh.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var a=e.containerInfo;Qy(e.current,2,null,e,null,null),Rm(),a[Ke]=null}};function Qm(e){this._internalRoot=e}Qm.prototype.unstable_scheduleHydration=function(e){if(e){var a=bn();e={blockedOn:null,target:e,priority:a};for(var s=0;s<Dl.length&&a!==0&&a<Dl[s].priority;s++);Dl.splice(s,0,e),s===0&&tb(e)}};var sb=n.version;if(sb!=="19.2.7")throw Error(o(527,sb,"19.2.7"));_.findDOMNode=function(e){var a=e._reactInternals;if(a===void 0)throw typeof e.render=="function"?Error(o(188)):(e=Object.keys(e).join(","),Error(o(268,e)));return e=y(a),e=e!==null?w(e):null,e=e===null?null:e.stateNode,e};var NC={bundleType:0,version:"19.2.7",rendererPackageName:"react-dom",currentDispatcherRef:$,reconcilerVersion:"19.2.7"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Ym=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Ym.isDisabled&&Ym.supportsFiber)try{ee=Ym.inject(NC),he=Ym}catch{}}return Tf.createRoot=function(e,a){if(!c(e))throw Error(o(299));var s=!1,l="",m=bm,v=wm,M=Eu;return a!=null&&(a.unstable_strictMode===!0&&(s=!0),a.identifierPrefix!==void 0&&(l=a.identifierPrefix),a.onUncaughtError!==void 0&&(m=a.onUncaughtError),a.onCaughtError!==void 0&&(v=a.onCaughtError),a.onRecoverableError!==void 0&&(M=a.onRecoverableError)),a=Vy(e,1,!1,null,null,s,l,null,m,v,M,rb),e[Ke]=a.current,jh(e),new Qh(a)},Tf.hydrateRoot=function(e,a,s){if(!c(e))throw Error(o(299));var l=!1,m="",v=bm,M=wm,L=Eu,Q=null;return s!=null&&(s.unstable_strictMode===!0&&(l=!0),s.identifierPrefix!==void 0&&(m=s.identifierPrefix),s.onUncaughtError!==void 0&&(v=s.onUncaughtError),s.onCaughtError!==void 0&&(M=s.onCaughtError),s.onRecoverableError!==void 0&&(L=s.onRecoverableError),s.formState!==void 0&&(Q=s.formState)),a=Vy(e,1,!0,a,s??null,l,m,Q,v,M,L,rb),a.context=Ky(null),s=a.current,l=Ts(),l=ht(l),m=xa(l),m.callback=null,Sa(s,m,l),s=l,a.current.lanes=s,Wn(a,s),Bi(a),e[Ke]=a.current,jh(e),new Qm(a)},Tf.version="19.2.7",Tf}var bb;function yk(){if(bb)return Jh.exports;bb=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(),Jh.exports=vk(),Jh.exports}var bk=yk();const wk="https://otbyfkjxrkngvjziawki.supabase.co",xk="sb_publishable_NpUs0RDJH2YnllsqTKO6TQ_1jTdSsNQ",Sk={getItem:()=>null,setItem:()=>{},removeItem:()=>{}},wb=typeof window<"u"&&!!window.liveDesk,Et=fk(wk,xk,{auth:{autoRefreshToken:!0,persistSession:!wb,storage:wb?Sk:void 0,detectSessionInUrl:!0,flowType:"pkce",storageKey:"livedesk.mindexec.supabase.auth"}}),Ck=new Set(["browserLanguage","platform","online","viewport","timezone","screen"]),kk={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])=>Ck.has(n)&&r!==void 0))}};function Mk(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 Ak(t=kk){return t.collect()}async function Nk(t,n="livedesk"){const{data:r,error:o}=await Et.from("app_admins").select("role").eq("user_id",t).limit(1);if(o)throw o;const c=r?.[0]?.role||"user";if(c!=="owner"){const{error:A}=await Et.rpc("register_product_access",{p_product_key:n,p_access_type:"free"});if(A)throw A}const[u,f,h]=await Promise.all([Et.from("products").select("id, product_key, name, description, sort_order").order("sort_order"),Et.from("product_admins").select("product_id, role").eq("user_id",t),Et.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(A=>String(A.product_id)),w=(h.data||[]).map(A=>String(A.product_id)),b=c==="owner",x=b?g.map(A=>A.id):[...new Set([...y,...w])];return{products:g,access:{userId:t,globalRole:c,accessibleProductIds:x,managedProductIds:b?g.map(A=>A.id):y,canViewAllProducts:b,canViewAllPrivatePosts:b,canManageAllProducts:b,canCreateAnnouncements:b||y.length>0}}}async function Tk(t=""){const{data:n,error:r}=await Et.rpc("search_support_posts",{p_query:t.trim()||null,p_limit:250});if(r)throw r;return n||[]}async function Rk(t){const{data:n,error:r}=await Et.from("support_attachments").select("*").eq("post_id",t).order("created_at");if(r)throw r;const o=n||[];return Promise.all(o.map(async c=>{const u=await Et.storage.from("support-attachments").createSignedUrl(c.storage_path,3600);return{...c,signed_url:u.data?.signedUrl||void 0}}))}async function jk(){const{data:t,error:n}=await Et.from("support_notifications").select("*").order("created_at",{ascending:!1}).limit(30);if(n)throw n;return t||[]}async function Ek(t){const{error:n}=await Et.rpc("mark_support_notification_read",{p_notification_id:t});if(n)throw n}async function xb(t){const{data:n,error:r}=await Et.from("support_comments").select("*").eq("post_id",t).order("created_at");if(r)throw r;return n||[]}async function Dk(t){const{data:n,error:r}=await Et.from("support_votes").select("post_id").eq("user_id",t);if(r)throw r;return new Set((n||[]).map(o=>String(o.post_id)))}async function Ik(t){const{data:n,error:r}=await Et.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?Ak():{}});if(r)throw r;const o=Array.isArray(n)?n[0]?.post_id:n?.post_id;if(!o)throw new Error("Support post was not created.");return String(o)}const Lk=new Set(["image/png","image/jpeg","image/webp","text/plain","text/markdown","application/json","application/pdf"]);async function _k(t,n){if(!Lk.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",o=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`,c=`${t}/${o}-${r}`,u=await Et.storage.from("support-attachments").upload(c,n,{contentType:n.type,upsert:!1});if(u.error)throw u.error;const{data:f,error:h}=await Et.rpc("add_support_attachment",{p_post_id:t,p_storage_path:c,p_file_name:r,p_mime_type:n.type,p_size_bytes:n.size});if(h)throw await Et.storage.from("support-attachments").remove([c]),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 Fk(t,n,r,o){const{error:c}=await Et.rpc("update_support_post",{p_post_id:t,p_title:n,p_body:r,p_visibility:o});if(c)throw c}async function Pk(t,n){const{error:r}=await Et.rpc("add_support_comment",{p_post_id:t,p_body:n});if(r)throw r}async function Ok(t){const{data:n,error:r}=await Et.rpc("toggle_support_vote",{p_post_id:t});if(r)throw r;const o=Array.isArray(n)?n[0]:n;return{voted:!!o?.voted,totalVotes:Number(o?.total_votes||0)}}async function Bk(t,n){const{error:r}=await Et.rpc("change_support_post_status",{p_post_id:t,p_target_status:n});if(r)throw r}async function Hk(t){const{error:n}=await Et.rpc("set_support_post_hidden",{p_post_id:t,p_hidden:!0});if(n)throw n}async function zk(t,n){const{error:r}=await Et.rpc("set_support_post_locked",{p_post_id:t,p_locked:n});if(r)throw r}async function $k(t,n){const{error:r}=await Et.rpc("set_support_post_pinned",{p_post_id:t,p_pinned:n});if(r)throw r}async function Uk(t,n){const{error:r}=await Et.rpc("mark_support_duplicate",{p_post_id:t,p_duplicate_of_post_id:n});if(r)throw r}async function qk(t,n){const{error:r}=await Et.rpc("accept_support_answer",{p_post_id:t,p_comment_id:n});if(r)throw r}async function Wk(t,n=!0){const{error:r}=await Et.rpc("hide_support_comment",{p_comment_id:t,p_hidden:n});if(r)throw r}const Og=[{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"}],Gk=[{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"}],Vk={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"]},Kk={type:"all",product:"",status:"all",visibility:"all",sort:"recent",query:""};function ng(){if(typeof window>"u")return Kk;const t=new URLSearchParams(window.location.search),n=window.location.pathname.match(/^\/support\/(questions|issues|features|announcements)$/)?.[1],r=t.get("type")||n||"",o=r==="questions"||r==="question"?"question":r==="issues"||r==="issue"?"issue":r==="features"||r==="feature"?"feature":r==="announcements"||r==="announcement"?"announcement":"all",c=t.get("visibility"),u=t.get("sort");return{type:o,product:t.get("product")||"",status:t.get("status")||"all",visibility:c==="public"||c==="private"?c:"all",sort:u==="votes"||u==="newest"?u:"recent",query:t.get("q")||""}}function Qk(t){return t==="all"?"":t==="question"?"questions":t==="issue"?"issues":t==="feature"?"features":"announcements"}function Yk(t,n){const r={...t,...n},o=new URLSearchParams;r.product&&o.set("product",r.product),r.status!=="all"&&o.set("status",r.status),r.visibility!=="all"&&o.set("visibility",r.visibility),r.sort!=="recent"&&o.set("sort",r.sort),r.query&&o.set("q",r.query);const c=Qk(r.type),u=o.toString();return`/support${c?`/${c}`:""}${u?`?${u}`:""}`}function Xm(t){const n=new Date(t);return Number.isFinite(n.getTime())?n.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"}):t}function ag(t){return t.replaceAll("-"," ").replace(/\b\w/g,n=>n.toUpperCase())}function Sb(t){return t==="question"?IC:t==="issue"?Sx:t==="feature"?LC:_C}function Cb(t){return Og.find(n=>n.id===t)?.shortLabel||t}function rg(t,n){return t.find(r=>r.id===n)?.name||"Product"}function rs(t){const n=Mk(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 _x({session:t,currentProductKey:n="livedesk",appVersion:r="",onSignIn:o}){const[c,u]=d.useState(()=>ng()),[f,h]=d.useState(null),[g,y]=d.useState([]),[w,b]=d.useState([]),[x,A]=d.useState(""),[k,N]=d.useState([]),[E,D]=d.useState([]),[T,F]=d.useState([]),[O,P]=d.useState(()=>new Set),[z,I]=d.useState(!0),[X,se]=d.useState(""),[Z,G]=d.useState(""),[K,me]=d.useState(!1),[V,ne]=d.useState(!1),[$,_]=d.useState(""),[ie,be]=d.useState(()=>ng().query),[H,te]=d.useState(!1),[le,Ce]=d.useState(!1),[Ae,_e]=d.useState(""),[ue,He]=d.useState(""),[ze,et]=d.useState("free"),[Xe,Ze]=d.useState(""),[Ue,Y]=d.useState(""),[Se,ye]=d.useState("admin"),[je,$e]=d.useState(""),[B,lt]=d.useState(""),[Nt,Ht]=d.useState(""),[ke,qe]=d.useState(""),[Ye,_t]=d.useState(""),[tt,pe]=d.useState([]),[Ne,Be]=d.useState({productId:"",postType:"question",title:"",body:"",visibility:"public",includeEnvironment:!0,files:[]}),Oe=d.useCallback(q=>{const at={...c,...q};u(at),typeof window<"u"&&window.history.pushState({},"",Yk(c,q))},[c]);d.useEffect(()=>{const q=()=>u(ng());return window.addEventListener("popstate",q),()=>window.removeEventListener("popstate",q)},[]);const We=d.useCallback(async()=>{const q=await Tk(c.query);return b(q),t?.user.id&&P(await Dk(t.user.id)),q},[c.query,t?.user.id]),Rt=d.useCallback(async()=>{if(!t?.user.id){h(null),y([]),b([]),A(""),F([]),I(!1);return}I(!0),G("");try{const q=await Nk(t.user.id,n);h(q.access),y(q.products),await We(),F(await jk())}catch(q){G(rs(q))}finally{I(!1)}},[n,We,t?.user.id]);d.useEffect(()=>{Rt()},[Rt]);const ee=d.useMemo(()=>f?f.canViewAllProducts?g:g.filter(q=>f.accessibleProductIds.includes(q.id)):[],[f,g]),he=d.useMemo(()=>{const q=ee.find(at=>at.product_key===c.product);return f?.canViewAllProducts&&!c.product||c.product==="all"&&f?.canViewAllProducts?"all":q?q.product_key:ee.some(at=>at.product_key===n)?n:ee[0]?.product_key||""},[f?.canViewAllProducts,ee,n,c.product]),Fe=he==="all"?"":ee.find(q=>q.product_key===he)?.id||"",fe=d.useMemo(()=>{const q=new Map(g.map(ht=>[ht.id,ht.product_key]));return[...w.filter(ht=>c.type!=="all"&&ht.post_type!==c.type||he!=="all"&&Fe&&ht.product_id!==Fe||c.status==="needs-response"&&!["open","needs-info"].includes(ht.status)||c.status!=="all"&&c.status!=="needs-response"&&ht.status!==c.status||c.visibility!=="all"&&ht.visibility!==c.visibility?!1:q.has(ht.product_id))].sort((ht,Zt)=>c.sort==="votes"?Zt.vote_count-ht.vote_count||Zt.updated_at.localeCompare(ht.updated_at):c.sort==="newest"?Zt.created_at.localeCompare(ht.created_at):Number(Zt.is_pinned)-Number(ht.is_pinned)||Zt.updated_at.localeCompare(ht.updated_at))},[w,g,c.sort,c.status,c.type,c.visibility,Fe,he]),xe=fe.find(q=>q.id===x)||fe[0]||null,nt=!!(xe&&f&&(f.canViewAllProducts||f.managedProductIds.includes(xe.product_id))),ct=!!(xe&&t?.user.id===xe.author_id)||nt;d.useEffect(()=>{if(!xe){A(""),N([]),ne(!1);return}xe.id!==x&&A(xe.id)},[xe,x]),d.useEffect(()=>{let q=!0;return x?(xb(x).then(at=>{q&&N(at)}).catch(at=>{q&&G(rs(at))}),Rk(x).then(at=>{q&&D(at)}).catch(at=>{q&&G(rs(at))}),()=>{q=!1}):(N([]),D([]),()=>{q=!1})},[x]),d.useEffect(()=>{!Ne.productId&&ee[0]&&Be(q=>({...q,productId:Fe||ee[0].id}))},[ee,Ne.productId,Fe]),d.useEffect(()=>{be(c.query)},[c.query]),d.useEffect(()=>{!ue&&ee[0]&&He(ee[0].id),!Ue&&ee[0]&&Y(ee[0].id)},[ee,ue,Ue]);const ft=q=>{xe&&b(at=>at.map(ht=>ht.id===xe.id?{...ht,...q}:ht))},dt=async q=>{if(q.preventDefault(),!(!t||!Ne.productId)){se("create"),G("");try{const at=await Ik({productId:Ne.productId,postType:Ne.postType,title:Ne.title,body:Ne.body,visibility:Ne.postType==="announcement"?"public":Ne.visibility,appVersion:r,includeEnvironment:Ne.postType==="issue"&&Ne.includeEnvironment});for(const Zt of tt)await _k(at,Zt);const ht=await We();me(!1),pe([]),Be(Zt=>({...Zt,title:"",body:"",files:[]})),A(at),ht.some(Zt=>Zt.id===at)||await Rt()}catch(at){G(rs(at))}finally{se("")}}},Dt=async q=>{if(q.preventDefault(),!!xe){se("edit"),G("");try{await Fk(xe.id,xe.title,xe.body,xe.visibility),ne(!1),await We()}catch(at){G(rs(at))}finally{se("")}}},Yt=async q=>{if(q.preventDefault(),!(!xe||!$.trim())){se("comment"),G("");try{await Pk(xe.id,$),_(""),N(await xb(xe.id)),await We()}catch(at){G(rs(at))}finally{se("")}}},cn=async()=>{if(!(!xe||xe.post_type!=="feature")){se("vote"),G("");try{const q=await Ok(xe.id);P(at=>{const ht=new Set(at);return q.voted?ht.add(xe.id):ht.delete(xe.id),ht}),ft({vote_count:q.totalVotes})}catch(q){G(rs(q))}finally{se("")}}},Xt=async q=>{if(xe){se("status"),G("");try{await Bk(xe.id,q),ft({status:q}),await We()}catch(at){G(rs(at))}finally{se("")}}},oa=async()=>{if(!(!xe||!window.confirm("Hide this Support post from the board?"))){se("hide"),G("");try{await Hk(xe.id),A(""),await We()}catch(q){G(rs(q))}finally{se("")}}},Na=async()=>{if(xe){se("lock"),G("");try{await zk(xe.id,!xe.is_locked),ft({is_locked:!xe.is_locked}),await We()}catch(q){G(rs(q))}finally{se("")}}},Pn=async()=>{if(xe){se("pin"),G("");try{await $k(xe.id,!xe.is_pinned),ft({is_pinned:!xe.is_pinned}),await We()}catch(q){G(rs(q))}finally{se("")}}},Wn=async q=>{if(xe){se(`accept-${q}`),G("");try{await qk(xe.id,q),ft({accepted_comment_id:q,status:xe.post_type==="question"?"answered":xe.status}),await We()}catch(at){G(rs(at))}finally{se("")}}},la=async()=>{if(!(!xe||!ke||ke===xe.id)){se("duplicate"),G("");try{await Uk(xe.id,ke),A(""),qe(""),await We()}catch(q){G(rs(q))}finally{se("")}}},Pe=async q=>{if(!q.read_at)try{await Ek(q.id),F(at=>at.map(ht=>ht.id===q.id?{...ht,read_at:new Date().toISOString()}:ht))}catch(at){G(rs(at))}q.post_id&&A(q.post_id),te(!1)};return t?z&&!f?i.jsxs("section",{className:"support-page support-loading",children:[i.jsx(hd,{className:"support-spin",size:23})," Loading Support Board..."]}):i.jsxs("section",{className:"support-page",children:[i.jsx("header",{className:"support-page-header support-page-actions-only",children:i.jsxs("div",{className:"support-header-actions",children:[i.jsxs("div",{className:"support-notification-wrap",children:[i.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>te(q=>!q),title:"Notifications",children:[i.jsx(jC,{size:16})," ",T.filter(q=>!q.read_at).length>0&&i.jsx("b",{children:T.filter(q=>!q.read_at).length})]}),H&&i.jsxs("div",{className:"support-notification-popover",children:[i.jsx("strong",{children:"Notifications"}),T.length===0?i.jsx("span",{className:"support-muted",children:"No notifications yet."}):T.map(q=>i.jsxs("button",{type:"button",className:q.read_at?"":"unread",onClick:()=>{Pe(q)},children:[i.jsx("b",{children:q.title}),i.jsx("span",{children:q.body}),i.jsx("small",{children:Xm(q.created_at)})]},q.id))]})]}),f?.canViewAllProducts&&i.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>Ce(q=>!q),children:[i.jsx(Aa,{size:16})," Admin"]}),i.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{Rt()},disabled:z,children:[i.jsx(hd,{size:16,className:z?"support-spin":""})," Refresh"]}),i.jsxs("button",{className:"support-primary-button",type:"button",onClick:()=>me(!0),disabled:ee.length===0,children:[i.jsx(Yh,{size:17})," New request"]})]})}),Z&&i.jsxs("div",{className:"support-error",role:"alert",children:[i.jsx(vr,{size:17})," ",i.jsx("span",{children:Z}),i.jsx("button",{type:"button",onClick:()=>G(""),"aria-label":"Dismiss error",children:i.jsx(vr,{size:15})})]}),K&&i.jsxs("form",{className:"support-composer",onSubmit:q=>{dt(q)},children:[i.jsxs("div",{className:"support-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"New Support request"}),i.jsx("strong",{children:"Describe one actionable problem or idea."})]}),i.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>me(!1),"aria-label":"Close composer",children:i.jsx(vr,{size:18})})]}),i.jsxs("div",{className:"support-form-grid",children:[i.jsxs("label",{children:[i.jsx("span",{children:"Product"}),i.jsx("select",{value:Ne.productId,onChange:q=>Be(at=>({...at,productId:q.target.value})),children:ee.map(q=>i.jsx("option",{value:q.id,children:q.name},q.id))})]}),i.jsxs("label",{children:[i.jsx("span",{children:"Type"}),i.jsx("select",{value:Ne.postType,onChange:q=>Be(at=>({...at,postType:q.target.value})),children:Og.filter(q=>q.id!=="announcement"||f?.canCreateAnnouncements).map(q=>i.jsx("option",{value:q.id,children:q.label},q.id))})]}),i.jsxs("label",{className:"support-form-wide",children:[i.jsx("span",{children:"Title"}),i.jsx("input",{required:!0,minLength:3,maxLength:180,value:Ne.title,onChange:q=>Be(at=>({...at,title:q.target.value})),placeholder:"A short, searchable summary"})]}),i.jsxs("label",{className:"support-form-wide",children:[i.jsx("span",{children:Ne.postType==="issue"?"What happened?":Ne.postType==="feature"?"Describe the desired behavior":Ne.postType==="announcement"?"Announcement":"Question"}),i.jsx("textarea",{required:!0,value:Ne.body,onChange:q=>Be(at=>({...at,body:q.target.value})),placeholder:"Include the context another person needs to respond.",rows:6})]}),i.jsxs("label",{children:[i.jsx("span",{children:"Visibility"}),i.jsxs("select",{value:Ne.visibility,disabled:Ne.postType==="announcement",onChange:q=>Be(at=>({...at,visibility:q.target.value})),children:[i.jsx("option",{value:"public",children:"Public"}),i.jsx("option",{value:"private",children:"Private"})]})]}),Ne.postType==="issue"&&i.jsxs("label",{className:"support-checkbox",children:[i.jsx("input",{type:"checkbox",checked:Ne.includeEnvironment,onChange:q=>Be(at=>({...at,includeEnvironment:q.target.checked}))}),i.jsx("span",{children:"Attach safe browser/runtime details"})]}),i.jsxs("label",{className:"support-form-wide",children:[i.jsx("span",{children:"Attachments"}),i.jsx("input",{type:"file",multiple:!0,accept:"image/png,image/jpeg,image/webp,text/plain,text/markdown,application/json,application/pdf",onChange:q=>pe(Array.from(q.target.files||[]).slice(0,5))}),i.jsx("small",{className:"support-muted",children:"Up to 5 files, 10 MB each. Images, text, JSON, Markdown, and PDF."})]})]}),i.jsxs("div",{className:"support-composer-footer",children:[i.jsx("span",{children:tt.length>0?`${tt.length} attachment${tt.length===1?"":"s"} selected.`:"Private posts are visible only to you and the product support staff."}),i.jsxs("button",{className:"support-primary-button",type:"submit",disabled:X==="create",children:[i.jsx(Vf,{size:16})," ",X==="create"?"Submitting...":"Submit request"]})]})]}),i.jsxs("div",{className:"support-tabs",role:"tablist","aria-label":"Support post type",children:[i.jsx("button",{className:c.type==="all"?"active":"",type:"button",onClick:()=>Oe({type:"all"}),children:"All"}),Og.map(q=>{const at=Sb(q.id);return i.jsxs("button",{className:c.type===q.id?"active":"",type:"button",onClick:()=>Oe({type:q.id}),children:[i.jsx(at,{size:15})," ",q.label]},q.id)})]}),le&&f?.canViewAllProducts&&i.jsxs("section",{className:"support-admin-panel",children:[i.jsxs("div",{className:"support-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Owner controls"}),i.jsx("strong",{children:"Products and access are managed by immutable user IDs behind these email lookup forms."})]}),i.jsx(Aa,{size:19})]}),i.jsxs("div",{className:"support-admin-grid",children:[i.jsxs("form",{onSubmit:q=>{},children:[i.jsx("strong",{children:"Grant product access"}),i.jsx("input",{type:"email",required:!0,placeholder:"User email",value:Ae,onChange:q=>_e(q.target.value)}),i.jsx("select",{value:ue,onChange:q=>He(q.target.value),children:ee.map(q=>i.jsx("option",{value:q.id,children:q.name},q.id))}),i.jsxs("select",{value:ze,onChange:q=>et(q.target.value),children:[i.jsx("option",{value:"free",children:"Free"}),i.jsx("option",{value:"user",children:"User"}),i.jsx("option",{value:"paid",children:"Paid"}),i.jsx("option",{value:"beta",children:"Beta"}),i.jsx("option",{value:"staff",children:"Staff"})]}),i.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:Ye==="access",children:[i.jsx(qi,{size:15})," Grant access"]})]}),i.jsxs("form",{onSubmit:q=>{},children:[i.jsx("strong",{children:"Assign product admin"}),i.jsx("input",{type:"email",required:!0,placeholder:"Admin email",value:Xe,onChange:q=>Ze(q.target.value)}),i.jsx("select",{value:Ue,onChange:q=>Y(q.target.value),children:ee.map(q=>i.jsx("option",{value:q.id,children:q.name},q.id))}),i.jsxs("select",{value:Se,onChange:q=>ye(q.target.value),children:[i.jsx("option",{value:"admin",children:"Admin"}),i.jsx("option",{value:"support",children:"Support"}),i.jsx("option",{value:"moderator",children:"Moderator"})]}),i.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:Ye==="product-admin",children:[i.jsx(Aa,{size:15})," Assign admin"]})]}),i.jsxs("form",{onSubmit:q=>{},children:[i.jsx("strong",{children:"Add a product"}),i.jsx("input",{required:!0,pattern:"[a-z0-9][a-z0-9_-]{1,48}",placeholder:"product-key",value:je,onChange:q=>$e(q.target.value)}),i.jsx("input",{required:!0,placeholder:"Product name",value:B,onChange:q=>lt(q.target.value)}),i.jsx("input",{placeholder:"Description",value:Nt,onChange:q=>Ht(q.target.value)}),i.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:Ye==="product",children:[i.jsx(Yh,{size:15})," Add product"]})]})]})]}),i.jsxs("form",{className:"support-search-bar",onSubmit:q=>{q.preventDefault(),Oe({query:ie.trim()})},children:[i.jsxs("label",{children:[i.jsx("span",{children:"Search Support"}),i.jsx("input",{value:ie,onChange:q=>be(q.target.value),placeholder:"Search titles and request details"})]}),i.jsxs("button",{className:"support-secondary-button",type:"submit",children:[i.jsx(ib,{size:15})," Search"]}),c.query&&i.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{be(""),Oe({query:""})},"aria-label":"Clear search",children:i.jsx(vr,{size:16})})]}),i.jsxs("div",{className:"support-filter-bar",children:[i.jsxs("div",{className:"support-filter-title",children:[i.jsx(ib,{size:16}),i.jsx("span",{children:"Filter"})]}),i.jsxs("label",{children:[i.jsx("span",{children:"Product"}),i.jsxs("select",{value:he,onChange:q=>Oe({product:q.target.value}),disabled:!f?.canViewAllProducts&&ee.length<=1,children:[i.jsx("option",{value:"all",children:"All products"}),ee.map(q=>i.jsx("option",{value:q.product_key,children:q.name},q.id))]})]}),i.jsxs("label",{children:[i.jsx("span",{children:"Status"}),i.jsx("select",{value:c.status,onChange:q=>Oe({status:q.target.value}),children:Gk.map(q=>i.jsx("option",{value:q.id,children:q.label},q.id))})]}),i.jsxs("label",{children:[i.jsx("span",{children:"Visibility"}),i.jsxs("select",{value:c.visibility,onChange:q=>Oe({visibility:q.target.value}),children:[i.jsx("option",{value:"all",children:"All visibility"}),i.jsx("option",{value:"public",children:"Public"}),i.jsx("option",{value:"private",children:"Private"})]})]}),i.jsxs("label",{children:[i.jsx("span",{children:"Sort"}),i.jsxs("select",{value:c.sort,onChange:q=>Oe({sort:q.target.value}),children:[i.jsx("option",{value:"recent",children:"Recently updated"}),i.jsx("option",{value:"newest",children:"Newest"}),i.jsx("option",{value:"votes",children:"Most votes"})]})]})]}),f?.canViewAllProducts&&i.jsxs("div",{className:"support-admin-shortcuts",children:[i.jsxs("span",{children:[i.jsx(Aa,{size:15})," Owner view"]}),i.jsx("button",{type:"button",onClick:()=>Oe({status:"needs-response"}),children:"Needs response"}),i.jsx("button",{type:"button",onClick:()=>Oe({visibility:"private"}),children:"Private requests"}),i.jsx("button",{type:"button",onClick:()=>Oe({type:"feature",status:"all",sort:"votes"}),children:"High-vote features"})]}),i.jsxs("div",{className:"support-board-layout",children:[i.jsxs("section",{className:"support-post-list","aria-label":"Support posts",children:[i.jsxs("div",{className:"support-list-heading",children:[i.jsxs("span",{children:[fe.length," request",fe.length===1?"":"s"]}),i.jsx("small",{children:he==="all"?"All products":rg(ee,Fe)})]}),fe.length===0?i.jsxs("div",{className:"support-list-empty",children:[i.jsx(Hf,{size:25}),i.jsx("strong",{children:"No posts match these filters."}),i.jsx("span",{children:"Start with a focused question, issue report, or feature request."}),ee.length>0&&i.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>me(!0),children:[i.jsx(Yh,{size:16})," Create the first request"]})]}):fe.map(q=>{const at=Sb(q.post_type);return i.jsxs("button",{type:"button",className:`support-post-row ${q.id===xe?.id?"active":""}`,onClick:()=>{A(q.id),ne(!1)},children:[i.jsx("span",{className:"support-post-row-icon",children:i.jsx(at,{size:17})}),i.jsxs("span",{className:"support-post-row-copy",children:[i.jsxs("span",{className:"support-post-row-meta",children:[i.jsx("b",{children:rg(g,q.product_id)}),i.jsx("em",{children:Cb(q.post_type)}),q.visibility==="private"&&i.jsx(Ui,{size:13})]}),i.jsx("strong",{children:q.title}),i.jsxs("small",{children:[ag(q.status)," · ",Xm(q.updated_at)," · ",q.comment_count," comments"]})]}),q.post_type==="feature"&&i.jsxs("span",{className:"support-vote-count",children:[i.jsx(xx,{size:14})," ",q.vote_count]})]},q.id)})]}),i.jsx("section",{className:"support-post-detail","aria-label":"Support post detail",children:xe?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"support-detail-head",children:[i.jsxs("div",{className:"support-detail-badges",children:[i.jsx("span",{className:"support-product-badge",children:rg(g,xe.product_id)}),i.jsx("span",{className:"support-type-badge",children:Cb(xe.post_type)}),i.jsx("span",{className:`support-status-badge status-${xe.status}`,children:ag(xe.status)}),xe.visibility==="private"&&i.jsxs("span",{className:"support-private-badge",children:[i.jsx(Ui,{size:13})," Private"]})]}),i.jsxs("div",{className:"support-detail-actions",children:[ct&&i.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>ne(q=>!q),title:"Edit post",children:i.jsx(EC,{size:16})}),nt&&i.jsxs(i.Fragment,{children:[i.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{Pn()},disabled:X==="pin",title:xe.is_pinned?"Unpin post":"Pin post",children:i.jsx(ob,{size:16})}),i.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{Na()},disabled:X==="lock",title:xe.is_locked?"Unlock post":"Lock post",children:i.jsx(Ui,{size:16})}),i.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{oa()},disabled:X==="hide",title:"Hide post",children:i.jsx(lb,{size:16})})]})]})]}),V?i.jsxs("form",{className:"support-edit-form",onSubmit:q=>{Dt(q)},children:[i.jsx("input",{value:xe.title,onChange:q=>ft({title:q.target.value}),minLength:3,maxLength:180,required:!0}),i.jsx("textarea",{value:xe.body,onChange:q=>ft({body:q.target.value}),rows:9,required:!0}),i.jsxs("div",{className:"support-edit-actions",children:[i.jsxs("select",{value:xe.visibility,onChange:q=>ft({visibility:q.target.value}),children:[i.jsx("option",{value:"public",children:"Public"}),i.jsx("option",{value:"private",children:"Private"})]}),i.jsxs("button",{className:"support-primary-button",type:"submit",disabled:X==="edit",children:[i.jsx(qi,{size:16})," Save changes"]})]})]}):i.jsxs(i.Fragment,{children:[i.jsx("h3",{children:xe.title}),i.jsx("div",{className:"support-detail-body",children:xe.body.split(`
10
- `).map((q,at)=>i.jsx("p",{children:q||" "},`${xe.id}-body-${at}`))})]}),i.jsxs("div",{className:"support-detail-meta",children:[i.jsxs("span",{children:["Opened ",Xm(xe.created_at)]}),xe.app_version&&i.jsxs("span",{children:["Version ",xe.app_version]}),xe.platform&&i.jsx("span",{children:xe.platform}),xe.is_locked&&i.jsxs("span",{children:[i.jsx(Ui,{size:13})," Locked"]}),xe.is_pinned&&i.jsxs("span",{children:[i.jsx(ob,{size:13})," Pinned"]})]}),i.jsxs("div",{className:"support-detail-controls",children:[xe.post_type==="feature"&&i.jsxs("button",{className:`support-vote-button ${O.has(xe.id)?"voted":""}`,type:"button",onClick:()=>{cn()},disabled:X==="vote",children:[i.jsx(DC,{size:16})," ",O.has(xe.id)?"Voted":"Vote"," ",i.jsx("b",{children:xe.vote_count})]}),nt&&i.jsxs("label",{className:"support-status-control",children:[i.jsx("span",{children:"Change status"}),i.jsx("select",{value:xe.status,onChange:q=>{Xt(q.target.value)},disabled:X==="status",children:(Vk[xe.post_type]||[]).map(q=>i.jsx("option",{value:q,children:ag(q)},q))})]}),nt&&i.jsxs(i.Fragment,{children:[i.jsxs("select",{className:"support-status-control",value:ke,onChange:q=>qe(q.target.value),children:[i.jsx("option",{value:"",children:"Duplicate of..."}),fe.filter(q=>q.id!==xe.id&&q.product_id===xe.product_id).map(q=>i.jsx("option",{value:q.id,children:q.title.slice(0,55)},q.id))]}),i.jsx("button",{className:"support-secondary-button",type:"button",onClick:()=>{la()},disabled:!ke||X==="duplicate",children:"Merge duplicate"})]})]}),E.length>0&&i.jsxs("div",{className:"support-attachments",children:[i.jsx("div",{className:"support-section-heading",children:i.jsxs("div",{children:[i.jsx("span",{children:"Attachments"}),i.jsxs("strong",{children:[E.length," file",E.length===1?"":"s"]})]})}),E.map(q=>i.jsxs("a",{href:q.signed_url,target:"_blank",rel:"noreferrer",children:[i.jsx(mv,{size:14})," ",q.file_name,i.jsxs("small",{children:[Math.ceil(q.size_bytes/1024)," KB"]})]},q.id))]}),i.jsxs("div",{className:"support-comments",children:[i.jsxs("div",{className:"support-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Discussion"}),i.jsxs("strong",{children:[k.length," comment",k.length===1?"":"s"]})]}),xe.is_locked&&i.jsxs("span",{className:"support-locked-label",children:[i.jsx(Ui,{size:14})," Locked"]})]}),k.length===0?i.jsx("p",{className:"support-muted",children:"No response yet. Keep the conversation focused on this request."}):i.jsx("div",{className:"support-comment-list",children:k.map(q=>i.jsxs("article",{className:`support-comment ${q.is_staff_answer?"staff":""} ${xe.accepted_comment_id===q.id?"accepted":""}`,children:[i.jsxs("div",{className:"support-comment-head",children:[i.jsx("strong",{children:q.is_staff_answer?"LiveDesk Support":q.author_id===t.user.id?"You":"Support user"}),q.is_staff_answer&&i.jsxs("span",{children:[i.jsx(Aa,{size:13})," Staff answer"]}),xe.accepted_comment_id===q.id&&i.jsxs("span",{children:[i.jsx(Oa,{size:13})," Accepted"]}),i.jsx("time",{children:Xm(q.created_at)})]}),i.jsx("p",{children:q.body}),i.jsxs("div",{className:"support-comment-actions",children:[(t.user.id===xe.author_id||nt)&&xe.post_type==="question"&&xe.accepted_comment_id!==q.id&&i.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{Wn(q.id)},disabled:X===`accept-${q.id}`,children:[i.jsx(qi,{size:14})," Accept answer"]}),nt&&i.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{Wk(q.id)},title:"Hide comment",children:i.jsx(lb,{size:14})})]})]},q.id))}),!xe.is_locked&&i.jsxs("form",{className:"support-comment-form",onSubmit:q=>{Yt(q)},children:[i.jsx("textarea",{value:$,onChange:q=>_(q.target.value),placeholder:"Add a focused reply...",rows:3}),i.jsxs("button",{className:"support-primary-button",type:"submit",disabled:X==="comment"||!$.trim(),children:[i.jsx(Vf,{size:15})," Reply"]})]})]})]}):i.jsxs("div",{className:"support-detail-empty",children:[i.jsx(Hf,{size:28}),i.jsx("strong",{children:"Select a Support request"}),i.jsx("span",{children:"Its discussion and staff actions will appear here."})]})})]})]}):i.jsx("section",{className:"support-page support-auth-page",children:i.jsxs("div",{className:"support-empty-hero",children:[i.jsx("span",{className:"support-hero-icon",children:i.jsx(Hf,{size:28})}),i.jsx("p",{className:"support-eyebrow",children:"LiveDesk Support"}),i.jsx("h2",{children:"Get help, report issues, and shape the product."}),i.jsx("p",{children:"Sign in to see the products attached to your account and submit a private or public request."}),i.jsxs("button",{className:"support-primary-button",type:"button",onClick:o,children:[i.jsx(Aa,{size:17})," Sign in with Google"]})]})})}function Zm(t){return!!t&&typeof t=="object"}function Fx(t){let n=t;return Zm(n)&&"data"in n&&(n=n.data),Zm(n)&&"session"in n&&(n=n.session),!Zm(n)||typeof n.access_token!="string"||!n.access_token||!Zm(n.user)||typeof n.user.id!="string"||!n.user.id?null:n}function kb(t){return t?.access_token?t.refresh_token?"":"refresh-token-required":"access-token-required"}const Bg=15e3;function Xk(t,n=Bg){const r=Number(t),o=Number.isFinite(Number(n))?Number(n):Bg;return Math.max(250,Math.min(12e4,Math.trunc(Number.isFinite(r)?r:o)))}class Mb 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 Zk(t,n,r){const o=Xk(n),c=new AbortController;let u=!1;const f=()=>{c.signal.aborted||c.abort(t?.reason)};t?.aborted?f():t?.addEventListener("abort",f,{once:!0});const h=setTimeout(()=>{u=!0,c.signal.aborted||c.abort(new Mb(o))},o);try{return await r(c.signal)}catch(g){throw u?new Mb(o):g}finally{clearTimeout(h),t?.removeEventListener("abort",f)}}function jp(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}const $f=5179,qn=Vl(`http://127.0.0.1:${$f}`);function Jk(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 eM(t){const n=t.trim().toLowerCase();return n==="localhost"||n==="127.0.0.1"||n==="::1"||n==="[::1]"}function tM(t){const n=t.trim().toLowerCase();return!n||n==="0.0.0.0"||n==="::"||n==="[::]"}function nM(t){const n=Jk(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 aM(t){return t.includes(":")&&!t.startsWith("[")?`[${t}]`:t}function rM(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 o=new URL(r),c=o.hostname.replace(/^\[|\]$/g,""),u=Number(o.port);return!c||!Number.isInteger(u)||u<1||u>65535||tM(c)?null:{host:c,port:u}}catch{return null}}function Vl(t){const n=String(t||"").trim()||`http://127.0.0.1:${$f}`,r=/^[a-z][a-z\d+.-]*:\/\//i.test(n)?n:`http://${n}`;try{const o=new URL(r);return o.port||(o.port=String($f)),o.hash="",o.search="",o.toString().replace(/\/+$/,"")}catch{return`http://127.0.0.1:${$f}`}}function sM(t){const n=rM(t);return n?Vl(`http://${aM(n.host)}:${$f}`):""}function Ab(t){const r=[t?.endpoint,...Array.isArray(t?.endpoint_candidates)?t.endpoint_candidates:[]].map(o=>sM(String(o||""))).filter(Boolean);return[...new Set(r)]}function Uf(t=qn){if(!(typeof window>"u"||window.location.protocol!=="https:"))try{const n=new URL(t);if(n.protocol!=="http:")return;if(eM(n.hostname))return"loopback";if(nM(n.hostname))return"local"}catch{return}}function Up(t,n=qn){const r=new URL(t,Vl(n));return r.protocol=r.protocol==="https:"?"wss:":"ws:",r.toString()}async function rt(t,n,r=qn){const o=Vl(r),{timeoutMs:c=Bg,signal:u,...f}=n||{},h={...f,headers:{"Content-Type":"application/json",...f.headers||{}},cache:"no-store"},g=Uf(o);return g&&(h.targetAddressSpace=g),Zk(u,c,async y=>{h.signal=y;let w;try{w=await fetch(`${o}${t}`,h)}catch(x){throw!y.aborted&&g?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."):x}let b=null;try{b=await w.json()}catch(x){if(y.aborted)throw x;b=null}if(!w.ok){const x=b&&typeof b=="object"&&"error"in b?String(b.error||""):"";throw new Error(`${w.status} ${x||w.statusText}`)}return b})}async function Px({baseUrl:t=qn,targetRole:n,previousRuntimePid:r=0,allowedStates:o=["running","waiting-auth"],timeoutMs:c=3e4}){const u=Date.now()+c;let f=null;for(;Date.now()<u;){try{const g=await rt("/api/runtime/status",void 0,t),y=String(g.role||"").toLowerCase(),w=String(g.state||"").toLowerCase(),b=Number(g.runtimePid||0),x=r>1?b>1&&b!==r:b>1;if(y===n&&o.map(A=>A.toLowerCase()).includes(w)&&x)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 iM(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 o=r.toString();let c=0;const u=()=>{fetch(o,{cache:"no-store",mode:"no-cors"}).then(()=>window.location.replace(o)).catch(()=>{if(c+=1,c>=n){window.location.replace(o);return}window.setTimeout(u,250)})};u()}function Ox(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 Sp(t){await navigator.clipboard.writeText(t)}function Bx({size:t=22}){return i.jsxs("svg",{width:t,height:t,viewBox:"0 0 28 28",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[i.jsx("rect",{x:"2.5",y:"4",width:"14",height:"9",rx:"1.5",stroke:"currentColor",strokeWidth:"1.7",opacity:"0.42"}),i.jsx("path",{d:"M7 16v1.5h5",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",opacity:"0.42"}),i.jsx("rect",{x:"10.5",y:"2.5",width:"14",height:"9",rx:"1.5",stroke:"currentColor",strokeWidth:"1.7",opacity:"0.62"}),i.jsx("path",{d:"M15 14.5V16h5",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",opacity:"0.62"}),i.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"}),i.jsx("path",{d:"M12 21v1.5H9.5M16 21v1.5h2.5M9.5 22.5h9",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round"})]})}const Hx={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."},Hg={en:Hx,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 qp(t){const n=t?[t]:typeof navigator>"u"?["en"]:navigator.languages?.length?navigator.languages:[navigator.language];for(const r of n){const o=String(r||"").trim(),c=o.toLowerCase();if(!c)continue;if(c.startsWith("zh-tw")||c.startsWith("zh-hk"))return"zh-TW";if(c.startsWith("zh"))return"zh";if(c.startsWith("pt"))return"pt-BR";const u=c.split("-")[0];if(Hg[o])return o;if(Hg[u])return u}return"en"}function Ep(t,n){const r=qp(n);return Hg[r]?.[t]||Hx[t]}function zg(t,n,r){return`${t}
11
- ${Ep(n,r)}`}const zx={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"},oM={en:zx,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"}},$x={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"},lM={en:$x,ko:{eyebrow:"컴퓨터 역할",title:"이 컴퓨터를 Hub로 사용할까요?",description:"Hub는 Client 컴퓨터를 연결하고 관리합니다.",restartNotice:"다른 컴퓨터가 Hub라면 이 컴퓨터가 새 Hub가 됩니다.",cancel:"취소",confirm:"Hub로 설정",closeLabel:"Hub 설정 확인 닫기"}};function cM(t){const n=qp(t);return oM[n]||zx}function uM(t){const n=qp(t);return lM[n]||$x}function dM(t=[]){return[...new Set(t.filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean))]}function fM(t=[],n=new Set){return t.find(r=>!n.has(r))||""}const mM=[{id:"docs",label:"Doc",icon:Rp},{id:"support",label:"Support",icon:Hf},{id:"pricing",label:"Pricing",icon:zf},{id:"settings",label:"Settings",icon:pv}],Nb=[0,1e3,2e3,5e3,1e4,2e4,3e4];function pM(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 Lc(t,n=!1){const r=n?"":sessionStorage.getItem("livedesk.client.csrf");if(r)return r;const o=await fetch(`${t}/api/runtime/status`,{cache:"no-store"}),c=await o.json().catch(()=>({}));if(!o.ok)throw new Error(c.error||`Client runtime returned HTTP ${o.status}.`);const u=String(c.csrfToken||"");return u&&sessionStorage.setItem("livedesk.client.csrf",u),u}function $g(t){return`${Math.max(0,Math.min(100,Number(t||0))).toFixed(0)}%`}function sg(t){return Number.isFinite(t)?`${Math.max(0,Math.min(100,Number(t))).toFixed(0)}%`:"—"}function Ux(t){return Number.isFinite(t)?$g(Number(t)):"0%"}function Wc(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 Tb(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 hM(t,n){const r=Number(t||0)/1073741824,o=Number(n||0)/1024**3;return o>0?`${r.toFixed(1)} / ${o.toFixed(1)} GB`:"Checking..."}function gM(t,n){return!Number.isFinite(n)||Number(n)<=0?"Dedicated memory unavailable":Number.isFinite(t)?`${Wc(t)} / ${Wc(n)}`:`${Wc(n)} available`}function vM(t){const n=Math.max(0,Math.floor(Number(t||0)/60)),r=Math.floor(n/1440),o=Math.floor(n%1440/60),c=n%60;return r>0?`${r}d ${o}h`:o>0?`${o}h ${c}m`:`${c}m`}function Jm({icon:t,label:n,value:r,detail:o,percent:c}){return i.jsxs("article",{className:"client-resource-metric",children:[i.jsxs("div",{className:"client-resource-metric-head",children:[i.jsx(t,{size:17}),i.jsx("span",{children:n}),i.jsx("strong",{children:r})]}),i.jsx("small",{title:o,children:o}),i.jsx("i",{"aria-hidden":"true",children:i.jsx("b",{style:{width:Ux(c)}})})]})}function yM(t,n){const r=t?.user.user_metadata||{},o=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(o).trim()||"Account"}function bM(t,n){const r=t?.user.user_metadata||{};return dM([r.avatar_url,r.picture,n?.userAvatarUrl,n?.auth?.avatarUrl])}function wM({page:t,status:n}){const o={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 i.jsxs("section",{className:"client-service-page",children:[i.jsx("span",{className:"client-unified-section-label",children:o.label}),i.jsx("h2",{children:o.title}),i.jsx("p",{children:o.body}),i.jsxs("div",{className:"client-service-page-card",children:[t==="docs"&&i.jsxs(i.Fragment,{children:[i.jsx("strong",{children:"Automatic connection"}),i.jsx("span",{children:"Start LiveDesk. This computer signs in, finds the Hub, and becomes available without another action."})]}),t==="pricing"&&i.jsxs(i.Fragment,{children:[i.jsx("strong",{children:"One plan, managed at the Hub"}),i.jsx("span",{children:"Computer access follows the account and plan used by the Hub."})]}),t==="settings"&&i.jsxs(i.Fragment,{children:[i.jsx("strong",{children:"Saved sign-in"}),i.jsx("span",{children:n?.auth?.persisted?"Enabled on this computer":"Sign in once to enable automatic reconnection"})]})]})]})}function xM({session:t,status:n,pin:r,error:o,roleChangeMessage:c,videoAccelerationBusy:u,slotInput:f,slotBusy:h,onSignIn:g,onPinChange:y,onSubmitPin:w,onSlotInputChange:b,onSaveSlot:x,onEnableVideoAcceleration:A}){const k=n?.connectionState==="connected",N=n?.videoAcceleration,E=u||N?.busy||N?.state==="installing",D=N?.ready?`${N.encoder||"H.264"} · ${N.driver||"VAAPI"}`:E?"Setting up…":N?.message||"Setup available",T=n?.system?.memoryTotalBytes?Number(n.system.memoryUsedBytes||0)/n.system.memoryTotalBytes*100:0,F=n?.system?.gpus||[],O=F.find(me=>Number.isFinite(me.usagePercent)||Number.isFinite(me.memoryTotalBytes))||F[0],P=Number.isFinite(O?.usagePercent)?Number(O?.usagePercent):null,z=Number.isFinite(O?.memoryTotalBytes)&&Number(O?.memoryTotalBytes)>0&&Number.isFinite(O?.memoryUsedBytes)?Number(O?.memoryUsedBytes)/Number(O?.memoryTotalBytes)*100:null,I=n?.system?.disks||[],X=n?.system?.network,se=!!X?.sampledAt,Z=X?.interfaces||[],G=[...new Set(Z.map(me=>me.name).filter(Boolean))],K=Z.map(me=>me.address).filter(Boolean);return i.jsxs("section",{className:"client-home-page",children:[i.jsxs("header",{className:"client-home-heading",children:[i.jsxs("div",{children:[i.jsx("p",{className:"client-unified-eyebrow",children:"THIS COMPUTER"}),i.jsx("h2",{children:n?.deviceName||"This Computer"})]}),i.jsxs("span",{className:`client-unified-role-chip ${k?"connected":""}`,children:[i.jsx(Ba,{size:15})," ",k?"Online":"Connecting"]})]}),i.jsxs("div",{className:"client-home-layout",children:[i.jsxs("section",{className:"client-main-surface","aria-label":"Client computer",children:[i.jsxs("div",{className:"client-main-surface-head",children:[i.jsxs("div",{children:[i.jsx("span",{className:"client-unified-section-label",children:"SYSTEM STATUS"}),i.jsx("strong",{children:"Hardware at a glance"})]}),i.jsxs("small",{children:[i.jsx(Mx,{size:14})," Uptime ",vM(n?.system?.uptimeSeconds)]})]}),i.jsxs("div",{className:"client-system-dashboard",children:[i.jsxs("section",{className:"client-performance-panel","aria-label":"Performance",children:[i.jsxs("div",{className:"client-system-subhead",children:[i.jsxs("div",{children:[i.jsx("span",{className:"client-unified-section-label",children:"PERFORMANCE"}),i.jsx("strong",{children:"Live resources"})]}),i.jsx("small",{children:"Live updates"})]}),i.jsxs("div",{className:"client-live-metrics",children:[i.jsx(Jm,{icon:cb,label:"CPU",value:$g(n?.system?.cpuUsagePercent),detail:n?.system?.cpuLogicalCores?`${n.system.cpuLogicalCores} logical cores · Current processor usage`:"Current processor usage",percent:n?.system?.cpuUsagePercent}),i.jsx(Jm,{icon:FC,label:"Memory",value:$g(T),detail:hM(n?.system?.memoryUsedBytes,n?.system?.memoryTotalBytes),percent:T}),i.jsx(Jm,{icon:PC,label:"GPU",value:sg(P),detail:O?.name||(n?.system?.hardwareCollecting?"Detecting graphics hardware…":"Graphics usage unavailable"),percent:P}),i.jsx(Jm,{icon:Wi,label:"VRAM",value:sg(z),detail:gM(O?.memoryUsedBytes,O?.memoryTotalBytes),percent:z})]})]}),i.jsxs("section",{className:"client-storage-panel","aria-label":"Local storage",children:[i.jsxs("div",{className:"client-system-subhead",children:[i.jsxs("div",{children:[i.jsx("span",{className:"client-unified-section-label",children:"STORAGE"}),i.jsx("strong",{children:"Local drives"})]}),i.jsx("small",{children:I.length>0?`${I.length} ${I.length===1?"drive":"drives"}`:n?.system?.hardwareCollecting?"Detecting…":"Unavailable"})]}),i.jsxs("div",{className:"client-disk-list",children:[I.map(me=>i.jsxs("article",{className:"client-disk-row",children:[i.jsxs("div",{className:"client-disk-row-head",children:[i.jsxs("span",{children:[i.jsx(qc,{size:16}),i.jsx("strong",{children:me.mount||"Disk"}),i.jsx("small",{children:me.name||"Local disk"})]}),i.jsx("strong",{children:sg(me.usedPercent)})]}),i.jsxs("small",{children:[Wc(me.freeBytes)," free · ",Wc(me.totalBytes)," total"]}),i.jsx("i",{"aria-hidden":"true",children:i.jsx("b",{style:{width:Ux(me.usedPercent)}})})]},`${me.mount}-${me.name||""}`)),I.length===0&&i.jsxs("div",{className:"client-disk-empty",children:[i.jsx(qc,{size:18}),i.jsx("span",{children:n?.system?.hardwareCollecting?"Detecting local drives…":"Storage information is not available."})]})]})]}),i.jsxs("section",{className:"client-network-panel","aria-label":"Network activity",children:[i.jsxs("div",{className:"client-system-subhead",children:[i.jsxs("div",{children:[i.jsx("span",{className:"client-unified-section-label",children:"NETWORK"}),i.jsx("strong",{children:"Live traffic"})]}),i.jsx("small",{children:G.length>0?G.join(", "):"Detecting adapter"})]}),i.jsxs("div",{className:"client-network-live",children:[i.jsxs("div",{className:"client-network-adapter",children:[i.jsx(zp,{size:18}),i.jsxs("span",{children:[i.jsx("strong",{children:G.join(", ")||"Network"}),i.jsx("small",{children:K.join(" / ")||"Checking active connection"})]})]}),i.jsxs("div",{className:"client-network-rate download",children:[i.jsx(OC,{size:17}),i.jsxs("span",{children:[i.jsx("small",{children:"Receive"}),i.jsx("strong",{children:Tb(se?X?.receiveBytesPerSecond:void 0)})]})]}),i.jsxs("div",{className:"client-network-rate upload",children:[i.jsx(BC,{size:17}),i.jsxs("span",{children:[i.jsx("small",{children:"Send"}),i.jsx("strong",{children:Tb(se?X?.sendBytesPerSecond:void 0)})]})]}),i.jsx("small",{className:"client-network-total",children:se?`Total ${Wc(X?.receivedBytes)} received / ${Wc(X?.sentBytes)} sent`:"Traffic has not been measured yet."})]})]})]})]}),i.jsxs("aside",{className:"client-connection-panel",children:[i.jsx("span",{className:"client-unified-section-label",children:"LIVEDESK SERVICES"}),i.jsx("h3",{children:k?"Connected to the Hub":n?.authenticated?"Finding the Hub":"Connect this computer"}),k?i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"client-unified-copy",children:"This computer is available from the LiveDesk Hub."}),i.jsxs("div",{className:"client-service-status-list",children:[i.jsxs("div",{children:[i.jsx(Ba,{size:17}),i.jsxs("span",{children:[i.jsx("strong",{children:"Screen sharing"}),i.jsx("small",{children:n?.permissions?.screenCapture?"Active":"Waiting"})]})]}),i.jsxs("div",{children:[i.jsx(Aa,{size:17}),i.jsxs("span",{children:[i.jsx("strong",{children:"Remote control"}),i.jsx("small",{children:n?.permissions?.remoteInput?"Available":"Unavailable"})]})]}),i.jsxs("div",{children:[i.jsx(dd,{size:17}),i.jsxs("span",{children:[i.jsx("strong",{children:"File delivery"}),i.jsx("small",{children:n?.permissions?.files?"Ready to receive":"Unavailable"})]})]}),i.jsxs("div",{children:[i.jsx(Vc,{size:17}),i.jsxs("span",{children:[i.jsx("strong",{children:"Computer audio"}),i.jsx("small",{children:n?.permissions?.audio?"Available":"Unavailable"})]})]})]})]}):i.jsxs(i.Fragment,{children:[i.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?i.jsxs("button",{className:"client-unified-primary",type:"button",onClick:g,children:[i.jsx(Gc,{size:16})," Sign in with Google"]}):i.jsxs("p",{className:"client-unified-success",children:[i.jsx(Oa,{size:16})," Signed in as ",t?.user.email||t?.user.id||n?.userEmail||n?.userId||"saved account"]}),i.jsxs("div",{className:"client-unified-pin-row",children:[i.jsx(HC,{size:16}),i.jsx("input",{value:r,onChange:me=>y(me.target.value),placeholder:"6-digit Hub PIN",inputMode:"numeric","aria-label":"6-digit Hub PIN"}),i.jsx("button",{className:"client-unified-secondary",type:"button",onClick:w,disabled:r.length!==6,children:"Connect"})]})]}),N?.supported&&i.jsxs("div",{className:`client-video-acceleration state-${N.ready?"ready":N.state||"setup-required"}`,children:[i.jsx(cb,{size:17}),i.jsxs("span",{children:[i.jsx("strong",{children:"Hardware video"}),i.jsx("small",{children:D})]}),!N.ready&&N.canInstall&&i.jsx("button",{type:"button",onClick:A,disabled:E,title:"Install and verify Linux FFmpeg hardware video support",children:E?"Setting up":"Enable"})]}),(o||n?.lastError)&&i.jsxs("p",{className:"client-unified-error",role:"alert",children:[i.jsx(kx,{size:15})," ",o||n?.lastError]}),c&&i.jsx("p",{className:"client-unified-success",children:c}),i.jsxs("div",{className:"client-slot-setting",children:[i.jsxs("label",{htmlFor:"client-slot-number",children:[i.jsx("span",{children:"Slot"}),i.jsx("input",{id:"client-slot-number",value:f,onChange:me=>b(me.target.value),inputMode:"numeric",pattern:"[0-9]*",placeholder:"1-999","aria-label":"Wall slot number",disabled:!k||h})]}),i.jsxs("button",{type:"button",onClick:x,disabled:!k||h||!f,"aria-label":"Save slot number",title:"Save slot number",children:[i.jsx(pv,{size:17}),i.jsx("span",{children:h?"Saving":"Set"})]})]})]})]})]})}function SM({runtimeBaseUrl:t=""}){const[n,r]=d.useState(null),[o,c]=d.useState(null),[u,f]=d.useState(!1),[h,g]=d.useState(""),[y,w]=d.useState(""),[b,x]=d.useState(""),[A,k]=d.useState(!1),[N,E]=d.useState(!1),[D,T]=d.useState(""),[F,O]=d.useState(!1),[P,z]=d.useState(null),[I,X]=d.useState(!1),[se,Z]=d.useState("computer"),[G,K]=d.useState(!1),me=d.useRef(null),V=d.useRef(null),ne=d.useRef(!1),$=d.useRef(null),_=d.useRef(!1),ie=d.useRef(!1),be=d.useRef(0),H=d.useRef(!1),te=d.useMemo(()=>pM(t),[t]),le=d.useMemo(()=>yM(o,n),[o,n]),Ce=d.useMemo(()=>bM(o,n),[o,n]),Ae=JSON.stringify(Ce),[_e,ue]=d.useState(()=>new Set),He=fM(Ce,_e),ze=le.slice(0,1).toUpperCase()||"L";d.useEffect(()=>{ue(new Set)},[Ae]);const et=d.useCallback(pe=>{ue(Ne=>{if(!pe||Ne.has(pe))return Ne;const Be=new Set(Ne);return Be.add(pe),Be})},[]),Xe=d.useCallback(async()=>{if(w(""),window.liveDesk?.auth?.signInWithGoogle){const pe=await window.liveDesk.auth.signInWithGoogle();return pe?.ok===!1?(w(pe.error||"LiveDesk could not open the system browser for Google sign-in."),!1):!0}return window.location.assign(`${te}/auth/google`),!0},[te]),Ze=d.useCallback(async()=>{ie.current||(ie.current=!0,w("Your saved Google sign-in is incomplete. LiveDesk is reopening sign-in once to repair it."),await Et.auth.signOut({scope:"local"}).catch(()=>{}),c(null),await Xe()||(ie.current=!1))},[Xe]),Ue=d.useCallback(async pe=>{const Ne=kb(pe);if(Ne)throw new Error(Ne);if(ne.current)return!1;ne.current=!0;try{const Be=await window.liveDesk?.auth?.persistSession?.(pe);if(Be?.ok===!1)throw new Error(Be.error||"LiveDesk could not validate the desktop session.");for(let Oe=0;Oe<2;Oe+=1){const We=await Lc(te,Oe>0),Rt=await fetch(`${te}/api/auth/session`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":We},signal:AbortSignal.timeout(1e4),body:JSON.stringify({accessToken:pe.access_token,refreshToken:pe.refresh_token,expiresAt:pe.expires_at,user:{id:pe.user.id,email:pe.user.email}})}),ee=await Rt.json().catch(()=>({}));if(Rt.status===403&&Oe===0){sessionStorage.removeItem("livedesk.client.csrf");continue}if(!Rt.ok)throw new Error(ee.error||`Client runtime returned HTTP ${Rt.status}.`);return w(""),!0}throw new Error("Client runtime rejected the session transfer.")}finally{ne.current=!1}},[te]),Y=d.useCallback(()=>{const pe=$.current;if(pe)return pe;const Ne=(async()=>{try{const Be=await fetch(`${te}/api/client/status`,{cache:"no-store",signal:AbortSignal.timeout(1500)}),Oe=await Be.json().catch(()=>({}));if(!Be.ok)throw new Error(Oe.error||`Client runtime returned HTTP ${Be.status}.`);if(Oe.csrfToken&&sessionStorage.setItem("livedesk.client.csrf",Oe.csrfToken),String(Oe.role||"").toLowerCase()==="hub")throw new Error("This computer is assigned to the Hub role.");r(Oe)}catch(Be){w(Be instanceof Error?Be.message:String(Be))}})();return $.current=Ne,Ne.finally(()=>{$.current===Ne&&($.current=null)}),Ne},[te]);d.useEffect(()=>{let pe=!1,Ne=null;const Be=async()=>{await Y(),pe||(Ne=window.setTimeout(()=>{Be()},2e3))};return Be(),()=>{pe=!0,Ne!==null&&window.clearTimeout(Ne)}},[Y]),d.useEffect(()=>{if(H.current)return;const pe=Number(n?.slotNumber||0);T(pe>0?String(pe):"")},[n?.slotNumber]),d.useEffect(()=>{if(!P)return;const pe=window.setTimeout(()=>z(null),5e3);return()=>window.clearTimeout(pe)},[P]);const Se=d.useCallback(async()=>{const pe=Date.now();if(!(!n?.authenticated||n.connectionState==="connected"||!["waiting","reconnecting"].includes(String(n.agent?.state||""))||pe-be.current<4e3)){be.current=pe;try{const Ne=await fetch(`${te}/api/client/reconnect`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Lc(te)},body:JSON.stringify({onlyIfWaiting:!0,reason:"app-active"})});if(!Ne.ok)throw new Error(`Client reconnect returned HTTP ${Ne.status}.`);await Y()}catch(Ne){w(Ne instanceof Error?Ne.message:String(Ne))}}},[te,Y,n]);d.useEffect(()=>{const pe=()=>{Se()},Ne=()=>{Se()},Be=()=>{document.visibilityState==="visible"&&Se()};return window.addEventListener("online",pe),window.addEventListener("focus",Ne),document.addEventListener("visibilitychange",Be),()=>{window.removeEventListener("online",pe),window.removeEventListener("focus",Ne),document.removeEventListener("visibilitychange",Be)}},[Se]),d.useEffect(()=>{if(!u||!n||!o?.access_token||n.authenticated)return;if(kb(o)==="refresh-token-required"){Ze().catch(We=>{ie.current=!1,w(We instanceof Error?We.message:String(We))});return}let pe=!1,Ne,Be=0;const Oe=async()=>{if(pe)return;try{const Rt=await Ue(o);if(await Y(),Rt)return}catch(Rt){w(Rt instanceof Error?Rt.message:String(Rt))}if(pe)return;const We=Nb[Math.min(Be,Nb.length-1)];Be+=1,Ne=window.setTimeout(()=>{Oe()},We)};return Oe(),()=>{pe=!0,Ne!==void 0&&window.clearTimeout(Ne)}},[u,Y,Ze,o,n,Ue]),d.useEffect(()=>{const pe=new URLSearchParams(window.location.search),Ne=pe.get("auth_error");if(!Ne)return;w(Ne),pe.delete("auth_error");const Be=pe.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${Be?`?${Be}`:""}${window.location.hash}`)},[]),d.useEffect(()=>{let pe=!0;if(!window.liveDesk?.auth)return c(null),f(!0),Y(),()=>{pe=!1};const Ne=window.liveDesk?.auth?.onComplete?.(Oe=>{Oe.ok&&Oe.session?Et.auth.setSession(Oe.session).catch(We=>w(We instanceof Error?We.message:String(We))):Oe.error&&w(Oe.error)});(async()=>{try{const Oe=window.liveDesk?.auth?.getSession?await window.liveDesk.auth.getSession():await Et.auth.getSession();if(!pe)return;const We=Fx(Oe);c(We),Y()}catch(Oe){pe&&w(Oe instanceof Error?Oe.message:String(Oe))}finally{pe&&f(!0)}})();const{data:Be}=Et.auth.onAuthStateChange((Oe,We)=>{pe&&(c(We),f(!0),Y())});return()=>{pe=!1,Ne?.(),Be.subscription.unsubscribe()}},[Y]),d.useEffect(()=>{if(!u||!n||_.current||ie.current||o||n.authenticated)return;const pe=new URLSearchParams(window.location.search);if(!pe.has("livedesk_launch"))return;_.current=!0,pe.delete("livedesk_launch");const Ne=pe.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${Ne?`?${Ne}`:""}${window.location.hash}`),Xe().catch(Be=>w(Be instanceof Error?Be.message:String(Be)))},[u,o,Xe,n]);const ye=async()=>{K(!1),window.liveDesk?.auth?.persistSession?(await Et.auth.signOut(),(await window.liveDesk.auth.persistSession(null))?.runtimeCleared===!1&&w("Signed out locally. The LiveDesk runtime could not be reached to clear its session.")):await fetch(`${te}/api/auth/session`,{method:"DELETE",headers:{"X-LiveDesk-CSRF":await Lc(te)}}).catch(()=>{}),c(null),await Y()};d.useEffect(()=>{if(!G)return;const pe=Be=>{Be.target instanceof Element&&Be.target.closest(".account-popover, .rail-account")||K(!1)},Ne=Be=>{Be.key==="Escape"&&K(!1)};return window.addEventListener("pointerdown",pe),window.addEventListener("keydown",Ne),()=>{window.removeEventListener("pointerdown",pe),window.removeEventListener("keydown",Ne)}},[G]);const je=d.useCallback((pe=!0)=>{A||(X(!1),pe&&window.requestAnimationFrame(()=>V.current?.focus()))},[A]),$e=d.useCallback(()=>{A||!n?.authenticated||(V.current=document.activeElement instanceof HTMLElement?document.activeElement:null,x(""),X(!0))},[A,n?.authenticated]);d.useEffect(()=>{if(!I)return;const pe=window.requestAnimationFrame(()=>me.current?.focus()),Ne=Oe=>{Oe.target instanceof Element&&Oe.target.closest(".client-hub-switch-popover, .client-hub-switch-trigger")||je(!1)},Be=Oe=>{Oe.key==="Escape"&&je()};return window.addEventListener("pointerdown",Ne),window.addEventListener("keydown",Be),()=>{window.cancelAnimationFrame(pe),window.removeEventListener("pointerdown",Ne),window.removeEventListener("keydown",Be)}},[je,I]);const B=async()=>{w("");try{const pe=await fetch(`${te}/api/client/pin`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Lc(te)},body:JSON.stringify({pin:h})}),Ne=await pe.json().catch(()=>({}));if(!pe.ok||Ne?.ok===!1)throw new Error(Ne?.error||"PIN could not be accepted.");g(""),await Y()}catch(pe){w(pe instanceof Error?pe.message:String(pe))}},lt=async()=>{X(!1),k(!0),x(""),w("");try{const pe=await fetch(`${te}/api/runtime/switch-role`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Lc(te)},body:JSON.stringify({role:"hub"})}),Ne=await pe.json().catch(()=>({}));if(!pe.ok||Ne?.ok===!1)throw new Error(Ne?.error||`Role change failed with HTTP ${pe.status}.`);x("Hub role accepted. LiveDesk is restarting this computer with the Hub Wall.");const Be=Number(n?.runtimePid||0);await Px({baseUrl:te,targetRole:"hub",previousRuntimePid:Be,allowedStates:["running"]}),window.location.reload()}catch(pe){w(pe instanceof Error?pe.message:String(pe)),k(!1)}},Nt=async()=>{if(F)return;const pe=Number(D);if(!Number.isInteger(pe)||pe<1||pe>999){z({kind:"error",message:"Enter a slot number from 1 to 999."});return}O(!0),z(null);try{const Ne=await fetch(`${te}/api/client/slot`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Lc(te)},body:JSON.stringify({slotNumber:pe})}),Be=await Ne.json().catch(()=>({}));if(!Ne.ok||Be.ok===!1){if(Be.error==="slot-taken"){const Oe=Be.conflict?.deviceName||Be.conflict?.hostname||Be.conflict?.deviceId||"another computer";throw new Error(`Slot ${String(pe).padStart(3,"0")} is already used by ${Oe}.`)}throw new Error(Be.error||`Slot update failed with HTTP ${Ne.status}.`)}H.current=!1,T(String(pe)),r(Be),z({kind:"success",message:`Slot ${String(pe).padStart(3,"0")} saved. LiveDesk is reconnecting this Client.`})}catch(Ne){z({kind:"error",message:Ne instanceof Error?Ne.message:String(Ne)})}finally{O(!1),await Y()}},Ht=async()=>{if(!N){E(!0),w("");try{const pe=await fetch(`${te}/api/client/video-acceleration/install`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Lc(te)},body:JSON.stringify({confirm:!0})}),Ne=await pe.json().catch(()=>({}));if(r(Ne),!pe.ok||Ne.videoAcceleration?.ready!==!0)throw new Error(Ne.videoAcceleration?.error||Ne.error||"Linux hardware video setup did not complete.")}catch(pe){w(pe instanceof Error?pe.message:String(pe))}finally{E(!1),await Y()}}},ke=!!(n?.authenticated||o),qe=d.useMemo(()=>qp(),[]),Ye=Ep("switch-to-hub",qe),_t=Ep("client",qe),tt=cM(qe);return i.jsxs("main",{className:"app-shell client-unified-shell",children:[i.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk Client tools",children:[i.jsx("div",{className:"rail-brand",title:"LiveDesk",children:i.jsx(Bx,{size:25})}),i.jsx("nav",{className:"rail-tools","aria-label":"Client navigation",children:i.jsxs("div",{className:"client-main-tool-slot",children:[i.jsxs("button",{className:"rail-tool client-main-tool client-hub-tool client-hub-switch-trigger accent-blue",type:"button",onClick:$e,disabled:A||!n?.authenticated,"aria-busy":A,"aria-expanded":I,"aria-haspopup":"dialog","aria-controls":I?"client-hub-switch-popover":void 0,"aria-label":`Hub. ${Ye}`,"data-tooltip":I?void 0:zg("Hub","switch-to-hub",qe),children:[i.jsx(Wi,{size:19}),i.jsx("span",{children:A?"Switching…":"Hub"})]}),i.jsxs("button",{className:`rail-tool client-main-tool accent-blue ${se==="computer"?"active":""}`,type:"button",onClick:()=>Z("computer"),"aria-current":se==="computer"?"page":void 0,"aria-label":`Client. ${_t}`,"data-tooltip":zg("Client","client",qe),children:[i.jsx(Ba,{size:19}),i.jsx("span",{children:"Client"})]})]})}),i.jsxs("div",{className:"rail-footer",children:[mM.map(pe=>{const Ne=pe.icon;return i.jsxs("button",{className:`rail-tool compact ${se===pe.id?"active":""}`,type:"button",onClick:()=>Z(pe.id),title:pe.label,children:[i.jsx(Ne,{size:18}),i.jsx("span",{children:pe.label})]},pe.id)}),i.jsxs("button",{className:`rail-account ${ke?"signed-in":""}`,type:"button",onClick:()=>K(pe=>!pe),"aria-expanded":G,"aria-haspopup":"dialog",title:ke?"Account":"Sign in",children:[ke&&He?i.jsx("img",{src:He,alt:le,referrerPolicy:"no-referrer",onError:()=>et(He)},He):ke?i.jsx("span",{className:"avatar-fallback",children:ze}):i.jsx(Gc,{size:18}),i.jsx("span",{children:ke?"Account":"Sign in"})]})]})]}),I&&i.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:[i.jsxs("header",{className:"client-hub-switch-head",children:[i.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:i.jsx(Wi,{size:19})}),i.jsx("span",{className:"client-hub-switch-eyebrow",children:tt.eyebrow}),i.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>je(),"aria-label":tt.closeLabel,children:i.jsx(vr,{size:17})})]}),i.jsx("h2",{id:"client-hub-switch-title",children:tt.title}),i.jsx("p",{id:"client-hub-switch-description",children:tt.description}),i.jsxs("p",{id:"client-hub-switch-restart",className:"client-hub-switch-notice",children:[i.jsx(Aa,{size:16,"aria-hidden":"true"}),i.jsx("span",{children:tt.restartNotice})]}),i.jsxs("div",{className:"client-hub-switch-actions",children:[i.jsx("button",{type:"button",onClick:()=>je(),children:tt.cancel}),i.jsxs("button",{ref:me,className:"primary",type:"button",onClick:()=>{lt()},disabled:A||!n?.authenticated,children:[i.jsx(Wi,{size:16}),tt.confirm]})]})]}),G&&i.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[i.jsxs("div",{className:"account-popover-head",children:[i.jsx("div",{className:"account-popover-avatar",children:ke&&He?i.jsx("img",{src:He,alt:le,referrerPolicy:"no-referrer",onError:()=>et(He)},He):ke?i.jsx("span",{children:ze}):i.jsx(Gc,{size:18})}),i.jsxs("div",{children:[i.jsx("strong",{children:ke?le:"Account"}),i.jsx("p",{children:o?.user.email||n?.userEmail||n?.userId||"Not signed in"})]})]}),i.jsxs("dl",{className:"account-popover-facts",children:[i.jsx("dt",{children:"User"}),i.jsx("dd",{children:o?.user.email||n?.userEmail||n?.userId||"Not signed in"}),i.jsx("dt",{children:"Runtime"}),i.jsx("dd",{children:n?"Local app ready":"Checking local app"}),i.jsx("dt",{children:"Session"}),i.jsx("dd",{children:n?.auth?.persisted?"Saved on this computer":ke?"Active for this run":"Not saved"}),i.jsx("dt",{children:"Role"}),i.jsx("dd",{children:"Client"})]}),ke?i.jsxs("button",{className:"account-popover-action",onClick:()=>{ye()},type:"button",children:[i.jsx(Cx,{size:16}),"Logout"]}):i.jsxs("button",{className:"account-popover-action primary",onClick:()=>{K(!1),Xe()},type:"button",children:[i.jsx(Gc,{size:16}),"Sign in with Google"]})]}),i.jsxs("section",{className:"desk-stage client-unified-stage",children:[i.jsx("header",{className:"topbar",children:i.jsxs("div",{className:"brand",children:[i.jsx("span",{className:"brand-mark",children:i.jsx(Vc,{size:18})}),i.jsxs("div",{children:[i.jsx("h1",{children:"LiveDesk"}),i.jsx("p",{children:"Client workspace"})]})]})}),se==="support"?i.jsx("section",{className:"client-unified-page",children:i.jsx(_x,{session:o,currentProductKey:"livedesk",appVersion:n?.appVersion||"",onSignIn:()=>{Xe()}})}):se!=="computer"?i.jsx("section",{className:"client-unified-page",children:i.jsx(wM,{page:se,status:n})}):i.jsx(xM,{session:o,status:n,pin:h,error:y,roleChangeMessage:b,videoAccelerationBusy:N,slotInput:D,slotBusy:F,onSignIn:()=>{Xe()},onPinChange:pe=>g(pe.replace(/\D/g,"").slice(0,6)),onSubmitPin:()=>{B()},onSlotInputChange:pe=>{H.current=!0,T(pe.replace(/\D/g,"").slice(0,3))},onSaveSlot:()=>{Nt()},onEnableVideoAcceleration:()=>{Ht()}})]}),P&&i.jsxs("div",{className:`client-side-toast ${P.kind}`,role:P.kind==="error"?"alert":"status",children:[P.kind==="error"?i.jsx(kx,{size:18}):i.jsx(Oa,{size:18}),i.jsx("span",{children:P.message}),i.jsx("button",{type:"button",onClick:()=>z(null),"aria-label":"Dismiss notification",children:i.jsx(vr,{size:16})})]})]})}function Pl(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 o=0;for(;Pl(t,n.inputIndex,1),t[n.inputIndex]===0;)o+=1,n.inputIndex+=1;const c=o*255+r+t[n.inputIndex];return n.inputIndex+=1,c}function ep(t,n,r,o){if(Pl(t,n.inputIndex,o),n.outputIndex+o>r.length)throw new Error("Invalid LZO1X block: output overrun.");r.set(t.subarray(n.inputIndex,n.inputIndex+o),n.outputIndex),n.inputIndex+=o,n.outputIndex+=o}function CM(t,n,r,o){const c=n-r;if(c<=0||o<=0)throw new Error("Invalid LZO1X block: invalid match distance.");let u=Math.min(c,o);for(t.set(t.subarray(r,r+u),n);u<o;){const f=Math.min(u,o-u);t.copyWithin(n+u,n,n+f),u+=f}return n+o}function qx(t,n){if(!(t instanceof Uint8Array)||t.length<3||n<0)throw new Error("Invalid LZO1X block.");const r=new Uint8Array(n),o={inputIndex:0,outputIndex:0};let c=0,u=0;if(t[o.inputIndex]>=22){const f=t[o.inputIndex]-17;o.inputIndex+=1,ep(t,o,r,f),c=4}else t[o.inputIndex]>=18&&(c=t[o.inputIndex]-17,o.inputIndex+=1,ep(t,o,r,c));for(;;){Pl(t,o.inputIndex,1);const f=t[o.inputIndex];o.inputIndex+=1;let h,g;if((f&192)!==0)Pl(t,o.inputIndex,1),g=o.outputIndex-((t[o.inputIndex]<<3)+(f>>2&7)+1),o.inputIndex+=1,u=(f>>5)+1,h=f&3;else if((f&32)!==0){u=(f&31)+2,u===2&&(u+=ig(t,o,31)),Pl(t,o.inputIndex,2);const y=t[o.inputIndex]|t[o.inputIndex+1]<<8;o.inputIndex+=2,g=o.outputIndex-((y>>2)+1),h=y&3}else if((f&16)!==0){u=(f&7)+2,u===2&&(u+=ig(t,o,7)),Pl(t,o.inputIndex,2);const y=t[o.inputIndex]|t[o.inputIndex+1]<<8;if(o.inputIndex+=2,g=o.outputIndex-(((f&8)<<11)+(y>>2)),h=y&3,g===o.outputIndex)break;g-=16384}else if(c===0){let y=f+3;y===3&&(y+=ig(t,o,15)),ep(t,o,r,y),c=4;continue}else c!==4?(Pl(t,o.inputIndex,1),h=f&3,g=o.outputIndex-((f>>2)+(t[o.inputIndex]<<2)+1),o.inputIndex+=1,u=2):(Pl(t,o.inputIndex,1),h=f&3,g=o.outputIndex-((f>>2)+(t[o.inputIndex]<<2)+2049),o.inputIndex+=1,u=3);if(g<0||o.outputIndex+u+h>r.length)throw new Error("Invalid LZO1X block: lookbehind overrun.");o.outputIndex=CM(r,o.outputIndex,g,u),c=h,ep(t,o,r,h)}if(u!==3||o.inputIndex!==t.length||o.outputIndex!==r.length)throw new Error("Invalid LZO1X block: incomplete output.");return r}const Rb=16,jb=8,kM=24*1024*1024,Wx=new Uint8Array(new Uint32Array([16909060]).buffer)[0]===4,Ug=new Uint32Array(65536);for(let t=0;t<Ug.length;t+=1){const n=Math.round((t>>11&31)*255/31),r=Math.round((t>>5&63)*255/63),o=Math.round((t&31)*255/31);Ug[t]=Wx?(n|r<<8|o<<16|4278190080)>>>0:(n<<24|r<<16|o<<8|255)>>>0}function Ll(t,n){return t[n]|t[n+1]<<8}function MM(t,n){const r=Number(n);if(!Number.isSafeInteger(r)||r<Rb||r>kM)throw new Error(`Invalid Mode 5 packet length: ${n}.`);const o=t instanceof Uint8Array?t:new Uint8Array(t),c=qx(o,r);if(c[0]!==76||c[1]!==68||c[2]!==53||c[3]!==68)throw new Error("Invalid Mode 5 packet magic.");if(c[4]!==1)throw new Error(`Unsupported Mode 5 packet version: ${c[4]}.`);const u=(c[5]&1)!==0,f=Ll(c,6),h=Ll(c,8),g=Ll(c,10),y=Ll(c,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=Rb;for(let x=0;x<y;x+=1){if(b+jb>c.length)throw new Error("Mode 5 tile header is truncated.");const A=Ll(c,b),k=Ll(c,b+2),N=Ll(c,b+4),E=Ll(c,b+6);b+=jb;const D=N*E*2;if(N<=0||E<=0||N>g||E>g||A+N>f||k+E>h||b+D>c.length)throw new Error(`Invalid Mode 5 tile ${x}.`);w.push({x:A,y:k,width:N,height:E,pixels:c.subarray(b,b+D)}),b+=D}if(b!==c.length)throw new Error(`Mode 5 packet has ${c.length-b} trailing bytes.`);return{keyFrame:u,width:f,height:h,tileSize:g,tiles:w}}function AM(t,n,r,o){if(!(t instanceof Uint8ClampedArray)||t.length!==n*r*4||o.width!==n||o.height!==r)throw new Error("Mode 5 canvas state does not match the packet dimensions.");let c=n,u=r,f=0,h=0;const g=new Uint32Array(t.buffer,t.byteOffset,t.byteLength>>>2);for(const y of o.tiles){const w=Wx&&(y.pixels.byteOffset&1)===0?new Uint16Array(y.pixels.buffer,y.pixels.byteOffset,y.pixels.byteLength>>>1):null;let b=0;for(let x=0;x<y.height;x+=1){let A=(y.y+x)*n+y.x;for(let k=0;k<y.width;k+=1){const N=b<<1,E=w?w[b]:y.pixels[N]|y.pixels[N+1]<<8;g[A]=Ug[E],b+=1,A+=1}}c=Math.min(c,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 o.tiles.length>0?{x:c,y:u,width:f-c,height:h-u}:null}const yr=new WeakMap,Eb=854,Db=480,NM=3840,TM=2160,RM=500,Qf=new WeakMap,qg=new WeakMap,Zc=new Set,Kc=new Set,Ul=new WeakMap,Qc=new Set,gd=new WeakMap,Wg=new WeakMap,Gg=new WeakMap,Dp=new WeakMap,Gx=4,jM=2,EM=2,DM=2,IM=18,LM=0,_M=250,FM=80,PM=5,OM=150,BM=1200,HM=18,zM=.65,$M=8,UM=16,qM=180,WM=3,yv=2e3,Vx=64,Kx=32*1024*1024,GM=500,VM=new Uint8Array(0),bv=250,KM=globalThis.LIVEDESK_ENABLE_CANVAS_VISUAL_SAMPLING===!0;let Qx=1,Yx=0,Xx=0,Vg=0,QM=0;const _f=[];let Jf=0,Zx=0,Jx,eS=0,tS,nS;function em(t,n){_f.push({sequence:++QM,type:t,canvasId:gd.get(n)||0,observedAt:Date.now(),activeDecoderCount:Zc.size,hardwareLeaseCount:Kc.size,hardwareReleaseGeneration:Jf}),_f.length>256&&_f.splice(0,_f.length-256)}let Lo={h264DecodeAcceleration:"prefer-hardware"};function YM(t){t.h264DecodeAcceleration&&(Lo={...Lo,h264DecodeAcceleration:t.h264DecodeAcceleration})}function XM(t){const{payload:n,...r}=t;return r}function ZM(t){return{...t,payload:VM}}function aS(t){try{return t.paintIsCancelled()}catch{return!0}}function Wp(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 JM(t){const n=t.pendingFrames.entries().next().value;return n?Wp(t,n[0]):void 0}function rS(t){t.pendingTrimTimer!==null&&(window.clearTimeout(t.pendingTrimTimer),t.pendingTrimTimer=null),t.pendingFrames.clear(),t.pendingFrameBytes=0,t.pendingFrameEvictedThroughTimestamp=-1}function Gp(t,n=performance.now()){for(;t.pendingFrames.size>0;){const r=t.pendingFrames.entries().next().value;if(!r)break;const o=n-r[1].queuedAt>yv,c=t.pendingFrames.size>Vx,u=t.pendingFrameBytes>Kx;if(!o&&!c&&!u)break;t.pendingFrameEvictedThroughTimestamp=Math.max(t.pendingFrameEvictedThroughTimestamp,r[0]),Wp(t,r[0]),t.pendingFrameEvictionCount+=1}}function eA(t,n,r,o,c,u=performance.now()){Wp(t,n);const f={frame:XM(r),queuedAt:u,queueSize:o,encodedByteLength:Math.max(0,Math.floor(Number(r.payload.byteLength||0))),paintIsCancelled:c};t.pendingFrames.set(n,f),t.pendingFrameBytes+=f.encodedByteLength,Gp(t,u),t.pendingFrameHighWaterMark=Math.max(t.pendingFrameHighWaterMark,t.pendingFrames.size),t.pendingFrameByteHighWaterMark=Math.max(t.pendingFrameByteHighWaterMark,t.pendingFrameBytes)}function sS(t,n){if(n.pendingTrimTimer!==null||n.pendingFrames.size===0)return;const r=n.pendingFrames.values().next().value;if(!r)return;const o=Math.max(1,yv-(performance.now()-r.queuedAt)+1);n.pendingTrimTimer=window.setTimeout(()=>{n.pendingTrimTimer=null,yr.get(t)===n&&(Gp(n),sS(t,n))},o)}function iS(t){return Kc.delete(t)?(Jf+=1,em("hardware-release",t),!0):!1}function tA(t,n,r){if(n!=="prefer-hardware"||!r)return!1;const o=Ul.get(t);return!o||o.requested!==n||o.actual!=="prefer-software"||Jf<=o.failedHardwareReleaseGeneration?!1:(Ul.delete(t),Qc.delete(t),Zx+=1,Jx=Date.now(),!0)}function Kg(t,n=Lo.h264DecodeAcceleration){const r=Ul.get(t);return r?.requested===n?(r.actual!=="prefer-hardware"&&(Kc.delete(t),Qc.add(t)),r.actual):(r&&(Ul.delete(t),Qc.delete(t)),n!=="prefer-hardware"?(iS(t),Qc.delete(t),n):(Kc.has(t)||Kc.add(t),"prefer-hardware"))}function wv(t,n,r){if(n!=="prefer-hardware")return!1;const o=Ul.get(t),c=yr.get(t),u=Date.now();return gd.has(t)||gd.set(t,Qx++),Ul.set(t,{requested:n,actual:"prefer-software",reason:r,failedAt:u,failureCount:(o?.requested===n?o.failureCount:0)+1,codec:c?.codec||o?.codec||"",latencyMode:c?.latencyMode||o?.latencyMode||"smooth",inputCount:c?.inputSerial??o?.inputCount??0,outputCount:c?.outputSerial??o?.outputCount??0,lastInputAt:c?.lastInputAt??o?.lastInputAt??0,lastOutputAt:c?.lastOutputAt??o?.lastOutputAt??0,lastPaintAt:c?.lastPaintAt??o?.lastPaintAt??0,decodeQueueHighWaterMark:Math.max(c?.decodeQueueHighWaterMark??0,o?.decodeQueueHighWaterMark??0),decodeQueueOverflowSamples:Math.max(c?.decodeQueueOverflowSamples??0,o?.decodeQueueOverflowSamples??0),decodeQueueOverflowAgeMs:c?.decodeQueueOverflowStartedAt?Math.max(0,performance.now()-c.decodeQueueOverflowStartedAt):o?.decodeQueueOverflowAgeMs,failedHardwareReleaseGeneration:Jf}),Kc.delete(t),Qc.add(t),eS+=1,tS=r,nS=u,!0}function nA(t,n,r,o=64){try{let c=Wg.get(t);c||(c={canvas:document.createElement("canvas"),lastHash:"",initialized:!1},Wg.set(t,c));const u=Math.max(8,Math.min(64,Math.round(o))),f=Math.max(1,Math.round(u*Math.max(1,r)/Math.max(1,n)));(c.canvas.width!==u||c.canvas.height!==f)&&(c.canvas.width=u,c.canvas.height=f);const h=c.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 x=0;x<g.length;x+=4)y^=g[x],y=Math.imul(y,16777619),y^=g[x+1],y=Math.imul(y,16777619),y^=g[x+2],y=Math.imul(y,16777619);const w=(y>>>0).toString(16).padStart(8,"0"),b=!c.initialized||w!==c.lastHash;return c.initialized=!0,c.lastHash=w,{visualHash:w,visualChanged:b}}catch{return{visualHash:"",visualChanged:!0}}}function Qg(t,n,r,o=bv,c=64,u){if(!KM&&u)return oS(t,u);let f=Gg.get(t);f||(f={lastHash:"",initialized:!1,lastCanvasSampleAt:0},Gg.set(t,f));const h=performance.now();if(f.initialized&&o>0&&h-f.lastCanvasSampleAt<o)return{visualHash:f.lastHash,visualChanged:!1};const g=nA(t,n,r,c);return f.initialized=!0,f.lastHash=g.visualHash,f.lastCanvasSampleAt=h,g}function oS(t,n){let r=Dp.get(t);r||(r={lastHash:"",initialized:!1},Dp.set(t,r));const o=String(n.contentHash||""),c=!r.initialized||!o||o!==r.lastHash;return r.initialized=!0,r.lastHash=o,{visualHash:o,visualChanged:c}}function lS(t,n,r=!1){const o=qg.get(t);if(o)return o;const c=t.getContext("2d",{alpha:!1,desynchronized:n==="interactive",willReadFrequently:r});if(c){const u=c.getContextAttributes?.(),f={context:c,presentation:u?.desynchronized?"desync":"sync"};return qg.set(t,f),f}return null}function aA(t){const n=String(t.frameMode||t.mode||"").toLowerCase(),r=String(t.compression||"").toLowerCase(),o=String(t.mimeType||"").toLowerCase();return n==="mode2-lzo"||r==="lzo1x"||o==="application/vnd.livedesk.lzo-rgb565"||n==="mode2-lz4"||String(t.compression||"").toLowerCase()==="lz4"||o==="application/vnd.livedesk.lz4-raw"}function rA(t){return String(t.frameMode||t.mode||"").toLowerCase()==="mode3-h264-hw"||String(t.codec||"").toLowerCase()==="h264"||String(t.mimeType||"").toLowerCase()==="video/h264"}function sA(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 Ib(t,n,r){let o=r,c=n;if(o===15){let u=255;for(;u===255;){if(c>=t.length)throw new Error("Invalid LZ4 block: length overrun.");u=t[c],c+=1,o+=u}}return{length:o,cursor:c}}function iA(t,n){const r=new Uint8Array(n);let o=0,c=0;for(;o<t.length;){const u=t[o];o+=1;const f=Ib(t,o,u>>4);o=f.cursor;const h=f.length;if(o+h>t.length||c+h>r.length)throw new Error("Invalid LZ4 block: literal overrun.");if(r.set(t.subarray(o,o+h),c),o+=h,c+=h,o>=t.length)break;if(o+2>t.length)throw new Error("Invalid LZ4 block: missing offset.");const g=t[o]|t[o+1]<<8;if(o+=2,g<=0||g>c)throw new Error("Invalid LZ4 block: bad match offset.");const y=Ib(t,o,u&15);o=y.cursor;const w=y.length+4;if(c+w>r.length)throw new Error("Invalid LZ4 block: match overrun.");let b=c-g;for(let x=0;x<w;x+=1)r[c]=r[b],c+=1,b+=1}if(c!==r.length)throw new Error("Invalid LZ4 block: incomplete output.");return r}function oA(t){const n=Math.max(1,Math.floor(t.width||0)),r=Math.max(1,Math.floor(t.height||0)),o=String(t.compression||"").toLowerCase(),c=String(t.pixelFormat||t.codec||"").toLowerCase();if(o==="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,x=Math.floor(t.uncompressedByteLength||b);if(w!==2||x!==b)throw new Error(`Invalid mode2 RGB565 frame size: ${x} for ${n}x${r}.`);if(c&&c!=="rgb565le"&&c!=="rgb565")throw new Error(`Unsupported mode2 pixel format: ${c}`);const A=qx(t.payload,b),k=new Uint8ClampedArray(n*r*4);for(let N=0,E=0;N<A.length;N+=2,E+=4){const D=A[N]|A[N+1]<<8,T=D>>11&31,F=D>>5&63,O=D&31;k[E]=T<<3|T>>2,k[E+1]=F<<2|F>>4,k[E+2]=O<<3|O>>2,k[E+3]=255}return new ImageData(k,n,r)}const f=Math.max(1,Math.floor(t.bytesPerPixel||4)),h=Math.max(n*r*f,Math.floor(t.uncompressedByteLength||0)),g=iA(t.payload,h);if(f!==4)throw new Error(`Unsupported mode2 pixel size: ${f}`);const y=new Uint8ClampedArray(n*r*4);if(c==="rgba32"||c==="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 Lb(t,n="smooth",r=Lo.h264DecodeAcceleration){const o=window.VideoDecoder;if(!o||!window.EncodedVideoChunk)throw new Error("WebCodecs H.264 decode is not supported in this browser.");const c=yr.get(t);if(c&&c.decoder.state!=="closed"&&c.latencyMode===n)return c;c&&Xs(t);let u;const f=new o({output:h=>{if(yr.get(t)!==u){h.close();return}const g=Number(h.timestamp||0),y=performance.now();u.outputSerial+=1,Gp(u,y);let w=Wp(u,g);if(!w&&g>u.pendingFrameEvictedThroughTimestamp&&u.pendingFrames.size>0&&(w=JM(u),u.timestampFallbacks+=1),!w){u.pendingFrameUnmatchedOutputCount+=1,u.droppedForLatency+=1,u.lastOutputAt=y,h.close();return}if(aS(w)){u.droppedForLatency+=1,u.lastOutputAt=y,h.close();return}const b=h.displayWidth||h.codedWidth||t.width||960,x=h.displayHeight||h.codedHeight||t.height||540,A=Number(w?.frame.durationUs||0),k=Number(h.duration||0),N=Math.max(16,Math.min(250,(A>0?A:k||83333)/1e3));for(u.targetPaintIntervalMs=N,u.decodedFrames.push({videoFrame:h,pending:w,decodedAt:y,width:b,height:x,durationMs:N}),u.lastOutputAt=y;u.decodedFrames.length>xv(u);)Ip(u,u.decodedFrames.shift(),"capacity");u.renderQueueHighWaterMark=Math.max(u.renderQueueHighWaterMark,u.decodedFrames.length),uS(u),u.renderTimer!==null&&u.renderScheduledAt>0&&performance.now()-u.renderScheduledAt>GM&&(typeof document>"u"||document.visibilityState==="visible")&&(window.cancelAnimationFrame(u.renderTimer),u.renderTimer=null,u.renderScheduledAt=0),u.renderTimer!==null&&u.decodedFrames.length>=Gx&&(window.cancelAnimationFrame(u.renderTimer),u.renderTimer=null,u.renderScheduledAt=0),Lp(t,u)},error:()=>{yr.get(t)===u&&(wv(t,u.requestedAcceleration,"decoder-error"),Xs(t))}});return Yx+=1,gd.has(t)||gd.set(t,Qx++),u={decoder:f,configured:!1,configKey:"",codec:"",requestedAcceleration:r,hardwareAcceleration:Kg(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,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},yr.set(t,u),Zc.add(t),Vg=Math.max(Vg,Zc.size),em("create",t),u}function cS(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}function Ip(t,n,r="other"){n&&(n.videoFrame.close(),t.droppedForLatency+=1,r==="capacity"?t.renderQueueCapacityDropCount+=1:r==="age"&&(t.renderQueueAgeDropCount+=1))}function xv(t){return t.latencyMode==="interactive"?EM:String(t.decodedFrames[0]?.pending?.frame.frameMode||t.decodedFrames[0]?.pending?.frame.mode||"").toLowerCase()==="mode4-h264-atlas"?jM:Gx}function uS(t,n=performance.now()){const r=xv(t);for(;t.decodedFrames.length>r;)Ip(t,t.decodedFrames.shift(),"capacity");const o=t.latencyMode==="interactive"?FM:_M;let c=t.decodedFrames[0];for(;t.decodedFrames.length>0&&c&&n-c.decodedAt>o;)Ip(t,t.decodedFrames.shift(),"age"),c=t.decodedFrames[0]}function dS(t,n){if(n.hardwareAcceleration!=="prefer-hardware"||n.latencyMode==="interactive"||n.flushTimer!==null||n.flushInFlight)return;const r=OM;n.flushTimer=window.setTimeout(async()=>{n.flushTimer=null;const o=performance.now();if(Gp(n,o),yr.get(t)!==n||n.decoder.state!=="configured"||n.pendingFrames.size===0||n.inputSerial<=n.lastFlushInputSerial||n.lastOutputAt>0&&o-n.lastOutputAt<r)return;const c=n.inputSerial;n.flushInFlight=!0,n.flushCount+=1,n.keyFrameSeen=!1;try{await n.decoder.flush(),n.lastFlushInputSerial=Math.max(n.lastFlushInputSerial,c)}catch{yr.get(t)===n&&Cp(n)}finally{n.flushInFlight=!1,yr.get(t)===n&&n.inputSerial>c&&n.pendingFrames.size>0&&performance.now()-n.lastOutputAt>=r&&dS(t,n)}},r)}function lA(t,n,r,o){const c=performance.now();if(n.interactiveBackingWidth>0&&n.interactiveBackingHeight>0&&c-n.interactiveBackingMeasuredAt<RM)return{width:Math.min(r,n.interactiveBackingWidth),height:Math.min(o,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=u.width>0?Math.round(u.width*f):Eb,g=u.height>0?Math.round(u.height*f):Db,y=Math.min(1,h/r,g/o),w=Math.min(1,Math.max(Eb/r,Db/o)),b=Math.min(1,NM/r,TM/o),x=Math.max(.01,Math.min(b,Math.max(w,y)));return n.interactiveBackingWidth=Math.max(1,Math.round(r*x)),n.interactiveBackingHeight=Math.max(1,Math.round(o*x)),n.interactiveBackingMeasuredAt=c,{width:n.interactiveBackingWidth,height:n.interactiveBackingHeight}}function _b(t,n,r){const o=performance.now();try{if(!r.pending||aS(r.pending)){n.droppedForLatency+=1;return}const c=n.latencyMode==="interactive"?lA(t,n,r.width,r.height):{width:r.width,height:r.height},u=c.width,f=c.height;(t.width!==u||t.height!==f)&&(t.width=u,t.height=f);const h=lS(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"?oS(t,r.pending.frame):Qg(t,r.width,r.height,bv,64,r.pending.frame),b=ZM(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,o-r.pending.queuedAt),decodedForMs:Math.max(0,r.decodedAt-r.pending.queuedAt),scheduledForMs:Math.max(0,o-r.decodedAt),drawMs:Math.max(0,g-o),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,visualHash:w.visualHash,visualChanged:w.visualChanged,paintedAt:g})}catch{}}n.lastPaintAt=performance.now()}finally{r.videoFrame.close()}}function Lp(t,n){if(n.renderTimer!==null||n.decodedFrames.length===0)return;const r=Math.max(16,Math.min(250,n.targetPaintIntervalMs||1e3/12)),o=()=>{if(n.renderTimer=null,n.renderScheduledAt=0,n.decodedFrames.length===0)return;const c=performance.now();if(uS(n,c),n.decodedFrames.length===0)return;if(n.latencyMode==="interactive"){const g=n.targetPaintIntervalMs<=20;if(g&&!n.interactiveBufferPrimed){n.interactiveBufferStartedAt<=0&&(n.interactiveBufferStartedAt=c,n.interactiveBufferWaitCount+=1);const w=n.decodedFrames.length>=DM,b=c-n.interactiveBufferStartedAt>=IM;if(!w&&!b){n.renderScheduledAt=performance.now(),n.renderTimer=window.requestAnimationFrame(o);return}n.interactiveBufferWaitMs+=Math.max(0,c-n.interactiveBufferStartedAt),n.interactiveBufferPrimed=!0}else g||(n.interactiveBufferPrimed=!0);const y=n.decodedFrames.shift();if(y)try{_b(t,n,y)}catch{}n.decodedFrames.length===0&&(n.interactiveQueueDrainCount+=1,n.interactiveBufferPrimed=!1,n.interactiveBufferStartedAt=0),Lp(t,n);return}const u=n.lastPaintAt>0?n.lastPaintAt+r:c+LM;if(!(c+PM>=u||n.decodedFrames.length>=Math.max(1,xv(n)-1))){n.renderScheduledAt=performance.now(),n.renderTimer=window.requestAnimationFrame(o);return}const h=n.decodedFrames.shift();if(h)try{_b(t,n,h)}catch{}Lp(t,n)};n.renderScheduledAt=performance.now(),n.renderTimer=window.requestAnimationFrame(o)}function fS(t,n){if(yr.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;)Ip(n,n.decodedFrames.shift());return n.lastPaintAt=0,n.interactiveBufferPrimed=!1,n.interactiveBufferStartedAt=0,Lp(t,n),!0}function og(){if(!(typeof document>"u"||document.visibilityState!=="visible"))for(const t of Zc){const n=yr.get(t);if(!n||n.decoder.state==="closed"){Zc.delete(t);continue}fS(t,n)}}typeof document<"u"&&typeof window<"u"&&(document.addEventListener("visibilitychange",og),window.addEventListener("focus",og),window.addEventListener("pageshow",og));function Xs(t){iS(t),Zc.delete(t),Dp.delete(t);const n=yr.get(t);if(n){yr.delete(t),Xx+=1,rS(n),n.onPaint=void 0,cS(n);try{n.decoder.state!=="closed"&&n.decoder.close()}catch{}em("close",t)}}function ad(t){t&&(Ul.delete(t),Qc.delete(t),qg.delete(t),Gg.delete(t),Wg.delete(t),Dp.delete(t),Qf.delete(t),Xs(t))}function cA(t,n){const r=yr.get(t),o=Ul.get(t);if(!r&&!o)return null;const c=f=>f>0?Math.max(0,n-f):void 0,u=r?.pendingFrames.values().next().value;return{canvasId:gd.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||o?.codec||"",requestedAcceleration:r?.requestedAcceleration||o?.requested||Lo.h264DecodeAcceleration,configuredAcceleration:r?.hardwareAcceleration||o?.actual||Lo.h264DecodeAcceleration,latencyMode:r?.latencyMode||o?.latencyMode||"smooth",decodeQueueSize:Math.max(0,Number(r?.decoder.decodeQueueSize||0)),decodeQueueHighWaterMark:Math.max(0,Number(r?.decodeQueueHighWaterMark??0),Number(o?.decodeQueueHighWaterMark??0)),decodeQueueOverflowSamples:Math.max(0,Number(r?.decodeQueueOverflowSamples??0),Number(o?.decodeQueueOverflowSamples??0)),decodeQueueOverflowAgeMs:r?.decodeQueueOverflowStartedAt?Math.max(0,n-r.decodeQueueOverflowStartedAt):o?.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:Vx,pendingFrameMaxBytes:Kx,pendingFrameMaxAgeMs:yv,renderQueueSize:r?.decodedFrames.length||0,renderQueueHighWaterMark:r?.renderQueueHighWaterMark||0,renderQueueCapacityDropCount:r?.renderQueueCapacityDropCount||0,renderQueueAgeDropCount:r?.renderQueueAgeDropCount||0,targetPaintIntervalMs:Math.max(0,Number(r?.targetPaintIntervalMs||0)),droppedForLatency:Math.max(0,Number(r?.droppedForLatency||0)),inputCount:r?.inputSerial??o?.inputCount??0,outputCount:r?.outputSerial??o?.outputCount??0,lastInputAgeMs:c(r?.lastInputAt??o?.lastInputAt??0),lastOutputAgeMs:c(r?.lastOutputAt??o?.lastOutputAt??0),lastPaintAgeMs:c(r?.lastPaintAt??o?.lastPaintAt??0),softwareFallbackReason:o?.reason,softwareFallbackAt:o?.failedAt,softwareFallbackCount:o?.failureCount||0}}function tp(t){const n=performance.now(),o=(t?[t]:[...new Set([...Zc,...Qc])]).map(f=>cA(f,n)).filter(f=>f!==null),c=o.reduce((f,h)=>f+h.pendingFrameCount,0),u=o.reduce((f,h)=>f+h.pendingFrameBytes,0);return{capturedAt:Date.now(),hardwareRequestPolicy:"all-active",activeDecoderCount:o.filter(f=>f.decoderState!=="fallback-pending").length,hardwareLeaseCount:Kc.size,hardwareReleaseGeneration:Jf,hardwareRecoveryProbeCount:Zx,lastHardwareRecoveryProbeAt:Jx,activeSoftwareFallbackCount:o.filter(f=>f.configuredAcceleration==="prefer-software"&&f.requestedAcceleration==="prefer-hardware").length,decoderCreateCount:Yx,decoderCloseCount:Xx,activeDecoderHighWaterMark:Vg,decoderLifecycleEvents:_f.map(f=>({...f})),softwareFallbackEventCount:eS,lastSoftwareFallbackReason:tS,lastSoftwareFallbackAt:nS,pendingFrameCount:c,pendingFrameBytes:u,canvases:o}}function Cp(t,n=1){try{t.decoder.state!=="closed"&&t.decoder.reset()}catch{}t.configured=!1,t.configKey="",t.keyFrameSeen=!1,rS(t),cS(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 uA(t,n,r=performance.now()){const o=Math.max(0,Number.isFinite(n)?n:0);if(t.decodeQueueHighWaterMark=Math.max(t.decodeQueueHighWaterMark,o),o<=$M)return t.decodeQueueOverflowStartedAt=0,t.decodeQueueOverflowSamples=0,!1;t.decodeQueueOverflowStartedAt<=0?(t.decodeQueueOverflowStartedAt=r,t.decodeQueueOverflowSamples=1):t.decodeQueueOverflowSamples+=1;const c=Math.max(0,r-t.decodeQueueOverflowStartedAt);return o>=UM||t.decodeQueueOverflowSamples>=WM&&c>=qM}function dA(t,n,r,o,c,u){n.decoder.configure(r),n.configured=!0,n.configKey=o,n.codec=r.codec,n.requestedAcceleration=u,n.hardwareAcceleration=c,n.keyFrameSeen=!1,n.nextChunkTimestampUs=0,n.lastInputFrameSeq=void 0,em("configure",t)}function fA(t,n){if(n.latencyMode!=="interactive"||n.hardwareAcceleration!=="prefer-hardware")return!1;const r=performance.now();if(r-n.healthSampleStartedAt<BM)return!1;const o=n.inputSerial-n.healthInputSerial,c=n.outputSerial-n.healthOutputSerial;return n.healthSampleStartedAt=r,n.healthInputSerial=n.inputSerial,n.healthOutputSerial=n.outputSerial,o<HM||c/Math.max(1,o)>=zM?!1:(wv(t,n.requestedAcceleration,"interactive-health"),Xs(t),!0)}function rd(t,n=1){if(!t)return!1;const r=yr.get(t);return r?(r.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(n))),Xs(t),!0):!1}function mA(t){if(!t)return!1;const n=yr.get(t);return n?fS(t,n):!1}function pA(t,n,r,o="interactive"){Xs(t);const c=performance.now(),u=MM(n.payload,n.uncompressedByteLength||0),f=String(n.streamId||"mode5");let h=Qf.get(t);if(!h||h.streamId!==f||h.width!==u.width||h.height!==u.height){const N=new Uint8ClampedArray(u.width*u.height*4);for(let E=3;E<N.length;E+=4)N[E]=255;h={streamId:f,width:u.width,height:u.height,rgba:N,imageData:new ImageData(N,u.width,u.height),keyFrameSeen:!1,inputSerial:0,outputSerial:0},Qf.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=AM(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 x=lS(t,o),A=performance.now();w&&x?.context.putImageData(h.imageData,0,0,w.x,w.y,w.width,w.height);const k=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,k-c),decodedForMs:Math.max(0,b-c),scheduledForMs:0,drawMs:Math.max(0,k-A),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:x?.presentation||"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:String(n.contentHash||""),visualChanged:Number(n.deltaVisualTileCount||0)>0,paintedAt:k})}const lg=[{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 Fb(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 hA(t){let n=0;for(;n<t.length;){const r=Fb(t,n);if(!r)break;const o=r.index+r.length,c=Fb(t,o),u=c?.index??t.length;if(o<u&&(t[o]&31)===7){const f=[];let h=0;for(let g=o+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=c?c.index:t.length}return""}function gA(t,n,r,o,c=""){const u=Math.ceil(t/16)*Math.ceil(n/16),f=r>0?1e6/r:30,h=u*f,g=lg.find(y=>u<=y.maxFrameSize&&h<=y.maxMacroblocksPerSecond)||lg[lg.length-1];return hA(o)||c||`avc1.42E0${g.code.toString(16).toUpperCase().padStart(2,"0")}`}function mS(t,n,r,o,c="smooth",u=()=>!1,f=!0){Qf.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=o||Lo.h264DecodeAcceleration,x=n.isKeyFrame===!0||String(n.chunkType||"").toLowerCase()==="key";tA(t,b,x);let A=Lb(t,c,b);const k=gA(g,y,w,n.payload,A.codec);let N=Kg(t,b),E="";const D=()=>{E=[n.streamId||"",n.commandId||"",g,y,k,h,b,N,c].join("|")};D(),A.onPaint=r,A.configured&&A.decoder.state!=="configured"&&(A.configured=!1,A.configKey=""),A.configured&&A.configKey!==E&&(Xs(t),A=Lb(t,c,b),A.onPaint=r,N=Kg(t,b),D());const T=()=>({codec:k,codedWidth:g,codedHeight:y,hardwareAcceleration:N,optimizeForLatency:!0,avc:{format:h}}),F=se=>A.hardwareAcceleration!=="prefer-hardware"||!wv(t,A.requestedAcceleration,se)?!1:(Xs(t),f&&x&&mS(t,n,r,b,c,u,!1),!0),O=()=>{try{return dA(t,A,T(),E,N,b),!0}catch(se){if(F("configure-error"))return!1;throw Xs(t),se}};if(!A.configured&&!O())return;const P=Number(n.streamFrameSeq||0);if(P>0&&A.lastInputFrameSeq!==void 0&&(P<=A.lastInputFrameSeq&&(!x||P===A.lastInputFrameSeq||(Cp(A,A.lastInputFrameSeq-P+1),!O()))||P>A.lastInputFrameSeq+1&&(Cp(A,P-A.lastInputFrameSeq-1),!x||!O()))||(P>0&&(A.lastInputFrameSeq=P),!x&&!A.keyFrameSeen))return;x&&(A.keyFrameSeen=!0);const z=Number(A.decoder.decodeQueueSize||0);if(uA(A,z)){if(A.latencyMode==="interactive"&&A.hardwareAcceleration==="prefer-hardware"){F("decode-queue-overflow");return}if(Cp(A),!x||!O())return;A.keyFrameSeen=!0}const I=A.nextChunkTimestampUs;A.nextChunkTimestampUs+=w,eA(A,I,n,z,u),sS(t,A),A.inputSerial+=1,A.lastInputAt=performance.now(),A.inputSerial===1&&em("first-input",t);const X=new EncodedVideoChunk({type:x?"key":"delta",timestamp:I,duration:w,data:n.payload});try{A.decoder.decode(X)}catch(se){if(F("decode-error"))return;throw Xs(t),se}dS(t,A),fA(t,A)}async function cg(t,n,r,o,c,u="smooth",f=r){if(sA(n)){r()||pA(t,n,o,u);return}if(rA(n)){r()||mS(t,n,o,c,u,f);return}if(Qf.delete(t),aA(n)){Xs(t);const x=oA(n);if(r())return;(t.width!==x.width||t.height!==x.height)&&(t.width=x.width,t.height=x.height);const A=t.getContext("2d"),k=performance.now();A?.putImageData(x,0,0);const N=performance.now(),E=Qg(t,x.width,x.height,bv,64,n);o?.(n,{deviceId:n.deviceId,frameSeq:n.frameSeq,mode:n.frameMode||n.mode||n.codec||n.mimeType,width:x.width,height:x.height,byteLength:n.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,N-k),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:Lo.h264DecodeAcceleration,decoderLabel:"lzo-rgb565",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:E.visualHash,visualChanged:E.visualChanged,paintedAt:N});return}Xs(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 x=performance.now();b.clearRect(0,0,y,w),b.drawImage(g,0,0,y,w);const A=performance.now(),k=Qg(t,y,w);o?.(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,A-x),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:Lo.h264DecodeAcceleration,decoderLabel:"image",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:k.visualHash,visualChanged:k.visualChanged,paintedAt:A})}g.close()}function vA(t){queueMicrotask(t)}function yA(t){return t?(t.width=0,t.height=0,!0):!1}function Vp(t,n){if(!t)return!1;try{n?.(t)}finally{yA(t)}return!0}function Sv(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 bA(t,n){if(!t||!n)return 0;const r=Number(t.get(n)||0);return Number.isSafeInteger(r)&&r>0?r:Sv(t,n)}function Pb(t,n){return Sv(t,n)}function Ob(t,n,r){return!!t&&!!n&&Number(r)>0&&Number(t.get(n)||0)===Number(r)}function wA(t,n,r){if(!t||!t.has(n))return!1;const o=t.get(n);return t.delete(n),Vp(o,r)}function xA(t,n,r){const o=new Set;for(const c of t||[])if(c){for(const u of c.values())u&&o.add(u);c.clear()}for(const c of n||[])c&&o.add(c);for(const c of o)Vp(c,r);return o.size}function SA(t,{isCurrent:n,dispose:r,schedule:o=vA}){return!t||typeof n!="function"?!1:(o(()=>{n(t)||Vp(t,r)}),!0)}const CA=new Uint8Array(0);function $c(t){if(!t||typeof t!="object")return t;const n=t.payload;return n instanceof Uint8Array&&n.byteLength===0?t:{...t,payload:CA}}function kA(t,n){const r=$c(n);return t.set(n.deviceId,r),r}function MA(t,n){for(const[r,o]of n.entries())t.set(r,$c(o));return n.clear(),new Map(t)}const AA=1500;function NA(t={}){const n=Math.max(10,Math.min(1e4,Number(t.closeDeadlineMs)||AA)),r=typeof t.setTimeout=="function"?t.setTimeout:setTimeout,o=typeof t.clearTimeout=="function"?t.clearTimeout:clearTimeout,c=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&&(o(y.timer),y.timer=null);try{y.socket.removeEventListener?.("close",y.handleClose)}catch{}return c.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 x={entry:y,socket:b,timer:null,settled:!1,handleClose:null};x.handleClose=()=>g(x,!1),u.set(y,x),c.add(x),h=Math.max(h,c.size);try{b.addEventListener?.("close",x.handleClose)}catch{}x.timer=r(()=>{if(!x.settled){try{b.close()}catch{}g(x,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(x,!1),!0},snapshot(){return{closingSocketCount:c.size,closingSocketTimerCount:[...c].filter(y=>y.timer!==null).length,closingSocketTimeoutCount:f,maximumClosingSocketCount:h}}})}function TA(t,n="livedesk-frame-socket-release",r=null){if(!t)return 0;const o=[t],c=new Set;let u=0;for(;o.length>0;){const f=o.pop();if(!f||c.has(f))continue;c.add(f);const h=f.handoffFrom;f.handoffFrom=void 0,h&&!c.has(h)&&o.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 Bb=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"]),RA=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 jA(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 EA(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 DA(){return{ownerKey:"",values:Object.create(null)}}function Hb(t){t&&(t.ownerKey="",t.values=Object.create(null))}function IA(t,n,r){if(!t||!n||!EA(t,r))return!1;const o=jA(r);if(n.ownerKey!==o&&(n.ownerKey=o,n.values=Object.create(null)),t.nativeCaptureTelemetryAvailable===!1){for(const c of Bb)c!=="nativeCaptureTelemetryAvailable"&&(delete n.values[c],delete t[c]);return n.values.nativeCaptureTelemetryAvailable=!1,!0}if(t.nativeCaptureResourceTelemetryAvailable===!1)for(const c of RA)delete n.values[c],delete t[c];for(const c of Bb)Object.prototype.hasOwnProperty.call(t,c)?n.values[c]=t[c]:Object.prototype.hasOwnProperty.call(n.values,c)&&(t[c]=n.values[c]);return!0}const pS=new ArrayBuffer(0);function LA(t){return`${String(t?.streamId||"")}:${Number(t?.frameSeq||0)}`}function _A(t){return!t||typeof t!="object"||t.payload instanceof ArrayBuffer&&t.payload.byteLength===0?t:{...t,payload:pS}}function FA(){let t=null,n="";return{accept(r){t=_A(r)},publish(){const r=t;if(t=null,!r)return null;const o=LA(r);return o===n?null:(n=o,r)},clear(){t=null,n=""},inspect(){return{pending:t?1:0,pendingPayloadBytes:Number(t?.payload?.byteLength||0),publishedKey:n}}}}const PA=0,OA=1,zb=3;function mr(t){return Math.max(0,Math.floor(Number(t)||0))}function gi(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 BA(){const t=new Set;let n=null;const r={ownerCount:0,socketCount:0,audioContextCount:0,workletNodeCount:0,workletPortCount:0},o=()=>{let c=0,u=0,f=0,h=0;for(const g of t){const y=Number(g.socket?.readyState);c+=g.socket&&y!==zb?1:0,u+=g.audioContext===null?0:1,f+=mr(g.workletNodeCount),h+=mr(g.workletPortCount)}r.ownerCount=Math.max(r.ownerCount,t.size),r.socketCount=Math.max(r.socketCount,c),r.audioContextCount=Math.max(r.audioContextCount,u),r.workletNodeCount=Math.max(r.workletNodeCount,f),r.workletPortCount=Math.max(r.workletPortCount,h)};return{createOwner({deviceId:c,socket:u,audioContext:f,statsTimer:h=null}){n=null;const g={deviceId:String(c||""),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),o(),g},recordTerminalFailure(c,u,f="playback"){return t.has(c)?(n={deviceId:c.deviceId,phase:String(f||"playback").slice(0,64),message:String(u||"Remote audio playback failed.").slice(0,512)},!0):!1},deactivate(c){return t.has(c)?(c.active=!1,gi(t,c)):!1},setSocket(c,u){return t.has(c)?(c.socket=u||null,o(),gi(t,c)):!1},setAudioContext(c,u){return t.has(c)?(c.audioContext=u||null,o(),gi(t,c)):!1},setStatsTimer(c,u){return t.has(c)?(c.statsTimer=u??null,gi(t,c)):!1},setScheduledSourceCount(c,u){return t.has(c)?(c.scheduledSourceCount=mr(u),gi(t,c)):!1},setPendingDecodeCount(c,u){return t.has(c)?(c.pendingDecodeCount=mr(u),gi(t,c)):!1},setWorkletNode(c,u,f,h=c?.workletNodeCreateCount){return t.has(c)?(c.workletNodeCount=mr(u),c.workletPortCount=mr(f),c.workletNodeCreateCount=mr(h),o(),gi(t,c)):!1},setPcmRing(c,u,f){return t.has(c)?(c.pcmRingCapacityBytes=mr(u),c.pcmRingBufferedBytes=Math.min(c.pcmRingCapacityBytes,mr(f)),gi(t,c)):!1},setPendingWorkletPackets(c,u,f,h=c?.pendingWorkletPacketHighWater,g=c?.pendingWorkletByteHighWater){return t.has(c)?(c.pendingWorkletPacketCount=mr(u),c.pendingWorkletPacketBytes=mr(f),c.pendingWorkletPacketHighWater=Math.max(c.pendingWorkletPacketHighWater,mr(h)),c.pendingWorkletByteHighWater=Math.max(c.pendingWorkletByteHighWater,mr(g)),gi(t,c)):!1},setRetainedFrame(c,u,f=0){return t.has(c)?(c.retainedFrameCount=mr(u),c.retainedPayloadBytes=mr(f),gi(t,c)):!1},releaseIfDrained(c){return gi(t,c)},hasOwner(c){return t.has(c)},snapshot(){const c=[...t].map(f=>{const h=Number(f.socket?.readyState),g=f.socket&&h!==zb?1:0;return{deviceId:f.deviceId,active:f.active,socketCount:g,openSocketCount:h===OA?1:0,connectingSocketCount:h===PA?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=>c.reduce((h,g)=>h+mr(g[f]),0);return{ownerCount:c.length,activeOwnerCount:c.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:c}}}}const ha=BA();function HA(){let t=Promise.resolve(),n=0,r=0,o=0;return{acquire(c){const u=++o;let f=!1,h=!1,g=!1,y;const w=new Promise(k=>{y=k}),b=Promise.resolve(t).catch(()=>{});t=b.then(()=>w);const x=()=>g?!1:(g=!0,f&&(n=Math.max(0,n-1)),y(),!0),A=b.then(async()=>{if(h||g)return x(),null;f=!0,n+=1,r=Math.max(r,n);try{return await c({ownerId:u,release:x})}catch(k){throw x(),k}});return{ownerId:u,ready:A,release:x,cancel(){h=!0,f||x()}}},snapshot(){return{activeOwnerCount:n,ownerHighWater:r,nextOwnerId:o}}}}const zA=HA(),$b=1e3;function $A({enabled:t,now:n,lastPublishedAt:r,intervalMs:o=$b}){if(!t)return!1;const c=Math.max(0,Number(n)||0),u=Math.max(0,Number(r)||0),f=Math.max(1,Number(o)||$b);return u<=0||c-u>=f}const hS="livedesk-remote-audio-v1",UA=250,qA=80,Yg=4;function WA(t){const n=String(t||"").toLowerCase();return n.includes("audio/pcm")||n.includes("f32le")||n.includes("s16le")}function Xg(t={},n={}){const r=String(n.deviceId||""),o=String(n.streamId||"");return!!r&&!!o&&String(t.deviceId||"")===r&&String(t.streamId||"")===o}function GA(t={},n={}){if(!Xg(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)),o=Math.max(0,Math.floor(Number(n.lastFrameSeq)||0));return r>0&&r<=o?{accepted:!1,reason:"sequence-not-newer",nextFrameSeq:o}:{accepted:!0,reason:"",nextFrameSeq:r}}function VA(t={}){const n=String(t.capturePhase||"").toLowerCase(),r=String(t.backendKind||"").toLowerCase(),o=t.captureAlive===!0?!0:t.captureAlive===!1?!1:null,c=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?c===!0&&u>0:!1,b=n==="starting"||n==="capture-active-awaiting-current-pcm",x=n==="active"&&o===!0&&g&&w,A=n==="failed"||n==="stopped"||o===!1||n==="active"&&(!g||!w);let k="";return b?k="awaiting-current-pcm":!f&&!h?k="backend-unknown":n!=="active"?k=n?`phase-${n}`:"phase-unknown":o!==!0?k="capture-not-alive":y===!0&&c!==!0?k="external-helper-not-alive":y===!0&&u<=0&&(k="external-helper-pid-missing"),{capturePhase:n,backendKind:r,captureAlive:o,helperAlive:c,helperPid:u,helperRequired:y,inProcessBackend:f,externalHelperBackend:h,backendKnown:g,helperReady:w,awaitingCurrentPcm:b,healthy:x,failed:A,reason:k}}function ql(t,n){const r=Math.floor(Number(t));return Number.isFinite(r)&&r>0?r:n}function Cv(t={}){const n=Math.max(8e3,Math.min(192e3,ql(t.sampleRate,48e3))),r=Math.max(1,Math.min(8,ql(t.channels,2))),o=String(t.mimeType||"").toLowerCase(),u=String(t.sampleFormat||"").toLowerCase()==="s16le"||o.includes("s16le")||o.includes("audio/l16")?"s16le":"f32le";return{sampleRate:n,channels:r,sampleFormat:u}}function kv(t={}){const n=Cv(t),r=Math.max(1,Math.min(250,ql(t.maxDurationMs,250))),o=Math.max(1,Math.ceil(n.sampleRate*r/1e3));return{...n,maxDurationMs:r,capacityFrames:o,capacityBytes:o*n.channels*Float32Array.BYTES_PER_ELEMENT}}function KA(t={}){const n=kv(t),r=Math.max(0,Math.min(n.maxDurationMs,ql(t.targetLeadMs,80))),o=Math.min(n.capacityFrames,Math.max(1,Math.ceil(n.sampleRate*r/1e3)));let c=new Float32Array(n.capacityFrames*n.channels),u=0,f=0,h=0,g=0,y=!1,w=!1,b=0,x=0,A=0;const k={acceptedFrames:0,droppedFrames:0},N=()=>(A+=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:x,started:!w&&y,disposed:w}),E=()=>{u=0,f=0,h=0,g=0,y=!1},D=()=>{w||(E(),c=new Float32Array(0),w=!0)},T=(P,z=0,I,X=n.sampleFormat)=>{if(k.acceptedFrames=0,k.droppedFrames=0,w||!(P instanceof ArrayBuffer))return k;const se=Math.max(0,Math.floor(Number(z)||0)),Z=Math.max(0,P.byteLength-se),G=Math.min(Z,Math.max(0,Math.floor(Number(I??Z)||0))),K=X==="s16le",me=K?2:4,V=me*n.channels,ne=Math.floor(G/V);if(ne<=0)return k;const $=Math.min(ne,n.capacityFrames),_=ne-$,ie=Math.max(0,h+$-n.capacityFrames);ie>0&&(u=(u+ie)%n.capacityFrames,h-=ie);const be=_+ie;b+=be;const H=new DataView(P,se,G);for(let te=_;te<ne;te+=1){const le=f*n.channels,Ce=te*n.channels;for(let Ae=0;Ae<n.channels;Ae+=1){const ue=(Ce+Ae)*me,He=K?H.getInt16(ue,!0)/32768:H.getFloat32(ue,!0);c[le+Ae]=Number.isFinite(He)?Math.max(-1,Math.min(1,He)):0}f=(f+1)%n.capacityFrames}return h+=$,!y&&h>=o&&(y=!0),k.acceptedFrames=$,k.droppedFrames=be,k};return{writePcm:(P={})=>T(P.buffer,P.byteOffset,P.byteLength,P.sampleFormat),writePcmBuffer:T,readToChannels:(P,z=n.sampleRate)=>{if(!Array.isArray(P)||P.length===0)return;let I=Number.POSITIVE_INFINITY;for(let Z=0;Z<P.length;Z+=1){const G=P[Z];I=Math.min(I,G?.length||0)}if(w||!Number.isFinite(I)||I<=0||!y){for(let Z=0;Z<P.length;Z+=1)P[Z]?.fill?.(0);return}const X=Math.max(8e3,Math.min(192e3,ql(z,n.sampleRate))),se=n.sampleRate/X;for(let Z=0;Z<I;Z+=1){if(h<=0){y=!1,x+=1,g=0;for(let me=0;me<P.length;me+=1)P[me].fill(0,Z);break}const G=u*n.channels;for(let me=0;me<P.length;me+=1){const V=Math.min(me,n.channels-1);P[me][Z]=c[G+V]}g+=se;const K=Math.min(h,Math.floor(g));K>0&&(u=(u+K)%n.capacityFrames,h-=K,g-=K)}},flush:E,dispose:D,snapshot:N,getSnapshotCount:()=>A}}function QA(t={}){const n=Math.max(1,Math.min(Yg,ql(t.maxPendingPackets,Yg))),r=Math.max(1,ql(t.maxPendingBytes,1)),o=new Map;let c=0,u=0,f=0,h=0,g=0,y=!1;const w=()=>({terminal:y,maxPendingPackets:n,maxPendingBytes:r,pendingPacketCount:o.size,pendingPacketBytes:c,pendingPacketHighWater:u,pendingByteHighWater:f,acceptedCount:h,droppedCount:g});return{claim(b,x){const A=typeof b=="number"&&Number.isFinite(b)?b:String(b||""),k=Math.max(0,Math.floor(Number(x)||0));return y||!A||k<=0||o.has(A)||o.size>=n||c+k>r?(g+=1,!1):(o.set(A,k),c+=k,u=Math.max(u,o.size),f=Math.max(f,c),h+=1,!0)},acknowledge(b){const x=typeof b=="number"&&Number.isFinite(b)?b:String(b||""),A=o.get(x);return A===void 0?!1:(o.delete(x),c=Math.max(0,c-A),!0)},terminate(){return o.clear(),c=0,y=!0,w()},getPendingPacketCount:()=>o.size,getPendingPacketBytes:()=>c,getPendingPacketHighWater:()=>u,getPendingByteHighWater:()=>f,snapshot:w}}function Kp(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 o=`const ${r} = ${Function.prototype.toString.call(t)};`;return r===n?o:`${o}
12
- const ${n} = ${r};`}const YA=Kp(ql,"positiveInteger"),XA=Kp(Cv,"normalizeRemoteAudioPcmFormat"),ZA=Kp(kv,"remoteAudioPcmRingCapacity"),JA=Kp(KA,"createRemoteAudioPcmRing"),e1=`
13
- const REMOTE_AUDIO_PCM_RING_MAX_MS = ${UA};
14
- const REMOTE_AUDIO_PCM_TARGET_LEAD_MS = ${qA};
15
- ${YA}
16
- ${XA}
17
- ${ZA}
18
- ${JA}
19
-
20
- class LiveDeskRemoteAudioProcessor extends AudioWorkletProcessor {
21
- constructor() {
22
- super();
23
- this.ring = null;
24
- this.ringSampleRate = 0;
25
- this.ringChannels = 0;
26
- this.ringSampleFormat = '';
27
- this.disposed = false;
28
- this.reportFrames = 0;
29
- this.port.onmessage = event => this.handleMessage(event?.data || {});
30
- }
31
-
32
- postRingState(type, extra = {}) {
33
- const ringState = this.ring?.snapshot?.() || {
34
- capacityBytes: 0,
35
- bufferedBytes: 0,
36
- bufferedMs: 0,
37
- droppedFrames: 0,
38
- underflowCount: 0
39
- };
40
- this.port.postMessage({
41
- type,
42
- ...extra,
43
- ringCapacityBytes: Number(ringState.capacityBytes || 0),
44
- ringBufferedBytes: Number(ringState.bufferedBytes || 0),
45
- ringBufferedMs: Number(ringState.bufferedMs || 0),
46
- ringDroppedFrames: Number(ringState.droppedFrames || 0),
47
- ringUnderflowCount: Number(ringState.underflowCount || 0)
48
- });
49
- }
50
-
51
- handleMessage(message) {
52
- const type = String(message.type || '');
53
- if (type === 'dispose') {
54
- this.disposed = true;
55
- this.ring?.dispose?.();
56
- this.ring = null;
57
- this.ringSampleRate = 0;
58
- this.ringChannels = 0;
59
- this.ringSampleFormat = '';
60
- this.postRingState('disposed');
61
- return;
62
- }
63
- if (this.disposed) {
64
- if (type === 'pcm') {
65
- this.port.postMessage({
66
- type: 'packet-terminal',
67
- packetId: message.packetId ?? 0,
68
- acceptedFrames: 0,
69
- droppedFrames: 0
70
- });
71
- }
72
- return;
73
- }
74
- if (type === 'flush') {
75
- this.ring?.flush?.();
76
- this.postRingState('ring-state');
77
- return;
78
- }
79
- if (type !== 'pcm') {
80
- return;
81
- }
82
-
83
- try {
84
- const sourceSampleRate = Math.max(
85
- 8_000,
86
- Math.min(192_000, positiveInteger(message.sampleRate, 48_000))
87
- );
88
- const sourceChannels = Math.max(
89
- 1,
90
- Math.min(8, positiveInteger(message.channels, 2))
91
- );
92
- const sourceSampleFormat =
93
- message.sampleFormat === 's16le' ? 's16le' : 'f32le';
94
- const ringCreated = !this.ring
95
- || this.ringSampleRate !== sourceSampleRate
96
- || this.ringChannels !== sourceChannels
97
- || this.ringSampleFormat !== sourceSampleFormat;
98
- if (ringCreated) {
99
- this.ring?.dispose?.();
100
- this.ring = createRemoteAudioPcmRing({
101
- sampleRate: sourceSampleRate,
102
- channels: sourceChannels,
103
- sampleFormat: sourceSampleFormat,
104
- maxDurationMs: REMOTE_AUDIO_PCM_RING_MAX_MS,
105
- targetLeadMs: REMOTE_AUDIO_PCM_TARGET_LEAD_MS
106
- });
107
- this.ringSampleRate = sourceSampleRate;
108
- this.ringChannels = sourceChannels;
109
- this.ringSampleFormat = sourceSampleFormat;
110
- this.postRingState('ring-configured');
111
- }
112
- const result = this.ring.writePcmBuffer(
113
- message.buffer,
114
- message.byteOffset,
115
- message.byteLength,
116
- sourceSampleFormat
117
- );
118
- this.port.postMessage({
119
- type: 'packet-terminal',
120
- packetId: message.packetId ?? 0,
121
- acceptedFrames: Number(result.acceptedFrames || 0),
122
- droppedFrames: Number(result.droppedFrames || 0)
123
- });
124
- } catch (error) {
125
- this.port.postMessage({
126
- type: 'processor-error',
127
- packetId: message.packetId ?? 0,
128
- error: error instanceof Error ? error.message : String(error)
129
- });
130
- }
131
- }
132
-
133
- process(_inputs, outputs) {
134
- try {
135
- if (this.disposed) {
136
- return false;
137
- }
138
- const output = outputs && outputs.length > 0 ? outputs[0] : null;
139
- if (!output) {
140
- return true;
141
- }
142
- const outputFrames = output.length > 0 ? output[0].length : 0;
143
- if (this.ring) {
144
- this.ring.readToChannels(output, sampleRate);
145
- } else {
146
- for (let channelIndex = 0; channelIndex < output.length; channelIndex += 1) {
147
- output[channelIndex].fill(0);
148
- }
149
- }
150
- this.reportFrames += outputFrames;
151
- if (this.reportFrames >= Math.max(1, Math.floor(sampleRate / 4))) {
152
- this.reportFrames = 0;
153
- this.postRingState('ring-state');
154
- }
155
- return true;
156
- } catch (error) {
157
- this.disposed = true;
158
- this.port.postMessage({
159
- type: 'processor-error',
160
- packetId: 0,
161
- error: error instanceof Error ? error.message : String(error)
162
- });
163
- return false;
164
- }
165
- }
166
- }
167
-
168
- registerProcessor(
169
- '${hS}',
170
- LiveDeskRemoteAudioProcessor
171
- );
172
- `,Ub="livedesk_remote_host_targets",t1="livedesk_entitlements",qb=4e3,n1=2500,Mv=new TextDecoder,Zg=new Set;function a1(){const t=[...Zg].map(r=>r()),n=r=>t.reduce((o,c)=>o+Number(c[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"),restartTokenCount:n("restartTokenCount"),retainedFrameCount:n("retainedFrameCount"),retainedPayloadBytes:n("retainedPayloadBytes"),owners:t}}function r1(){return ha.snapshot()}function s1(t){const r=(Array.isArray(t)?t:[t||qn]).map(o=>Vl(o||qn));return[...new Set(r.filter(Boolean))]}function i1(){const[t,n]=d.useState(null),[r,o]=d.useState(!0);return d.useEffect(()=>{let c=!0;const u=window.liveDesk?.auth?.onComplete?.(h=>{h.ok&&h.session&&Et.auth.setSession(h.session)});(window.liveDesk?.auth?.getSession?.()||Et.auth.getSession()).then(h=>{c&&(n(Fx(h)),o(!1))});const{data:{subscription:f}}=Et.auth.onAuthStateChange((h,g)=>{n(g),o(!1),window.liveDesk?.auth?.persistSession?.(g)});return()=>{c=!1,u?.(),f.unsubscribe()}},[]),{session:t,loading:r}}function o1(t,n=!0){const[r,o]=d.useState(null),[c,u]=d.useState([]),[f,h]=d.useState(""),[g,y]=d.useState(""),w=d.useRef(new Map),b=d.useRef(null),x=Array.isArray(t)?t.join(`
173
- `):String(t||""),A=d.useMemo(()=>s1(t),[x]),k=d.useMemo(()=>A.find(D=>Uf(D)==="loopback")||A[0]||qn,[A]),N=d.useCallback(async D=>{if(!n){o(null),u([]),y(""),h("");return}let T=null;const F=Date.now(),O=A.filter(P=>(w.current.get(P)||0)<=F);if(O.length===0)throw new Error("No LiveDesk Hub endpoint is reachable. Retrying shortly.");for(const P of O)try{const[z,I]=await Promise.all([rt("/api/remote/status",{signal:D,timeoutMs:qb},P),rt("/api/remote/devices",{signal:D,timeoutMs:qb},P)]);if(D?.aborted)throw D.reason||new Error("LiveDesk Hub snapshot cancelled.");if(!Array.isArray(I.devices))throw new Error("Invalid Hub devices response.");w.current.delete(P),o(z),u(I.devices),y(P),h("");return}catch(z){if(D?.aborted)throw z;T=z,w.current.set(P,Date.now()+1e4)}throw y(""),T||new Error("No LiveDesk Hub endpoint is reachable.")},[n,A]),E=d.useCallback(()=>{w.current.clear(),jp(b,()=>N()).catch(D=>{h(D instanceof Error?D.message:String(D))})},[N]);return d.useEffect(()=>{if(!n){o(null),u([]),y(""),h("");return}let D=!0,T=null;const F=new AbortController,O=()=>{jp(b,()=>N(F.signal)).catch(z=>{D&&!F.signal.aborted&&h(z instanceof Error?z.message:String(z))}).finally(()=>{D&&!F.signal.aborted&&(T=window.setTimeout(O,n1))})};return O(),()=>{D=!1,F.abort(new Error("LiveDesk Hub snapshot polling stopped.")),T!==null&&window.clearTimeout(T)}},[n,N]),{status:r,devices:c,error:f,refresh:E,hubBaseUrl:g||k,hubCandidates:A}}function l1(t){const[n,r]=d.useState(null),[o,c]=d.useState(""),u=t?.user?.id||"",f=d.useCallback(async()=>{if(!u){r(null);return}const{data:h,error:g}=await Et.from(Ub).select("*").eq("user_id",u).maybeSingle();if(g){c(g.message);return}r(h),c("")},[u]);return d.useEffect(()=>{f()},[f]),d.useEffect(()=>{if(!u)return;const h=Et.channel(`livedesk-remote-host-targets-${u.replace(/[^a-zA-Z0-9]/g,"")}`).on("postgres_changes",{event:"*",schema:"public",table:Ub,filter:`user_id=eq.${u}`},g=>r(g.new)).subscribe();return()=>{Et.removeChannel(h)}},[u]),{target:n,error:o,refresh:f}}function c1(t){const[n,r]=d.useState(null),[o,c]=d.useState(!1),[u,f]=d.useState(""),h=t?.user?.id||"",g=d.useCallback(async()=>{if(!h){r(null),f(""),c(!1);return}c(!0);const{data:w,error:b}=await Et.from(t1).select("*").eq("user_id",h).eq("product_key","livedesk").maybeSingle();if(b){f(b.message),c(!1);return}r(w),f(""),c(!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:o,error:u,refresh:g}}const qf={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},u1=2500,d1=3e4,f1=64*1024,m1=64*1024,p1=6,h1=p1,gS=new Map;function g1(t){return gS.get(t)}const Wb={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function v1(t,n,r){const o=Number(n);if(!Number.isFinite(o)||o<=0)return 0;const c=r-o,u=t.minimumHubClockOffsetMs;if(!Number.isFinite(u)||c<Number(u))return t.minimumHubClockOffsetMs=c,0;const f=Math.max(0,c-Number(u));return f>d1?(t.minimumHubClockOffsetMs=c,0):f}function pt(t){if(t==null||t==="")return;const n=Number(t);return Number.isFinite(n)?n:void 0}const y1=["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 b1(t){return Number(t.nativeCaptureTelemetryVersion)>=5&&y1.every(n=>pt(t[n])!==void 0)&&typeof t.nativeOutputQueueAwaitingKeyFrame=="boolean"&&t.nativeCopyTelemetryAvailable===!0}function w1(t,n,r){if(!t||typeof t!="object")return null;const o=t,c=String(o.deviceId||n||"").trim(),u=String(o.sessionId||"").trim(),f=String(o.streamId||"").trim(),h=o.streamPurpose==="control"?"control":o.streamPurpose==="wall"?"wall":null,g=String(o.commandId||"").trim(),y=Number(o.captureGeneration||0),w=Number(o.monitorIndex??-1);return!c||c!==n||!h||h!==r||!u||!f||!g||!Number.isSafeInteger(y)||y<=0||!Number.isSafeInteger(w)||w<0?null:{deviceId:c,sessionId:u,streamId:f,streamPurpose:h,commandId:g,captureGeneration:y,monitorIndex:w}}function Gb(t,n,r=qn,o={}){const[c,u]=d.useState(new Map),[f,h]=d.useState("idle"),[g,y]=d.useState(""),[w,b]=d.useState(qf),x=d.useRef(new Map),A=d.useRef(new Map),k=d.useRef(new Map),N=d.useRef(null);N.current===null&&(N.current=NA());const E=d.useRef(0),D=d.useRef(new Map),T=d.useRef({enabled:!1,token:"",reason:""}),F=d.useRef(new Map),O=d.useRef(null),[P,z]=d.useState(0),I=d.useRef(o.onFrame),X=d.useRef(o.onStreamReady),se=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),Z=d.useMemo(()=>[...t].sort().join(","),[t]),G=n&&Z.length>0,K=d.useRef(!1);d.useLayoutEffect(()=>(K.current=G,()=>{K.current=!1}),[G]);const me=Number.isFinite(o.fps)?Number(o.fps):2,V=Number.isFinite(o.maxWidth)?Number(o.maxWidth):640,ne=Number.isFinite(o.maxHeight)?Number(o.maxHeight):360,$=Number.isFinite(o.quality)?Number(o.quality):45,_=String(o.frameMode||o.mode||"mode3-h264-hw").trim()||"mode3-h264-hw",ie=o.streamPurpose==="control"?"control":"wall",be=o.forceRestart===!0,H=String(o.forceRestartToken||"").trim(),te=String(o.restartReason||"").trim();T.current={enabled:be,token:H,reason:te};const le=d.useMemo(()=>{const Ue=Object.entries(o.monitorSelections||{}).filter(([Y])=>!!Y).sort(([Y],[Se])=>Y.localeCompare(Se));return JSON.stringify(Object.fromEntries(Ue))},[o.monitorSelections]),Ce=d.useMemo(()=>{const Ue=Object.entries(o.connectionSessionIds||{}).filter(([Y])=>!!Y).map(([Y,Se])=>[Y,String(Se||"").trim()]).sort(([Y],[Se])=>Y.localeCompare(Se));return JSON.stringify(Object.fromEntries(Ue))},[o.connectionSessionIds]);d.useEffect(()=>{I.current=o.onFrame},[o.onFrame]),d.useEffect(()=>{X.current=o.onStreamReady},[o.onStreamReady]);const Ae=d.useCallback((Ue,Y="livedesk-frame-socket-release")=>{TA(Ue,Y,N.current)},[]),_e=d.useCallback(Ue=>{const Y=F.current.get(Ue);Y!==void 0&&(window.clearTimeout(Y),F.current.delete(Ue))},[]),ue=d.useCallback((Ue,Y=!0)=>{for(const Se of F.current.values())window.clearTimeout(Se);F.current.clear();for(const Se of k.current.values())Se.expectedBinding=void 0,Ae(Se,Ue);k.current.clear(),D.current.clear(),x.current=new Map,A.current.clear(),se.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},Y&&(u(new Map),y(""),b(qf),h("idle"))},[Ae]),He=d.useCallback(()=>{const Ue=[...k.current.values()].map(Y=>Y.socket);if(Ue.length===0){h("idle");return}if(Ue.some(Y=>Y.readyState===WebSocket.OPEN)){h("open");return}if(Ue.some(Y=>Y.readyState===WebSocket.CONNECTING)){h("connecting");return}h("closed")},[]),ze=d.useCallback((Ue,Y,Se,ye)=>{if(Y.disposed||Y.socket.readyState!==WebSocket.OPEN)return!1;try{return Y.socket.send(JSON.stringify({...Y.payload,type:"restart-live",deviceIds:[Ue],forceRestart:!0,restartReason:Se,restartToken:ye})),Y.expectedBinding=void 0,Hb(Y.sparseTelemetry),!0}catch{return!1}},[]),et=d.useCallback((Ue,Y)=>{if(!K.current||Y.disposed||!Ue||Ue.byteLength<5)return;const Se=Date.now(),je=new DataView(Ue).getUint32(0,!1);if(je<=0||je+4>Ue.byteLength)return;const $e=new Uint8Array(Ue,4,je),B=JSON.parse(Mv.decode($e));IA(B,Y.sparseTelemetry,Y.expectedBinding);const lt=pt(B.hubPacketEpochMs),Nt=lt!==void 0&&lt>0?lt:void 0,Ht=v1(Y,Nt,Se);if(Ht>u1)return;const ke=new Uint8Array(Ue,4+je),qe=pt(B.nativeCaptureTelemetryVersion),Ye=pt(B.nativeCaptureTelemetryAgeMs),_t=pt(B.hubClientDropped),tt=pt(B.hubClientQueueDepth),pe=pt(B.hubClientQueueLimit),Ne=pt(B.hubClientBufferedBytes),Be=_t!==void 0&&tt!==void 0&&pe!==void 0&&Ne!==void 0,Oe={deviceId:String(B.deviceId||""),kind:B.kind==="thumbnail"?"thumbnail":"live",frameSeq:Number(B.frameSeq||0),streamFrameSeq:Number(B.streamFrameSeq||0)||void 0,streamId:String(B.streamId||""),commandId:B.commandId?String(B.commandId):void 0,sessionId:B.sessionId?String(B.sessionId):void 0,captureGeneration:Number(B.captureGeneration||0)||void 0,currentGenerationVerified:!1,streamPurpose:B.streamPurpose?String(B.streamPurpose):void 0,width:Number(B.width||0),height:Number(B.height||0),sourceWidth:Number(B.sourceWidth||0)||void 0,sourceHeight:Number(B.sourceHeight||0)||void 0,mimeType:String(B.mimeType||"image/jpeg"),mode:B.mode?String(B.mode):void 0,frameMode:B.frameMode?String(B.frameMode):void 0,frameProfile:B.frameProfile?String(B.frameProfile):void 0,encoding:B.encoding?String(B.encoding):void 0,codec:B.codec?String(B.codec):void 0,compression:B.compression?String(B.compression):void 0,pixelFormat:B.pixelFormat?String(B.pixelFormat):void 0,bytesPerPixel:Number(B.bytesPerPixel||0)||0,uncompressedByteLength:Number(B.uncompressedByteLength||0)||0,h264Format:B.h264Format?String(B.h264Format):void 0,isKeyFrame:B.isKeyFrame===!0,chunkType:B.chunkType?String(B.chunkType):void 0,timestampUs:Number(B.timestampUs||0)||0,durationUs:Number(B.durationUs||0)||0,sourceGapMs:Number(B.sourceGapMs||0)||0,agentSendGapMs:Number(B.agentSendGapMs||0)||0,agentSendDurationMs:Number(B.agentSendDurationMs||0)||0,agentSendDurationFrameSeq:Number(B.agentSendDurationFrameSeq||0)||0,agentPaceMs:Number(B.agentPaceMs||0)||0,agentQueueBeforePaceMs:Number(B.agentQueueBeforePaceMs||0)||0,agentFrameAgeMs:Number(B.agentFrameAgeMs||0)||0,inputFeedbackEventId:B.inputFeedbackEventId?String(B.inputFeedbackEventId):void 0,inputFeedbackInputSeq:pt(B.inputFeedbackInputSeq),inputFeedbackInputType:B.inputFeedbackInputType?String(B.inputFeedbackInputType):void 0,inputFeedbackIssuedAtEpochMs:pt(B.inputFeedbackIssuedAtEpochMs),inputFeedbackHubReceivedAtEpochMs:pt(B.inputFeedbackHubReceivedAtEpochMs),inputFeedbackHubForwardedAtEpochMs:pt(B.inputFeedbackHubForwardedAtEpochMs),inputFeedbackAgentReceivedAtEpochMs:pt(B.inputFeedbackAgentReceivedAtEpochMs),inputFeedbackAppliedAtEpochMs:pt(B.inputFeedbackAppliedAtEpochMs),inputFeedbackAgentApplyMs:pt(B.inputFeedbackAgentApplyMs),inputFeedbackApplyToCaptureMs:pt(B.inputFeedbackApplyToCaptureMs),inputFeedbackCaptureTimestampAvailable:typeof B.inputFeedbackCaptureTimestampAvailable=="boolean"?B.inputFeedbackCaptureTimestampAvailable:void 0,nativeCaptureTelemetryAvailable:typeof B.nativeCaptureTelemetryAvailable=="boolean"?B.nativeCaptureTelemetryAvailable:void 0,nativeCaptureTelemetryVersion:qe===void 0?void 0:Math.max(0,qe),nativeCaptureTelemetryAgeMs:Ye===void 0?void 0:Math.max(0,Ye),nativeEncoderHardwareAccelerationKnown:typeof B.nativeEncoderHardwareAccelerationKnown=="boolean"?B.nativeEncoderHardwareAccelerationKnown:void 0,nativeEncoderHardwareAccelerated:typeof B.nativeEncoderHardwareAccelerated=="boolean"?B.nativeEncoderHardwareAccelerated:void 0,nativeEncoderHardwareQueryStatus:B.nativeEncoderHardwareQueryStatus?String(B.nativeEncoderHardwareQueryStatus):void 0,nativeCaptureDisplayId:pt(B.nativeCaptureDisplayId),nativeCaptureFps:pt(B.nativeCaptureFps),nativeCompressionFps:pt(B.nativeCompressionFps),nativeEncodedFps:pt(B.nativeEncodedFps),nativeCaptureSampleCount:pt(B.nativeCaptureSampleCount),nativeEncodableFrameCount:pt(B.nativeEncodableFrameCount),nativeSkippedFrameCount:pt(B.nativeSkippedFrameCount),nativeCompressionOutputCount:pt(B.nativeCompressionOutputCount),nativeEncodedFrameCount:pt(B.nativeEncodedFrameCount),nativeEncodeFramesInFlight:pt(B.nativeEncodeFramesInFlight),nativeEncodePendingFrameCount:pt(B.nativeEncodePendingFrameCount),nativeEncodeTimestampOwnerCount:pt(B.nativeEncodeTimestampOwnerCount),nativeEncodeTimestampOwnerHighWatermark:pt(B.nativeEncodeTimestampOwnerHighWatermark),nativeBackpressureCoalescedFrameCount:pt(B.nativeBackpressureCoalescedFrameCount),nativeBackpressureSkippedFrameCount:pt(B.nativeBackpressureSkippedFrameCount),nativeEncodePendingReplacedFrameCount:pt(B.nativeEncodePendingReplacedFrameCount),nativeIdleSkippedFrameCount:pt(B.nativeIdleSkippedFrameCount),nativeVideoToolboxActiveSessionCount:pt(B.nativeVideoToolboxActiveSessionCount),nativeVideoToolboxSessionHighWatermark:pt(B.nativeVideoToolboxSessionHighWatermark),nativeOutputQueueDepth:pt(B.nativeOutputQueueDepth),nativeOutputQueueBytes:pt(B.nativeOutputQueueBytes),nativeOutputQueueOldestAgeMs:pt(B.nativeOutputQueueOldestAgeMs),nativeOutputQueueHighWatermark:pt(B.nativeOutputQueueHighWatermark),nativeOutputQueueDroppedCount:pt(B.nativeOutputQueueDroppedCount),nativeOutputQueueAwaitingKeyFrame:typeof B.nativeOutputQueueAwaitingKeyFrame=="boolean"?B.nativeOutputQueueAwaitingKeyFrame:void 0,nativeCopyTelemetryAvailable:typeof B.nativeCopyTelemetryAvailable=="boolean"?B.nativeCopyTelemetryAvailable:void 0,nativeAnnexBAccessUnitAllocationCount:pt(B.nativeAnnexBAccessUnitAllocationCount),nativeAnnexBPayloadCopyCount:pt(B.nativeAnnexBPayloadCopyCount),nativeAnnexBPayloadCopiedBytes:pt(B.nativeAnnexBPayloadCopiedBytes),nativeAndPipeResidenceAgeMs:pt(B.nativeAndPipeResidenceAgeMs),pipePayloadAllocationCount:pt(B.pipePayloadAllocationCount),pipePayloadCopyCount:pt(B.pipePayloadCopyCount),pipePayloadCopiedBytes:pt(B.pipePayloadCopiedBytes),handoffDroppedFrameCount:pt(B.handoffDroppedFrameCount),handoffRecoveryKeyFrameRequestCount:pt(B.handoffRecoveryKeyFrameRequestCount),handoffOldestFrameAgeMs:pt(B.handoffOldestFrameAgeMs),nativeCaptureResourceTelemetryAvailable:B.nativeCaptureResourceTelemetryAvailable===!0?b1(B):B.nativeCaptureResourceTelemetryAvailable===!1?!1:void 0,nativeCaptureTelemetryAt:B.nativeCaptureTelemetryAt?String(B.nativeCaptureTelemetryAt):void 0,droppedByAgent:Number(B.droppedByAgent||0)||0,hubIngressDropped:Number(B.hubIngressDropped||0)||0,hubClientDropped:_t,transport:B.transport?String(B.transport):void 0,videoTransport:B.videoTransport?String(B.videoTransport):void 0,frameTransportActive:B.frameTransportActive?String(B.frameTransportActive):void 0,frameTransportProtocol:B.frameTransportProtocol?String(B.frameTransportProtocol):void 0,frameTransportState:B.frameTransportState?String(B.frameTransportState):void 0,frameTransportReason:B.frameTransportReason?String(B.frameTransportReason):void 0,frameTransportChangedAt:B.frameTransportChangedAt?String(B.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(B.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(B.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:B.frameTransportP2pReady===!0,hubClientQueueTelemetryAvailable:Be,hubClientQueueDepth:tt,hubClientQueueLimit:pe,hubClientBufferedBytes:Ne,udpIncompleteFrames:Number(B.udpIncompleteFrames||0)||0,hardwareEncoder:B.hardwareEncoder?String(B.hardwareEncoder):void 0,platformProfile:B.platformProfile?String(B.platformProfile):void 0,monitorIndex:Number.isFinite(Number(B.monitorIndex))?Number(B.monitorIndex):void 0,monitorCount:Number.isFinite(Number(B.monitorCount))?Number(B.monitorCount):void 0,requestedFps:Number(B.requestedFps||0)||0,effectiveFps:Number(B.effectiveFps||0)||0,captureTimingAvailable:B.captureTimingAvailable===!0,captureAverageMs:pt(B.captureAverageMs),captureP95Ms:pt(B.captureP95Ms),slowFrameCount:Number(B.slowFrameCount||0)||0,captureHelperRestarts:Number(B.captureHelperRestarts||0)||0,capturedAt:String(B.capturedAt||""),receivedAt:String(B.receivedAt||""),hubPacketAt:B.hubPacketAt?String(B.hubPacketAt):void 0,hubPacketEpochMs:Nt,browserReceivedEpochMs:Se,hubPacketTransitAgeMs:Nt!==void 0?Ht:void 0,byteLength:Number(B.byteLength||ke.byteLength),contentHash:B.contentHash?String(B.contentHash):void 0,captureMs:pt(B.captureMs),captureStageMs:pt(B.captureStageMs),convertMs:Number(B.convertMs||0)||0,compressMs:Number(B.compressMs||0)||0,captureSourceSerial:Number(B.captureSourceSerial||0)||0,captureSourceSkipped:Number(B.captureSourceSkipped||0)||0,deltaTileSize:Number(B.deltaTileSize||0)||0,deltaTileCount:Number(B.deltaTileCount||0)||0,deltaVisualTileCount:Number(B.deltaVisualTileCount||0)||0,deltaRefreshTileCount:Number(B.deltaRefreshTileCount||0)||0,deltaTotalTiles:Number(B.deltaTotalTiles||0)||0,payload:ke};if(!Oe.deviceId)return;const We=Y.expectedBinding;if(!We)return;const Rt=Oe.deviceId===We.deviceId&&String(Oe.sessionId||"")===We.sessionId&&Oe.streamId===We.streamId&&String(Oe.commandId||"")===We.commandId&&Number(Oe.captureGeneration||0)===We.captureGeneration&&Number(Oe.monitorIndex??-1)===We.monitorIndex&&String(Oe.streamPurpose||"")===We.streamPurpose;if(!Rt)return;Oe.currentGenerationVerified=Rt;const ee=Number(Y.payload.monitorSelections?.[Oe.deviceId]);if(Number.isFinite(ee)&&Number.isFinite(Number(Oe.monitorIndex))&&Number(Oe.monitorIndex)!==ee)return;const he={streamId:Y.lastFrameStreamId,commandId:Y.lastFrameCommandId,order:Y.lastFrameOrder},Fe=Number(Oe.streamFrameSeq||Oe.frameSeq||0),fe=!!he.commandId&&!!Oe.commandId,xe=he.streamId===Oe.streamId&&(!fe||he.commandId===Oe.commandId),nt=he.order;if(xe&&nt>=Fe&&(nt===Fe||fe))return;Y.lastFrameStreamId=Oe.streamId,Y.lastFrameCommandId=Oe.commandId||"",Y.lastFrameOrder=Fe;const ct=se.current;ct.totalFrames+=1,ct.totalBytes+=ke.byteLength,ct.sampleFrames+=1,ct.sampleBytes+=ke.byteLength;const ft=!x.current.has(Oe.deviceId)&&!A.current.has(Oe.deviceId),dt=kA(A.current,Oe);ft&&(x.current.set(Oe.deviceId,dt),A.current.delete(Oe.deviceId),u(new Map(x.current))),I.current?.(Oe)},[]);d.useEffect(()=>{if(!n||!Z)return;se.current.sampleStartedAt=performance.now();const Ue=window.setInterval(()=>{if(!K.current)return;const Y=performance.now(),Se=se.current,ye=Math.max(1,Y-Se.sampleStartedAt);b({totalFrames:Se.totalFrames,totalBytes:Se.totalBytes,framesPerSecond:Se.sampleFrames*1e3/ye,bytesPerSecond:Se.sampleBytes*1e3/ye,sampleMs:ye,lastUpdatedAt:Date.now()}),u(MA(x.current,A.current)),Se.sampleFrames=0,Se.sampleBytes=0,Se.sampleStartedAt=Y},2e3);return O.current=Ue,()=>{window.clearInterval(Ue),O.current===Ue&&(O.current=null)}},[n,Z]),d.useEffect(()=>{const Ue=()=>{const Y=new Set,Se=[...k.current.values()];for(;Se.length>0;){const B=Se.pop();!B||Y.has(B)||(Y.add(B),B.handoffFrom&&Se.push(B.handoffFrom))}const ye=[...x.current.values(),...A.current.values()],je=[...Y],$e=N.current?.snapshot()||{closingSocketCount:0,closingSocketTimerCount:0,closingSocketTimeoutCount:0};return{deviceKey:Z,active:K.current,socketCount:je.length+$e.closingSocketCount,openSocketCount:je.filter(B=>B.socket.readyState===WebSocket.OPEN).length,connectingSocketCount:je.filter(B=>B.socket.readyState===WebSocket.CONNECTING).length,closingSocketCount:$e.closingSocketCount,closingSocketTimerCount:$e.closingSocketTimerCount,closingSocketTimeoutCount:$e.closingSocketTimeoutCount,expectedBindingCount:je.filter(B=>!!B.expectedBinding).length,reconnectTimerCount:F.current.size,statsTimerCount:O.current===null?0:1,restartTokenCount:D.current.size,retainedFrameCount:ye.length,retainedPayloadBytes:ye.reduce((B,lt)=>B+Math.max(0,Number(lt.payload?.byteLength||0)),0)}};return Zg.add(Ue),()=>{Zg.delete(Ue)}},[Z]),d.useEffect(()=>{const Ue=Z?Z.split(",").filter(Boolean):[];if(!G){ue(n?"livedesk-no-devices":"livedesk-stream-inactive");return}const Y=new Set(Ue),Se=performance.now();for(const ye of F.current.keys())Y.has(ye)||_e(ye);for(const[ye,je]of k.current.entries())Y.has(ye)||(_e(ye),Ae(je,"livedesk-device-unsubscribed"),k.current.delete(ye),D.current.delete(ye),x.current.delete(ye),A.current.delete(ye));se.current.sampleStartedAt<=0&&(se.current.sampleStartedAt=Se,b({...qf,lastUpdatedAt:Date.now()}));for(const ye of Ue){_e(ye);const je=Number(o.monitorSelections?.[ye]),$e=Number.isInteger(je)&&je>=0?je:0,B={[ye]:$e},lt={type:"subscribe",deviceIds:[ye],autoStartLive:n,fps:me,maxWidth:V,maxHeight:ne,quality:$,mode:_,frameMode:_,streamPurpose:ie,monitorSelections:B},Nt=String(o.connectionSessionIds?.[ye]||"").trim(),Ht=JSON.stringify({subscribePayload:lt,connectionSessionId:Nt}),ke=k.current.get(ye),qe=Number(ke?.payload.monitorSelections?.[ye]),Ye=Number(B[ye]),_t=!!ke&&Number.isFinite(qe)&&Number.isFinite(Ye)&&qe!==Ye,tt=!!ke&&ke?.connectionSessionId!==Nt;if(ke){const fe=ke.socket.readyState===WebSocket.CONNECTING||ke.socket.readyState===WebSocket.OPEN;if(ke.payloadKey===Ht&&fe&&!ke.disposed)continue}const pe=ke&&(ke.socket.readyState===WebSocket.CONNECTING||ke.socket.readyState===WebSocket.OPEN)&&!ke.disposed?ke.handoffFrom&&!ke.handoffCompleted?ke.handoffFrom:ke:void 0,Ne=ke&&ke!==pe?ke:void 0,Be=new WebSocket(Up(`/api/remote/frames/ws?devices=${encodeURIComponent(ye)}`,r));Be.binaryType="arraybuffer";const Oe=DA(),We={socket:Be,payload:lt,payloadKey:Ht,connectionSessionId:Nt,generation:E.current+1,monitorRestartToken:_t?`monitor-${ye}-${Ye}-${E.current+1}`:"",disposed:!1,handoffFrom:pe,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1,sparseTelemetry:Oe,releaseOwnedState:()=>Hb(Oe)};E.current=We.generation,(_t||tt)&&(x.current.delete(ye),A.current.delete(ye),u(new Map(x.current))),k.current.set(ye,We),Ne&&(Ne.handoffFrom=void 0,Ae(Ne,"livedesk-subscription-superseded"));const Rt=()=>{if(!K.current||We.disposed||k.current.get(ye)!==We){Ae(We,"livedesk-stale-frame-socket");return}_e(ye),y("");const fe=T.current,xe=fe.enabled&&(!fe.token||D.current.get(ye)!==fe.token),nt=xe||We.monitorRestartToken!=="",ct=xe?fe.token:We.monitorRestartToken,ft=xe?fe.reason:We.monitorRestartToken?"monitor-selection-change":"";Be.send(JSON.stringify({...We.payload,forceRestart:nt,restartReason:nt?ft:"",restartToken:nt?ct:""})),xe&&fe.token&&D.current.set(ye,fe.token);const dt=We.handoffFrom;We.handoffFrom=void 0,We.handoffCompleted=!0,dt&&!dt.disposed&&Ae(dt,"livedesk-subscription-replaced"),He()},ee=fe=>{if(!K.current||We.disposed||k.current.get(ye)!==We)return;if(typeof fe.data=="string"){try{const nt=JSON.parse(fe.data),ct=(ft,dt=!0)=>{const Dt=w1(ft,ye,ie);return Dt?(We.expectedBinding=Dt,dt&&X.current?.(Dt),!0):!1};if(nt?.type==="RemoteFrameSubscriptionError")y(String(nt.error||"control-stream-start-failed"));else if(nt?.type==="RemoteFrameLiveAutoStart"){const dt=(Array.isArray(nt.skipped)?nt.skipped:[]).find(Dt=>Dt?.deviceId===ye);if(dt)dt.reason==="CAPTURE_TRANSITION_IN_PROGRESS"&&dt.retryScheduled===!0?y(""):y(String(dt.reason||"control-stream-start-failed"));else if(Array.isArray(nt.started)){const Dt=nt.started.find(Yt=>Yt?.deviceId===ye);Dt&&(y(""),ct(Dt,Dt.ready===!0))}}else nt?.type==="RemoteFrameStreamReady"&&nt.deviceId===ye&&ct(nt)&&y("")}catch{}return}const xe=fe.data instanceof ArrayBuffer?fe.data:null;xe&&(y(""),et(xe,We))},he=()=>{!K.current||We.disposed||k.current.get(ye)!==We||h("connecting")},Fe=()=>{const fe=!We.disposed;We.disposed=!0,We.handoffCompleted=!0;const xe=We.detachListeners;We.detachListeners=void 0,xe?.();const nt=k.current.get(ye);let ct=!1;if(nt===We){const ft=We.handoffFrom;We.handoffFrom=void 0,ft&&!ft.disposed&&(ft.socket.readyState===WebSocket.CONNECTING||ft.socket.readyState===WebSocket.OPEN)?(k.current.set(ye,ft),ct=!0):k.current.delete(ye)}if(He(),fe&&K.current&&nt===We&&!ct){const ft=window.setTimeout(()=>{F.current.get(ye)===ft&&F.current.delete(ye),K.current&&z(dt=>dt+1)},750);_e(ye),F.current.set(ye,ft)}};We.detachListeners=()=>{Be.removeEventListener("open",Rt),Be.removeEventListener("message",ee),Be.removeEventListener("error",he),Be.removeEventListener("close",Fe)},Be.addEventListener("open",Rt),Be.addEventListener("message",ee),Be.addEventListener("error",he),Be.addEventListener("close",Fe)}He()},[n,_e,Ae,Ce,Z,me,_,et,r,ne,V,le,o.monitorSelections,$,P,ue,ie,G,He]),d.useEffect(()=>{if(!G||!be||!H)return;const Ue=Z?Z.split(",").filter(Boolean):[];for(const Y of Ue){if(D.current.get(Y)===H)continue;const Se=k.current.get(Y);!Se||!ze(Y,Se,te,H)||D.current.set(Y,H)}},[Z,be,H,te,ze,G]),d.useEffect(()=>()=>{ue("livedesk-hook-unmount",!1)},[ue]);const Xe=d.useCallback((Ue,Y="browser-stale")=>{if(!G)return!1;const Se=Array.isArray(Ue)&&Ue.length>0?Ue:Z.split(",").filter(Boolean);if(Se.length===0)return!1;let ye=!1;for(const je of Se){const $e=k.current.get(je);!$e||$e.socket.readyState!==WebSocket.OPEN||(ye=ze(je,$e,Y,`${Date.now()}-${Math.random().toString(36).slice(2)}`)||ye)}return ye},[Z,ze,G]),Ze=d.useCallback((Ue,Y="browser-reconnect")=>{if(!G)return!1;const Se=Array.isArray(Ue)&&Ue.length>0?Ue:Z.split(",").filter(Boolean);if(Se.length===0)return!1;let ye=!1;for(const je of Se){const $e=k.current.get(je);$e&&(_e(je),Ae($e,`livedesk-${Y}`),k.current.delete(je),D.current.delete(je),x.current.delete(je),A.current.delete(je),ye=!0)}return ye&&u(new Map(x.current)),z(je=>je+1),He(),!0},[_e,Ae,Z,G,He]);return{frames:c,state:f,error:g,stats:w,restartLive:Xe,reconnectLive:Ze}}function x1(t,n,r=qn,o={}){const[c,u]=d.useState(null),[f,h]=d.useState(null),[g,y]=d.useState("idle"),[w,b]=d.useState(qf),x=d.useRef(null),A=d.useRef(o.onFrame),k=d.useRef(null),N=d.useRef(0),E=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),D=d.useMemo(()=>[...new Set(t.filter(Boolean))].join(","),[t]),T=d.useMemo(()=>[...new Set((o.captureDeviceIds||t).filter(Boolean))].join(","),[t,o.captureDeviceIds]),F=d.useMemo(()=>JSON.stringify(o.monitorSelections||{}),[o.monitorSelections]),O=d.useMemo(()=>{const G=Object.entries(o.connectionSessionIds||{}).filter(([K])=>!!K).map(([K,me])=>[K,String(me||"").trim()]).sort(([K],[me])=>K.localeCompare(me));return JSON.stringify(Object.fromEntries(G))},[o.connectionSessionIds]),P=d.useMemo(()=>({deviceIds:D.split(",").filter(Boolean),captureDeviceIds:T.split(",").filter(Boolean),fps:Number(o.fps||20),inputFps:Number(o.inputFps||8),width:Number(o.width||1920),height:Number(o.height||1080),tileWidth:Number(o.tileWidth||320),tileHeight:Number(o.tileHeight||180),monitorSelections:o.monitorSelections||{}}),[T,D,F,o.fps,o.height,o.inputFps,o.monitorSelections,o.tileHeight,o.tileWidth,o.width]),z=d.useMemo(()=>JSON.stringify({atlasConfiguration:P,connectionSessionKey:O}),[P,O]),I=d.useRef(P);I.current=P;const X=n&&P.deviceIds.length>0,se=d.useCallback(G=>G.readyState!==WebSocket.OPEN?!1:(G.send(JSON.stringify({type:"configure",...I.current})),!0),[]);d.useEffect(()=>{A.current=o.onFrame},[o.onFrame]),d.useEffect(()=>{if(!X)return;E.current.sampleStartedAt=performance.now();const G=window.setInterval(()=>{const K=E.current,me=performance.now(),V=Math.max(1,me-K.sampleStartedAt);b({totalFrames:K.totalFrames,totalBytes:K.totalBytes,framesPerSecond:K.sampleFrames*1e3/V,bytesPerSecond:K.sampleBytes*1e3/V,sampleMs:V,lastUpdatedAt:Date.now()});const ne=k.current;ne&&ne.frameSeq!==N.current&&(N.current=ne.frameSeq,u(ne)),K.sampleFrames=0,K.sampleBytes=0,K.sampleStartedAt=me},1e3);return()=>window.clearInterval(G)},[X]),d.useEffect(()=>{if(!X){x.current?.close(),x.current=null,u(null),k.current=null,N.current=0,h(null),y("idle"),b(qf);return}let G=!1,K=0;const me=()=>{if(G)return;const V=new WebSocket(Up("/api/remote/atlas/ws",r));V.binaryType="arraybuffer",x.current=V,y("connecting"),V.addEventListener("open",()=>{E.current.sampleStartedAt=performance.now(),y("open"),se(V)}),V.addEventListener("message",ne=>{if(typeof ne.data=="string"){try{const _=JSON.parse(ne.data);_?.type==="Mode4AtlasLayout"&&h({layoutVersion:Number(_.layoutVersion||0),width:Number(_.width||1920),height:Number(_.height||1080),columns:Number(_.columns||1),rows:Number(_.rows||1),tiles:Array.isArray(_.tiles)?_.tiles:[]})}catch{}return}const $=ne.data instanceof ArrayBuffer?ne.data:null;if(!(!$||$.byteLength<5))try{const _=Date.now(),be=new DataView($).getUint32(0,!1);if(be<=0||be+4>$.byteLength)return;const H=JSON.parse(Mv.decode(new Uint8Array($,4,be))),te=new Uint8Array($,4+be),le=pt(H.hubClientDropped),Ce=pt(H.hubClientQueueDepth),Ae=pt(H.hubClientQueueLimit),_e=pt(H.hubClientBufferedBytes),ue={deviceId:String(H.deviceId||"__livedesk_mode4_atlas__"),kind:"live",frameSeq:Number(H.frameSeq||0),streamFrameSeq:Number(H.streamFrameSeq||0)||void 0,streamId:String(H.streamId||"mode4-atlas"),commandId:H.commandId?String(H.commandId):void 0,width:Number(H.width||1920),height:Number(H.height||1080),sourceWidth:Number(H.sourceWidth||H.width||1920),sourceHeight:Number(H.sourceHeight||H.height||1080),mimeType:String(H.mimeType||"video/h264"),mode:String(H.mode||"mode4-h264-atlas"),frameMode:String(H.frameMode||"mode4-h264-atlas"),frameProfile:String(H.frameProfile||"mode4-h264-atlas-v1"),encoding:String(H.encoding||"video-atlas"),codec:String(H.codec||"h264"),compression:String(H.compression||"video/h264"),h264Format:String(H.h264Format||"annexb"),isKeyFrame:H.isKeyFrame===!0,chunkType:String(H.chunkType||""),timestampUs:Number(H.timestampUs||0),durationUs:Number(H.durationUs||0),transport:H.transport?String(H.transport):void 0,videoTransport:H.videoTransport?String(H.videoTransport):void 0,frameTransportActive:H.frameTransportActive?String(H.frameTransportActive):void 0,frameTransportProtocol:H.frameTransportProtocol?String(H.frameTransportProtocol):void 0,frameTransportState:H.frameTransportState?String(H.frameTransportState):void 0,frameTransportReason:H.frameTransportReason?String(H.frameTransportReason):void 0,frameTransportChangedAt:H.frameTransportChangedAt?String(H.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(H.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(H.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:H.frameTransportP2pReady===!0,hubClientQueueTelemetryAvailable:le!==void 0&&Ce!==void 0&&Ae!==void 0&&_e!==void 0,hubClientDropped:le,hubClientQueueDepth:Ce,hubClientQueueLimit:Ae,hubClientBufferedBytes:_e,udpIncompleteFrames:Number(H.udpIncompleteFrames||0)||0,hardwareEncoder:H.hardwareEncoder?String(H.hardwareEncoder):void 0,platformProfile:H.platformProfile?String(H.platformProfile):void 0,capturedAt:String(H.capturedAt||""),receivedAt:String(H.receivedAt||""),hubPacketAt:H.hubPacketAt?String(H.hubPacketAt):void 0,hubPacketEpochMs:Number(H.hubPacketEpochMs||0)||void 0,browserReceivedEpochMs:_,byteLength:te.byteLength,layoutVersion:Number(H.layoutVersion||0),atlasComposeMs:Number(H.atlasComposeMs||0),atlasPoolStarved:Number(H.atlasPoolStarved||0),atlasReadyTiles:Number(H.atlasReadyTiles||0),atlasTileCount:Number(H.atlasTileCount||0),atlasInputRevision:Number(H.atlasInputRevision||0),atlasSourceNewestAtEpochMs:Number(H.atlasSourceNewestAtEpochMs||0),atlasSourceOldestAtEpochMs:Number(H.atlasSourceOldestAtEpochMs||0),atlasSourceMaxAgeMs:Number(H.atlasSourceMaxAgeMs||0),payload:te},He=E.current;He.totalFrames+=1,He.totalBytes+=te.byteLength,He.sampleFrames+=1,He.sampleBytes+=te.byteLength,k.current=ue,N.current===0&&(N.current=ue.frameSeq,u(ue)),A.current?.(ue)}catch{}}),V.addEventListener("error",()=>y("error")),V.addEventListener("close",()=>{x.current===V&&(x.current=null),!G&&(y("closed"),K=window.setTimeout(me,1200))})};return me(),()=>{G=!0,window.clearTimeout(K),x.current?.close(),x.current=null}},[X,r,se]),d.useEffect(()=>{if(!X)return;const G=x.current;G&&se(G)},[z,X,se]);const Z=d.useCallback(()=>{const G=x.current;return G?se(G):!1},[se]);return{frame:c,layout:f,state:g,stats:w,refreshInputs:Z}}function S1(t,n=qn){const r=d.useRef(null),o=d.useRef(0),c=d.useRef(0),u=d.useRef(new Map),f=d.useRef(""),[h,g]=d.useState("idle"),[y,w]=d.useState(""),[b,x]=d.useState(Wb),A=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,c.current=0,f.current="",u.current.clear(),g("idle"),w(""),x(Wb);return}let N=!1,E=0;const D=()=>{if(N)return;const T=new WebSocket(Up("/api/remote/input/ws",n));r.current=T,A.current.sampleStartedAt=performance.now(),g("connecting"),w(""),T.addEventListener("open",()=>{N||r.current!==T||(w(""),g("open"))}),T.addEventListener("message",F=>{if(!(N||r.current!==T||typeof F.data!="string"))try{const O=JSON.parse(F.data),P=Number(O.inputSeq||O.result?.inputSeq||0),z=String(O.deviceId||O.result?.deviceId||""),I=String(O.inputEventId||O.result?.inputEventId||""),X=u.current.get(P);if(z&&(X&&X.deviceId!==z||!X&&f.current&&f.current!==z)||X?.inputEventId&&I&&X.inputEventId!==I)return;if(O?.type==="RemoteInputError"){P>0&&u.current.delete(P),w(String(O.error||O.result?.error||"Remote input failed.")),T.readyState===WebSocket.OPEN&&g("open");return}if(O?.type!=="RemoteInputApplied")return;X&&(A.current.lastRoundTripMs=Math.max(0,performance.now()-X.sentAt),u.current.delete(P)),A.current.lastInputSeq=P,A.current.lastAgentApplyMs=Math.max(0,Number(O.agentApplyMs||0)),w(""),g("open")}catch{}}),T.addEventListener("close",()=>{N||r.current!==T||(r.current=null,g("closed"),E=window.setTimeout(D,1200))}),T.addEventListener("error",()=>{!N&&r.current===T&&g("error")})};return D(),()=>{N=!0,window.clearTimeout(E);const T=r.current;r.current=null,T?.close(),u.current.clear()}},[t,n]),d.useEffect(()=>{if(!t)return;const N=window.setInterval(()=>{const E=performance.now(),D=A.current,T=Math.max(1,E-D.sampleStartedAt);x({totalSent:D.totalSent,totalDropped:D.totalDropped,sentPerSecond:D.sampleSent*1e3/T,droppedPerSecond:D.sampleDropped*1e3/T,bufferedAmount:r.current?.bufferedAmount||0,lastInputType:D.lastInputType,lastInputSeq:D.lastInputSeq,lastRoundTripMs:D.lastRoundTripMs,lastAgentApplyMs:D.lastAgentApplyMs,lastUpdatedAt:Date.now()}),D.sampleSent=0,D.sampleDropped=0,D.sampleStartedAt=E},1e3);return()=>window.clearInterval(N)},[t]);const k=d.useCallback((N,E)=>{const D=r.current;if(!D||D.readyState!==WebSocket.OPEN||!N)return!1;const T=String(E.type||"").toLowerCase(),F=T==="pointermove",P=F||T==="wheel",z=A.current;if(P&&D.bufferedAmount>f1)return z.totalDropped+=1,z.sampleDropped+=1,z.lastInputType=`${T}-coalescible-drop`,!1;if(!P&&D.bufferedAmount>m1){z.lastInputType=`${T||"input"}-fail-closed`,w("Remote input channel was reset because ordered input could not drain.");try{D.close(4001,"ordered-input-backpressure")}catch{}return!1}const I=o.current+1;o.current=I;const X=`${I}-${crypto.randomUUID()}`,se=Date.now(),Z=!P||I-c.current>=h1;for(Z&&(u.current.set(I,{sentAt:performance.now(),deviceId:N,inputEventId:X}),P&&(c.current=I)),f.current=N,F||gS.set(N,{inputSeq:I,inputType:T||"input",sentAt:performance.now()});u.current.size>256;){const G=u.current.keys().next().value;if(G===void 0)break;u.current.delete(G)}try{D.send(JSON.stringify({type:"input",requestId:P?"":crypto.randomUUID(),fireAndForget:P,deviceId:N,input:{...E,inputEventId:X,inputSeq:I,requestAck:Z,issuedAtEpochMs:se,issuedAt:new Date(se).toISOString()}}))}catch{u.current.delete(I),w("Remote input channel closed before the ordered input was queued.");try{D.close(4002,"input-send-failed")}catch{}return!1}return z.totalSent+=1,z.sampleSent+=1,z.lastInputType=T||"input",!0},[]);return{state:h,sendInput:k,stats:b,error:y}}const sd={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},C1=.25,Vb=300,Kb=2,np=1500,ug=5e3,k1=2e3,Qb=1e4,Rf=[0,1e3,3e3];function Yb(t){const n=Date.parse(String(t||""));return Number.isFinite(n)?Math.max(0,Date.now()-n):0}function M1(t,n,r=qn,o=0,c=!1,u="",f,h){const g=d.useRef(null),[y,w]=d.useState("idle"),[b,x]=d.useState(null),[A,k]=d.useState(sd),[N,E]=d.useState(""),D=d.useRef(c);return D.current=c,d.useEffect(()=>{c||(x(T=>T===null?T:null),k(T=>T===sd?T:sd))},[c]),d.useEffect(()=>{if(!n||!t){w("idle"),x(null),k(sd),E("");return}w("connecting"),x(null),k(sd),E("");const T=window.AudioContext||window.webkitAudioContext;if(!T){w("unsupported"),k(sd),E("Audio playback is not supported in this browser.");return}let F=!1,O=null;const P=zA.acquire(({release:z})=>{if(F){z();return}const I=new T({latencyHint:"interactive"});g.current=I;let X=String(u||"").trim();const se="/api/remote/audio/ws?devices="+encodeURIComponent(t)+(X?"&streamId="+encodeURIComponent(X):""),Z=new WebSocket(Up(se,r));Z.binaryType="arraybuffer";const G=ha.createOwner({deviceId:t,socket:Z,audioContext:I,statsTimer:null});let K=!1;const me=()=>{const ee=ha.releaseIfDrained(G);return(ee||!ha.hasOwner(G))&&!K&&(K=!0,z()),ee},V=kv({sampleRate:192e3,channels:8}).capacityBytes,ne=QA({maxPendingPackets:Yg,maxPendingBytes:V}),$=FA(),_={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(I.state),stalledCount:0,automaticRestarts:0,maximumAcceptedGapMs:0,activeStreamId:X,lastCaptureStatusAt:0,lastPcmAtEpochMs:0,workletRingCapacityBytes:0,workletRingBufferedBytes:0,workletRingBufferedMs:0,workletRingDroppedFrames:0,workletRingUnderflowCount:0};let ie=!1,be=!1,H=null,te=0,le=0,Ce="",Ae=!1,_e=()=>{},ue="connecting",He="";const ze=ee=>{ie||ee===ue||(ue=ee,w(ee))},et=ee=>{ie||ee===He||(He=ee,E(ee))};let Xe=0,Ze=!1,Ue=0,Y=0,Se=0,ye=!1;const je=()=>{ha.setPendingWorkletPackets(G,ne.getPendingPacketCount(),ne.getPendingPacketBytes(),ne.getPendingPacketHighWater(),ne.getPendingByteHighWater())},$e=ee=>{_.workletRingCapacityBytes=Math.max(0,Math.min(V,Number(ee.ringCapacityBytes||0)||0)),_.workletRingBufferedBytes=Math.max(0,Math.min(_.workletRingCapacityBytes,Number(ee.ringBufferedBytes||0)||0)),_.workletRingBufferedMs=Math.max(0,Math.min(C1*1e3,Number(ee.ringBufferedMs||0)||0)),_.workletRingDroppedFrames=Math.max(_.workletRingDroppedFrames,Number(ee.ringDroppedFrames||0)||0),_.workletRingUnderflowCount=Math.max(_.workletRingUnderflowCount,Number(ee.ringUnderflowCount||0)||0),ha.setPcmRing(G,_.workletRingCapacityBytes,_.workletRingBufferedBytes)},B=()=>{const ee=H;if(H=null,Ae=!1,ee){ee.onprocessorerror=null,ee.port.onmessage=null;try{ee.disconnect()}catch{}try{ee.port.close()}catch{}}ne.terminate(),je(),_.workletRingCapacityBytes=0,_.workletRingBufferedBytes=0,_.workletRingBufferedMs=0,ha.setPcmRing(G,0,0),ha.setWorkletNode(G,0,0,te),me()},lt=ee=>{const he=ee.data||{},Fe=String(he.type||"");if((Fe==="packet-terminal"||Fe==="processor-error")&&(ne.acknowledge(typeof he.packetId=="number"?he.packetId:String(he.packetId||"")),je()),Fe==="packet-terminal"){const fe=Math.max(0,Number(he.droppedFrames||0)||0);fe>0&&(_.workletRingDroppedFrames+=fe,_.resyncs+=1)}if(Fe==="ring-configured"||Fe==="ring-state"||Fe==="disposed"){const fe=_.workletRingDroppedFrames;$e(he),_.workletRingDroppedFrames>fe&&(_.resyncs+=1)}Fe==="disposed"?B():Fe==="processor-error"&&_e(String(he.error||"Remote audio worklet processing failed."))},Nt=()=>{if(!(!H||!Ae))try{H.port.postMessage({type:"flush"})}catch{_e("Remote audio worklet could not be flushed.")}},Ht=()=>{Z.readyState===WebSocket.OPEN&&Z.send(JSON.stringify({type:"subscribe",deviceIds:[t],streamIdsByDeviceId:X?{[t]:X}:{}}))},ke=()=>{_.audioContextState=String(I.state),!ie&&(_.audioContextState==="suspended"||_.audioContextState==="interrupted"?ze("suspended"):_.audioContextState==="closed"&&(ze("error"),et("The browser audio context is closed. Toggle Remote Audio off and on to recover.")))},qe=async()=>{if(ie||String(I.state)==="closed")return!1;try{if(String(I.state)!=="running"&&await I.resume(),_.audioContextState=String(I.state),!ie&&!Ze&&_.audioContextState==="running"){const ee=_.lastAcceptedAt>0&&performance.now()-_.lastAcceptedAt<=np,he=_.lastCaptureStatusAt>0&&performance.now()-_.lastCaptureStatusAt<=ug&&_.captureHealthy;ze(ee?"playing":he?"silent":"open")}return _.audioContextState==="running"}catch(ee){return ie||(ze("suspended"),et(ee instanceof Error?"Audio playback is suspended: "+ee.message:"Audio playback is suspended.")),!1}},Ye=async()=>{if(!I.audioWorklet||typeof AudioWorkletNode>"u")throw new Error("AudioWorklet is unavailable in this browser.");const ee=new Blob([e1],{type:"text/javascript"});Ce=URL.createObjectURL(ee);try{await I.audioWorklet.addModule(Ce)}finally{URL.revokeObjectURL(Ce),Ce=""}if(ie||String(I.state)==="closed")return;const he=new AudioWorkletNode(I,hS,{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[Kb],channelCount:Kb,channelCountMode:"explicit"});te+=1,H=he,he.port.onmessage=lt,he.onprocessorerror=()=>{_e("Remote audio worklet stopped unexpectedly.")},he.connect(I.destination),Ae=!0,ha.setWorkletNode(G,1,1,te)},_t=(ee,he,Fe,fe)=>{const xe=H;if(ie||!Ae||!xe||he.byteLength<=0)return!1;const nt=Cv({sampleRate:ee.sampleRate,channels:ee.channels,mimeType:ee.mimeType}),ct=++le;if(!ne.claim(ct,he.byteLength))return je(),!1;je();try{return xe.port.postMessage({type:"pcm",packetId:ct,buffer:he,byteOffset:Fe,byteLength:fe,sampleRate:nt.sampleRate,channels:nt.channels,mimeType:ee.mimeType,sampleFormat:nt.sampleFormat},[he]),!0}catch{return ne.acknowledge(ct),je(),!1}},tt=async()=>{if(ie||Ze||Z.readyState!==WebSocket.OPEN)return;if(Ue>=Rf.length){ze("error"),et("Remote audio stopped sending frames. Toggle Audio off and on to retry.");return}const ee=Ue;Ue+=1,Ze=!0,_.stalledCount+=1,_.automaticRestarts+=1,ze("reconnecting");try{if(!f)throw new Error("Remote audio restart owner is unavailable.");const he=await f(t);if(ie||!he)return;X=he,Ht();const Fe=performance.now();Xe=Fe,_.lastPacketAt=Fe,_.lastAcceptedAt=0,_.lastCaptureStatusAt=0,_.lastPcmAtEpochMs=0,_.captureAlive=null,_.helperAlive=null,_.helperReady=!1,_.captureHealthy=!1,_.captureStatusFailed=!1,_.captureAwaitingCurrentPcm=!1,_.captureAwaitingSinceAt=0,_.capturePhase="",_.backendKind="",_.helperRequired=!1,_.helperPid=0,_.nativeCallbackDiagnosticsAvailable=!1,_.nativeRejectedCallbackCount=0,_.nativeCurrentnessDropCount=0,_.nativeLastDropReason="",_.silentForMs=0,_.activeStreamId=X,_.lastFrameSeq=0,_.maximumAcceptedGapMs=0,Nt(),Y=Fe+(Rf[ee+1]??3e3),et(""),ie||ze("open")}catch(he){ie||(Y=performance.now()+(Rf[ee+1]??3e3),ze("error"),et(he instanceof Error?"Remote audio restart failed: "+he.message:"Remote audio restart failed."))}finally{Ze=!1}},pe=()=>{_.drops+=1},Ne=window.setInterval(()=>{if(ie)return;const ee=performance.now(),he=_.lastPacketAt>0?Math.max(0,ee-_.lastPacketAt):Xe>0?Math.max(0,ee-Xe):0,Fe=_.lastAcceptedAt>0?Math.max(0,ee-_.lastAcceptedAt):0,fe=_.lastCaptureStatusAt>0?Math.max(0,ee-_.lastCaptureStatusAt):0,xe=Z.readyState===WebSocket.OPEN,nt=_.lastCaptureStatusAt>0,ct=nt&&fe<=ug&&_.captureHealthy,ft=nt&&_.captureStatusFailed&&fe>k1,dt=nt&&fe>ug,Dt=!nt&&Xe>0&&ee-Xe>Qb,Yt=_.captureAwaitingCurrentPcm&&_.captureAwaitingSinceAt>0&&ee-_.captureAwaitingSinceAt>Qb,cn=Xe>0&&(_.lastAcceptedAt<=0?ee-Xe>np:Fe>np);if(xe&&Xe>0&&(ft||dt||Dt||Yt)?Ue>=Rf.length&&!Ze?(ze("error"),et("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!Ze&&ee>=Y?tt():Ze||ze("stalled"):xe&&cn&&!Ze&&_.audioContextState!=="suspended"&&_.audioContextState!=="interrupted"&&ze(ct?"silent":"open"),$A({enabled:D.current,now:ee,lastPublishedAt:Se})){Se=ee,k({queuedMs:_.workletRingBufferedMs,browserAgeMs:_.browserAgeMs,captureAgeMs:_.captureAgeMs,captureStatusAgeMs:fe,silentForMs:_.silentForMs,captureAlive:_.captureAlive,helperAlive:_.helperAlive,helperReady:_.helperReady,captureHealthy:_.captureHealthy,captureAwaitingCurrentPcm:_.captureAwaitingCurrentPcm,capturePhase:_.capturePhase,backendKind:_.backendKind,helperRequired:_.helperRequired,helperPid:_.helperPid,captureRestartCount:_.captureRestartCount,nativeCallbackDiagnosticsAvailable:_.nativeCallbackDiagnosticsAvailable,nativeRejectedCallbackCount:_.nativeRejectedCallbackCount,nativeCurrentnessDropCount:_.nativeCurrentnessDropCount,nativeLastDropReason:_.nativeLastDropReason,localProcessingAgeMs:_.localProcessingAgeMs,lastPacketAgeMs:he,lastAcceptedAgeMs:Fe,framesReceived:_.framesReceived,drops:_.drops,resyncs:_.resyncs,pendingDecodes:_.pendingDecodes,lastFrameSeq:_.lastFrameSeq,audioContextState:_.audioContextState,stalledCount:_.stalledCount,automaticRestarts:_.automaticRestarts,maximumAcceptedGapMs:_.maximumAcceptedGapMs,workletRingCapacityBytes:_.workletRingCapacityBytes,workletRingBufferedBytes:_.workletRingBufferedBytes,workletRingDroppedFrames:_.workletRingDroppedFrames,workletRingUnderflowCount:_.workletRingUnderflowCount,lastUpdatedAt:Date.now()});const Xt=$.publish();Xt&&(ye=!0,ha.setRetainedFrame(G,1,Xt.payload.byteLength),x(Xt))}else!D.current&&ye&&(ye=!1,$.clear(),ha.setRetainedFrame(G,0,0))},250);ha.setStatsTimer(G,Ne);const Be=()=>{ke(),(String(I.state)==="suspended"||String(I.state)==="interrupted")&&qe()},Oe=()=>{document.visibilityState==="visible"&&qe()},We=()=>{qe()};I.addEventListener("statechange",Be),document.addEventListener("visibilitychange",Oe),window.addEventListener("pageshow",We),window.addEventListener("pointerdown",We),window.addEventListener("keydown",We),ze("connecting"),et(""),ke();const Rt=(ee,he,Fe,fe,xe)=>{if(_.localProcessingAgeMs=Math.max(0,performance.now()-xe),ie||_.localProcessingAgeMs>Vb||!Xg(ee,{deviceId:t,streamId:X}))return pe(),!1;_.activeStreamId!==X&&(_.activeStreamId=X,_.lastFrameSeq=0,_.maximumAcceptedGapMs=0,Nt());const nt=GA(ee,{deviceId:t,streamId:X,lastFrameSeq:_.lastFrameSeq});if(!nt.accepted||!_t(ee,he,Fe,fe))return pe(),!1;_.browserAgeMs=Yb(ee.receivedAt),_.captureAgeMs=Yb(ee.capturedAt);const ct=performance.now();_.lastAcceptedAt>0&&(_.maximumAcceptedGapMs=Math.max(_.maximumAcceptedGapMs,ct-_.lastAcceptedAt)),_.lastAcceptedAt=ct,_.framesReceived+=1,_.lastFrameSeq=nt.nextFrameSeq,Ue=0,Y=0,D.current&&($.accept(ee),ye=!0,ha.setRetainedFrame(G,1,0)),String(I.state)!=="running"&&qe();const ft=String(I.state)==="running";return ft&&et(""),ze(ft?"playing":"suspended"),!0};_e=(ee="")=>{if(!be){if(be=!0,ee&&(ha.recordTerminalFailure(G,ee,ee.includes("setup failed")?"setup":"processor"),ze(ee.includes("AudioWorklet is unavailable")?"unsupported":"error"),et(ee),h?.(t,X,"browser-audio-playback-failed").catch(()=>{})),ie=!0,ha.deactivate(G),window.clearInterval(Ne),ha.setStatsTimer(G,null),I.removeEventListener("statechange",Be),document.removeEventListener("visibilitychange",Oe),window.removeEventListener("pageshow",We),window.removeEventListener("pointerdown",We),window.removeEventListener("keydown",We),$.clear(),ha.setRetainedFrame(G,0,0),H)try{H.port.postMessage({type:"dispose"})}catch{}try{Z.close()}catch{}Z.readyState===WebSocket.CLOSED&&ha.setSocket(G,null),I.close().catch(()=>{}).finally(()=>{B(),String(I.state)==="closed"&&ha.setAudioContext(G,null),me()}),g.current===I&&(g.current=null),me()}},Ye().catch(ee=>{_e(ee instanceof Error?`Remote audio worklet setup failed: ${ee.message}`:"Remote audio worklet setup failed.")}),Z.addEventListener("open",()=>{ie||(Xe=performance.now(),_.lastPacketAt=Xe,_.lastAcceptedAt=0,_.lastCaptureStatusAt=0,_.lastPcmAtEpochMs=0,_.captureAlive=null,_.helperAlive=null,_.helperReady=!1,_.captureHealthy=!1,_.captureStatusFailed=!1,_.captureAwaitingCurrentPcm=!1,_.captureAwaitingSinceAt=0,_.capturePhase="",_.backendKind="",_.helperRequired=!1,_.helperPid=0,_.maximumAcceptedGapMs=0,_.silentForMs=0,ze("open"),Ht(),qe())}),Z.addEventListener("message",ee=>{if(typeof ee.data=="string")return;const he=ee.data instanceof ArrayBuffer?ee.data:null;if(!he||he.byteLength<5)return;const Fe=performance.now();_.lastPacketAt=Fe;try{const xe=new DataView(he).getUint32(0,!1);if(xe<=0||xe+4>he.byteLength){pe();return}const nt=new Uint8Array(he,4,xe),ct=JSON.parse(Mv.decode(nt)),ft=new Uint8Array(he,4+xe),dt=String(ct.deviceId||""),Dt=String(ct.streamId||"");if(!Xg({deviceId:dt,streamId:Dt},{deviceId:t,streamId:X})){pe();return}const Yt=String(ct.frameKind||ct.kind||"").toLowerCase();if(ct.type==="remote.audio.status"||Yt==="audio-status"){_.lastCaptureStatusAt=Fe;const Xt=VA(ct);if(_.captureAlive=Xt.captureAlive,_.helperAlive=Xt.helperAlive,_.helperReady=Xt.helperReady,_.captureHealthy=Xt.healthy,_.captureStatusFailed=Xt.failed,_.captureAwaitingCurrentPcm=Xt.awaitingCurrentPcm,Xt.awaitingCurrentPcm?_.captureAwaitingSinceAt||=Fe:_.captureAwaitingSinceAt=0,_.capturePhase=Xt.capturePhase,_.backendKind=Xt.backendKind,_.helperRequired=Xt.helperRequired===!0,_.helperPid=Xt.helperPid,_.captureRestartCount=Math.max(0,Number(ct.restartCount||0)||0),_.nativeCallbackDiagnosticsAvailable=ct.callbackDiagnosticsAvailable===!0,_.nativeRejectedCallbackCount=_.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(ct.rejectedCallbackCount||0)||0):0,_.nativeCurrentnessDropCount=_.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(ct.currentnessDropCount||0)||0):0,_.nativeLastDropReason=_.nativeCallbackDiagnosticsAvailable?String(ct.lastDropReason||""):"",_.lastPcmAtEpochMs=Math.max(0,Number(ct.lastPcmAtEpochMs||0)||0),_.silentForMs=Math.max(0,Number(ct.silentForMs||0)||0),_.captureAgeMs=_.lastPcmAtEpochMs>0?Math.max(0,Date.now()-_.lastPcmAtEpochMs):_.silentForMs,_.captureHealthy){if(Ue=0,Y=0,!Ze){et("");const oa=String(I.state)==="running",Na=_.lastAcceptedAt>0&&performance.now()-_.lastAcceptedAt<=np;ze(oa?Na?"playing":"silent":"suspended")}}else _.captureAwaitingCurrentPcm&&!Ze?ze("open"):_.captureStatusFailed&&!Ze&&ze("stalled");return}const cn={deviceId:dt,frameSeq:Number(ct.frameSeq||0),streamId:Dt,mimeType:String(ct.mimeType||"audio/webm;codecs=opus"),sampleRate:Number(ct.sampleRate||48e3),channels:Number(ct.channels||2),capturedAt:String(ct.capturedAt||""),receivedAt:String(ct.receivedAt||""),byteLength:Number(ct.byteLength||ft.byteLength),payload:pS};if(!cn.deviceId||ie)return;if(performance.now()-Fe>Vb){pe();return}if(WA(cn.mimeType)){Rt(cn,he,ft.byteOffset,ft.byteLength,Fe);return}pe(),ze("error"),et(`Unsupported remote audio format "${cn.mimeType}". Requesting a bounded PCM restart.`),!Ze&&Ue<Rf.length&&(Y=0,tt());return}catch(fe){ie||(ze("error"),et(fe instanceof Error?fe.message:String(fe)))}}),Z.addEventListener("error",()=>{ie||(ze("error"),et("Remote audio WebSocket error."))}),Z.addEventListener("close",()=>{ha.setSocket(G,null),me(),ie||ze("closed")}),O=()=>{_e()}});return P.ready.catch(z=>{F||(w("error"),E(z instanceof Error?`Remote audio owner setup failed: ${z.message}`:"Remote audio owner setup failed."))}),()=>{F=!0,O?O():P.cancel()}},[t,n,r,o,f,h]),{state:y,lastFrame:b,stats:A,error:N}}const A1=3;function Xb(t,n,r){const o=Math.max(1,Number(r)||1),c=Math.max(0,Math.min(o,Number(t)-Number(n))),u=Math.min(o/2,A1);return c<=u?0:c>=o-u?1:c/o}function N1(t,n,r){return{normalizedX:Xb(t,r.left,r.width),normalizedY:Xb(n,r.top,r.height)}}const _p=Object.freeze({shiftKey:Object.freeze(["ShiftLeft","ShiftRight"]),ctrlKey:Object.freeze(["ControlLeft","ControlRight"]),altKey:Object.freeze(["AltLeft","AltRight"]),metaKey:Object.freeze(["MetaLeft","MetaRight"])}),T1=Object.freeze({shiftKey:"ShiftLeft",ctrlKey:"ControlLeft",altKey:"AltLeft",metaKey:"MetaLeft"}),Zb=Object.freeze({OSLeft:"MetaLeft",OSRight:"MetaRight"}),Jg=64;function Qp(t,n=80){return String(t||"").replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,n)}function ev(t){const n=Qp(t);return Object.prototype.hasOwnProperty.call(Zb,n)?Zb[n]:n}function Jb(t={}){const n=Qp(t.key),r=Number.isFinite(Number(t.location))?Math.max(0,Math.min(3,Math.trunc(Number(t.location)))):0,o=r===2?"Right":"Left";return n==="Shift"?`Shift${o}`:n==="Control"?`Control${o}`:n==="Alt"||n==="AltGraph"?`Alt${o}`:n==="Meta"||n==="OS"?`Meta${o}`:n?`Key:${r}:${n}`.slice(0,80):""}function tv(t={}){const n=ev(t.code);return["Shift","Control","Alt","AltGraph","Meta","OS"].includes(n)?Jb({...t,key:n}):n||Jb(t)}function kp(t){for(const[n,r]of Object.entries(_p))if(r.includes(t))return n;return""}function Ol(t,n){return _p[n].some(r=>t.has(r))}function ap(t,n,r={},o="",c=""){for(const u of Object.keys(_p)){const f=r[u]===!0,h=_p[u];if(u===o){if(c==="keyup"&&!f)for(const g of h)n.has(g)||t.delete(g);continue}if(f){!Ol(t,u)&&t.size<Jg&&t.add(T1[u]);continue}for(const g of h)n.has(g)||t.delete(g)}}function R1(t,n){if(t.length!==n.size)return!1;let r=0;for(const o of n){if(t[r]!==o)return!1;r+=1}return!0}function ew(t){for(const n of[...t])kp(n)||t.delete(n)}function nv(t){return{shiftKey:Ol(t,"shiftKey"),ctrlKey:Ol(t,"ctrlKey"),altKey:Ol(t,"altKey"),metaKey:Ol(t,"metaKey")}}function j1(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 E1(t,n,r){const o=tv(t),c=Qp(t.key),u=Number(t.keyCode??t.which),f=Number(t.location);return{type:n,key:c,code:o,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:c.length===1?c:"",repeat:n==="keydown"&&t.repeat===!0,pressedCodes:[...r],...nv(r)}}function D1(){const t=new Set,n=new Set,r=()=>({pressedCodes:[...t]});return{event(o={},c=""){if(c!=="keydown"&&c!=="keyup")return null;const u=tv(o);if(!u)return null;const f=kp(u),h=t.has(u),g=[...t];return f?c==="keydown"?(ap(t,n,o,f,c),t.size<Jg&&t.add(u)):(n.has(u)||t.delete(u),ap(t,n,o,f,c)):(ap(t,n,o),c==="keydown"?t.size<Jg&&t.add(u):t.delete(u)),c==="keyup"&&f==="metaKey"&&!Ol(t,"metaKey")&&ew(t),c==="keydown"&&h&&o.repeat!==!0&&R1(g,t)?null:E1(o,c,t)},modifier(o,c){const u=ev(o),f=kp(u);if(!f)return null;const h=n.has(u);return c===h?null:(c?(n.add(u),t.add(u)):(n.delete(u),t.delete(u),f==="metaKey"&&!Ol(t,"metaKey")&&ew(t)),{type:c?"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(),...nv(t)})},reset(o="keyboard-owner-reset",c=!1){const u=t.size>0;return t.clear(),n.clear(),!u&&!c?null:{type:"keyboard.reset",reason:Qp(o,120)||"keyboard-owner-reset",pressedCodes:[],shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1,repeat:!1}},isPressed(o={}){const c=typeof o=="string"?ev(o):tv(o);if(t.has(c))return!0;const u=kp(c);return!!u&&Ol(t,u)},snapshot(){return{...r(),latchedCodes:[...n],...nv(t)}}}}const vS=64,I1=2;function yS(t){const n=Math.floor(Number(t));return Number.isFinite(n)?Math.max(1,Math.min(vS,n)):1}function Av(t){const n=Math.floor(Number(t));return Number.isFinite(n)?Math.max(0,Math.min(vS-1,n)):0}function bS(t){const n=String(t||"").trim().toLowerCase();return n==="macos"||n==="darwin"||n==="mac"||n==="macosx"||n==="linux"||n.startsWith("linux ")}function L1(t,n,r){const o=String(n||"").trim();if(!o)return t||null;const c=String(r||"").trim();return t&&t.fingerprint===o&&(c?t.sampleId===c:t.sampleId==="")?t:{fingerprint:o,sampleId:c,consecutiveSamples:t?.fingerprint===o?t.consecutiveSamples+1:1}}function wS({platform:t,topologyFingerprint:n,consecutiveTopologySamples:r}){return bS(t)?!!String(n||"").trim()&&Number(r)>=I1:!0}function _1({requestedIndex:t,monitorCount:n,platform:r,topologyFingerprint:o,consecutiveTopologySamples:c}){const u=Av(t),f=yS(n);return u<f||!wS({platform:r,topologyFingerprint:o,consecutiveTopologySamples:c})?u:f-1}function F1(t,n,r){const o=Av(t),c=yS(n);return o<c||bS(r)?o:c-1}function Wl(t){const n=Number(t);return Number.isSafeInteger(n)&&n>0?n:0}function ga(t){return String(t||"").trim()}function rp(t,n,r={}){return{deviceId:ga(t),transitionGeneration:Wl(n),sessionId:ga(r.sessionId),streamId:ga(r.streamId),commandId:ga(r.commandId),captureGeneration:Wl(r.captureGeneration),monitorIndex:Math.max(0,Math.floor(Number(r.monitorIndex)||0))}}function $n(t,n){return!!t&&!!n&&ga(t.deviceId)===ga(n.deviceId)&&Wl(t.transitionGeneration)===Wl(n.transitionGeneration)}function tw({deviceId:t,requestTransitionGeneration:n,currentTransitionGeneration:r,actualControlOwner:o}){const c=ga(t),u=Wl(n),f=Wl(r);return!!c&&u>0&&u===f&&(!o||ga(o.deviceId)===c)}function nw(t,n){const r=Promise.resolve(t).catch(()=>{}).then(n);return{result:r,tail:r.then(()=>{},()=>{})}}function sp(t,n,r){const o=ga(t);return!o||!n||ga(n.deviceId)!==o?!1:!r||ga(r.deviceId)!==o}function dg(t,n){if(!t||!n)return!1;const r=Wl(n.captureGeneration),o=ga(n.commandId),c=ga(n.sessionId),u=ga(n.streamId),f=Number(t.monitorIndex);return!r||!o||!c||!u||!Number.isInteger(f)||f<0?!1:ga(t.deviceId)===ga(n.deviceId)&&ga(t.sessionId)===c&&ga(t.streamId)===u&&ga(t.commandId)===o&&Wl(t.captureGeneration)===r&&ga(t.streamPurpose).toLowerCase()==="control"&&f===n.monitorIndex}function P1(t,n){const r=Promise.resolve(t).catch(()=>{}).then(n);return{result:r,tail:r.then(()=>{},()=>{})}}function O1(){let t=Promise.resolve(),n=Promise.resolve();const r=o=>{const c=P1(t,o);return t=c.tail,c.result};return{enqueue:r,enqueueStop(o){const c=r(o);return n=c.then(()=>{}),n.catch(()=>{}),c},enqueueStart(o){const c=n;return r(async()=>(await c,o()))}}}function B1(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 H1(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:20,slowWallFps:5,fastWallFps:20,directPopulationThrottle:!1,adaptiveMinimumCurrentSampleMs:750,adaptiveDownshiftStableMs:6e3,adaptiveDownshiftConsecutiveSamples:3,missingDeliveryRatio:.72,recoveryDeliveryRatio:.88,recoveryByteRatio:.52,recoveryGapRatio:.7,controlWallReuseMaxFps:24,scalableAtlasMinInputFps:8,scalableAtlasMaxInputFps:20,scalableAtlasAggregateInputFps:120,atlasOutputFps:20,directDecodeAcceleration:"prefer-hardware",directLatencyMode:"interactive"});function av(t){return t==="slow"?ta.slowWallFps:ta.fastWallFps}function z1(t,n){const r=Number.isFinite(Number(n))?Math.max(0,Math.floor(Number(n))):Number.POSITIVE_INFINITY;if(r<=0)return[];const o=(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))}),c=[],u=new Set;for(const f of o){const h=String(f.deviceId).trim();if(!u.has(h)&&(u.add(h),c.push(h),c.length>=r))break}return c}function $1(t,n){const r=Math.max(0,Math.floor(Number(n)||0));return t===!0&&r>0}function jf({mode4Enabled:t,directMode4WallEnabled:n,isMac:r}){return"direct"}function U1({mode4Enabled:t,directMode4WallEnabled:n,adaptiveFps:r,directDeviceCount:o,adaptive:c=!0}){return Math.max(1,Math.floor(Number(r)||1))}function q1({directDeviceCount:t,requestedFps:n,measuredFramesPerSecond:r,measuredPaintFramesPerSecond:o,measuredBytesPerSecond:c,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),x=Math.max(0,Number(o)||0),A=Math.max(0,Number(c)||0),k=Math.max(1,Number(u)||1),N=Math.max(0,Number(f)||0),E=Math.max(0,Number(h)||0),D=Math.max(1,Number(g)||1),T=y*w,F=T>8&&b<T*ta.missingDeliveryRatio,O=T>8&&x<T*ta.missingDeliveryRatio,P=A>k||N>D||F||O,z=b>=T*ta.recoveryDeliveryRatio&&x>=T*ta.recoveryDeliveryRatio&&A<k*ta.recoveryByteRatio&&N<D*ta.recoveryGapRatio&&E<D*ta.recoveryGapRatio;return{expectedFramesPerSecond:T,estimatedMissingFrames:F,estimatedMissingPaints:O,overloaded:P,healthyForRecovery:z}}function W1({receiveSampleMs:t,paintSampleMs:n,currentGenerationVerified:r,frameRequestedFps:o,adaptiveFps:c}){const u=Number(t),f=Number(n),h=Number(o),g=Number(c);return r===!0&&Number.isFinite(u)&&u>=ta.adaptiveMinimumCurrentSampleMs&&Number.isFinite(f)&&f>=ta.adaptiveMinimumCurrentSampleMs&&Number.isFinite(h)&&h>0&&h===g}function G1({deviceCount:t,targetFps:n,adaptive:r=!0}){const o=Math.max(1,Math.floor(Number(t)||1)),c=Math.max(1,Math.min(ta.scalableAtlasMaxInputFps,Math.floor(Number(n)||ta.scalableAtlasMaxInputFps)));if(!r)return c;const u=Math.max(ta.scalableAtlasMinInputFps,Math.min(ta.scalableAtlasMaxInputFps,Math.floor(ta.scalableAtlasAggregateInputFps/o)));return Math.min(c,u)}function V1(t,n){return{acceleration:ta.directDecodeAcceleration,latencyMode:ta.directLatencyMode}}const ud=999;function Yf(t){const n=Number(t);if(!Number.isFinite(n))return 0;const r=Math.floor(n);return r>=1&&r<=ud?r:0}function K1(t){return String(t?.deviceName||t?.hostname||t?.deviceId||"Unknown Client").trim()||"Unknown Client"}function Nv(t,n){return{deviceId:String(t?.deviceId||"").trim(),label:K1(t),platform:String(t?.platform||"").trim(),slotNumber:Yf(n)}}function Yc(t){const n=Array.isArray(t)?t:[],r=new Map,o=new Set;for(const c of n){const u=String(c?.deviceId||"").trim(),f=Yf(c?.slotNumber);if(!u||!f||r.has(u)||o.has(f))continue;const h={deviceId:u,label:String(c?.label||u).trim()||u,platform:String(c?.platform||"").trim(),slotNumber:f};r.set(u,h),o.add(f)}return[...r.values()].sort((c,u)=>c.slotNumber-u.slotNumber||c.deviceId.localeCompare(u.deviceId))}function Q1(t){return Yc((Array.isArray(t)?t:[]).flatMap((n,r)=>n?.deviceId?[Nv(n,r+1)]:[]))}function Y1({connectedDevices:t,entries:n,minimumSlotCount:r=0}){const o=Yc(n),c=(Array.isArray(t)?t:[]).filter(w=>w?.deviceId).slice().sort((w,b)=>{const x=Yf(w.slotNumber)||ud+1,A=Yf(b.slotNumber)||ud+1;return x-A||String(w.deviceId).localeCompare(String(b.deviceId))}),u=o.reduce((w,b)=>Math.max(w,b.slotNumber),0),f=Math.min(ud,Math.max(0,Math.floor(Number(r)||0),u,c.length)),h=Array.from({length:f},(w,b)=>({slotNumber:b+1,device:null,saved:null,offline:!1,persisted:!1})),g=new Map(c.map(w=>[String(w.deviceId),w])),y=new Set;for(const w of o){for(;h.length<w.slotNumber&&h.length<ud;)h.push({slotNumber:h.length+1,device:null,saved:null,offline:!1,persisted:!1});const b=h[w.slotNumber-1];if(!b)continue;const x=g.get(w.deviceId)||null;b.device=x,b.saved=w,b.offline=!x,b.persisted=!0,y.add(w.deviceId)}for(const w of c){const b=String(w.deviceId);if(y.has(b))continue;let x=h.find(A=>!A.device&&!A.saved);if(!x&&h.length<ud&&(x={slotNumber:h.length+1,device:null,saved:null,offline:!1,persisted:!1},h.push(x)),!x)break;x.device=w,x.saved=Nv(w,x.slotNumber),x.offline=!1,x.persisted=!1,y.add(b)}return h}function xS(t){return Yc((Array.isArray(t)?t:[]).flatMap(n=>String(n?.saved?.deviceId||n?.device?.deviceId||"").trim()?[n.device?Nv(n.device,n.slotNumber):{...n.saved,slotNumber:n.slotNumber}]:[]))}function X1(t,n,r){const o=String(n||"").trim(),c=Yf(r),u=xS(t);if(!o||!c)return u;const f=u.find(y=>y.deviceId===o);if(!f||f.slotNumber===c)return u;const h=u.find(y=>y.slotNumber===c),g=f.slotNumber;return f.slotNumber=c,h&&(h.slotNumber=g),Yc(u)}const zc={revision:0,settings:{security:{accessMode:"trusted-only"},control:{allowKeyboardMouse:!0,allowRemoteRestart:!1},filesAudio:{allowFileTransfer:!0,allowRemoteAudio:!0,rollingBufferEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0}}},Z1=[{id:"connection",label:"Connection",icon:zp},{id:"remote-access",label:"Remote Access",icon:Aa},{id:"capture-audio",label:"Capture & Audio",icon:Ig},{id:"agent",label:"Agent",icon:zl}];function Mp(t,n){return t?.settings?.[n]||zc.settings[n]||{}}function aw(t,n){return{...t,settings:{...t.settings,[n.section]:{...Mp(t,n.section),[n.key]:n.value}}}}function fg(t){return{revision:Number(t.revision||0),updatedAt:t.updatedAt,settings:t.settings}}function _c({icon:t,title:n,description:r,children:o,recommended:c=!1}){return i.jsxs("div",{className:"product-setting-row",children:[i.jsx("div",{className:"product-setting-control",children:o}),t&&i.jsx("span",{className:"product-setting-icon",children:i.jsx(t,{size:17})}),i.jsxs("div",{className:"product-setting-copy",children:[i.jsx("strong",{children:n}),c&&i.jsx("em",{children:"Recommended"}),i.jsx("small",{children:r})]})]})}function Ef({checked:t,onChange:n,label:r}){return i.jsxs("label",{className:"product-switch",children:[i.jsx("input",{"aria-label":r,type:"checkbox",checked:t,onChange:o=>n(o.target.checked)}),i.jsx("span",{})]})}function rw({value:t,onChange:n,options:r,label:o}){return i.jsx("select",{"aria-label":o,value:String(t),onChange:c=>n(c.target.value),children:r.map(([c,u])=>i.jsx("option",{value:c,children:u},c))})}function J1({hubUrl:t="",runtimeRole:n="hub",runtimeDeviceId:r="",sessionAccessToken:o="",initialTab:c="connection",pin:u,agent:f,captureGallery:h}){const[g,y]=d.useState(c),[w,b]=d.useState(null),[x,A]=d.useState("loading"),[k,N]=d.useState(""),[E,D]=d.useState("idle"),[T,F]=d.useState(""),O=d.useRef(null),P=d.useRef(null),z=d.useRef([]),I=d.useRef(Promise.resolve()),X=d.useRef(0),se=d.useRef(0);d.useEffect(()=>{const te=++se.current;let le=!0;return z.current=[],P.current=null,O.current=null,I.current=Promise.resolve(),A("loading"),rt("/api/settings",void 0,t).then(Ce=>{if(!le||te!==se.current)return;const Ae=fg(Ce);P.current=Ae,O.current=Ae,b(Ae),A("saved")}).catch(Ce=>{!le||te!==se.current||(N(Ce instanceof Error?Ce.message:String(Ce)),P.current=zc,O.current=zc,b(zc),A("failed"))}),()=>{le=!1}},[t]);const Z=async(te,le,Ce)=>{const Ae={id:++X.current,section:te,key:le,value:Ce},_e=se.current;z.current.push(Ae);const ue=aw(O.current||P.current||zc,Ae);O.current=ue,b(ue),A("saving"),N(""),I.current=I.current.then(async()=>{if(_e!==se.current)return;let He=null,ze=null;for(let Ze=0;Ze<2&&!He;Ze+=1){const Ue=P.current||zc;try{const Y=await rt("/api/settings",{method:"PATCH",body:JSON.stringify({revision:Ue.revision,[Ae.section]:{[Ae.key]:Ae.value}})},t);He=fg(Y)}catch(Y){if(ze=Y,Ze!==0||!String(Y instanceof Error?Y.message:Y).startsWith("409 "))break;try{const Se=await rt("/api/settings",void 0,t);if(_e!==se.current)return;P.current=fg(Se)}catch(Se){ze=Se;break}}}if(_e!==se.current)return;z.current=z.current.filter(Ze=>Ze.id!==Ae.id),He&&(P.current=He);const et=P.current||zc,Xe=z.current.reduce(aw,et);O.current=Xe,b(Xe),He?(N(""),A(z.current.length>0?"saving":"saved")):(A(z.current.length>0?"saving":"failed"),N(ze instanceof Error?ze.message:String(ze||"Settings could not be saved.")))}),await I.current},G=(te,le)=>Ce=>{Z(te,le,Ce)},K=async()=>{if(n!=="hub"||!r||!o){D("failed"),F("Sign in to this Hub before changing its runtime role.");return}D("changing"),F("");try{const te=await rt("/api/runtime/status",void 0,t);await rt("/api/runtime/role",{method:"POST",headers:{Authorization:`Bearer ${o}`},body:JSON.stringify({role:"client"})},t),D("accepted"),await Px({baseUrl:t,targetRole:"client",previousRuntimePid:Number(te.runtimePid||0),allowedStates:["running","waiting-auth"]}),iM(5179)}catch(te){D("failed"),F(te instanceof Error?te.message:String(te))}},me=Mp(w,"security"),V=Mp(w,"control"),ne=Mp(w,"filesAudio"),$=`settings-panel-${g}`,_=i.jsxs("div",{className:"settings-tab-content product-settings-content",children:[u,i.jsxs("section",{className:"settings-section-card runtime-role-settings",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Runtime role"}),i.jsx("h3",{children:"Use this computer as a Client"})]}),i.jsx(Nx,{size:20})]}),i.jsx("p",{className:"settings-help",children:"Stop hosting from this computer and reconnect it to the selected Hub."}),E==="accepted"?i.jsx("p",{className:"settings-help runtime-role-success",children:"LiveDesk is restarting as Client."}):T?i.jsx("p",{className:"settings-help runtime-role-error",role:"alert",children:T}):null,i.jsx("button",{className:"settings-reset",onClick:()=>{K()},disabled:E==="changing"||n!=="hub",type:"button",children:E==="changing"?"Switching role...":"Switch this computer to Client"})]})]}),ie=i.jsxs("div",{className:"settings-tab-content product-settings-content",children:[i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Remote access"}),i.jsx("h3",{children:"Who may connect?"})]}),i.jsx(Ui,{size:20})]}),i.jsx(_c,{icon:Aa,title:"Access mode",description:"Choose the default permission boundary for remote sessions.",recommended:!0,children:i.jsx(rw,{value:String(me.accessMode),onChange:G("security","accessMode"),label:"Access mode",options:[["trusted-only","Trusted devices only"],["block-remote-access","Block remote access"]]})})]}),i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Session permissions"}),i.jsx("h3",{children:"What may remote users do?"})]}),i.jsx(Ba,{size:20})]}),i.jsx(_c,{icon:Ba,title:"Keyboard and mouse control",description:"Allow Control to send keyboard and pointer input.",recommended:!0,children:i.jsx(Ef,{checked:!!V.allowKeyboardMouse,onChange:G("control","allowKeyboardMouse"),label:"Keyboard and mouse control"})}),i.jsx(_c,{icon:Ax,title:"Power actions",description:"Allow confirmed sleep, restart, and shut down commands from the Hub.",children:i.jsx(Ef,{checked:!!V.allowRemoteRestart,onChange:G("control","allowRemoteRestart"),label:"Power actions"})}),i.jsx(_c,{icon:Ig,title:"File transfer",description:"Allow files to be delivered to connected computers.",children:i.jsx(Ef,{checked:!!ne.allowFileTransfer,onChange:G("filesAudio","allowFileTransfer"),label:"File transfer"})}),i.jsx(_c,{icon:Vc,title:"Remote audio",description:"Allow sound capture from connected computers.",children:i.jsx(Ef,{checked:!!ne.allowRemoteAudio,onChange:G("filesAudio","allowRemoteAudio"),label:"Remote audio"})})]})]}),be=i.jsxs("div",{className:"settings-tab-content product-settings-content",children:[i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Capture"}),i.jsx("h3",{children:"Recording defaults"})]}),i.jsx(Ig,{size:20})]}),i.jsx(_c,{icon:Vc,title:"Keep a Last 30s buffer",description:"Keep recent video in memory until you explicitly save it.",children:i.jsx(Ef,{checked:!!ne.rollingBufferEnabled,onChange:G("filesAudio","rollingBufferEnabled"),label:"Keep a Last 30s buffer"})}),i.jsx(_c,{icon:Vc,title:"Timelapse interval",description:"Choose how often a timelapse frame is captured.",children:i.jsx(rw,{value:Number(ne.timelapseIntervalSeconds),onChange:te=>G("filesAudio","timelapseIntervalSeconds")(Number(te)),label:"Timelapse interval",options:[["5","5 seconds"],["10","10 seconds"],["30","30 seconds"],["60","60 seconds"]]})})]}),h]}),H=g==="connection"?_:g==="remote-access"?ie:g==="capture-audio"?be:f;return i.jsxs("section",{className:"settings-page",children:[i.jsx("div",{className:"settings-page-tabs",role:"tablist","aria-label":"LiveDesk settings",children:Z1.map(({id:te,label:le,icon:Ce})=>i.jsxs("button",{className:g===te?"active":"",id:`settings-tab-${te}`,role:"tab","aria-selected":g===te,"aria-controls":`settings-panel-${te}`,tabIndex:g===te?0:-1,onClick:()=>y(te),type:"button",children:[i.jsx(Ce,{size:16}),le]},te))}),x==="saving"&&i.jsx("div",{className:"product-save-state",role:"status",children:"Saving settings..."}),k&&i.jsx("div",{className:"agent-settings-alert error",role:"alert",children:k}),i.jsx("section",{className:"settings-page-panel",id:$,role:"tabpanel","aria-labelledby":`settings-tab-${g}`,tabIndex:0,children:H})]})}function eN({children:t}){return i.jsx("div",{className:"settings-tab-content",children:t})}const sw={enabled:!1};function iw(t){return{enabled:t?.enabled===!0}}async function tN(t,n,r){let o=null;for(let c=0;c<2;c+=1){const u=await rt("/api/settings",{signal:r},n);if(u.settings.agent?.enabled===t)return;try{await rt("/api/settings",{method:"PATCH",signal:r,body:JSON.stringify({revision:u.revision,agent:{enabled:t}})},n);return}catch(f){if(o=f,c!==0||!String(f instanceof Error?f.message:f).startsWith("409 "))throw f}}throw o}function nN({hubUrl:t}){const[n,r]=d.useState(sw),[o,c]=d.useState(null),[u,f]=d.useState(""),[h,g]=d.useState(""),[y,w]=d.useState(""),b=d.useRef(0),x=d.useRef(null);d.useEffect(()=>{let P=!0;x.current?.abort();const z=new AbortController;x.current=z;const I=++b.current;return c(null),r(sw),f(""),w(""),g(""),rt("/api/settings/agent",{signal:z.signal},t).then(X=>{!P||z.signal.aborted||I!==b.current||(c(X.settings),r(iw(X.settings)))}).catch(X=>{P&&!z.signal.aborted&&I===b.current&&w(X instanceof Error?X.message:String(X))}),()=>{P=!1,z.abort(),x.current===z&&(x.current=null)}},[t]);const A=(P,z)=>r(I=>({...I,[P]:z})),k=P=>{c(P),r(iw(P))},N=()=>({generation:b.current,controller:x.current}),E=P=>P.generation===b.current&&P.controller!==null&&P.controller===x.current&&!P.controller.signal.aborted,D=async()=>{if(!o){w("Agent settings are not available yet.");return}const P=N();if(E(P)){f("save"),w(""),g("");try{if(await tN(n.enabled,t,P.controller.signal),!E(P))return;const z=await rt("/api/settings/agent",{signal:P.controller.signal},t);if(!E(P))return;k(z.settings),g("Codex Agent settings saved.")}catch(z){E(P)&&w(z instanceof Error?z.message:String(z))}finally{E(P)&&f("")}}},T=async()=>{const P=N();if(E(P)){f("test"),w(""),g("");try{const z=await rt("/api/settings/agent/test",{method:"POST",signal:P.controller.signal,body:JSON.stringify({})},t);if(!E(P))return;const I=await rt("/api/settings/agent",{signal:P.controller.signal},t);if(!E(P))return;k(I.settings);const X=Number.isFinite(z.connection?.latencyMs)?Math.max(0,Math.round(z.connection.latencyMs)):null;g(`Codex Agent connection verified${X!==null?` in ${X} ms.`:"."}`)}catch(z){E(P)&&w(z instanceof Error?z.message:String(z))}finally{E(P)&&f("")}}},F=o?.codexInstallation==="installed"&&o.codexAuth==="signed-in",O=o!==null;return i.jsxs("div",{className:"settings-tab-content agent-settings-content",children:[i.jsx("section",{className:"settings-section-card agent-enable-card",children:i.jsxs("label",{className:"settings-toggle agent-enable-toggle",children:[i.jsx("input",{type:"checkbox",checked:n.enabled,onChange:P=>A("enabled",P.target.checked),disabled:!O||u!==""}),i.jsx("span",{children:"Enable Codex Agent"})]})}),y&&i.jsx("div",{className:"agent-settings-alert error",role:"alert",children:y}),h&&i.jsx("div",{className:"agent-settings-alert success",role:"status",children:h}),i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Connection"}),i.jsx("h3",{children:"Codex SDK / CLI"})]}),i.jsx(Aa,{size:20})]}),i.jsxs("div",{className:"agent-connection-row",children:[i.jsx("span",{className:`agent-connection-dot ${F?"connected":o?.codexAuth==="not-signed-in"?"unavailable":""}`}),i.jsx("span",{children:o?.codexInstallation==="not-installed"?"Codex SDK not installed":o?.codexAuth==="signed-in"?"Codex CLI signed in":o?.codexAuth==="not-signed-in"?"Codex CLI sign-in required":"Codex status not tested"}),i.jsxs("button",{className:"settings-reset",onClick:()=>{T()},disabled:u!=="",type:"button",children:[i.jsx(zC,{size:15})," ",u==="test"?"Testing":"Test connection"]})]}),i.jsxs("p",{className:"settings-help",children:[i.jsx($C,{size:12})," The Hub uses the installed Codex SDK / CLI to plan approved commands and run them through LiveDesk Agent tools on selected computers."]})]}),i.jsx("div",{className:"settings-action-row agent-settings-actions",children:i.jsxs("button",{className:"text-button primary",onClick:()=>{D()},disabled:!O||u!=="",type:"button",children:[i.jsx(UC,{size:15})," ",u==="save"?"Saving":"Save Agent settings"]})})]})}new Date().valueOf();function Gi(t){const[n,r]=d.useState(t),o=d.useRef(t);return d.useEffect(()=>{if(o.current!==t){if(Array.isArray(o.current)&&Array.isArray(t)&&o.current.length===0&&t.length===0)return;o.current=t,r(t)}},[t]),[n,r]}function Tv(t,n){return typeof t=="function"?typeof n=="object"?t(n):t():t}function vd(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 aN(t,n="data-id"){const r=vd(t,n);return r?r.getAttribute(n):null}function Xf(t,n="data-id"){const r=vd(t,n);return r?Yp(r,n):null}function Yp(t,n="data-id"){const r=t.getAttribute(n);return r?rN(r):null}function Ha(t){return typeof t=="string"?":"+t:t}function rN(t){if(t.startsWith(":"))return t.substring(1);const n=t*1;return isNaN(n)?t:n}function sN(){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 ss=sN();function Rv(t){Object.assign(ss,t)}function ow(t,n,r){function o(c){const u=vd(c);if(!u)return;const f=Yp(u);if(typeof n=="function")return n(f,c);let h,g=c.target;for(;g!=u;){if(h=g.dataset?g.dataset.action:null,h&&n[h]){n[h](f,c);return}g=g.parentNode}n[r]&&n[r](f,c)}ss.addEvent(t,r,o)}function yd(t,n){ow(t,n,"click"),n.dblclick&&ow(t,n.dblclick,"dblclick")}function iN(t,n){for(let r=t.length-1;r>=0;r--)if(t[r]===n){t.splice(r,1);break}}function oN(t,n,r){for(let o=0;o<Io.length;o++){if(o===r)continue;const c=Io[o],u=c.props.parent?.();if(u&&t.contains(u)&&c.node.contains(n))return!0}return!1}var SS=new Date,Fp=!1,ip=[],Io=[],lw=t=>{const n=t.target;if(Fp||!n.isConnected){Fp=!1;return}for(let r=Io.length-1;r>=0;r--){const{node:o,date:c,props:u}=Io[r];if(!(c>SS)&&!o.contains(n)&&o!==n&&(oN(o,n,r)||(u.callback&&u.callback(t),u.modal||t.defaultPrevented)))break}},lN=t=>{SS=new Date,Fp=!0;for(let n=Io.length-1;n>=0;n--){const{node:r}=Io[n];if(!r.contains(t.target)&&r!==t.target){Fp=!1;break}}};function Vi(t,n){ip.length||(ip=[ss.addGlobalEvent("click",lw,t),ss.addGlobalEvent("contextmenu",lw,t),ss.addGlobalEvent("mousedown",lN,t)]),typeof n!="object"&&(n={callback:n});const r={node:t,date:new Date,props:n};return Io.push(r),{destroy(){iN(Io,r),Io.length||(ip.forEach(o=>o()),ip=[])}}}var op=t=>t.indexOf("bottom")!==-1,lp=t=>t.indexOf("left")!==-1,cp=t=>t.indexOf("right")!==-1,mg=t=>t.indexOf("top")!==-1,cw=t=>t.indexOf("fit")!==-1,Df=t=>t.indexOf("overlap")!==-1,cN=t=>t.split("-").every(n=>["center","fit"].indexOf(n)>-1),uN=t=>{const n=t.match(/(start|center|end)/);return n?n[0]:null};function dN(t,n){let r=0;const o=ss.getTopNode(t);for(;t&&t!==o;){const c=getComputedStyle(t).position;if((c==="absolute"||c==="relative"||c==="fixed")&&(r=parseInt(getComputedStyle(t).zIndex)||0),t=t.parentNode,t===n)break}return r}var ma,pr,If,Xa;function CS(t,n,r="bottom",o=0,c=0){if(!t)return null;ma=o,pr=c,If="auto";let u=0,f=0,h=r;const g=kS(t),y=Df(r)?ss.getTopNode(t):g;if(!g)return null;const w=g.getBoundingClientRect(),b=t.getBoundingClientRect(),x=y.getBoundingClientRect(),A=window.getComputedStyle(y),k={left:0,top:0,bottom:0,right:0};for(const O in k){const P=`border-${O}-width`;k[O]=parseFloat(A.getPropertyValue(P))}if(n){const O=dN(n,g);u=Math.max(O+1,20)}if(n){if(Xa=n.getBoundingClientRect(),cw(r)&&(If=Xa.width+"px"),r!=="point")if(cN(r))cw(r)?ma=0:(ma=x.width/2,f=1),pr=(x.height-b.height)/2;else{const O=Df(r)?0:1;ma=cp(r)?Xa.right+O:Xa.left-O,pr=op(r)?Xa.bottom+1:Xa.top;const P=uN(r);P&&(cp(r)||lp(r)?P==="center"?pr-=(b.height-Xa.height)/2:P==="end"&&(pr-=b.height-Xa.height):(op(r)||mg(r))&&(P==="center"?ma-=(b.width-Xa.width)/2:P==="end"&&(ma-=b.width-Xa.width),Df(r)||(ma+=1)))}}else Xa={left:o,right:o,top:c,bottom:c};const N=(lp(r)||cp(r))&&(op(r)||mg(r));lp(r)&&(f=2);const E=ma-b.width-x.left;n&&lp(r)&&!N&&E<0&&(ma=Xa.right,f=0,h=h.replace("left","right"));const D=ma+b.width*(1-f/2)-x.right;if(D>0)if(!cp(r))ma=x.right-k.right-b.width;else{const O=Xa.left-x.x-b.width;n&&!N&&O>=0?(ma=Xa.left-b.width,h=h.replace("right","left")):ma-=D+k.right}f&&(ma=Math.round(ma-b.width*f/2));const T=E<0||D>0||!N;mg(r)&&(pr=Xa.top-b.height,n&&pr<x.y&&T&&(pr=Xa.bottom,h=h.replace("top","bottom")));const F=pr+b.height-x.bottom;return F>0&&(n&&op(r)&&T?(pr-=b.height+Xa.height+1,h=h.replace("bottom","top")):pr-=F+k.bottom),ma-=w.left+k.left,pr-=w.top+k.top,ma=(Df(r)?ma:Math.max(ma,0))+y.scrollLeft,pr=(Df(r)?pr:Math.max(pr,0))+y.scrollTop,If=If||"auto",{at:h,x:ma,y:pr,z:u,width:If}}function kS(t){const n=ss.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 fN(t){const n=[];let r=t;const o=ss.getTopNode(t);for(;r&&r!==o&&!r.getAttribute("data-wx-portal-root");)getComputedStyle(r).position==="absolute"&&n.push(r),r=r.parentNode;return n}var uw=new Date().valueOf();function jv(){return uw+=1,uw}function gr(t){return t<10?"0"+t:t.toString()}function mN(t){const n=gr(t);return n.length==2?"0"+n:n}function MS(t){const n=Math.floor(t/11)*11;return{start:n,end:n+11}}function pg(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 o=new Date(r.getFullYear(),0,1),c=Math.round((r.getTime()-o.getTime())/864e5);return 1+Math.floor(c/7)}var dw=["",""];function pN(t,n,r){switch(t){case"%d":return gr(n.getDate());case"%m":return gr(n.getMonth()+1);case"%j":return n.getDate();case"%n":return n.getMonth()+1;case"%y":return gr(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 gr((n.getHours()+11)%12+1);case"%g":return(n.getHours()+11)%12+1;case"%G":return n.getHours();case"%H":return gr(n.getHours());case"%i":return gr(n.getMinutes());case"%a":return((n.getHours()>11?r.pm:r.am)||dw)[0];case"%A":return((n.getHours()>11?r.pm:r.am)||dw)[1];case"%s":return gr(n.getSeconds());case"%S":return mN(n.getMilliseconds());case"%W":return gr(pg(n));case"%w":{const o=r.weekStart??1;if(o===1)return gr(pg(n));const c=(n.getDay()-o+7)%7,u=(1-o+7)%7,f=new Date(n.valueOf());return f.setDate(n.getDate()+(u-c)),gr(pg(f))}case"%c":{let o=n.getFullYear()+"";return o+="-"+gr(n.getMonth()+1),o+="-"+gr(n.getDate()),o+="T",o+=gr(n.getHours()),o+=":"+gr(n.getMinutes()),o+=":"+gr(n.getSeconds()),o}case"%Q":return Math.floor(n.getMonth()/3)+1;default:return t}}var hN=/%[a-zA-Z]/g;function fd(t,n){return typeof t=="function"?t:function(r){return r?(r.getMonth||(r=new Date(r)),t.replace(hN,o=>pN(o,r,n))):""}}function fw(t){return t&&typeof t=="object"&&!Array.isArray(t)}function rv(t,n){for(const r in n){const o=n[r];fw(t[r])&&fw(o)?t[r]=rv({...t[r]},n[r]):t[r]=n[r]}return t}function tm(t){return{getGroup(n){const r=t[n];return o=>r&&r[o]||o},getRaw(){return t},extend(n,r){if(!n)return this;let o;return r?o=rv({...n},t):o=rv({...t},n),tm(o)}}}var gN=Lx();const vN="en-US",yN={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},bN={ok:"OK",cancel:"Cancel",select:"Select","No data":"No data","Rows per page":"Rows per page","Total pages":"Total pages"},wN={timeFormat:"%H:%i",dateFormat:"%m/%d/%Y",monthYearFormat:"%F %Y",yearFormat:"%Y"},AS={core:bN,calendar:yN,formats:wN,lang:vN},Ev=d.createContext(""),NS=d.createContext({}),xi=d.createContext(null),TS=d.createContext(null),$a=Object.freeze(Object.defineProperty({__proto__:null,fieldId:TS,helpers:NS,i18n:xi,theme:Ev},Symbol.toStringTag,{value:"Module"}));function RS(t){const n=d.useContext(TS),[r]=d.useState(()=>t||n||jv());return r}function Wf({type:t="",css:n="",icon:r="",disabled:o=!1,title:c="",tooltip:u,text:f="",children:h,onClick:g}){const y=d.useMemo(()=>{let b=t?t.split(" ").filter(x=>x!=="").map(x=>"wx-"+x).join(" "):"";return n+(n?" ":"")+b},[t,n]),w=b=>{g&&g(b)};return i.jsxs("button",{title:c,className:`wx-2ZWgb4 wx-button ${y} ${r&&!h?"wx-icon":""}`,disabled:o,onClick:w,"data-tooltip-text":u,children:[r&&i.jsx("i",{className:"wx-2ZWgb4 "+r}),h||f||" "]})}function xN({id:t,label:n="",inputValue:r="",value:o=!1,onChange:c,disabled:u=!1,css:f=""}){const h=RS(t),[g,y]=Gi(o),w=({target:b})=>{const x=b.checked;y(x),c&&c({value:x,inputValue:r})};return i.jsxs("div",{className:`wx-2IvefP wx-checkbox ${f}`,children:[i.jsx("input",{type:"checkbox",id:h,disabled:u,className:"wx-2IvefP wx-check",checked:g,value:r,onChange:w}),i.jsxs("label",{htmlFor:h,className:"wx-2IvefP wx-label",children:[i.jsx("span",{className:"wx-2IvefP wx-before"}),n&&i.jsx("span",{className:"wx-2IvefP wx-after",children:n})]})]})}function Dv({theme:t="",target:n,children:r}){const o=d.useRef(null),c=d.useRef(null),[u,f]=d.useState(null);o.current||(o.current=document.createElement("div"));const h=d.useContext(Ev);return d.useEffect(()=>{f(n||SN(c.current)||ss.getTopNode(c.current))},[c.current]),i.jsxs(i.Fragment,{children:[i.jsx("span",{ref:c,style:{display:"none"}}),c.current&&u?gN.createPortal(i.jsx("div",{className:`wx-3ZWsT0 wx-${t||h}-theme`,children:r}),u):null]})}function SN(t){const n=ss.getTopNode(t);for(;t&&t!==n&&!t.getAttribute("data-wx-portal-root");)t=t.parentNode;return t}function CN({left:t=0,top:n=0,at:r="bottom",parent:o=null,width:c="auto",css:u="",onCancel:f,children:h,trackScroll:g=!1}){const[y,w]=d.useState(0),[b,x]=d.useState(0),[A,k]=d.useState("auto"),[N,E]=d.useState(!1),D=d.useRef(null),T=d.useRef(null),F=d.useRef(f);d.useEffect(()=>{F.current=f},[f]);function O(z){return o&&(c+"").indexOf("%")>-1?c.replace(/(\d+)%/,(I,X)=>(X=X*o.offsetWidth/100+"px",c.replace(I,X))):c&&c!=="auto"?c:z}const P=d.useCallback(()=>{if(!D.current)return;const z=CS(D.current,o,r,t,n);z&&(w(z.x),x(z.y),k(O(z.width)))},[D,o,r,t,n,c]);return d.useLayoutEffect(()=>{const z=X=>{F.current&&X.target!==T.current&&D.current&&!D.current.contains(X.target)&&F.current(X)};let I;return requestAnimationFrame(()=>{P(),E(!0),g&&D.current&&(T.current=kS(D.current),T.current&&T.current.addEventListener("scroll",z,!0)),o&&(I=new ResizeObserver(P),I.observe(o))}),()=>{g&&T.current&&T.current.removeEventListener("scroll",z,!0),I?.disconnect()}},[]),d.useLayoutEffect(()=>{P()},[o,r,t,n]),d.useEffect(()=>{const z=I=>{F.current&&F.current(I)};if(D.current)return Vi(D.current,{callback:z,parent:()=>o}).destroy},[o]),i.jsx("div",{ref:D,className:["wx-37M6Fj","wx-popup",u].filter(Boolean).join(" "),style:{position:"absolute",visibility:N?"visible":"hidden",top:b+"px",left:y+"px",width:A},children:h})}function kN({position:t="bottom",align:n="start",autoFit:r=!0,onCancel:o=null,width:c="100%",css:u="",children:f}){const h=d.useRef(null),[g,y]=d.useState(t),[w,b]=d.useState(n),x=d.useRef(o);return d.useEffect(()=>{x.current=o},[o]),d.useEffect(()=>{if(r){const A=h.current;if(A){const k=A.getBoundingClientRect(),N=document.body.getBoundingClientRect();k.right>=N.right&&b("end"),k.bottom>=N.bottom&&y("top")}}},[]),d.useEffect(()=>{if(h.current){const A=k=>{x.current&&x.current(k)};return Vi(h.current,A).destroy}},[]),i.jsx("div",{ref:h,className:["wx-dropdown",`wx-${g}-${w}`,u||"","wx-aaaVytZW"].filter(Boolean).join(" "),style:{width:c},children:f})}function Iv({position:t="bottom",align:n="start",autoFit:r=!0,inline:o=!1,onCancel:c,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)},[]),i.jsxs(i.Fragment,{children:[g&&(o?i.jsx(kN,{onCancel:c,position:t,align:n,autoFit:r,width:u,...h,children:f}):i.jsx(Dv,{children:i.jsx(CN,{parent:g,at:b,onCancel:c,width:u,...h,children:f})})),i.jsx("span",{ref:w,className:"wx-portal-node wx-32GZ52"})]})}function Xp(){return tm(AS)}function MN(){let t=null,n=!1,r=!1,o,c,u,f;const h=(b,x,A,k,N)=>{o=b,c=x,u=A,f=k,r=N},g=b=>{t=b,n=t!==null,u(t)},y=(b,x)=>{if(!r&&b!==null&&o){const A=o.querySelectorAll(".wx-list > .wx-item")[b];A&&(A.scrollIntoView({block:"nearest"}),x&&x.preventDefault())}},w=(b,x)=>{const A=b===null?null:Math.max(0,Math.min(t+b,c.length-1));A!==t&&(g(A),o?y(A,x):requestAnimationFrame(()=>y(A,x)))};return{move:b=>{const x=Xf(b),A=c.findIndex(k=>k.id===x);A!==t&&g(A)},keydown:(b,x)=>{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:x||0,b);break;case"ArrowUp":w(n?-1:x||0,b);break}},init:h,navigate:w}}const mw=10,AN=d.memo(function({data:t,checkboxes:n,itemTemplate:r,value:o}){return i.jsxs(i.Fragment,{children:[n&&i.jsx(xN,{id:t.id,css:"wx-list-checkbox",value:o&&o.includes(t.id)}),r?Tv(r,{option:t}):t.label]})});function pw({visibleItems:t,visibleRange:n,navIndex:r,checkboxes:o,itemTemplate:c,value:u,measureRefCallback:f}){return t.map((h,g)=>{const y=n.start+g;return i.jsx("div",{ref:g===0?f:void 0,className:`wx-233fr7 wx-item ${y===r?"wx-focus":""}`,"data-id":h.id,children:i.jsx(AN,{data:h,checkboxes:o,itemTemplate:c,value:u})},h.id)})}function Zp({items:t=[],children:n,onSelect:r,onReady:o,virtualized:c=!1,checkboxes:u,multiselect:f,value:h,...g}){const y=d.useRef(),w=d.useRef(!1),b=d.useRef(MN()),[x,A]=d.useState(null),k=d.useRef(x),[N,E]=d.useState(0),[D,T]=d.useState(24),F=d.useRef(!1),O=(d.useContext(xi)||Xp()).getGroup("core"),P=d.useRef(t);d.useEffect(()=>{P.current=t},[t]);const z=d.useRef(h);d.useEffect(()=>{z.current=h},[h]);const I=d.useRef(0);d.useEffect(()=>{I.current=D},[D]);const X=d.useCallback(le=>{le&&le.stopPropagation();const Ce=P.current,Ae=z.current,_e=k.current;let ue;const He=Ce[_e]?.id;f?Ae&&Ae.includes(He)?ue=Ae.filter(ze=>ze!==He):ue=[...Ae||[],He]:ue=He,r&&r({id:ue})},[f,r]),se=d.useRef(X);d.useEffect(()=>{se.current=X},[X]);const Z=d.useCallback(le=>{if(y.current){let Ce=le*I.current-y.current.clientHeight+I.current;E(Ce),y.current.scrollTop=Ce}},[I.current]),G=d.useCallback(le=>{y.current=le,c&&(le&&!w.current&&k.current!==null&&requestAnimationFrame(()=>{y.current&&(Z(k.current),w.current=!0)}),le||(w.current=!1))},[Z]),K=d.useCallback(le=>{if(!le||F.current)return;const Ce=le.getBoundingClientRect().height;Ce&&(T(Ce),I.current=Ce,F.current=!0)},[]);d.useEffect(()=>{b.current.init(y.current,t,le=>{A(le),k.current=le},le=>se.current(le),c)},[t,y.current,c]),d.useEffect(()=>{const le=(Ae,_e)=>{b.current.navigate(Ae,_e),Z(k.current)},Ce=(Ae,_e)=>{const ue=k.current,He=P.current;if(ue!==0&&ue!==He.length-1&&(Ae.key==="ArrowDown"||Ae.key==="ArrowUp")&&Ae.preventDefault(),b.current.keydown(Ae,_e),y.current){const ze=y.current.scrollTop<=k.current*I.current,et=y.current.scrollTop+y.current.clientHeight>=k.current*I.current+I.current;ze?et||Z(k.current):(y.current.scrollTop=k.current*I.current,E(y.current.scrollTop))}};o&&o({navigate:c?le:b.current.navigate,keydown:c?Ce:b.current.keydown,move:b.current.move})},[]);const me=d.useRef(0),V=d.useRef(t);V.current!==t&&(V.current=t,me.current+=1);const ne=d.useCallback(()=>{b.current.navigate(null)},[b]),$=d.useCallback(le=>{c&&E(le.target.scrollTop)},[c]),_=d.useMemo(()=>Math.ceil((y.current?.clientHeight||0)/D),[D,N]),ie=d.useMemo(()=>{if(!c)return{start:0,end:t.length};if(!t.length)return{start:0,end:0};const le=Math.floor(N/D),Ce=le+_;return{start:Math.max(0,le-mw),end:Math.min(t.length,Ce+mw)}},[c,t,N,D,_]),be=d.useMemo(()=>{if(!c)return t;const{start:le,end:Ce}=ie;return t.slice(le,Ce).map(Ae=>({...Ae}))},[c,t,ie]),H=ie.start*D,te=t.length*D;return d.useEffect(()=>{c&&E(0)},[t,c]),d.useEffect(()=>{x===null&&(w.current=!1)},[x]),x===null?null:i.jsx(Iv,{onCancel:ne,...g,children:i.jsx("div",{className:"wx-233fr7 wx-list",ref:G,onClick:X,onMouseMove:b.current.move,onScroll:$,children:t.length?c?i.jsx("div",{className:"wx-233fr7 wx-list-wrapper",style:{height:`${te}px`},children:i.jsx("div",{className:"wx-233fr7 wx-list-content",style:{transform:`translateY(${H}px)`},children:i.jsx(pw,{visibleRange:ie,visibleItems:be,navIndex:x,measureRefCallback:K,checkboxes:u,itemTemplate:n,value:h})})}):i.jsx(pw,{visibleRange:ie,visibleItems:be,navIndex:x,measureRefCallback:K,checkboxes:u,itemTemplate:n,value:h}):i.jsx("div",{className:"wx-233fr7 wx-no-data",children:O("No data")})})},me.current)}function Lv({value:t="",id:n,readonly:r=!1,focus:o=!1,select:c=!1,type:u="text",placeholder:f="",disabled:h=!1,error:g=!1,title:y="",tooltip:w,css:b="",icon:x="",clear:A=!1,onChange:k}){const N=RS(n),[E,D]=Gi(t),T=d.useRef(null),F=d.useMemo(()=>x&&b.indexOf("wx-icon-left")===-1?"wx-icon-right "+b:b,[x,b]),O=d.useMemo(()=>x&&b.indexOf("wx-icon-left")!==-1,[x,b]);d.useEffect(()=>{const se=setTimeout(()=>{o&&T.current&&T.current.focus(),c&&T.current&&T.current.select()},1);return()=>clearTimeout(se)},[o,c]);const P=d.useCallback(se=>{const Z=se.target.value;D(Z),k&&k({value:Z,input:!0})},[k]),z=d.useCallback(se=>k&&k({value:se.target.value}),[k]);function I(se){se.stopPropagation(),D(""),k&&k({value:""})}let X=u;return u!=="password"&&u!=="number"&&(X="text"),d.useEffect(()=>{const se=z,Z=T.current;return Z.addEventListener("change",se),()=>{Z&&Z.removeEventListener("change",se)}},[z]),i.jsxs("div",{className:`wx-hQ64J4 wx-text ${F} ${g?"wx-error":""} ${h?"wx-disabled":""} ${A?"wx-clear":""}`,"data-tooltip-text":w,children:[i.jsx("input",{className:"wx-hQ64J4 wx-input",ref:T,id:N,readOnly:r,disabled:h,placeholder:f,type:X,title:y,value:E,onInput:P}),A&&!h&&E?i.jsxs(i.Fragment,{children:[i.jsx("i",{className:"wx-hQ64J4 wx-icon wxi-close",onClick:I}),O&&i.jsx("i",{className:`wx-hQ64J4 wx-icon ${x}`})]}):x?i.jsx("i",{className:`wx-hQ64J4 wx-icon ${x}`}):null]})}function NN({date:t,type:n,part:r,onShift:o}){const{calendar:c,formats:u}=d.useContext(xi).getRaw(),f=t.getFullYear(),h=d.useMemo(()=>{switch(n){case"month":return fd(u.monthYearFormat,c)(t);case"year":return fd(u.yearFormat,c)(t);case"duodecade":{const{start:y,end:w}=MS(f),b=fd(u.yearFormat,c);return`${b(new Date(y,0,1))} - ${b(new Date(w,11,31))}`}default:return""}},[t,n,f,c,u]);function g(){o&&o({diff:0,type:n})}return i.jsxs("div",{className:"wx-8HQVQV wx-header",children:[r!=="right"?i.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-left",onClick:()=>o&&o({diff:-1,type:n})}):i.jsx("span",{className:"wx-8HQVQV wx-spacer"}),i.jsx("span",{className:"wx-8HQVQV wx-label",onClick:g,children:h}),r!=="left"?i.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-right",onClick:()=>o&&o({diff:1,type:n})}):i.jsx("span",{className:"wx-8HQVQV wx-spacer"})]})}function _v({onClick:t,children:n}){return i.jsx("button",{className:"wx-3s8W4d wx-button",onClick:t,children:n})}function TN({value:t,current:n,part:r="",markers:o=null,css:c="",onCancel:u,onChange:f}){const h=(d.useContext(xi)||Xp()).getRaw().calendar,g=(h.weekStart||7)%7,y=h.dayShort.slice(g).concat(h.dayShort.slice(0,g)),w=(P,z,I)=>new Date(P.getFullYear(),P.getMonth()+(z||0),P.getDate()+(I||0));let b=r!=="normal";function x(P){const z=P.getDay();return z===0||z===6}function A(){const P=w(n,0,1-n.getDate());return P.setDate(P.getDate()-(P.getDay()-(g-7))%7),P}function k(){const P=w(n,1,-n.getDate());return P.setDate(P.getDate()+(6-P.getDay()+g)%7),P}const N=d.useRef(0);function E(P,z){z.timeStamp!==N.current&&(N.current=z.timeStamp,z.stopPropagation(),f&&f(new Date(P)),u&&u())}const D=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]),T=d.useMemo(()=>{const P=A(),z=k(),I=n.getMonth();let X=[];for(let se=P;se<=z;se.setDate(se.getDate()+1)){const Z={day:se.getDate(),in:se.getMonth()===I,date:se.valueOf()};let G="";if(G+=Z.in?"":" wx-inactive",G+=D.indexOf(Z.date)>-1?" wx-selected":"",b){const K=Z.date==D[0],me=Z.date==D[1];K&&!me?G+=" wx-left":me&&!K&&(G+=" wx-right"),Z.date>D[0]&&Z.date<D[1]&&(G+=" wx-inrange")}if(G+=x(se)?" wx-weekend":"",o){const K=o(se);K&&(G+=" "+K)}X.push({...Z,css:G})}return X},[n,D,b,o]),F=d.useRef(null);let O=d.useRef({});return O.current.click=E,d.useEffect(()=>{yd(F.current,O.current)},[]),i.jsxs("div",{className:`wx-398RBS wx-month ${c}`,children:[i.jsx("div",{className:"wx-398RBS wx-weekdays",children:y.map(P=>i.jsx("div",{className:"wx-398RBS wx-weekday",children:P},P))}),i.jsx("div",{className:"wx-398RBS wx-days",ref:F,children:T.map(P=>i.jsx("div",{className:`wx-398RBS wx-day ${P.css} ${P.in?"":"wx-out"}`,"data-id":P.date,children:P.day},P.date))})]})}function RN({value:t,current:n,part:r,onCancel:o,onChange:c,onShift:u}){const f=d.useRef(new Date),[h,g]=Gi(t||f.current),[y,w]=Gi(n||f.current),b=d.useContext(xi).getRaw().calendar,x=b.monthShort||[],A=d.useMemo(()=>y.getMonth(),[y]),k=d.useCallback((D,T)=>{if(D!=null){T.stopPropagation();const F=new Date(y);F.setMonth(D),w(F),u&&u({current:F})}r==="normal"&&g(new Date(y)),o&&o()},[y,r,u,o]),N=d.useCallback(()=>{const D=new Date(jS(h,r)||y);D.setMonth(y.getMonth()),D.setFullYear(y.getFullYear()),c&&c(D)},[h,y,r,c]),E=d.useCallback(D=>{const T=D.target.closest("[data-id]");if(T){const F=parseInt(T.getAttribute("data-id"),10);k(F,D)}},[k]);return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"wx-34U8T8 wx-months",onClick:E,children:x.map((D,T)=>i.jsx("div",{className:"wx-34U8T8 wx-month"+(A===T?" wx-current":""),"data-id":T,children:D},T))}),i.jsx("div",{className:"wx-34U8T8 wx-buttons",children:i.jsx(_v,{onClick:N,children:b.done})})]})}const hg="wx-1XEF33",jN=({value:t,current:n,onCancel:r,onChange:o,onShift:c,part:u})=>{const f=d.useContext(xi).getRaw().calendar,[h,g]=Gi(n),[y,w]=Gi(t),b=d.useMemo(()=>h.getFullYear(),[h]),x=d.useMemo(()=>{const{start:D,end:T}=MS(b),F=[];for(let O=D;O<=T;++O)F.push(O);return F},[b]),A={click:k};function k(D,T){if(D){T.stopPropagation();const F=new Date(h);F.setFullYear(D),g(F),c&&c({current:F})}u==="normal"&&w(new Date(h)),r&&r()}function N(){const D=new Date(jS(y,u)||h);D.setFullYear(h.getFullYear()),o&&o(D)}const E=d.useRef(null);return d.useEffect(()=>{E.current&&yd(E.current,A)},[]),i.jsxs(i.Fragment,{children:[i.jsx("div",{className:hg+" wx-years",ref:E,children:x.map((D,T)=>i.jsx("div",{className:hg+` wx-year ${b==D?"wx-current":""} ${T===0?"wx-prev-decade":""} ${T===11?"wx-next-decade":""}`,"data-id":D,children:D},T))}),i.jsx("div",{className:hg+" wx-buttons",children:i.jsx(_v,{onClick:N,children:f.done})})]})},hw={month:{component:TN,next:DN,prev:EN},year:{component:RN,next:LN,prev:IN},duodecade:{component:jN,next:FN,prev:_N}};function EN(t){return t=new Date(t),t.setMonth(t.getMonth()-1),t}function DN(t){return t=new Date(t),t.setMonth(t.getMonth()+1),t}function IN(t){return t=new Date(t),t.setFullYear(t.getFullYear()-1),t}function LN(t){return t=new Date(t),t.setFullYear(t.getFullYear()+1),t}function _N(t){return t=new Date(t),t.setFullYear(t.getFullYear()-10),t}function FN(t){return t=new Date(t),t.setFullYear(t.getFullYear()+10),t}function jS(t,n){let r;if(n==="normal")r=t;else{const{start:o,end:c}=t;n==="left"?r=o:n=="right"?r=c:r=o&&c}return r}const PN=["clear","today"];function ON(t){if(t==="done")return-1;if(t==="clear")return null;if(t==="today")return new Date}function BN({value:t,current:n,onCurrentChange:r,part:o="normal",markers:c=null,buttons:u,css:f="",onShift:h,onChange:g}){const y=d.useContext(xi).getGroup("calendar"),[w,b]=d.useState("month"),x=Array.isArray(u)?u:u?PN:[],A=(T,F)=>{T.preventDefault(),g&&g({value:F})},k=()=>{w==="duodecade"?b("year"):w==="year"&&b("month")},N=T=>{const{diff:F,current:O}=T;if(F===0){w==="month"?b("year"):w==="year"&&b("duodecade");return}if(F){const P=hw[w];r(F>0?P.next(n):P.prev(n))}else O&&r(O);h&&h()},E=T=>{b("month"),g&&g({select:!0,value:T})},D=d.useMemo(()=>hw[w].component,[w]);return i.jsx("div",{className:`wx-2Gr4AS wx-calendar ${o!=="normal"&&o!=="both"?"wx-part":""} ${f}`,children:i.jsxs("div",{className:"wx-2Gr4AS wx-wrap",children:[i.jsx(NN,{date:n,part:o,type:w,onShift:N}),i.jsxs("div",{children:[i.jsx(D,{value:t,current:n,onCurrentChange:r,part:o,markers:c,onCancel:k,onChange:E,onShift:N}),w==="month"&&x.length>0&&i.jsx("div",{className:"wx-2Gr4AS wx-buttons",children:x.map(T=>i.jsx("div",{className:"wx-2Gr4AS wx-button-item",children:i.jsx(_v,{onClick:F=>A(F,ON(T)),children:y(T)})},T))})]})]})})}function Fv(t){let{words:n=null,optional:r=!1,children:o}=t,c=d.useContext(xi);const u=d.useMemo(()=>{let f=c;return(!f||!f.extend)&&(f=tm(AS)),n!==null&&(f=f.extend(n,r)),f},[n,r,c]);return i.jsx(xi.Provider,{value:u,children:o})}function gw(t,n,r,o){if(!t||o){const c=n?new Date(n):new Date;c.setDate(1),r(c)}else if(t.getDate()!==1){const c=new Date(t);c.setDate(1),r(c)}}const HN=["clear","today"];function ES({value:t,current:n,markers:r=null,buttons:o=HN,css:c="",onChange:u}){const[f,h]=Gi(t),[g,y]=Gi(n);d.useEffect(()=>{gw(g,f,y,!1)},[f,g]);const w=d.useCallback(x=>{const A=x.value;A?(h(new Date(A)),gw(g,new Date(A),y,!0)):h(null),u&&u({value:A?new Date(A):null})},[u,g]),b=d.useCallback(x=>{y(x)},[y]);return g?i.jsx(Fv,{children:i.jsx(BN,{value:f,current:g,markers:r,buttons:o,css:c,onChange:w,onCurrentChange:b})}):null}function zN(t){return t||(t={}),t.width||(t.width="unset"),t}const $N=["clear","today"];function UN({value:t,id:n,disabled:r=!1,error:o=!1,placeholder:c="",format:u="",buttons:f=$N,css:h="",title:g="",tooltip:y,editable:w=!1,clear:b=!1,onChange:x,dropdown:A={}}){const{calendar:k,formats:N}=(d.useContext(xi)||Xp()).getRaw(),E=u||N?.dateFormat;let D=typeof E=="function"?E:fd(E,k);const[T,F]=d.useState(t),[O,P]=d.useState(!1);d.useEffect(()=>{F(t)},[t]);function z(){P(!1)}function I(Z){const G=Z===T||Z&&T&&Z.valueOf()===T.valueOf()||!Z&&!T;F(Z),G||x&&x({value:Z}),setTimeout(z,1)}const X=d.useMemo(()=>T?D(T):"",[T,D]);function se({value:Z,input:G}){if(!w&&!b||G)return;let K=typeof w=="function"?w(Z):Z?new Date(Z):null;K=isNaN(K)?T||null:K||null,I(K)}return d.useEffect(()=>{const Z=z;return window.addEventListener("scroll",Z),()=>window.removeEventListener("scroll",Z)},[]),i.jsxs("div",{className:"wx-1lKOFG wx-datepicker",onClick:()=>P(!0),children:[i.jsx(Lv,{css:`wx-date-input ${h}`,title:g,tooltip:y,value:X,id:n,readonly:!w,disabled:r,error:o,placeholder:c,onInput:z,onChange:se,icon:"wxi-calendar",clear:b}),O&&!r&&i.jsx(Iv,{onCancel:z,...zN(A),children:i.jsx(ES,{buttons:f,value:T,onChange:Z=>I(Z.value)})})]})}function qN({value:t="",options:n=[],textOptions:r=null,placeholder:o="",disabled:c=!1,error:u=!1,title:f="",tooltip:h,textField:g="label",clear:y=!1,css:w="",children:b,onChange:x,dropdown:A={}}){const k=d.useRef(null),N=d.useRef(null);let[E,D]=Gi(t);function T(I){k.current=I.navigate,N.current=I.keydown}const F=d.useMemo(()=>E||E===0?(r||n).find(I=>I.id===E):null,[E,r,n]),O=d.useCallback(({id:I})=>{(I||I===0)&&(D(I),k.current(null),x&&x({value:I}))},[D,x]),P=d.useCallback(I=>{I.stopPropagation(),D(""),x&&x({value:""})},[D,x]),z=d.useCallback(()=>n.findIndex(I=>I.id===E),[n,E]);return i.jsxs("div",{className:`wx-2YgblL wx-richselect ${w} ${u?"wx-2YgblL wx-error":""} ${c?"wx-2YgblL wx-disabled":""} ${b?"":"wx-2YgblL wx-nowrap"}`,title:f,onClick:()=>k.current(z()),onKeyDown:I=>N.current(I,z()),tabIndex:0,"data-tooltip-text":h,children:[i.jsx("div",{className:"wx-2YgblL wx-label",children:F?b?b(F):F[g]:o?i.jsx("span",{className:"wx-2YgblL wx-placeholder",children:o}):" "}),y&&!c&&E?i.jsx("i",{className:"wx-2YgblL wx-icon wxi-close",onClick:P}):i.jsx("i",{className:"wx-2YgblL wx-icon wxi-angle-down"}),!c&&i.jsx(Zp,{items:n,onReady:T,onSelect:O,...A,children:({option:I})=>b?b(I):I[g]})]})}const WN=({options:t=[],value:n="",css:r="",children:o,onChange:c})=>{const[u,f]=d.useState(n),h=g=>{f(g),c&&c({value:g})};return d.useEffect(()=>{f(n)},[n]),i.jsx("div",{className:`wx-0hMO7P wx-segmented ${r}`,children:t.map(g=>i.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:o?Tv(o,{option:g}):i.jsxs(i.Fragment,{children:[g.icon&&i.jsx("i",{className:`wx-0hMO7P wx-icon ${g.icon} ${g.label?"":"wx-only"}`}),g.label&&i.jsx("span",{className:"wx-0hMO7P wx-label",children:g.label})]})},g.id))})};function GN({notice:t={}}){function n(){t.remove&&t.remove()}return i.jsxs("div",{className:`wx-11sNg5 wx-notice wx-${t.type?t.type:""}`,role:"status","aria-live":"polite",children:[i.jsx("div",{className:"wx-11sNg5 wx-text",children:t.text}),i.jsx("div",{className:"wx-11sNg5 wx-button",children:i.jsx("i",{className:"wx-11sNg5 wxi-close",onClick:n})})]})}function VN({data:t=[]}){return i.jsx("div",{className:"wx-3nwoO9 wx-notices",children:t.map(n=>i.jsx(GN,{notice:n},n.id))})}function sv({title:t="",buttons:n=["cancel","ok"],header:r,children:o,footer:c,css:u="",onConfirm:f,onCancel:h}){const g=(d.useContext(xi)||Xp()).getGroup("core"),y=d.useRef(null);d.useEffect(()=>{y.current?.focus()},[]);function w(x){switch(x.code){case"Enter":{const A=x.target.tagName;if(A==="TEXTAREA"||A==="BUTTON")return;f&&f({event:x});break}case"Escape":h&&h({event:x});break}}function b(x,A){const k={event:x,button:A};A==="cancel"?h&&h(k):f&&f(k)}return i.jsx("div",{className:`wx-1FxkZa wx-modal ${u}`,ref:y,tabIndex:0,onKeyDown:w,children:i.jsxs("div",{className:"wx-1FxkZa wx-window",children:[r||(t?i.jsx("div",{className:"wx-1FxkZa wx-header",children:t}):null),i.jsx("div",{children:o}),c||n&&i.jsx("div",{className:"wx-1FxkZa wx-buttons",children:n.map(x=>i.jsx("div",{className:"wx-1FxkZa wx-button",children:i.jsx(Wf,{type:`block ${x==="ok"?"primary":"secondary"}`,onClick:A=>b(A,x),children:g(x)})},x))})]})})}function KN({children:t},n){const[r,o]=d.useState(null),[c,u]=d.useState([]);return d.useImperativeHandle(n,()=>({showModal:f=>{const h={...f};return o(h),new Promise((g,y)=>{h.resolve=w=>{o(null),g(w)},h.reject=w=>{o(null),y(w)}})},showNotice:f=>{f={...f},f.id=f.id||jv(),f.remove=()=>u(h=>h.filter(g=>g.id!==f.id)),f.expire!=-1&&setTimeout(f.remove,f.expire||5100),u(h=>[...h,f])}}),[]),i.jsxs(i.Fragment,{children:[t,r&&i.jsx(sv,{title:r.title,buttons:r.buttons,onConfirm:r.resolve,onCancel:r.reject,children:r.message}),i.jsx(VN,{data:c})]})}const QN=d.forwardRef(KN);function YN(t){let{children:n}=t,r=d.useRef();const o=d.useMemo(()=>({showNotice:c=>r.current.showNotice(c),showModal:c=>r.current.showModal(c)}),[]);return i.jsx(NS.Provider,{value:o,children:i.jsx(QN,{ref:r,children:n})})}const XN=({value:t=!1,type:n="",icon:r="",disabled:o=!1,iconActive:c="",onClick:u,title:f="",tooltip:h,css:g="",text:y="",textActive:w="",children:b,active:x,onChange:A})=>{const[k,N]=Gi(t),E=d.useMemo(()=>(k?"pressed":"")+(n?" "+n:""),[k,n]),D=d.useCallback(T=>{let F=!k;u&&u(T),T.defaultPrevented||(N(F),A&&A({value:F}))},[k,u,A]);return k&&x?i.jsx(Wf,{title:f,tooltip:h,text:k&&w||y,css:g,type:E,icon:k&&c||r,onClick:D,disabled:o,children:Tv(x,{value:k})}):b?i.jsx(Wf,{title:f,tooltip:h,text:k&&w||y,css:g,type:E,icon:k&&c||r,onClick:D,disabled:o,children:b}):i.jsx(Wf,{title:f,tooltip:h,text:k&&w||y,css:g,type:E,icon:k&&c||r,onClick:D,disabled:o})};function ZN(){return i.jsx(i.Fragment,{})}function vw(t){const{fonts:n=!0,children:r}=t;return i.jsx(Ev.Provider,{value:"willow",children:i.jsxs(i.Fragment,{children:[r&&r&&i.jsx("div",{className:"wx-theme wx-willow-theme",children:r}),n&&i.jsxs(i.Fragment,{children:[i.jsx("link",{rel:"preconnect",href:"https://cdn.svar.dev",crossOrigin:"true"}),i.jsx(ZN,{}),i.jsx("link",{rel:"stylesheet",href:"https://cdn.svar.dev/fonts/wxi/wx-icons.css"})]})]})})}Rv(ss);const Pv={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 DS=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 JN=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 c=0;c<t.length;c++){const u=t[c];u.parent=u.parent||n,u.data=null,r.set(u.id,u)}for(let c=0;c<t.length;c++){const u=t[c],f=r.get(u.parent);f&&(f.data||(f.data=[]),f.data.push(u))}const o=r.get(n);this.setLevel(o,o.$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]:yw(r,n,t):r.data=[t]}addAfter(t,n){if(!n)return this.add(t,-1);const r=this.byId(n),o=this.byId(r.parent),c=up(o,r.id)+1;t.parent=o.id,t.$level=o.$level+1,this.add(t,c)}remove(t){const n=this._pool.get(t);this._remove(n);const r=this._pool.get(n.parent);r.data=r.data.filter(o=>o.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 o=this._pool.get(r.parent),c=up(o,r.id);r={...r,...n},o&&c>=0&&(o.data[c]=r,o.data=[...o.data]),this._pool.set(r.id,r)}move(t,n,r){const o=this._pool.get(t),c=n==="child",u=this._pool.get(r),f=u.$level+(c?1:0);if(!o||!u)return;const h=this._pool.get(o.parent),g=c?u:this._pool.get(u.parent);g.data||(g.data=[]);const y=up(h,o.id);eT(h,y);const w=c?g.data.length:up(g,u.id)+(n==="after"?1:0);if(yw(g,w,o),h.id===g.id&&y===w)return null;o.parent=g.id,o.$level!==f&&(o.$level=f,this.setLevel(o,f+1,!0)),this.update(o.id,o),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&&IS(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((o,c)=>{t(this.byId(o.id),c),this.eachChild(t,o.id)})}setLevel(t,n,r){t.data&&(t.data=t.data.map(o=>(r&&(o={...o},this._pool.set(o.id,o)),o.$level=n,o.data&&this.setLevel(o,n+1,r),o)))}};function IS(t,n){t.forEach(r=>{n.push(r),r.open===!0&&IS(r.data,n)})}function eT(t,n){const r=[...t.data];r.splice(n,1),t.data=r}function yw(t,n,r){const o=[...t.data];o.splice(n,0,r),t.data=o}function up(t,n){return t?.data.findIndex(r=>r.id===n)}var LS=2,tT=class{constructor(n){n&&(this._writable=n.writable,this._async=n.async),this._values={},this._state={}}setState(n,r=0){const o={};return this._wrapProperties(n,this._state,this._values,"",o,r),o}getState(){return this._values}getReactive(){return this._state}_wrapProperties(n,r,o,c,u,f){for(const h in n){const g=r[h],y=o[h],w=n[h];if(g&&(y===w&&typeof w!="object"||w instanceof Date&&y instanceof Date&&y.getTime()===w.getTime()))continue;const b=c+(c?".":"")+h;g?(g.__parse(w,b,u,f)&&(o[h]=w),f&LS?u[b]=g.__trigger:g.__trigger()):(w&&w.__reactive?r[h]=this._wrapNested(w,w,b,u):r[h]=this._wrapWritable(w),o[h]=w),u[b]=u[b]||null}}_wrapNested(n,r,o,c){const u=this._wrapWritable(n);return this._wrapProperties(n,u,r,o,c,0),u.__parse=(f,h,g,y)=>(this._wrapProperties(f,u,r,h,g,y),!1),u}_wrapWritable(n){const r=[],o=function(){for(let c=0;c<r.length;c++)r[c](n)};return{subscribe:c=>(r.push(c),this._async?setTimeout(c,1,n):c(n),()=>{const u=r.indexOf(c);u>=0&&r.splice(u,1)}),__trigger:()=>{r.length&&(this._async?setTimeout(o,1):o())},__parse:function(c){return n=c,!0}}}};function bw(t,n){return Object.defineProperty(t,"__reactive",{value:!0,enumerable:!1,writable:!1}),t}var nT=class{constructor(n,r,o,c){typeof n=="function"?this._setter=n:this._setter=n.setState.bind(n),this._routes=r,this._parsers=o,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=>_S(f,this._sources,1)))}),this._bus=c}init(n){const r={};for(const o in n)if(this._prev[o]!==n[o]){const c=this._parsers[o];r[o]=c?c(n[o]):n[o]}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,LS);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 o=n.signals[r];o&&o()}}}setState(n,r=[]){const o=this._setter(n);return this._triggerUpdates(o,r),o}_triggerUpdates(n,r){const o=Object.keys(n),c=!r.length;r=r||[];for(let u=0;u<o.length;u++){const f=o[u],h=this._triggers.get(f);h&&h.forEach(g=>{r.indexOf(g)==-1&&r.push(g)})}c&&this._execNext(r)}_execNext(n){for(;n.length;){n.sort((o,c)=>o.length<c.length?1:-1);const r=n[n.length-1];n.splice(n.length-1),r.exec(n)}}};function _S(t,n,r){const o=n.get(t);if(!o)return r;const c=Object.keys(o).map(u=>_S(u,n,r+1));return Math.max(...c)}var aT=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(n,r,o){let c=this._handlers[n];c?o&&o.intercept?c.unshift(r):c.push(r):c=this._handlers[n]=[r],o&&o.tag&&this._tag.set(r,o.tag)}intercept(n,r,o){this.on(n,r,{...o,intercept:!0})}detach(n){for(const r in this._handlers){const o=this._handlers[r];for(let c=o.length-1;c>=0;c--)this._tag.get(o[c])===n&&o.splice(c,1)}}async exec(n,r){const o=this._handlers[n];if(o)for(let c=0;c<o.length;c++){const u=o[c](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 id=1024;function Zf(t){return t<id?`${t} B`:t<id**2?`${(t/id).toFixed(1)} KB`:t<id**3?`${(t/id**2).toFixed(1)} MB`:`${(t/id**3).toFixed(1)} GB`}function ww(t,n){n||(n={key:"name",order:"asc"});const r=t.filter(f=>f.type==="folder"),o=t.filter(f=>f.type!=="folder"),c=r.sort(xw(n)),u=o.sort(xw(n));return[...c,...u]}function rT(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 sT(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 xw({key:t,order:n}){const r=n==="asc"?rT:sT;return(o,c)=>r(o[t],c[t])}function Ov(t,n){const r=t==="/"?1:t.split("/").length;return r>=n.length?null:n[r].id}function iT(t){return t.length>1?t[t.length-2].id:null}let oT=class extends JN{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,o){!n||!n.length||(n.forEach(c=>this.parseId(c,o?r:void 0)),super.parse(n,r))}parseId(n,r){if(n.parent===0)return;const o=n.id,c=o.lastIndexOf("/");if(n.parent=r??(c===0?"/":o.slice(0,c)),n.name=o.slice(c+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 o=this.byId(n);if(!o)return r;for(;o.id!==0;)r.push(o),o=this.byId(o.parent);return r.reverse()}findFiles(n,r="/"){const o=[],c=n.toLocaleLowerCase();return this.eachChild(u=>{u.name.toLowerCase().indexOf(c)!==-1&&o.push(u)},r),o}add(n,r){const o=this.byId(n.parent||"/"),c=n.data?[...n.data]:null;n.data=null,super.add(n,r??o.data?o.data.length:0),c&&c.forEach(u=>this.add(u))}renameFiles(n,r,o){const c=this.byId(n),u=this.normalizeFile(c,r),f=[];return u.data?.forEach(h=>f.push(this.renameFiles(h.id,u.id,o))),f.length&&(u.data=f),o[n]=u.id,u}copyFiles(n,r,o){const c={};return n.forEach(u=>{const f=this.renameFiles(u,r,c);this.add(f),o&&this.remove(u),c[u]=f.id}),c}moveFiles(n,r){if(this.byId(n[0]).parent!==r)return this.copyFiles(n,r,!0)}serialize(n="/"){const r=[],o=this.byId(n);return o?(o.data?.forEach(c=>{const{id:u,date:f,type:h,size:g,lazy:y}=c,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 o=n.name,c=o.lastIndexOf("."),u=c!==-1?o.slice(c+1):"",f=u?`.${u}`:"";let h=c!==-1?o.slice(0,c):o,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()}}},lT=class extends tT{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:x}=g[u];w=ww(w,x[b]);const A=[];A[u]={_files:w},this.setState({panels:A},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(k=>{const N=h.byId(k);N&&y.push(N)});const{path:w,_sorts:b}=g[u],x=ww(y,b[w]),A=[];A[u]={_selected:x},this.setState({panels:A},f)}});this._router=new nT(super.setState.bind(this),r,{data:u=>new oT(u)});const o=this.in=new aT;o.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 x=[...w[g].selected];if(f){const k=x.indexOf(u);k===-1?x.push(u):x.splice(k,1)}else if(h&&w[g]._lastSelected){const k=w[g]._files;let N=k.findIndex(T=>T.id==w[g]._lastSelected),E=k.findIndex(T=>T.id==u);E<N&&([N,E]=[E,N]);const D=k.slice(N,E+1).map(T=>T.id);x=[...new Set([...x,...D])]}else x=u?[u]:[];const A=[];A[g]={selected:x,_lastSelected:u,_selectNavigation:y==="navigation"},this.setState({panels:A})}),o.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}),o.exec("select-file",{panel:f}),h&&h.forEach(x=>o.exec("select-file",{id:x,panel:f,toggle:!0})),w.lazy&&o.exec("request-data",{id:u})}}),o.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}))}),o.on("open-tree-folder",({id:u,mode:f})=>{const{data:h}=this.getState();h.update(u,{open:f}),this.setState({data:h})}),o.on("show-preview",({mode:u})=>{this.setState({preview:u})}),o.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 x={[f]:b.id};w.data?.forEach(k=>x={...g.moveFiles([k.id],b.id),...x});const A=y.map(k=>({selected:k.selected,_crumbs:k._crumbs,_lastSelected:k._lastSelected,_sorts:k._sorts}));g.remove(f),this._updatePanels(A,x),this.setState({data:g,panels:A})}}),o.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}),o.exec("select-file",{id:y.id})}),o.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})}),o.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(x=>b[x]),this.setState({data:g}),y[w].path==h&&(o.exec("select-file",{}),f.forEach(x=>{o.exec("select-file",{id:b[x],toggle:!0})}))}),o.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(A=>b[A]);const x=y.map(A=>({selected:A.selected,_crumbs:A._crumbs,_lastSelected:A._lastSelected,_sorts:A._sorts}));this._updatePanels(x,b,!0),this.setState({data:g,panels:x}),y[w].path==h&&(o.exec("select-file",{}),f.forEach(A=>{o.exec("select-file",{id:b[A],toggle:!0})}))}});let c=null;o.on("filter-files",({text:u})=>{if(!u){c&&this.setState({...c});return}o.exec("select-file",{});const{panels:f,mode:h}=this.getState();c||(c={panels:f,mode:h,search:""}),this.setState({mode:"search",search:u})}),o.on("set-mode",({mode:u})=>{const{activePanel:f}=this.getState(),h=[];h[f]={_selectNavigation:!1};const g={mode:u,search:"",panels:h};c=null,this.setState(g)}),o.on("set-active-panel",({panel:u})=>{this.setState({activePanel:u})}),o.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 o=0;o<2;o++)n[o]=bw({_crumbs:[],_files:[],_selected:[],_sorts:{},path:"/",selected:[],...n[o]});const r={panels:bw(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,o){const{data:c}=this.getState();n.forEach(u=>{const f=[];u.selected.forEach(y=>{c.byId(y)?f.push(y):!o&&r[y]&&f.push(r[y])}),u.selected=f,c.byId(u._lastSelected)||(u._lastSelected=o?null:r[u._lastSelected]||null);const h={};Object.keys(u._sorts).forEach(y=>{c.byId(y)?h[y]=u._sorts[y]:r[y]&&!o&&(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]:c.byId(g.id)||(u.path="/"))})}_isPlacedIntoSelf(n,r){return n.some(o=>o===r||this.getState().data.getParents(r).some(c=>c.id===o))}};function cT(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 uT(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 dT(t,n="data-id"){const r=uT(t,n);return r?r.getAttribute(n):null}new Date().valueOf();function fT(t,n){const{api:r}=n;function o(u,f){const h=n.getPanel(),g=h.selected,y=f.ctrlKey||f.metaKey,w=f.shiftKey;let b;const x=g?.[0]?r.getFile(g[0]):null;g?.length?g.length>1?b=n.menuOptions("multiselect"):b=n.menuOptions(x.type,x):b=n.menuOptions("body");const A=`${y?"ctrl+":""}${w?"shift+":""}${u}`,k=b?b.find(E=>E.hotkey?.toLowerCase()===A):!1,N=n.performAction;if(k)switch(A){case"ctrl+c":N("copy");break;case"ctrl+x":N("move");break;case"ctrl+v":N("paste",x);break;case"delete":N("delete");break;case"ctrl+r":f.preventDefault(),N("rename",x);break;case"ctrl+d":f.preventDefault(),N("download",x);break;default:k.handler?.({context:x})}switch(u){case"enter":{if(y||w)break;const{_crumbs:E,_selectNavigation:D}=h;if(D){const T=iT(E);if(T){const F=Ov(T,E);r.exec("set-path",{id:T,selected:[F]})}}else if(g.length===1){const T=r.getFile(g[0]);T&&r.exec(T.type==="folder"?"set-path":"open-file",{id:T.id})}break}case"arrowup":case"arrowleft":{const{_files:E,_selected:D,path:T,_selectNavigation:F}=h;let O;if(D.length){const P=D.at(0).id,z=E.findIndex(I=>I.id===P);if(z!==-1){const I=z-1;E[I]?O=E[I].id:T!=="/"&&!(y||w)&&r.exec("select-file",{type:"navigation"})}}else{if(F)break;if(T!=="/"){r.exec("select-file",{type:"navigation"});break}O=E.at(0)?.id}O&&r.exec("select-file",{id:O,toggle:y,range:w});break}case"arrowdown":case"arrowright":{const{_files:E,_selected:D,path:T,_selectNavigation:F}=h;let O;if(D.length){const P=D.at(-1).id,z=E.findIndex(I=>I.id===P);if(z!==-1){const I=z+1;E[I]&&(O=E[I].id)}}else{if(T!=="/"&&!F){r.exec("select-file",{type:"navigation"});break}O=E.at(0)?.id}O&&r.exec("select-file",{id:O,toggle:y,range:w});break}}}function c(u){const f=u.code.replace("Key","").toLowerCase();o(f,u),f=="tab"&&setTimeout(()=>{const h=document.activeElement;h.className.indexOf("table")!=-1&&r.exec("set-active-panel",{panel:+dT(h,"data-panel")})})}return t.addEventListener("keydown",c),{destroy:()=>{t.removeEventListener("keydown",c)}}}function mT(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 pT(t,n="data-id"){const r=t.getAttribute(n);return r?hT(r):null}function hT(t){if(t.startsWith(":"))return t.substring(1);const n=t*1;return isNaN(n)?t:n}function gT(){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 vT=gT();new Date().valueOf();function FS(t){const[n,r]=d.useState(t),o=d.useRef(t);return d.useEffect(()=>{if(o.current!==t){if(Array.isArray(o.current)&&Array.isArray(t)&&o.current.length===0&&t.length===0)return;o.current=t,r(t)}},[t]),[n,r]}function yT(t,n,r){const[o,c]=d.useState(()=>n);return t||console.warn(`Writable ${r} is not defined`),d.useEffect(()=>t?t.subscribe(f=>{c(()=>f)}):void 0,[t]),o}function Tt(t,n){const r=t.getState(),o=t.getReactiveState();return yT(o[n],r[n],n)}function bT(t,n){const r=d.useRef(n);r.current=n;const[o,c]=d.useState(1);return d.useEffect(()=>t.subscribe(f=>{r.current=f,c(h=>h+1)}),[t]),[r.current,o]}function Zs(t,n){const r=t.getState(),o=t.getReactiveState();return bT(o[n],r[n])}function PS(t){const n={};return t.split(";").forEach(r=>{const[o,c]=r.split(":");if(c){let u=o.trim();u.indexOf("-")&&(u=u.replace(/-([a-z])/g,(f,h)=>h.toUpperCase())),n[u]=c.trim()}}),n}function OS(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 Sw(t,n,r){function o(c){const u=mT(c);if(!u)return;const f=pT(u);if(typeof n=="function")return n(f,c);let h,g=c.target;for(;g!=u;){if(h=g.dataset?g.dataset.action:null,h&&n[h]){n[h](f,c);return}g=g.parentNode}n[r]&&n[r](f,c)}return vT.addEvent(t,r,o)}function wT(t,n){const r=[Sw(t,n,"click")];return n.dblclick&&r.push(Sw(t,n.dblclick,"dblclick")),()=>{r.forEach(o=>o())}}function BS(t,n){return t.map((r,o)=>{const c=n(r,o);return r.data&&r.data.length&&(c.data=BS(r.data,n)),c}).filter(Boolean)}function HS(t,n){const r=[];return t.forEach(o=>{if(o.data){const c=HS(o.data,n);c.length&&r.push({...o,data:c})}else n(o)&&r.push(o)}),r}function xT(t){return BS(t,(n,r)=>{const o={...n,id:n.id||jv()};return o.type&&(o.comp=o.type),o.comp==="separator"&&t[r-1]?.comp==="separator"?null:o})}const zS={};function ST(t){return zS[t]||t}function CT(t,n){zS[t]=n}function kT({onClick:t,onShow:n,option:r}){const o=d.useRef(null),c=d.useCallback(()=>{n(r.data?r.id:!1,o.current)},[n,r]),u=d.useCallback(h=>{if(r.data){h.stopPropagation(),n(r.id,o.current);return}t(h)},[t,n,r]),f=d.useMemo(()=>r&&r.comp?ST(r.comp):null,[r]);return i.jsxs("div",{ref:o,className:`wx-cDCz9rZQ wx-option ${r.css||""} ${r.disabled?"wx-disabled":""}`,"data-id":Ha(r.id),onMouseEnter:c,onClick:u,children:[r.icon?i.jsx("i",{className:`wx-cDCz9rZQ wx-icon ${r.icon}`}):null,r.comp?f?i.jsx(f,{item:r,option:r}):null:i.jsxs("span",{className:"wx-cDCz9rZQ wx-value",children:[" ",r.text," "]}),r.subtext?i.jsx("span",{className:"wx-cDCz9rZQ wx-subtext",children:r.subtext}):null,r.data?i.jsx("i",{className:"wx-cDCz9rZQ wx-sub-icon wxi-angle-right"}):null]})}function Bv({options:t,left:n=0,top:r=0,at:o="bottom",parent:c=null,mount:u=null,context:f=null,css:h="",onClick:g,onCancel:y}){const[w,b]=d.useState(-1e4),[x,A]=d.useState(-1e4),[k,N]=d.useState(20),[E,D]=d.useState(),T=d.useRef(null),[F,O]=d.useState(!1),[P,z]=d.useState(null),I=d.useCallback(()=>{const V=CS(T.current,c,o,n,r);V&&(b(V.x),A(V.y),D(V.width));let ne=V?.z??20;const $=c?fN(c):[];let _=0;for(const ie of $){const be=parseInt(getComputedStyle(ie).zIndex,10);be>_&&(_=be)}_>=ne&&(ne=_+1),N(ne)},[c,o,n,r]);d.useEffect(()=>{u&&u(I)},[]);const X=d.useCallback(()=>{O(!1)},[]),se=d.useCallback((V,ne)=>{O(V),z(ne)},[]),Z=d.useMemo(()=>xT(t),[t]);d.useEffect(()=>{I()},[c,I]);const G=d.useRef(g),K=d.useRef(y),me=d.useRef(c);return d.useEffect(()=>{G.current=g},[g]),d.useEffect(()=>{K.current=y},[y]),d.useEffect(()=>{me.current=c},[c]),d.useEffect(()=>{if(!T.current)return;function V(ne){K.current?K.current(ne):G.current&&G.current({action:null,option:null})}return Vi(T.current,{callback:V,modal:!0,parent:()=>me.current}).destroy},[]),i.jsx("div",{ref:T,"data-wx-menu":"true",className:`wx-XMmAGqVx wx-menu ${h}`,style:{position:"absolute",top:x+"px",left:w+"px",width:E,zIndex:k},onMouseLeave:X,children:Z.map(V=>i.jsxs(d.Fragment,{children:[V.comp==="separator"?i.jsx("div",{className:"wx-XMmAGqVx wx-separator"}):i.jsx(kT,{option:V,onShow:se,onClick:ne=>{if(!V.data&&!ne.defaultPrevented){const $={context:f,action:V,option:V,event:ne};V.handler&&V.handler($),g&&g($),ne.stopPropagation()}}}),V.data&&F===V.id?i.jsx(Bv,{css:h,options:V.data,at:"right-overlap",parent:P,context:f,onClick:g,onCancel:y}):null]},V.id))})}const $S=d.forwardRef(function(t,n){const{options:r,at:o="bottom",resolver:c=null,dataKey:u="contextId",filter:f=null,css:h="",children:g,onClick:y}=t,[w,b]=d.useState(null),[x,A]=d.useState(null),[k,N]=d.useState(0),[E,D]=d.useState(0),T=d.useRef(null),F=d.useMemo(()=>`data-${u.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,[u]),O=d.useMemo(()=>w!==null&&f?HS(r,X=>f(X,w)):r,[w,f,r]);function P(X){A(null),y&&y(X)}function z(X){if(T.current===X){T.current=null;return}A(null),y&&y({action:null,option:null})}const I=d.useCallback((X,se)=>{if(!X){A(null);return}if(X.defaultPrevented)return;const Z=X.target;if(Z&&Z.dataset&&Z.dataset.menuIgnore)return;if(x&&x===Z){A(null),X.preventDefault();return}N(X.clientX+1),D(X.clientY+1);let G=typeof se<"u"?se:Xf(Z,F);c&&(G=c(G,X),!G)||(b(G),A(Z),T.current=X.nativeEvent||X,X.preventDefault())},[x,F,c]);return d.useImperativeHandle(n,()=>({show:I}),[I]),i.jsxs(i.Fragment,{children:[g?i.jsx("span",{onClick:I,"data-menu-ignore":"true",children:typeof g=="function"?g():g}):null,x?i.jsx(Dv,{children:i.jsx(Bv,{css:h,at:o,top:E,left:k,parent:x,context:w,onClick:P,onCancel:z,options:O},x)}):null]})}),MT=d.forwardRef(function(t,n){const{options:r,at:o="bottom",css:c="",children:u,onClick:f}=t,[h,g]=d.useState(null),y=d.useRef(null);function w(k){g(null),f&&f(k)}function b(k){if(y.current===k){y.current=null;return}g(null),f&&f({action:null,option:null})}const x=d.useCallback(k=>{g(k.target),y.current=k.nativeEvent||k,k.preventDefault()},[]);d.useImperativeHandle(n,()=>({show:x}),[x]);function A(k){let N=k.target;for(;!N.dataset.menuIgnore;)g(N),N=N.parentNode}return i.jsxs(i.Fragment,{children:[i.jsx("span",{onClick:A,"data-menu-ignore":"true",children:u}),h?i.jsx(Dv,{children:i.jsx(Bv,{css:c,at:o,parent:h,options:r,onClick:w,onCancel:b})}):null]})}),AT=d.forwardRef(function(t,n){const{options:r,at:o="bottom",resolver:c=null,dataKey:u="contextId",filter:f=null,css:h="",children:g,onClick:y}=t,w=d.useRef(null),b=d.useCallback((x,A)=>{w.current.show(x,A)},[]);return d.useImperativeHandle(n,()=>({show:b}),[b]),i.jsxs(i.Fragment,{children:[g?i.jsx("span",{onContextMenu:b,"data-menu-ignore":"true",children:g}):null,i.jsx($S,{css:h,at:o,options:r,resolver:c,dataKey:u,filter:f,ref:w,onClick:y})]})}),NT={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 TT=class{constructor(n,r,o,c,u){this.setFiles=n,this.setReady=r,this.setSignal=o,this.setDrag=c,u&&u.length&&this.setFiles(u)}open(n){this.setSignal(["click",n||{}])}getState(){let n="server";const r=this.files;for(let o=0;o<r.length;o++){if(r[o].status==="client")return"client";r[o].status==="error"&&(n="error")}return n}droparea(n,r){r=r||{};const o=()=>{r.dragEnter&&r.dragEnter(),this.setDrag(!0)},c=()=>{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",o),n.addEventListener("dragleave",c),n.addEventListener("dragover",u,!0),n.addEventListener("drop",f,!0),()=>{n.removeEventListener("dragenter",o),n.removeEventListener("dragleave",c),n.removeEventListener("dragover",u,!0),n.removeEventListener("drop",f,!0)}}updateFile(n,r){const o=this.files.findIndex(u=>u.id===n);if(o===-1)return;const c=[...this.files];return c[o]={...c[o],...r},this.files=c,this.setFiles(this.files),this.files[o]}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 US(t){const[n,r]=d.useState([]),[o,c]=d.useState(Promise.resolve(null)),[u,f]=d.useState(null),[h,g]=d.useState(!1),y=d.useRef();return y.current||(y.current=new TT(r,c,f,g,t)),y.current.files=n,y.current.ready=o,y.current.signal=u,y.current.drag=h,y.current}function RT(t,n){{if(t){const r=t.getGroup(n);if(r)return r}return tm(NT).getGroup(n)}}const jT=()=>Math.random().toString(36).substr(2,9),ET=({data:t,accept:n="",multiple:r=!0,folder:o=!1,uploadURL:c="",apiOnly:u=!1,disabled:f=!1,children:h,onChange:g,onUpload:y})=>{const w=d.useRef(null),b=d.useRef(null),[x,A]=d.useState({}),k=US(),N=t||k,E=d.useContext($a.i18n),D=RT(E,"uploader");d.useEffect(()=>{w.current&&o&&(w.current.webkitdirectory=!0)},[o]),d.useEffect(()=>{if(!u&&b.current&&!f)return N.droparea(b.current)},[u,f,b]);const T=Z=>{const G=new FormData;return G.append("upload",Z.file),fetch(c,{method:"POST",body:G}).then(K=>K.json()).then(K=>({id:Z.id,...K}),()=>({id:Z.id,status:"error"})).catch(K=>(console.log(K),{id:Z.id,status:"error"}))},F=(Z,G)=>{const K=N.updateFile(Z,G),me={...K,status:N.getState()};K&&K.uploaded&&K.uploaded(me),y&&y(me),K.temp&&N.deleteFile(K.id)},O=Z=>{if(!Z)return;const G=typeof c=="function"?c(Z):T(Z);N.setReady(G.then(K=>{K.status=K.status||"server",F(Z.id,K)}).catch(K=>{F(Z.id,{status:"error",error:K})}))},P=(Z,G)=>{const K={...G||x,id:jT(),status:"client",name:Z.name,file:Z};K.selected&&K.selected(K),g&&g(K),N.addFile(K,r),O(K),w.current&&(w.current.value="")},z=(Z,G,K)=>{Z.isFile?Z.file(me=>{P(me,K)}):Z.isDirectory&&Z.createReader().readEntries(me=>{me.forEach(V=>{z(V,G+V.name+"/",K)})})},I=Z=>{Array.from(Z.target.files).forEach(G=>P(G))},X=(Z,G)=>{Array.from(Z.dataTransfer.items).forEach(K=>{const me=K.webkitGetAsEntry();me&&z(me,"",G)})},se=()=>{w.current&&w.current.click()};return d.useEffect(()=>{if(N.signal){const[Z,G,K]=N.signal;A(G),Z==="click"?se():Z==="drop"&&X(K,G),N.setSignal(null)}},[N.signal]),u?i.jsxs(i.Fragment,{children:[i.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:I,accept:n,multiple:r,disabled:f}),h]}):i.jsxs("div",{className:`wx-at1A8tb8 wx-label ${N.drag?"wx-active":""} ${f?"wx-disabled":""}`,ref:b,children:[i.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:I,accept:n,multiple:r,disabled:f}),h||i.jsx("div",{className:"wx-at1A8tb8 wx-dropzone",children:i.jsxs("span",{children:[D("Drop files here or")," ",i.jsx("span",{className:"wx-at1A8tb8 wx-action",onClick:se,children:D("select files")})]})})]})};new Date().valueOf();function DT(t,n){if(Object.keys(t).length!==Object.keys(n).length)return!1;for(const r in n){const o=t[r],c=n[r];if(!Jp(o,c))return!1}return!0}function Jp(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(!Jp(t[r],n[r]))return!1;return!0}else return DT(t,n);return t===n}function iv(t){if(typeof t!="object"||t===null)return t;if(t instanceof Date)return new Date(t);if(t instanceof Array)return t.map(iv);const n={};for(const r in t)n[r]=iv(t[r]);return n}var qS=2,IT=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,o,c,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=o+(o?".":"")+f;h?(h.__parse(y,w,c,u)&&(r[f]=y),u&qS?c[w]=h.__trigger:h.__trigger()):(y&&y.__reactive?n[f]=this._wrapNested(y,y,w,c):n[f]=this._wrapWritable(y),r[f]=y),c[w]=c[w]||null}}_wrapNested(t,n,r,o){const c=this._wrapWritable(t);return this._wrapProperties(t,c,n,r,o,0),c.__parse=(u,f,h,g)=>(this._wrapProperties(u,c,n,f,h,g),!1),c}_wrapWritable(t){const n=[],r=function(){for(let o=0;o<n.length;o++)n[o](t)};return{subscribe:o=>(n.push(o),this._async?setTimeout(o,1,t):o(t),()=>{const c=n.indexOf(o);c>=0&&n.splice(c,1)}),__trigger:()=>{n.length&&(this._async?setTimeout(r,1):r())},__parse:function(o){return t=o,!0}}}},LT=class{constructor(t,n,r,o){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(c=>{c.in.forEach(u=>{const f=this._triggers.get(u)||[];f.push(c),this._triggers.set(u,f)}),c.out.forEach(u=>{const f=this._sources.get(u)||{};c.in.forEach(h=>f[h]=!0),this._sources.set(u,f)})}),this._routes.forEach(c=>{c.length=Math.max(...c.in.map(u=>WS(u,this._sources,1)))}),this._bus=o}init(t){const n={};for(const r in t)if(this._prev[r]!==t[r]){const o=this._parsers[r];n[r]=o?o(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,qS);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),o=!n.length;n=n||[];for(let c=0;c<r.length;c++){const u=r[c],f=this._triggers.get(u);f&&f.forEach(h=>{n.indexOf(h)==-1&&n.push(h)})}o&&this._execNext(n)}_execNext(t){for(;t.length;){t.sort((r,o)=>r.length<o.length?1:-1);const n=t[t.length-1];t.splice(t.length-1),n.exec(t)}}};function WS(t,n,r){const o=n.get(t);if(!o)return r;const c=Object.keys(o).map(u=>WS(u,n,r+1));return Math.max(...c)}var _T=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(t,n,r){let o=this._handlers[t];o?r&&r.intercept?o.unshift(n):o.push(n):o=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 o=r.length-1;o>=0;o--)this._tag.get(r[o])===t&&r.splice(o,1)}}async exec(t,n){const r=this._handlers[t];if(r)for(let o=0;o<r.length;o++){const c=r[o](n);if(c===!1||c&&c.then&&await c===!1)return}return this._nextHandler&&await this._nextHandler.exec(t,n),n}setNext(t){return this._nextHandler=t}};function FT(t){return n=>n[t]}function PT(t){return(n,r)=>n[t]=r}function Gl(t,n){return(n.getter||FT(n.id))(t)}function gg(t,n,r){return(n.setter||PT(n.id))(t,r)}function OT(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 $l(t,n){let r=Gl(t,n)??"";return n.template?r=n.template(r,t,n):n.optionsMap&&(Array.isArray(r)?r=r.map(o=>n.optionsMap.get(o)).join(", "):r=n.optionsMap.get(r)),typeof r>"u"?"":r+""}function BT(t,n){const r=/\n|"|;|,/;let o="";const c=n.rows||`
174
- `,u=n.cols||" ",f=t._columns,h=t.flatData;n.header!==!1&&f[0].header&&(o=Cw("header",f,o,u,c));for(let g=0;g<h.length;g++){const y=[];for(let w=0;w<f.length;w++){let b=$l(h[g],f[w]);r.test(b)&&(b='"'+b.replace(/"/g,'""')+'"'),y.push(b)}o+=(o?c:"")+y.join(u)}return n.footer!==!1&&f[0].footer&&(o=Cw("footer",f,o,u,c)),o}function Cw(t,n,r,o,c){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?c:"")+h.join(o)}return r}const HT="portrait",zT=100,$T="a4",UT={a3:{width:11.7,height:16.5},a4:{width:8.27,height:11.7},letter:{width:8.5,height:11}};function qT(t,n){const r=[];let o=[],c=0;const u=t.filter(h=>!h.hidden),f=WT(n);return u.forEach((h,g)=>{c+h.width<=f?(c+=h.width,o.push(h)):(o.length&&r.push(o),o=[h],c=h.width),g===u.length-1&&o.length&&r.push(o)}),r}function kw(t,n,r){const o=[];return t.forEach((c,u)=>{const f=c[n];for(let h=0;h<r.length;h++){o[h]||(o[h]=[]);const g={...f[h]};if(o[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(o[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,x)=>b+x.width,0),w>1&&(y=w-1)}for(let w=0;w<y;w++)o[h].push(null)}if(g.rowspan>1){const y=g.rowspan;for(let w=1;w<y;w++)o[h+w]||(o[h+w]=[]),o[h+w].push(null)}}}if(c.collapsed)for(let h=0;h<o.length;h++){const g=o[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-c.width)}}}),o.map(c=>c.filter(u=>u&&u.colspan!==0))}function WT(t){const{mode:n,ppi:r,paper:o}=t,{width:c,height:u}=UT[o];return GT(n==="portrait"?c:u,r)}function GT(t,n){return t*n}function VT(t={}){const{mode:n,ppi:r,paper:o}=t;return{mode:n||HT,ppi:r||zT,paper:o||$T}}function GS(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 KT(t,n,r){let o=t[r.id];if(r.filter.type==="richselect"&&o){const c=r.filter.config?.options||n.find(({id:u})=>u==r.id).options;c&&(o=c.find(({id:u})=>u==o).label)}return o??""}const Mw=["resize-column","hide-column","update-cell"],QT=["delete-row","update-row","update-cell"],YT=["move-item"],XT=["resize-column","move-item"];class ZT{undo=[];redo=[];progress={};in;getState;setState;_previousValues={};constructor(n,r,o){this.in=n,this.getState=r,this.setState=o,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:o}=this.getPrev(),c=o.findIndex(u=>u.id===r);return{action:"add-row",data:{id:r,row:o[c],before:c<o.length-1?o[c+1].id:void 0},source:{action:"delete-row",data:n}}}},"update-cell":{handler:n=>{const{id:r,column:o}=n,c=this.getRow(r),u=this.getColumn(o),f=Gl(c,u);return Jp(f,n.value)?null:{action:"update-cell",data:{id:r,column:o,value:f},source:{action:"update-cell",data:n}}}},"update-row":{handler:n=>{const{id:r,row:o}=n,c=this.getRow(r);for(const u in o)Object.keys(c).includes(u)||(c[u]=void 0);return{action:"update-row",data:{id:r,row:c},source:{action:"update-row",data:n}}}},"copy-row":{handler:n=>{const{id:r}=n,{data:o}=this.getState(),c=o.findIndex(f=>f.id===r),u=o[c];return{action:"delete-row",data:{id:r},source:{action:"add-row",data:{id:r,row:u,before:c<o.length-1?o[c+1].id:void 0}}}}},"resize-column":{handler:n=>{const{id:r,width:o}=n,c=this.getColumn(r),{_sizes:u}=this.getState();return{action:"resize-column",data:{id:r,width:c.width??u.columnWidth},source:{action:"resize-column",data:{id:r,width:o}}}}},"hide-column":{handler:n=>{const{id:r}=n,o=this.getColumn(r);return{action:"hide-column",data:{id:r,mode:o.hidden},source:{action:"hide-column",data:n}}}},"collapse-column":{handler:n=>{const{id:r,row:o,mode:c}=n;return{action:"collapse-column",data:{id:r,row:o,mode:typeof c=="boolean"?!c:c},source:{action:"collapse-column",data:n}}}},"move-item":{handler:n=>{const{id:r,target:o,mode:c}=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:o,mode:c}}}}},"open-row":{handler:n=>{const{id:r,nested:o}=n;return{action:"close-row",data:{id:r,nested:o},source:{action:"open-row",data:n}}}},"close-row":{handler:n=>{const{id:r,nested:o}=n;return{action:"open-row",data:{id:r,nested:o},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,o=>{if(!(o.eventSource==="undo"||o.eventSource==="redo"||o.skipUndo)){if(XT.includes(r)){(o.inProgress&&!this.progress[r]||typeof o.inProgress!="boolean")&&(YT.includes(r)&&this.setPrev("flatData"),Mw.includes(r)&&this.setPrev("columns")),this.progress[r]=o.inProgress;return}QT.includes(r)&&this.setPrev("data"),Mw.includes(r)&&this.setPrev("columns")}}),this.in.on(r,o=>{if(o.eventSource==="undo"||o.eventSource==="redo"||o.skipUndo||o.inProgress)return;const c=n[r].handler(o);c&&this.addToHistory(c)})}setPrev(n){this._previousValues[n]=iv(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(o=>o.id===n)}getTreeRow(n,r){for(let o=0;o<n.length;o++){if(n[o].id===r)return n[o];if(n[o].data){const c=this.getTreeRow(n[o].data,r);if(c)return c}}return null}getColumn(n){const{columns:r}=this.getPrev();return r.find(o=>o.id===n)}}function VS(t,n){return typeof t>"u"||t===null?-1:typeof n>"u"||n===null?1:t===n?0:t>n?1:-1}function JT(t,n){return-VS(t,n)}function eR(t,n){if(typeof n.sort=="function")return function(o,c){const u=n.sort(o,c);return t==="asc"?u:-u};const r=t==="asc"?VS:JT;return function(o,c){return r(Gl(o,n),Gl(c,n))}}function tR(t,n){if(!t||!t.length)return;const r=t.map(o=>{const c=n.find(u=>u.id==o.key);return eR(o.order,c)});return t.length===1?r[0]:function(o,c){for(let u=0;u<r.length;u++){const f=r[u](o,c);if(f!==0)return f}return 0}}const dp=28,nR=20;function aR(){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 Pp(t,n,r,o,c){const u=document.createElement("div"),f=document.createElement("div"),h=document.body;c=c?`${c}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=${c};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(),x=Math.ceil(b.width)+(o&&o.length?o[w]:0),A=Math.ceil(b.height);g=Math.max(g||0,x),y=Math.max(y||0,A)}return u.remove(),{width:g,height:y}}function Aw(t,n,r,o,c){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:x,rowspan:A,css:k}=h[y];if(!w){u[y]=Math.max(u[y]||0,o);continue}let N=0;if(b&&!x){let E=`wx-measure-cell-${n}`;if(E+=k?` ${k}`:"",N=Pp(w,E,c).width,(A>1||!h[y+1])&&r>y+1){const D=A||r-y,T=u.slice(y,y+D).reduce((F,O)=>F+O,0);if(T<N){const F=Math.ceil((N-T)/D);for(let O=y;O<y+D;O++)u[O]=(u[O]||o)+F}continue}}u[y]=Math.max(u[y]||o,N)}}return u}function rR(t,n,r){const o=[],c=[];let u="wx-measure-cell-body";u+=t.css?` ${t.css}`:"";for(let f=0;f<n.length;f++){const h=n[f],g=$l(h,t);g&&(o.push(g),t.treetoggle?c.push(n[f].$level*dp+(n[f].$count?dp:0)+(t.draggable?dp:0)):t.draggable&&c.push(dp))}return Pp(o,u,r,c).width}function sR(t,n){const r="wx-measure-cell-header",o=t.sort?nR:0;let c=t.header;if(typeof c=="string")return Pp(c,r,n).width+o;let u;Array.isArray(c)||(c=[c]);for(let f=0;f<c.length;f++){const h=c[f],g=typeof h=="string"?h:h.text,y=r+(typeof h=="string"?"":` ${h.css}`);let w=Pp(g,y,n).width;f===c.length-1&&(w+=o),u=Math.max(u||0,w)}return u}const iR={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&&lR(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 KS(t){return iR[t]}function oR(t,n){const r=[];for(const o in t){const c=n.find(g=>g.id==o),{config:u,type:f}=c.header.find(g=>g.filter).filter,h=t[o];r.push(g=>{const y=Gl(g,c);return u?.handler?u.handler(y,h):KS(f)(y,h)})}return o=>{for(let c=0;c<r.length;c++)if(!r[c](o))return!1;return!0}}function lR(t,n){return t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate()}let cR=class extends IT{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 LT(super.setState.bind(this),[{in:["columns","sizes","_skin"],out:["_columns","_sizes"],exec:c=>{const{columns:u,sizes:f,_skin:h}=this.getState(),g=this.copyColumns(u),y=g.reduce((x,A)=>Math.max(A.header.length,x),0),w=g.reduce((x,A)=>Math.max(A.footer.length,x),0);g.forEach(this.setCollapsibleColumns);const b=this.normalizeSizes(g,f,y,w,h);for(let x=0;x<g.length;x++)this.normalizeColumns(g,x,"header",y,b),this.normalizeColumns(g,x,"footer",w,b);this.setState({_columns:g,_sizes:b},c)}},{in:["data","tree","_filterIds"],out:["flatData","_rowHeightFromData"],exec:c=>{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(x=>y.has(x.id)):u,b=!h&&w.some(x=>x.rowHeight);this.setState({flatData:w,_rowHeightFromData:b},c)}}],{sizes:c=>({...r,...c})});const o=this.in=new _T;o.on("close-editor",({ignore:c})=>{const{editor:u}=this.getState();u&&(c||o.exec("update-cell",u),this.setState({editor:null}))}),o.on("open-editor",({id:c,column:u})=>{let f=this.getState().editor;f&&o.exec("close-editor",{});const h=this.getRow(c),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:c,value:Gl(h,g)??"",renderedValue:$l(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})}}),o.on("editor",({value:c})=>{let u=this.getState().editor;if(u){u={...u},u.value=c;const f=this.getColumn(u.column),h={...this.getRow(u.id)};gg(h,f,c),u.renderedValue=$l(h,f),this.setState({editor:u})}}),o.on("add-row",c=>{const u=this.getState();let{data:f}=u;const{select:h,_filterIds:g}=u,{row:y,before:w,after:b,select:x}=c;if(c.id=y.id=c.id||y.id||fp(),w||b){const k=w||b,N=f.findIndex(E=>E.id===k);f=[...f],f.splice(N+(b?1:0),0,c.row)}else f=[...f,c.row];const A={data:f};g&&(A._filterIds=[...g,c.id]),this.setState(A),!(typeof x=="boolean"&&!x)&&(x||h)&&o.exec("select-row",{id:y.id,show:!0})}),o.on("delete-row",c=>{const{data:u,selectedRows:f,focusCell:h,editor:g}=this.getState(),{id:y}=c,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"})}),o.on("update-cell",c=>{const u=this.getState();let{data:f}=u;f=[...f];const{tree:h}=u,{id:g,column:y,value:w}=c,b=this.getColumn(y);if(h){const x={...this._branches[g]};gg(x,b,w);const A=this.updateTreeRow(x);x.$parent===0&&(f=A)}else{const x=f.findIndex(k=>k.id===g),A={...f[x]};gg(A,b,w),f[x]=A}this.setState({data:f})}),o.on("update-row",c=>{let{data:u}=this.getState();const{id:f,row:h}=c,g=u.findIndex(y=>y.id===f);u=[...u],u[g]={...u[g],...h},this.setState({data:u})}),o.on("select-row",({id:c,toggle:u,range:f,mode:h,show:g,column:y})=>{const w=this.getState(),{focusCell:b}=w;let{selectedRows:x}=w;if(x.length||(f=u=!1),f){const{data:A}=this.getState();let k=A.findIndex(E=>E.id===x[x.length-1]),N=A.findIndex(E=>E.id===c);k>N&&([k,N]=[N,k]),A.slice(k,N+1).forEach(E=>{this.isSelected(E.id)||x.push(E.id)})}else if(u&&this.isSelected(c)){if(h===!0)return;x=x.filter(A=>A!==c)}else if(u){if(h===!1)return;x.push(c)}else x=[c];this.setState({selectedRows:[...x]}),b?.row!==c&&this.in.exec("focus-cell",{eventSource:"select-row"}),g&&this.in.exec("scroll",{row:c,column:y})}),this.in.on("focus-cell",c=>{const{row:u,column:f,eventSource:h}=c,{_columns:g,split:y}=this.getState();u&&f?(this.setState({focusCell:{row:u,column:f}}),h!=="click"&&((!y.left||g.findIndex(w=>w.id===c.column)>=y.left)&&(!y.right||g.findIndex(w=>w.id===c.column)<g.length-y.right)?this.in.exec("scroll",{row:u,column:f}):this.in.exec("scroll",{row:u}))):this.setState({focusCell:null})}),o.on("resize-column",c=>{const{id:u,auto:f,maxRows:h,inProgress:g}=c;if(g===!1)return;let y=c.width||0;const w=[...this.getState().columns],b=this.getColumn(u);if(f){if(f==="data"||f===!0){const{flatData:x,_skin:A}=this.getState();let k=x.length;h&&(k=Math.min(h,k));const N=x.slice(0,k);y=rR(b,N,A)}if(f==="header"||f===!0){const{_skin:x}=this.getState();y=Math.max(sR(b,x),y)}}b.width=Math.max(17,y),delete b.flexgrow,this.setState({columns:w})}),o.on("hide-column",c=>{const{id:u,mode:f}=c,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})):c.skipUndo=!0}),o.on("sort-rows",c=>{const{key:u,add:f,sort:h}=c,g=this.getState(),{columns:y,data:w,tree:b}=g;if(h){const T=[...w];T.sort(h),this.setState({data:T});return}const{order:x="asc"}=c;let A=g.sortMarks;const k=Object.keys(A),N=k.length;!f||!N||N===1&&A[u]?A={[u]:{order:x}}:(N===1&&(A[k[0]]={...A[k[0]],index:0}),A={...A,[u]:{order:x,index:typeof f=="number"?f:A[u]?.index??N}});const E=Object.keys(A).sort((T,F)=>A[T].index-A[F].index).map(T=>({key:T,order:A[T].order}));this.setState({sortMarks:A});const D=tR(E,y);if(D){const T=[...w];b?this.sortTree(T,D):T.sort(D),this.setState({data:T})}}),o.on("filter-rows",c=>{const{value:u,key:f,filter:h}=c;if(!Object.keys(c).length){this.setState({filterValues:{},_filterIds:null});return}const g=this.getState(),{data:y,tree:w,_columns:b}=g;let x=g.filterValues;const A={};f&&(x={...x,[f]:u},A.filterValues=x);const k=h??oR(x,b);let N=[];w?N=this.filterTree(y,k,N):y.forEach(E=>{k(E)&&N.push(E.id)}),A._filterIds=N,this.setState(A)}),o.on("collapse-column",c=>{const{id:u,row:f,mode:h}=c,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}))}),o.on("move-item",c=>{const{id:u,inProgress:f}=c;let{target:h,mode:g="after"}=c;const{data:y,flatData:w,tree:b}=this.getState(),x=w.findIndex(N=>N.id===u);let A;if(g==="up"||g==="down"){if(g==="up"){if(x===0)return;A=x-1,g="before"}else if(g==="down"){if(x===w.length-1)return;A=x+1,g="after"}h=w[A]&&w[A].id}else A=w.findIndex(N=>N.id===h);if(x===-1||A===-1||f===!1)return;let k;b||(k=this.moveItem(u,h,y,g)),this.setState({data:b?this.normalizeTreeRows(k):k})}),o.on("copy-row",c=>{const{id:u,target:f,mode:h="after"}=c,g=this.getState(),{flatData:y,_filterIds:w}=g;let{data:b}=g;const x=this.getRow(u);if(!x)return;const A={...x,id:fp()};c.id=A.id;const k=y.findIndex(E=>E.id===f);if(k===-1)return;b.splice(k+(h==="after"?1:0),0,A),b=[...b];const N={data:b};w&&(N._filterIds=[...w,A.id]),this.setState(N)}),o.on("open-row",c=>{const{id:u,nested:f}=c;this.toggleBranch(u,!0,f)}),o.on("close-row",c=>{const{id:u,nested:f}=c;this.toggleBranch(u,!1,f)}),o.on("export-data",c=>new Promise((u,f)=>{const h=c.format||"csv",g=`${c.fileName||"data"}.${h}`;if(h==="csv"){const y=BT(this.getState(),c.csv||{});c.download!==!1?OT(new Blob(["\uFEFF"+y],{type:"text/csv"}),g):c.result=y,u(!0)}else f()})),o.on("hotkey",({key:c,event:u,isInput:f})=>{switch(c){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,x=this.getNextEditor(this.getRow(b),this.getColumn(w));if(!x){const A=this.getNextRow(b);A&&(b=A.id,x=this.getNextEditor(A))}x&&(this.in.exec("open-editor",{id:b,column:x.id}),this.in.exec("focus-cell",{row:b,column:x.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,x=this.getPrevEditor(this.getRow(b),this.getColumn(w));if(!x){const A=this.getPrevRow(b);A&&(b=A.id,x=this.getPrevEditor(A))}x&&(this.in.exec("open-editor",{id:b,column:x.id}),this.in.exec("focus-cell",{row:b,column:x.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,x=this._getFirstVisibleColumn()?.id;b&&x&&(this.in.exec("focus-cell",{row:b,column:x,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,x=this._getLastVisibleColumn()?.id;b&&x&&(this.in.exec("focus-cell",{row:b,column:x,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}}}),o.on("scroll",c=>{const{_columns:u,split:f,_sizes:h,flatData:g,dynamic:y,_rowHeightFromData:w}=this.getState();let b=-1,x=-1,A=0,k=0;if(c.column){b=0;const N=u.findIndex(E=>E.id===c.column);A=u[N].width;for(let E=f.left??0;E<N;E++){const D=u[E];D.hidden||(b+=D.width)}}if(c.row&&!y){const N=g.findIndex(E=>E.id===c.row);N>=0&&(w?(x=g.slice(0,N).reduce((E,D)=>E+(D.rowHeight||h.rowHeight),0),k=g[N].rowHeight):x=h.rowHeight*N)}this.setState({scroll:{top:x,left:b,width:A,height:k||h.rowHeight}})}),o.on("scroll-to",c=>{const u={};c.top!==void 0&&(u.scrollTop=c.top),c.left!==void 0&&(u.scrollLeft=c.left),Object.keys(u).length&&this.setState(u)}),o.on("print",c=>{const u=VT(c);this.setState({_print:u}),this.setStateAsync({_print:null})}),o.on("undo",()=>{this._historyManager?.handleUndo()}),o.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(o=>{const c=new Worker(r);c.addEventListener("message",u=>{u.data.type==="init"&&o(c)})})}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=aR()),n.columns&&n.columns.forEach(r=>{r.options&&(r.optionsMap=new Map(r.options.map(o=>[o.id,o.label])))}),Jp(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 ZT(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(o=>o.id===n)}getRowIndex(n,r){return r||(r=this.getState().flatData),r.findIndex(o=>o.id===n)}getNextRow(n){const r=this.getState().flatData,o=this.getRowIndex(n,r);return r[o+1]}getPrevRow(n){const r=this.getState().flatData,o=this.getRowIndex(n,r);return r[o-1]}getColumn(n){return this.getState().columns.find(r=>r.id===n)}getNextColumn(n,r){const o=this.getState()._columns,c=o.findIndex(u=>u.id===n);return r?this._getFirstVisibleColumn(c+1):o[c+1]}getPrevColumn(n,r){const o=this.getState()._columns,c=o.findIndex(u=>u.id===n);return r?this._getLastVisibleColumn(c-1):o[c-1]}_getFirstVisibleColumn(n){const r=this.getState()._columns;let o=n??0;for(;o<r.length&&(r[o]?.hidden||r[o]?.collapsed);)o++;return r[o]}_getLastVisibleColumn(n){const r=this.getState()._columns;let o=n??r.length-1;for(;o<r.length&&(r[o]?.hidden||r[o]?.collapsed);)o--;return r[o]}isCellEditable(n,r){const{editor:o,hidden:c}=r;return!o||c?!1:typeof o=="function"?o(n,r):!0}getNextEditor(n,r){let o=this.getState().columns;if(r){const c=o.findIndex(u=>u.id===r.id);o=o.slice(c+1)}return o.find(c=>this.isCellEditable(n,c))}getPrevEditor(n,r){let o=this.getState().columns;if(r){const c=o.findLastIndex(u=>u.id===r.id);o=o.slice(0,c)}return o.findLast(c=>this.isCellEditable(n,c))}toggleBranch(n,r,o){let c=this._branches[n],{data:u}=this.getState();if(u=[...u],n!==0){c={...c,open:r};const f=this.updateTreeRow(c);c.$parent===0&&(u=f)}o&&c.data?.length&&c.data.forEach(f=>{const h=this.toggleKids(f,r,o);n===0&&(u=h)}),this.setState({data:u})}toggleKids(n,r,o){n={...n,open:r};const c=this.updateTreeRow(n);return o&&n.data?.length&&n.data.forEach(u=>{this.toggleKids(u,r,o)}),c}updateTreeRow(n){const r=n.id;this._branches[r]=n;const o=this._branches[n.$parent],c=o.data.findIndex(u=>u.id===r);return o.data=[...o.data],o.data[c]=n,o.data}isSelected(n){return this.getState().selectedRows.indexOf(n)!==-1}findAndRemove(n,r){for(let o=0;o<n.length;o++){if(n[o].id===r)return n.splice(o,1)[0];if(n[o].data){const c=[...n[o].data],u=this.findAndRemove(c,r);if(u)return n[o]={...n[o],data:c},u}}return null}insertItem(n,r,o,c){for(let u=0;u<n.length;u++){if(n[u].id===r){const f=n[u],h=c==="before"?u:u+1;if(f.data){if(c==="before"){const g=u>0?n[u-1]:null;return g?.data&&g.open?n[u-1]={...g,data:[...g.data,o]}:n.splice(h,0,o),!0}else if(f.open)return n[u]={...f,data:[o,...f.data]},!0}return n.splice(h,0,o),!0}if(n[u].data&&(n[u]={...n[u],data:[...n[u].data]},this.insertItem(n[u].data,r,o,c)))return!0}return!1}moveItem(n,r,o,c){const u=[...o],f=this.findAndRemove(u,n);return this.insertItem(u,r,f,c),u}copyColumns(n){const r=[];for(let o=0;o<n.length;o++){const c={...n[o]};this.copyHeaderFooter(c,"header"),this.copyHeaderFooter(c,"footer"),r[o]=c}return r}copyHeaderFooter(n,r){let o=n[r];o=Array.isArray(o)?[...o]:[o],o.forEach((c,u)=>{o[u]=typeof c=="string"?{text:c}:{...c}}),n[r]=o}setCollapsibleColumns(n,r,o){let c=n.header;for(let u=0;u<c.length;u++){const f=c[u];if(f.collapsible&&f.collapsed){if(f.collapsible!=="first"){n.collapsed=!0,n.width=36,f.vertical=!0;const g=c.length-u;c=c.slice(0,u+1),c[u].rowspan=g}const h=f.colspan;if(h){const g=c[u+1];let y=1;g&&g.colspan&&!g.collapsed&&(y=g.colspan);for(let w=y;w<h;w++){const b=o[r+w];b&&(b.hidden=!0)}}}}}normalizeColumns(n,r,o,c,u){const f=n[r];f.width||(f.width=f.flexgrow?17:u.columnWidth),f._colindex=r+1;const h=f[o],g=u[`${o}RowHeights`];for(let y=0;y<c;y++){const w=h[y];w.id=f.id,y===h.length-1&&(w.rowspan=w.rowspan?Math.min(w.rowspan,c-y):c-y);for(let b=1;b<w.rowspan;b++){h.splice(y+b,0,{_hidden:!0});for(let x=1;x<w.colspan;x++)n[r+x][o].splice(y+b,0,{})}if(w.rowspan){const b=(w.rowspan===c?g:g.slice(y,w.rowspan+y)).reduce((x,A)=>x+A,0);w.height=b,y+w.rowspan!=c&&w.height--}if(w.colspan){let b=f.width,x=f.flexgrow||0;const A=w.colspan;for(let k=1;k<A;k++){const N=n[r+k];N&&(N.hidden?w.colspan-=1:N.flexgrow?x+=N.flexgrow:b+=N.width||u.columnWidth),x?w.flexgrow=x:w.width=b}}else w.width=f.width,w.flexgrow=f.flexgrow;o==="header"&&w.filter&&typeof w.filter=="string"&&(w.filter={type:w.filter})}h.length>c&&(h.length=c),f[o]=h}normalizeRows(n){for(let r=0;r<n.length;r++)n[r].id||(n[r].id=fp());return n}normalizeTreeRows(n,r,o){return!r&&!o&&(this._branches={0:{data:n}}),n.forEach(c=>{c.id||(c.id=fp()),c.$level=r||0,c.$parent=o||0,this._branches[c.id]=c,c.data&&(c.data.length?(c.$count=c.data.length,this.normalizeTreeRows(c.data,c.$level+1,c.id)):(delete c.data,delete c.$count,delete c.open))}),n}sortTree(n,r){n.sort(r),n.forEach(o=>{o.data&&this.sortTree(o.data,r)})}filterTree(n,r,o){return n.forEach(c=>{r(c)&&o.push(c.id),c.data&&this.filterTree(c.data,r,o)}),o}flattenRows(n,r,o){const c=r;return n.forEach(u=>{(!o||o.includes(u.id))&&c.push(u),u.data?.length&&u.open!==!1&&this.flattenRows(u.data,c,o)}),c}createFilter(n){const{_columns:r}=this.getState(),o=[];for(const c in n){const u=r.find(y=>y.id==c),{config:f,type:h}=u.header.find(y=>y.filter).filter,g=n[c];o.push(y=>{const w=Gl(y,u);return f?.handler?f.handler(w,g):KS(h)(w,g)})}return c=>{for(let u=0;u<o.length;u++)if(!o[u](c))return!1;return!0}}searchRows(n,r){n=n.trim().toLowerCase();const o={};if(!n)return o;const{flatData:c,columns:u}=this.getState(),f=r?u.filter(h=>r[h.id]):u;return c.forEach(h=>{const g={};f.forEach(y=>{const w=$l(h,y);String(w).toLowerCase().includes(n)&&(g[y.id]=!0)}),Object.keys(g).length&&(o[h.id]=g)}),o}normalizeSizes(n,r,o,c,u){const f=Aw(n,"header",o,r.headerHeight,u),h=Aw(n,"footer",c,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}}},uR=new Date().valueOf();function fp(){return"temp://"+uR++}function dR(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 fR=class{constructor(){this.store=new Map}configure(t,n){this.node=n;for(const r in t)if(t[r]){const o=r.toLowerCase().replace(/[ ]/g,""),c=t[r];this.store.set(o,c)}}},md=[],mR={subscribe:t=>{pR();const n=new fR;return md.push(n),t(n),()=>{const r=md.findIndex(o=>o===n);r>=0&&md.splice(r,1)}}},Nw=!1;function pR(){Nw||(Nw=!0,document.addEventListener("keydown",t=>{if(md.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 o=n.join("+");for(let c=md.length-1;c>=0;c--){const u=md[c],f=u.store.get(o)||u.store.get(r);f&&u.node.contains(t.target)&&f(t,{key:o,evKey:r})}}}))}const hR={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 gR(t,{keys:n,exec:r}){if(!n)return;function o(f){const h=f.target;return h.tagName==="INPUT"||h.tagName==="TEXTAREA"||dR(h,"data-header-id")?.classList.contains("wx-filter")||!!h.closest(".wx-cell.wx-editor")}const c={};for(const f in n){const h=n[f];typeof h<"u"&&(typeof h=="function"?c[f]=h:h&&(c[f]=g=>{const y=o(g);r({key:f,event:g,isInput:y})}))}const u=mR.subscribe(f=>{f.configure(c,t)});return{destroy:()=>{u()}}}function vR(t,n){let r=null;n.scroll.subscribe(o=>{if(!o||o===r)return;r=o;const{left:c,top:u,height:f,width:h}=o,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(c>=0){const b=t.scrollLeft;c<b?t.scrollLeft=c:c+h>b+y-w&&(t.scrollLeft=c-y+h+w)}}),n.scrollLeft?.subscribe?.(o=>{requestAnimationFrame(()=>{Math.abs(t.scrollLeft-o)>1&&(t.scrollLeft=o)})}),n.scrollTop?.subscribe?.(o=>{requestAnimationFrame(()=>{Math.abs(t.scrollTop-o)>1&&(t.scrollTop=o)})})}const js=d.createContext(null);function yR(t,n){const r=new ResizeObserver(o=>{requestAnimationFrame(()=>n(o[0].contentRect))});return r.observe(t.parentNode),{destroy(){r.disconnect()}}}const Tw=5,bR=700;function Ap(t){const n=t.getBoundingClientRect(),r=document.body,o=n.top+r.scrollTop-r.clientTop||0,c=n.left+r.scrollLeft-r.clientLeft||0;return{y:Math.round(o),x:Math.round(c),width:t.offsetWidth,height:t.offsetHeight}}function ov(t,n){const r=Ap(n);return{x:t.clientX-r.x,y:t.clientY-r.y}}function wR(t,n){const r=n.current;let o=null,c,u,f=!1,h=!1;const g=document.createElement("DIV");g.className="wx-drag-zone",g.setAttribute("tabindex",-1);function y(){clearTimeout(c),c=null}function w(I){const X=vd(I);X&&(o={container:g,sourceNode:I.target,from:Yp(X),pos:ov(I,t)},u=o.pos,b(I))}function b(I){if(!o)return;const X=o.pos=ov(I,t);if(!f){if(!h&&!I?.target?.getAttribute("draggable-data")&&Math.abs(u.x-X.x)<Tw&&Math.abs(u.y-X.y)<Tw)return;if(P(I)===!1)return z()}if(h){const se=window.scrollX||document.documentElement.scrollLeft||document.body.scrollLeft,Z=window.scrollY||document.documentElement.scrollTop||document.body.scrollTop;o.targetNode=document.elementFromPoint(I.pageX-se,I.pageY-Z)}else o.targetNode=I.target;r.move&&r.move(I,o),g.style.left=-(o.offset?o.offset.x:0)+"px",g.style.top=o.pos.y+(o.offset?o.offset.y:0)+"px"}function x(I){g.parentNode&&g.parentNode.removeChild(g),g.innerHTML="",f&&r.end&&r.end(I,o),o=u=null,z()}function A(I){r.getReorder&&!r.getReorder()||I.button===0&&(O(I),window.addEventListener("mousemove",k),window.addEventListener("mouseup",N),w(I))}function k(I){b(I)}function N(I){x(I)}function E(I){if(r.getReorder&&!r.getReorder())return;c=setTimeout(()=>{h=!0,w(I.touches[0])},bR),O(I);function X(){c&&y(),I.target.removeEventListener("touchmove",D),I.target.removeEventListener("touchend",X),x(I)}I.target.addEventListener("touchmove",D),I.target.addEventListener("touchend",X),t.addEventListener("contextmenu",T)}function D(I){f?(I.preventDefault(),b(I.touches[0])):c&&y()}function T(I){if(f||c)return I.preventDefault(),!1}function F(I){I.preventDefault()}function O(I){if(!r.getDraggableInfo)return;const{hasDraggable:X}=r.getDraggableInfo();(!X||I.target.getAttribute("draggable-data"))&&(document.body.style.userSelect="none",document.body.style.webkitUserSelect="none")}function P(I){if(f=!0,r.start){if(r.start(I,o)===!1)return!1;t.appendChild(g),document.body.style.cursor="move"}}function z(I){f=h=!1,document.body.style.cursor="",document.body.style.userSelect="",document.body.style.webkitUserSelect="",window.removeEventListener("mousemove",k),window.removeEventListener("mouseup",N),I&&(t.removeEventListener("mousedown",A),t.removeEventListener("touchstart",E),t.removeEventListener("dragstart",F))}return t.addEventListener("mousedown",A),t.addEventListener("touchstart",E),t.addEventListener("dragstart",F),{destroy(){z(!0)}}}const xR=.004;function SR(){return{dirX:0,dirY:0,scrollSpeedFactor:1}}function CR(t,n,r,o){const{node:c,left:u,top:f,bottom:h,sense:g,xScroll:y,yScroll:w}=o,b=ov(t,c);r.scrollState||(r.scrollState=SR());let x=0,A=0;b.x<u+g?x=-1:b.x>n.width-g&&(x=1),b.y<f+Math.round(g/2)?A=-1:b.y>n.height-h-Math.round(g/2)&&(A=1),(r.scrollState.dirX!==x||r.scrollState.dirY!==A)&&(QS(r),r.scrollState.dirX=x,r.scrollState.dirY=A),(y&&r.scrollState.dirX!==0||w&&r.scrollState.dirY!==0)&&kR(r,o,{x:r.scrollState.dirX,y:r.scrollState.dirY})}function kR(t,n,r){t.autoScrollTimer||(t.autoScrollTimer=setTimeout(()=>{t.activeAutoScroll=setInterval(MR,15,t,n,r)},250))}function QS(t){t.scrollSpeedFactor=1,t.autoScrollTimer&&(t.autoScrollTimer=clearTimeout(t.autoScrollTimer),t.activeAutoScroll=clearInterval(t.activeAutoScroll))}function MR(t,n,r){const{x:o,y:c}=r;t.scrollSpeedFactor+=xR,o!==0&&NR(t,n,o),c!==0&&AR(t,n,c)}function AR(t,n,r){const o=n.node.scrollTop;YS(o+Math.round(n.sense/3)*t.scrollSpeedFactor*r,"scrollTop",n)}function NR(t,n,r){const o=n.node.scrollLeft;YS(o+Math.round(n.sense/3)*t.scrollSpeedFactor*r,"scrollLeft",n)}function YS(t,n,r){r.node[n]=t}function eh(t,n,r,o,c,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=`${o}px`),r.right&&(f.right=`${c}px`)),f}function XS(t,n,r){let o="";if(t.fixed)for(const c in t.fixed){let u=t.fixed[c]===-1;!u&&t.fixed.leftSize&&n.colspan&&(u=n.colspan+t._colindex-1===t.fixed.leftSize),o+=u?"wx-shadow ":"wx-fixed "}return o+=n.rowspan>1?"wx-rowspan ":"",o+=n.colspan>1?"wx-colspan ":"",o+=n.vertical?"wx-vertical ":"",o+=r?r(t)+" ":"",o}function TR(t){const{row:n,column:r,cellStyle:o=null,columnStyle:c=null,children:u,focusable:f}=t,h=d.useContext(js),g=Tt(h,"focusCell"),y=Tt(h,"search"),w=Tt(h,"reorder"),b=d.useMemo(()=>y?.rows[n.id]&&y.rows[n.id][r.id],[y,n.id,r.id]),x=d.useMemo(()=>eh(r.width,r.flexgrow,r.fixed,r.left,r.right),[r.width,r.flexgrow,r.fixed,r.left,r.right]);function A(P,z){let I="wx-cell";return I+=r.fixed?" "+(r.fixed===-1?"wx-shadow":"wx-fixed"):"",I+=P?" "+P(r):"",I+=z?" "+z(n,r):"",I+=r.treetoggle?" wx-tree-cell":"",I}const k=d.useMemo(()=>A(c,o),[c,o,r,n]),N=d.useMemo(()=>typeof r.draggable=="function"?r.draggable(n,r)!==!1:r.draggable,[r,n]),E=d.useRef(null);d.useEffect(()=>{E.current&&f&&g?.row===n.id&&g?.column===r.id&&E.current.focus()},[g,f,n.id,r.id]);const D=d.useCallback(()=>{f&&!g&&h.exec("focus-cell",{row:n.id,column:r.id,eventSource:"focus"})},[h,f,g,n.id,r.id]);function T(P){const z=new RegExp(`(${y.value.trim()})`,"gi");return String(P).split(z).map(I=>({text:I,highlight:z.test(I)}))}const F=d.useMemo(()=>{const P=r.fixed&&r.fixed.left===-1||r.fixed.right===-1,z=r.fixed&&r.fixed.right;return[k,P?"wx-shadow":"",z?"wx-fixed-right":""].filter(Boolean).join(" ")},[k,r]),O=r.cell;return i.jsxs("div",{className:"wx-TSCaXsGV "+F,ref:E,onFocus:D,style:x,"data-row-id":Ha(n.id),"data-col-id":Ha(r.id),tabIndex:f?"0":"-1",role:"gridcell","aria-colindex":r._colindex,"aria-readonly":r.editor?void 0:!0,children:[w&&r.draggable?N?i.jsx("i",{"draggable-data":"true",className:"wx-TSCaXsGV wx-draggable wxi-drag"}):i.jsx("i",{className:"wx-TSCaXsGV wx-draggable-stub"}):null,r.treetoggle?i.jsxs(i.Fragment,{children:[i.jsx("span",{style:{marginLeft:`${n.$level*28}px`}}),n.$count?i.jsx("i",{"data-action":"toggle-row",className:`wx-TSCaXsGV wx-table-tree-toggle wxi-menu-${n.open!==!1?"down":"right"}`}):null]}):null,O?i.jsx(O,{api:h,row:n,column:r,onAction:({action:P,data:z})=>h.exec(P,z)}):u?u():b?i.jsx("span",{children:T($l(n,r)).map(({highlight:P,text:z},I)=>P?i.jsx("mark",{className:"wx-TSCaXsGV wx-search",children:z},I):i.jsx("span",{children:z},I))}):$l(n,r)]})}function Rw(t,n){let r,o;function c(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){o=h.clientX-r,n&&n.move&&n.move(o)}function f(){t.style.opacity="",document.body.style.cursor="",document.body.style.userSelect="",n&&n.up&&n.up(o),window.removeEventListener("mousemove",u),window.removeEventListener("mouseup",f)}return t.addEventListener("mousedown",c),{destroy(){t.removeEventListener("mousedown",c)}}}function RR({filter:t,column:n,action:r,filterValue:o}){function c({value:u}){r({value:u,key:n.id})}return i.jsx(Lv,{...t.config??{},value:o,onChange:c})}function jR({filter:t,column:n,action:r,filterValue:o}){const c=d.useContext(js),u=Tt(c,"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(x=>{const A=Gl(x,n);b.includes(A)||b.push(A)}),b.map(x=>({id:x,label:x}))}function y({value:b}){r({value:b,key:n.id})}function w(b){b.key!=="Tab"&&b.preventDefault()}return i.jsx("div",{style:{width:"100%"},onKeyDown:w,children:i.jsx(qN,{placeholder:"",clear:!0,...t?.config??{},options:f,value:o,onChange:y,children:b=>h?h(b):b.label})})}function ER({filter:t,column:n,action:r,filterValue:o}){function c({value:u}){r({value:u,key:n.id})}return i.jsx("div",{className:"wx-aaaK5VYO",style:{width:"100%"},children:i.jsx(UN,{placeholder:"",clear:!0,...t?.config??{},value:o,onChange:c})})}function ZS(t){const{value:n,options:r=[],placeholder:o="",clear:c=!1,text:u=null,template:f=null,cell:h=null,dropdown:g={},autoOpen:y=!1,onChange:w,onAction:b}=t,[x,A]=FS(n||[]),k=d.useMemo(()=>(x||[]).map(Z=>r.find(G=>G.id===Z)).filter(Boolean),[x,r]),N=d.useRef(null),E=d.useRef(null),[D,T]=d.useState(null),F=()=>{const Z=x||[];if(!Z.length)return 0;const G=r.find(K=>Z.includes(K.id));return G?r.indexOf(G):0};function O(Z){E.current=Z.navigate,T(()=>Z.keydown),y&&Z.navigate(F())}d.useEffect(()=>{y&&(N.current?.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges())},[]);function P({id:Z}){A(Z),w&&w({value:Z})}function z(Z){Z.stopPropagation(),A([]),w&&w({value:[]})}function I(){E.current?.(F())}function X(){E.current?.(null)}function se(Z){D?.(Z,F())}return i.jsxs("div",{ref:N,className:"wx-multiselect wx-aadNNOwy",onClick:I,onKeyDown:se,tabIndex:0,children:[i.jsx("div",{className:"wx-label wx-aadNNOwy",children:f?f(k):h?i.jsx(h,{data:k,onAction:b}):u?i.jsx("span",{className:"wx-text wx-aadNNOwy",children:u}):k.length?i.jsx("span",{className:"wx-text wx-aadNNOwy",children:k.map(Z=>Z.label).join(", ")}):o?i.jsx("span",{className:"wx-placeholder wx-aadNNOwy",children:o}):" "}),c&&x?.length?i.jsx("i",{className:"wx-icon wxi-close wx-aadNNOwy",onClick:z}):i.jsx("i",{className:"wx-icon wxi-angle-down wx-aadNNOwy"}),i.jsx(Zp,{items:r,onReady:O,onSelect:P,multiselect:!0,checkboxes:!0,value:x||[],onCancel:X,...g,children:({option:Z})=>i.jsx("div",{className:"wx-option wx-aadNNOwy",children:f?f(Z):h?i.jsx(h,{data:Z,onAction:b}):Z.label})})]})}function DR({filter:t,column:n,action:r,filterValue:o}){const c=d.useContext($a.i18n)?.getGroup("grid")||tm(Pv).getGroup("grid"),u=d.useMemo(()=>({clear:!0,...t?.config||{}}),[t]),f=d.useMemo(()=>u.options||n.options,[u,n]),h=d.useMemo(()=>{const w=o?.length;return w?w<3?o.map(b=>n.optionsMap.get(b)).join(", "):w+" "+c("selected"):""},[o,n,c]);function g({value:w}){r({value:w,key:n.id})}function y(w){w.key!=="Tab"&&w.preventDefault()}return i.jsx("div",{style:{width:"100%"},onKeyDown:y,children:i.jsx(ZS,{placeholder:"",...u,options:f,value:o||[],text:h,onChange:g})})}const IR={text:RR,richselect:jR,datepicker:ER,multiselect:DR};function LR({filter:t,column:n}){const r=d.useContext(js),o=Tt(r,"filterValues");function c(f){r.exec("filter-rows",f)}const u=d.useMemo(()=>IR[t.type],[t.type]);return i.jsx(u,{filter:t,column:n,action:c,filterValue:o[n.id]})}function _R(t){const{cell:n,column:r,row:o,lastRow:c,sortRow:u,columnStyle:f,bodyHeight:h,hasSplit:g}=t,y=d.useContext(js),w=Tt(y,"sortMarks"),b=d.useMemo(()=>w?w[r.id]:void 0,[w,r.id]),x=d.useRef(),A=d.useCallback(V=>{x.current=n.flexgrow?V.parentNode.clientWidth:n.width},[n.flexgrow,n.width]),k=d.useCallback((V,ne)=>{y.exec("resize-column",{id:n.id,width:Math.max(1,(x.current||0)+V),inProgress:ne})},[y,n.id]),N=d.useCallback(V=>k(V,!0),[k]),E=d.useCallback(V=>k(V,!1),[k]),D=d.useCallback(V=>{if(!r.sort||n.filter)return;let ne=b?.order;ne&&(ne=ne==="asc"?"desc":"asc"),y.exec("sort-rows",{key:n.id,add:V.ctrlKey||V.metaKey,order:ne})},[y,n.id,n.filter,r.sort,b?.order]),T=d.useCallback(V=>{V&&V.stopPropagation(),y.exec("collapse-column",{id:n.id,row:o})},[y,n.id,o]),F=d.useCallback(V=>{V.key==="Enter"&&T()},[T]),O=d.useCallback(V=>{V.key==="Enter"&&!n.filter&&D(V)},[D,n.filter]),P=d.useMemo(()=>n.collapsed&&r.collapsed,[n.collapsed,r.collapsed]),z=d.useMemo(()=>P&&!g&&n.collapsible!=="header",[P,g,n.collapsible]),I=d.useMemo(()=>z?{top:-h/2,position:"absolute"}:{},[z,h]),X=d.useMemo(()=>eh(n.width,n.flexgrow,r.fixed,r.left,n.right??r.right,n.height+(P&&z?h:0)),[n.width,n.flexgrow,r.fixed,r.left,n.right,r.right,n.height,P,z,h]),se=d.useMemo(()=>XS(r,n,f),[r,n,f]),Z=d.useCallback(()=>Object.fromEntries(Object.entries(n).filter(([V])=>V!=="cell")),[n]),G=`wx-cell ${se} ${n.css||""} wx-collapsed`,K=["wx-cell",se,n.css||"",n.filter?"wx-filter":"",r.fixed&&r.fixed.right?"wx-fixed-right":""].filter(Boolean).join(" "),me=d.useRef(null);return d.useEffect(()=>{const V=me.current;if(!V)return;const ne=Rw(V,{down:A,move:N,up:E});return()=>{typeof ne=="function"&&ne()}},[A,N,E,Rw]),P?i.jsx("div",{className:"wx-RsQD74qC "+G,style:X,role:"button","aria-label":`Expand column ${n.text||""}`,"aria-expanded":!n.collapsed,tabIndex:0,onKeyDown:F,onClick:T,"data-header-id":Ha(r.id),children:i.jsx("div",{className:"wx-RsQD74qC wx-text",style:I,children:n.text||""})}):i.jsxs("div",{className:"wx-RsQD74qC "+K,style:X,onClick:D,"data-header-id":Ha(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:O,children:[n.collapsible?i.jsx("div",{className:"wx-RsQD74qC wx-collapse",role:"button","aria-label":n.collapsed?"Expand column":"Collapse column","aria-expanded":!n.collapsed,tabIndex:0,onKeyDown:F,onClick:T,children:i.jsx("i",{className:`wx-RsQD74qC wxi-angle-${n.collapsed?"down":"right"}`})}):null,n.cell?(()=>{const V=n.cell;return i.jsx(V,{api:y,cell:Z(),column:r,row:o,onAction:({action:ne,data:$})=>y.exec(ne,$)})})():n.filter?i.jsx(LR,{filter:n.filter,column:r}):i.jsx("div",{className:"wx-RsQD74qC wx-text",children:n.text||""}),r.resize&&c&&!n._hidden?i.jsx("div",{className:"wx-RsQD74qC wx-grip",role:"presentation","aria-label":"Resize column",ref:me,onClick:V=>V.stopPropagation(),children:i.jsx("div",{})}):null,u?i.jsx("div",{className:"wx-RsQD74qC wx-sort",children:b?i.jsxs(i.Fragment,{children:[typeof b.index<"u"?i.jsx("div",{className:"wx-RsQD74qC wx-order",children:b.index+1}):null,i.jsx("i",{className:`wx-RsQD74qC wxi-arrow-${b.order==="asc"?"up":"down"}`})]}):null}):null]})}function FR({cell:t,column:n,row:r,columnStyle:o}){const c=d.useContext(js),u=d.useMemo(()=>eh(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(()=>XS(n,t,o),[n,t,o]),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 i.jsx("div",{className:g,style:u,children:!n?.collapsed&&!t?.collapsed?t?.cell?hv.createElement(t.cell,{api:c,cell:h(),column:n,row:r,onAction:({action:y,data:w})=>c.exec(y,w)}):i.jsx("div",{className:"wx-6Sdi3Dfd wx-text",children:t?.text||""}):null})}function jw({deltaLeft:t,contentWidth:n,columns:r,type:o="header",columnStyle:c,bodyHeight:u}){const f=d.useContext(js),h=Tt(f,"_sizes"),g=Tt(f,"split"),y=d.useMemo(()=>h?.[`${o}RowHeights`],[h,o]),w=d.useMemo(()=>{let N=[];if(r&&r.length){const E=r[0][o].length;for(let D=0;D<E;D++){let T=0;N.push([]),r.forEach((F,O)=>{const P={...F[o][D]};T||N[D].push(P),P.colspan>1?T=P.colspan-1:T&&T--})}}return N},[r,o]),b=d.useMemo(()=>g?.left||g?.right,[g]);function x(N){return r.find(E=>E.id===N)}function A(N,E){let D=E;return N.rowspan&&(D+=N.rowspan-1),D===w.length-1}function k(N,E,D){if(!D.sort)return!1;for(let T=w.length-1;T>=0;T--){const F=D.header[T];if(!F.filter&&!F._hidden)return E===T}return A(N,E)}return i.jsx("div",{className:`wx-sAsPVaUK wx-${o}`,style:{paddingLeft:`${t}px`,width:`${n}px`},role:"rowgroup",children:w.map((N,E)=>i.jsx("div",{className:o==="header"?"wx-sAsPVaUK wx-h-row":"wx-sAsPVaUK wx-f-row",style:{height:`${y?.[E]}px`,display:"flex"},role:"row",children:N.map(D=>{const T=x(D.id);return o==="header"?i.jsx(_R,{cell:D,columnStyle:c,column:T,row:E,lastRow:A(D,E),bodyHeight:u,sortRow:k(D,E,T),hasSplit:b},D.id):i.jsx(FR,{cell:D,columnStyle:c,column:x(D.id),row:E},D.id)})},E))})}function PR({overlay:t}){const n=d.useContext(js);function r(c){return typeof c=="function"}const o=t;return i.jsx("div",{className:"wx-1ty666CQ wx-overlay",children:r(t)?i.jsx(o,{onAction:({action:c,data:u})=>n.exec(c,u)}):t})}function OR(t){const{editor:n,onSave:r,onApply:o}=t,[c,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=Vi(h.current,()=>r(!0));return()=>w.destroy()},[r]);function g(){h.current&&(u(h.current.value),o(h.current.value))}function y({key:w}){w==="Enter"&&r()}return i.jsx("input",{className:"wx-e7Ao5ejY wx-text",onInput:g,onKeyDown:y,ref:h,type:f,value:c})}function BR({editor:t,onAction:n,onSave:r,onApply:o,onCancel:c}){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]),x=d.useMemo(()=>t?.config?.cell,[t]),A=d.useMemo(()=>t?.config?.dropdown||{},[t]),k=d.useMemo(()=>({trackScroll:!0,...A}),[A]),N=d.useMemo(()=>(y||[]).findIndex(I=>I.id===u),[y,u]),E=d.useRef(null),D=d.useRef(null),T=d.useCallback(I=>{E.current=I.navigate,D.current=I.keydown,E.current(N)},[N,E]),F=d.useCallback(I=>{const X=I?.target?.value??"";g(X);const se=X?(t?.options||[]).filter(Z=>(Z.label||"").toLowerCase().includes(X.toLowerCase())):t?.options||[];w(se),se.length?E.current(-1/0):E.current(null)},[t]),O=d.useRef(null);d.useEffect(()=>{O.current&&O.current.focus()},[]);const P=d.useRef(r);d.useEffect(()=>{P.current=r},[r]),d.useEffect(()=>{if(!O.current)return;const I=Vi(O.current,()=>P.current(!0));return()=>I.destroy()},[]),d.useEffect(()=>{f(t?.value),g(t?.renderedValue),w(t?.options||[])},[t]);const z=d.useCallback(({id:I})=>{o(I),r()},[o,r]);return i.jsxs(i.Fragment,{children:[i.jsx("input",{className:"wx-0UYfSd1x wx-input",ref:O,value:h??"",onChange:F,onKeyDown:I=>D.current?D.current(I,N):void 0}),i.jsx(Zp,{items:y,onReady:T,onSelect:z,...k,onCancel:c,children:({option:I})=>b?b(I):x?i.jsx(x,{data:I,onAction:n}):I.label})]})}function HR({editor:t,onAction:n,onSave:r,onApply:o,onCancel:c}){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:k}){o(k),r()}const b=d.useRef(null),[x,A]=d.useState(null);return d.useEffect(()=>{b.current&&b.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),d.useEffect(()=>{if(!x)return;const k=Vi(x,()=>r(!0));return()=>k.destroy()},[x,r]),i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"wx-lNWNYUb6 wx-value",ref:b,tabIndex:0,onClick:c,onKeyDown:k=>k.preventDefault(),children:f?f(u):h?i.jsx(h,{data:t.value,onAction:n}):i.jsx("span",{className:"wx-lNWNYUb6 wx-text",children:t.renderedValue})}),i.jsx(Iv,{...y,onCancel:c,children:i.jsx("div",{ref:A,className:"wx-lNWNYUb6",children:i.jsx(ES,{value:u,onChange:w,buttons:t.config?.buttons})})})]})}function zR(t){const{editor:n}=t,r=t.onAction??t.onaction,o=t.onSave??t.onsave,c=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(F=>F.id===n.value)),[w]=d.useState(n.value),[b]=d.useState(n.options),x=d.useMemo(()=>b.findIndex(F=>F.id===w),[b,w]);function A({id:F}){c(F),o()}let k;const[N,E]=d.useState();function D(F){k=F.navigate,E(()=>F.keydown),k(x)}const T=d.useRef(null);return d.useEffect(()=>{T.current&&T.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),d.useEffect(()=>{if(!T.current)return;const F=Vi(T.current,()=>o(!0));return()=>F.destroy()},[o]),i.jsxs(i.Fragment,{children:[i.jsx("div",{ref:T,className:"wx-ywGRk611 wx-value",tabIndex:0,onClick:u,onKeyDown:F=>{N(F,x),F.preventDefault()},children:f.template?f.template(y):f.cell?(()=>{const F=f.cell;return i.jsx(F,{data:y,onAction:r})})():i.jsx("span",{className:"wx-ywGRk611 wx-text",children:n.renderedValue})}),i.jsx(Zp,{items:b,onReady:D,onSelect:A,...g,onCancel:u,children:({option:F})=>f.template?f.template(F):f.cell?(()=>{const O=f.cell;return i.jsx(O,{data:F,onAction:r})})():F.label})]})}function $R(t){const{editor:n,onAction:r,onSave:o,onApply:c}=t,u=n?.config||{},f=n?.options??[],h=n?.value||[],g=n?.renderedValue,y=d.useMemo(()=>({trackScroll:!0,...u.dropdown||{}}),[u]);function w({value:x}){c(x)}const b=d.useRef(null);return d.useEffect(()=>{if(!b.current)return;const x=Vi(b.current,()=>o(!0));return()=>x.destroy()},[o]),i.jsx("div",{ref:b,className:"wx-value wx-aacZ4gNU",onClick:()=>o(!0),children:i.jsx(ZS,{value:h,options:f,text:g,template:u.template,cell:u.cell,clear:u.clear,dropdown:y,autoOpen:!0,onChange:w,onAction:r})})}const UR={text:OR,combo:BR,datepicker:HR,richselect:zR,multiselect:$R};function qR({column:t,row:n}){const r=d.useContext(js),o=Tt(r,"editor"),c=d.useCallback((k,N)=>{r.exec("close-editor",{ignore:k}),N&&r.exec("focus-cell",{...N,eventSource:"click"})},[r]),u=d.useCallback(k=>{const N=k?null:{row:o?.id,column:o?.column};c(!1,N)},[o,c]),f=d.useCallback(()=>{c(!0,{row:o?.id,column:o?.column})},[o,c]),h=d.useCallback(k=>{r.exec("editor",{value:k})},[r]),g=d.useCallback(k=>{k.key==="Enter"&&o&&(t.editor.type==="multiselect"?h(o.value):f())},[o,t.editor,f,h]),y=d.useMemo(()=>eh(t.width,t.flexgrow,t.fixed,t.left,t.right),[t.width,t.flexgrow,t.fixed,t.left,t.right]),w=d.useMemo(()=>{let k=t.editor;if(typeof k=="function"&&(k=k(n,t)),!k)return null;let N=typeof k=="string"?k:k.type;return UR[N]},[t,n]),b=d.useRef(null);d.useEffect(()=>{b.current&&typeof y=="string"&&b.current.setAttribute("style",y)},[y]);const x=typeof n.$parent<"u"?"gridcell":"cell",A=typeof n.$parent<"u"?!t.editor:void 0;return i.jsx("div",{className:"wx-8l724t2g wx-cell wx-editor",ref:b,style:typeof y=="object"&&y!==null?y:void 0,role:x,"aria-readonly":A,tabIndex:-1,onClick:k=>k.stopPropagation(),onDoubleClick:k=>k.stopPropagation(),onKeyDown:g,children:w?i.jsx(w,{editor:o,onSave:u,onApply:h,onCancel:f,onAction:({action:k,data:N})=>r.exec(k,N)}):null})}function Ew(t){const{columns:n,type:r,columnStyle:o}=t,c=d.useContext(js),{filterValues:u,_columns:f,_sizes:h}=c.getState();function g(y){return o?" "+o(y):""}return i.jsx(i.Fragment,{children:n.map((y,w)=>i.jsx("tr",{children:y.map(b=>{const x=f.find(N=>N.id===b.id),A=`wx-print-cell-${r}${g(x)}${b.filter?" wx-print-cell-filter":""}${b.vertical?" wx-vertical":""}`,k=b.cell;return i.jsx("th",{style:PS(GS(b,h.columnWidth)),className:"wx-Gy81xq2u "+A,rowSpan:b.rowspan,colSpan:b.colspan,children:k?i.jsx(k,{api:c,cell:Object.fromEntries(Object.entries(b).filter(([N])=>N!=="cell")),column:x,row:w}):b.filter?i.jsx("div",{className:"wx-Gy81xq2u wx-print-filter",children:KT(u,f,b)}):i.jsx("div",{className:"wx-Gy81xq2u wx-text",children:b.text??""})},b.id)})},w))})}function WR(t){const{columns:n,rowStyle:r,columnStyle:o,cellStyle:c,header:u,footer:f,reorder:h}=t,g=d.useContext(js),{flatData:y,_sizes:w}=g.getState(),b=u&&kw(n,"header",w.headerRowHeights),x=f&&kw(n,"footer",w.footerRowHeights);function A(N,E){let D="";return D+=o?" "+o(E):"",D+=c?" "+c(N,E):"",D}function k(N,E){return typeof E.draggable=="function"?E.draggable(N,E)!==!1:E.draggable}return i.jsxs("table",{className:`wx-8NTMLH0z wx-print-grid ${n.some(N=>N.flexgrow)?"wx-flex-columns":""}`,children:[u?i.jsx("thead",{children:i.jsx(Ew,{columns:b,type:"header",columnStyle:o})}):null,i.jsx("tbody",{children:y.map((N,E)=>i.jsx("tr",{className:"wx-8NTMLH0z wx-row"+(r?" "+r(N):""),style:{height:`${N.rowHeight||w.rowHeight}px`},children:n.map(D=>D.collapsed?null:i.jsxs("td",{className:`wx-8NTMLH0z wx-print-cell wx-cell ${A(N,D)}`,style:PS(GS(D,w.columnWidth)),children:[h&&D.draggable?i.jsx("span",{className:"wx-8NTMLH0z wx-print-draggable",children:k(N,D)?i.jsx("i",{className:"wx-8NTMLH0z wxi-drag"}):null}):null,D.treetoggle?i.jsxs(i.Fragment,{children:[i.jsx("span",{style:{marginLeft:N.$level*28+"px"}}),N.$count?i.jsx("i",{className:`wx-8NTMLH0z wx-print-grid-tree-toggle wxi-menu-${N.open!==!1?"down":"right"}`}):null]}):null,D.cell?(()=>{const T=D.cell;return i.jsx(T,{api:g,row:N,column:D})})():i.jsx("span",{children:$l(N,D)})]},D.id))},E))}),f?i.jsx("tfoot",{children:i.jsx(Ew,{columns:x,type:"footer",columnStyle:o})}):null]})}function GR(t){const{config:n,...r}=t,o=d.useContext(js),{_skin:c,_columns:u}=o.getState(),f=d.useMemo(()=>qT(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}; }`,x=document.createElement("style");x.setAttribute("type","text/css"),x.setAttribute("media","print"),document.getElementsByTagName("head")[0].appendChild(x),x.appendChild(document.createTextNode(b)),window.print(),x.remove(),g.classList.remove("wx-print"),w.remove()},[]),i.jsx("div",{className:`wx-4zwCKA7C wx-${c}-theme wx-print-container`,ref:h,children:f.map((g,y)=>i.jsx("div",{className:"wx-4zwCKA7C wx-print-grid-wrapper",children:i.jsx(WR,{columns:g,...r})},y))})}function VR(t){const{header:n,footer:r,overlay:o,multiselect:c,onreorder:u,rowStyle:f,columnStyle:h,cellStyle:g,autoRowHeight:y,resize:w,clientWidth:b,clientHeight:x,responsiveLevel:A,hotkeys:k}=t,N=d.useContext(js),E=Tt(N,"dynamic"),D=Tt(N,"_columns"),T=Tt(N,"flatData"),F=Tt(N,"split"),O=Tt(N,"_sizes"),[P,z]=Zs(N,"selectedRows"),I=Tt(N,"select"),X=Tt(N,"editor"),se=Tt(N,"scrollLeft"),Z=Tt(N,"scrollTop"),G=Tt(N,"tree"),K=Tt(N,"focusCell"),me=Tt(N,"_print"),V=Tt(N,"undo"),ne=Tt(N,"reorder"),$=Tt(N,"_rowHeightFromData"),[_,ie]=d.useState(0);d.useEffect(()=>{ie(Pn())},[]);const[be,H]=d.useState(0),te=d.useMemo(()=>(D||[]).some(de=>!de.hidden&&de.flexgrow),[D]),le=d.useMemo(()=>O?.rowHeight||0,[O]),Ce=d.useRef(null),[Ae,_e]=d.useState(null),[ue,He]=d.useState(null),ze=d.useMemo(()=>{let de=[],De=0;return F&&F.left&&(de=(D||[]).slice(0,F.left).filter(Ke=>!Ke.hidden).map(Ke=>({...Ke})),de.forEach(Ke=>{Ke.fixed={left:1,leftSize:F.left},Ke.left=De,De+=Ke.width}),de.length&&(de[de.length-1].fixed.left=-1)),{columns:de,width:De}},[F,D]),et=d.useMemo(()=>{let de=[],De=0;if(F&&F.right){de=(D||[]).slice(F.right*-1).filter(Ke=>!Ke.hidden).map(Ke=>({...Ke}));for(let Ke=de.length-1;Ke>=0;Ke--){const wt=de[Ke];wt.fixed={right:1},wt.right=De,De+=wt.width}de.length&&(de[0].fixed={right:-1})}return{columns:de,width:De}},[F,D]),Xe=d.useMemo(()=>{const de=(D||[]).slice(F?.left||0,(D||[]).length-(F?.right??0)).filter(De=>!De.hidden);return de.forEach(De=>{De.fixed=0}),de},[D,F]),Ze=d.useMemo(()=>(D||[]).reduce((de,De)=>(De.hidden||(de+=De.width),de),0),[D]),Ue=1;function Y(de,De,Ke){let wt=De,Jt=de;if(Xe.length){let Ft=Xe.length;for(let mt=de;mt>=0;mt--)Xe[mt][Ke].forEach(Pt=>{Pt.colspan>1&&mt>de-Pt.colspan&&mt<Ft&&(Ft=mt)});if(Ft!==Xe.length&&Ft<de){for(let mt=Ft;mt<de;mt++)wt-=Xe[mt].width;Jt=Ft}}return{index:Jt,delta:wt}}const Se=d.useMemo(()=>{let de,De,Ke;const wt=se||0,Jt=(se||0)+(b||0);let Ft=0,mt=0,Pt=0,xt=0;Xe.forEach((Ot,Rn)=>{wt>Pt&&(Ft=Rn,xt=Pt),Pt=Pt+Ot.width,Jt>Pt&&(mt=Rn+Ue)});const mn={header:0,footer:0};for(let Ot=mt;Ot>=Ft;Ot--)["header","footer"].forEach(Rn=>{Xe[Ot]&&Xe[Ot][Rn].forEach(Bn=>{const Za=Bn.colspan;if(Za&&Za>1){const va=Za-(mt-Ot+1);va>0&&(mn[Rn]=Math.max(mn[Rn],va))}})});const na=Y(Ft,xt,"header"),wn=Y(Ft,xt,"footer"),On=na.delta,rn=na.index,br=wn.delta,wr=wn.index;return te&&Ze>(b||0)?de=De=Ke=[...ze.columns,...Xe,...et.columns]:(de=[...ze.columns,...Xe.slice(Ft,mt+1),...et.columns],De=[...ze.columns,...Xe.slice(rn,mt+mn.header+1),...et.columns],Ke=[...ze.columns,...Xe.slice(wr,mt+mn.footer+1),...et.columns]),{data:de||[],header:De||[],footer:Ke||[],d:xt,df:br,dh:On}},[Xe,ze,et,se,b,te,Ze]),ye=d.useMemo(()=>n&&O?.headerHeight||0,[n,O]),je=d.useMemo(()=>r&&O?.footerHeight||0,[r,O]),$e=d.useMemo(()=>b&&x?Ze>=b:!1,[b,x,Ze]),[B,lt]=d.useState(!1),Nt=d.useMemo(()=>(x||0)-ye-je-($e?_:0),[x,ye,je,$e,_]),Ht=d.useMemo(()=>Math.ceil((Nt||0)/(le||1))+1,[Nt,le]),ke=d.useRef([]),[qe,Ye]=d.useState(0),[_t,tt]=d.useState(void 0),pe=d.useMemo(()=>{let de=0,De=0;const Ke=2,wt=Z||0;if(y){let mt=wt;for(;mt>0;)mt-=ke.current[de]||le,de++;De=wt-mt;for(let Pt=Math.max(0,de-Ke-1);Pt<de;Pt++)De-=ke.current[de-Pt]||le;de=Math.max(0,de-Ke)}else{if($){let mt=0,Pt=0;for(let wn=0;wn<(T||[]).length;wn++){const On=T[wn].rowHeight||le;if(Pt+On>wt){mt=wn;break}Pt+=On}de=Math.max(0,mt-Ke);for(let wn=0;wn<de;wn++)De+=T[wn].rowHeight||le;let xt=0,mn=0;for(let wn=mt+1;wn<(T||[]).length;wn++){const On=T[wn].rowHeight||le;if(xt++,mn+On>Nt)break;mn+=On}const na=Math.min(E?E.rowCount:(T||[]).length,mt+xt+Ke);return{d:De,start:de,end:na}}de=Math.floor(wt/(le||1)),de=Math.max(0,de-Ke),De=de*(le||0)}const Jt=E?E.rowCount:(T||[]).length,Ft=Math.min(Jt,de+(Ht||0)+Ke);return{d:De,start:de,end:Ft}},[y,$,Z,le,E,T,Ht,Nt]),Ne=d.useMemo(()=>{const de=E?E.rowCount:(T||[]).length;if(y)return qe+pe.d+(de-(_t||0))*(le||0);if(!$)return de*(le||0);let De=0;for(let Ke=0;Ke<de;Ke++)De+=T[Ke]?.rowHeight||le;return De},[E,T,le,y,$,qe,pe.d,_t]),Be=d.useRef({});Be.current={clientWidth:b,clientHeight:x,fullHeight:Ne,headerHeight:ye,footerHeight:je,fullWidth:Ze,SCROLLSIZE:_};const Oe=d.useCallback(()=>{const de=Be.current;lt(de.clientWidth&&de.clientHeight?de.fullHeight+de.headerHeight+de.footerHeight>=de.clientHeight-(de.fullWidth>=de.clientWidth?de.SCROLLSIZE:0):!1)},[]);d.useEffect(()=>{const de=requestAnimationFrame(Oe);return()=>window.cancelAnimationFrame(de)},[be,Oe]),d.useEffect(()=>{Oe()},[x,Oe]);const We=d.useMemo(()=>te&&Ze<=(b||0)?(b||0)-0-(B?_:0):Ze,[te,Ze,b,B,_,$e]),Rt=d.useMemo(()=>te&&Ze<=(b||0)?b||0:We<(b||0)?Ze+(B?_:0):-1,[te,Ze,b,We,B,_]),ee=d.useRef({});d.useEffect(()=>{if(E&&(ee.current.start!==pe.start||ee.current.end!==pe.end)){const{start:de,end:De}=pe;ee.current={start:de,end:De},N&&N.exec&&N.exec("request-data",{row:{start:de,end:De}})}},[E,pe,N]);const he=d.useMemo(()=>E?T||[]:(T||[]).slice(pe.start,pe.end),[E,T,pe]),Fe=d.useMemo(()=>(P||[]).filter(de=>(he||[]).some(De=>De.id===de)),[z,he]),fe=d.useMemo(()=>pe.start,[pe.start]),xe=d.useRef({top:Z,left:se});xe.current={top:Z,left:se};const nt=d.useCallback(de=>{const De=de.target.scrollTop,Ke=de.target.scrollLeft,wt=xe.current;(De!==wt.top||Ke!==wt.left)&&N.exec("scroll-to",{top:De,left:Ke})},[N]),ct=d.useCallback(de=>{de.shiftKey&&de.preventDefault(),Ce.current&&Ce.current.focus&&Ce.current.focus()},[]),ft=d.useCallback(()=>!!(D||[]).find(de=>!!de.draggable),[D]),dt=d.useRef(null),Dt=d.useRef(null),Yt=d.useRef({dblclick:(de,De)=>{const Ke={id:de,column:Xf(De,"data-col-id")};N.exec("open-editor",Ke)},click:(de,De)=>{if(De.target.closest("input")||dt.current)return;const Ke=Xf(De,"data-col-id");if(K?.id!==de&&N.exec("focus-cell",{row:de,column:Ke,eventSource:"click"}),I===!1)return;const wt=c&&(De.ctrlKey||De.metaKey),Jt=c&&De.shiftKey;(wt||P.length>1||!P.includes(de))&&N.exec("select-row",{id:de,toggle:wt,range:Jt})},"toggle-row":de=>{const De=N.getRow(de);N.exec(De.open!==!1?"close-row":"open-row",{id:de})},"ignore-click":()=>!1}),cn=d.useMemo(()=>({top:ye,bottom:je,left:ze.width,xScroll:$e,yScroll:B,sense:y&&ue?ue.offsetHeight:Math.max(O?.rowHeight||0,40),node:Ce.current&&Ce.current.firstElementChild}),[ye,je,ze.width,$e,B,y,ue,O]);function Xt(de,De){const{container:Ke,sourceNode:wt,from:Jt}=De;if(ft()&&!wt.getAttribute("draggable-data"))return!1;_e(Jt),G&&N.getRow(Jt).open&&N.exec("close-row",{id:Jt,nested:!0});const Ft=vd(wt),mt=Ft.cloneNode(!0);mt.classList.remove("wx-selected"),mt.querySelectorAll("[tabindex]").forEach(na=>na.setAttribute("tabindex","-1")),Ke.appendChild(mt),He(mt);const Pt=(se||0)-Se.d,xt=B?_:0;Ke.style.width=Math.min((b||0)-xt,te&&Ze<=(b||0)?We:We-xt)+Pt+"px";const mn=Ap(Ft);De.offset={x:Pt,y:-Math.round(mn.height/2)},Dt.current||(Dt.current=de.clientY)}function oa(de,De){const{from:Ke}=De,wt=De.pos,Jt=Ap(Ce.current);wt.x=Jt.x;const Ft=cn.top;if(wt.y<Ft)wt.y=Ft;else{const mt=Jt.height-($e&&_>0?_:Math.round(cn.sense/2))-cn.bottom;wt.y>mt&&(wt.y=mt)}if(Ce.current.contains(De.targetNode)){const mt=vd(De.targetNode),Pt=mt&&Yp(mt);if(Pt&&Pt!==Ke){De.to=Pt;const xt=y?ue?.offsetHeight:O?.rowHeight;if(ue&&((Z||0)===0||wt.y>Ft+xt-1)){const mn=mt.getBoundingClientRect(),na=Ap(ue).y,wn=mn.y,On=na>wn?-1:1,rn=On===1?"after":"before",br=N.getState().flatData,wr=Math.abs(br.findIndex(Rn=>Rn.id===Ke)-br.findIndex(Rn=>Rn.id===Pt)),Ot=wr!==1?rn==="before"?"after":"before":rn;if(wr===1&&(On===-1&&de.clientY>Dt.current||On===1&&de.clientY<Dt.current))return;Dt.current=de.clientY,N.exec("move-item",{id:Ke,target:Pt,mode:Ot,inProgress:!0})}}u&&u({event:de,context:De})}CR(de,Jt,De,cn)}function Na(de,De){const{from:Ke,to:wt}=De;N.exec("move-item",{id:Ke,target:wt,inProgress:!1}),dt.current=setTimeout(()=>{dt.current=0},1),_e(null),He(null),Dt.current=null,QS(De)}function Pn(){const de=document.createElement("div");de.style.cssText="position:absolute;left:-1000px;width:100px;padding:0px;margin:0px;min-height:100px;overflow-y:scroll;",document.body.appendChild(de);const De=de.offsetWidth-de.clientWidth;return document.body.removeChild(de),De}const Wn=d.useMemo(()=>Rt>0?{width:`${Rt}px`}:void 0,[Rt]),la=d.useRef(null);function Pe(){Promise.resolve().then(()=>{let de=0,De=fe;const Ke=la.current;Ke&&(Array.from(Ke.children).forEach((wt,Jt)=>{ke.current[fe+Jt]=wt.offsetHeight,de+=wt.offsetHeight,De++}),Ye(de),tt(De))})}d.useEffect(()=>{he&&y&&Pe()},[he,y,fe]);let[q,at]=d.useState();d.useEffect(()=>{if(K&&(!I||!Fe.length||Fe.includes(K.row)))at({...K});else if(he.length&&Se.data.length){if(!q||Fe.length&&!Fe.includes(q.row)||he.findIndex(de=>de.id===q.row)===-1||Se.data.findIndex(de=>de.id===q.column&&!de.collapsed)===-1){const de=Fe[0]||he[0].id,De=Se.data.findIndex(Ke=>!Ke.collapsed);at(De!==-1?{row:de,column:Se.data[De].id}:null)}}else at(null)},[K]);const ht=d.useRef(null);d.useEffect(()=>{const de=Ce.current;if(!de)return;const De=yR(de,w);return()=>{typeof De=="function"&&De()}},[w]);const Zt=d.useRef({});Object.assign(Zt.current,{start:Xt,move:oa,end:Na,getReorder:()=>ne,getDraggableInfo:()=>({hasDraggable:ft()})}),d.useEffect(()=>{const de=Ce.current;return de?wR(de,Zt).destroy:void 0},[ne,Ce.current]),d.useEffect(()=>{const de=Ce.current;return de?gR(de,{keys:k!==!1&&{...hR,"ctrl+z":V,"ctrl+y":V,...k},exec:De=>N.exec("hotkey",De)}).destroy:void 0},[N,V,k]);const bn=d.useRef({scroll:N.getReactiveState().scroll,scrollLeft:N.getReactiveState().scrollLeft,scrollTop:N.getReactiveState().scrollTop});bn.current.getWidth=()=>(b||0)-(B?_:0),bn.current.getHeight=()=>Nt,bn.current.getScrollMargin=()=>ze.width+et.width,d.useEffect(()=>{vR(ht.current,bn.current)},[]);const Es=d.useRef(null);d.useEffect(()=>{const de=Es.current;if(!de)return;const De=[];De.push(Vi(de,()=>K&&N.exec("focus-cell",{eventSource:"click"})).destroy),De.push(wT(de,Yt.current)),H(de.clientHeight);const Ke=new ResizeObserver(()=>{H(de.clientHeight)});return Ke.observe(de),De.push(()=>Ke.disconnect()),()=>De.forEach(wt=>wt())},[]);const Ua=`wx-grid ${A?`wx-responsive-${A}`:""}`;return d.useEffect(()=>{K&&(he.some(de=>de.id===K.row)&&Se.data.some(de=>de.id===K.column&&!de.collapsed)||N.exec("focus-cell",{eventSource:"destroy"}))},[K,he,Se.data,N]),i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"wx-4VuBwK2D "+Ua,style:{"--header-height":`${ye}px`,"--footer-height":`${je}px`,"--split-left-width":`${ze.width}px`,"--split-right-width":`${et.width}px`},children:i.jsx("div",{ref:Ce,className:"wx-4VuBwK2D wx-table-box",style:Wn,role:G?"treegrid":"grid","aria-colcount":Se.data.length,"aria-rowcount":he.length,"aria-multiselectable":G&&c?!0:void 0,tabIndex:-1,children:i.jsxs("div",{ref:ht,className:"wx-4VuBwK2D wx-scroll",style:{overflowX:$e?"scroll":"hidden",overflowY:B?"scroll":"hidden"},onScroll:nt,children:[n?i.jsx("div",{className:"wx-4VuBwK2D wx-header-wrapper",children:i.jsx(jw,{contentWidth:We,deltaLeft:Se.dh,columns:Se.header,columnStyle:h,bodyHeight:Nt-+r})}):null,i.jsxs("div",{ref:Es,className:"wx-4VuBwK2D wx-body",style:{width:`${We}px`,height:`${Ne}px`},onMouseDown:de=>ct(de),children:[o?i.jsx(PR,{overlay:o}):null,i.jsx("div",{ref:la,className:"wx-4VuBwK2D wx-data",style:{paddingTop:`${pe.d}px`,paddingLeft:`${Se.d}px`},children:he.map((de,De)=>{const Ke=P.indexOf(de.id)!==-1,wt=Ae===de.id,Jt="wx-row"+(y?" wx-autoheight":"")+(f?" "+f(de):"")+(Ke?" wx-selected":"")+(wt?" wx-inactive":""),Ft=y?{minHeight:`${de.rowHeight||le}px`}:{height:`${de.rowHeight||le}px`};return i.jsx("div",{className:"wx-4VuBwK2D "+Jt,"data-id":Ha(de.id),"data-context-id":Ha(de.id),style:Ft,role:"row","aria-rowindex":De,"aria-expanded":de.open,"aria-level":G?de.$level+1:void 0,"aria-selected":G?Ke:void 0,tabIndex:-1,children:Se.data.map(mt=>mt.collapsed?i.jsx("div",{className:"wx-4VuBwK2D wx-cell wx-collapsed"},mt.id):X?.id===de.id&&X.column===mt.id?i.jsx(qR,{row:de,column:mt},mt.id):i.jsx(TR,{row:de,column:mt,columnStyle:h,cellStyle:g,reorder:ne,focusable:q?.row===de.id&&q?.column===mt.id},mt.id))},de.id)})})]}),r&&(T||[]).length?i.jsx(jw,{type:"footer",contentWidth:We,deltaLeft:Se.df,columns:Se.footer,columnStyle:h}):null]})})}),me?i.jsx(GR,{config:me,rowStyle:f,columnStyle:h,cellStyle:g,header:n,footer:r,reorder:ne}):null]})}const KR=t=>t.split("-").map(n=>n?n.charAt(0).toUpperCase()+n.slice(1):"").join(""),QR=d.forwardRef(function({data:t=[],columns:n=[],rowStyle:r=null,columnStyle:o=null,cellStyle:c=null,selectedRows:u,select:f=!0,multiselect:h=!1,header:g=!0,footer:y=!1,dynamic:w=null,overlay:b=null,reorder:x=!1,onReorder:A=null,autoRowHeight:k=!1,sizes:N,split:E,tree:D=!1,autoConfig:T=!1,init:F=null,responsive:O=null,sortMarks:P,undo:z=!1,hotkeys:I=null,filterValues:X,...se},Z){const G=d.useRef();G.current=se;const K=d.useMemo(()=>new cR(OS),[]),me=d.useMemo(()=>K.in,[K]),V=d.useRef(null);V.current===null&&(V.current=new DS((et,Xe)=>{const Ze="on"+KR(et);G.current&&G.current[Ze]&&G.current[Ze](Xe)}),me.setNext(V.current));const ne=d.useMemo(()=>({getState:K.getState.bind(K),getReactiveState:K.getReactive.bind(K),getStores:()=>({data:K}),exec:me.exec,setNext:et=>(V.current=V.current.setNext(et),V.current),intercept:me.intercept.bind(me),on:me.on.bind(me),detach:me.detach.bind(me),getRow:K.getRow.bind(K),getColumn:K.getColumn.bind(K)}),[K,me]),[$,_]=d.useState(0),[ie,be]=d.useState(0),[H,te]=d.useState(null),[le,Ce]=d.useState(null),Ae=d.useMemo(()=>{if(T&&!n.length&&t.length){const et=t[0],Xe=[];for(let Ze in et)if(Ze!=="id"&&Ze[0]!=="$"){let Ue={id:Ze,header:Ze[0].toUpperCase()+Ze.slice(1)};typeof T=="object"&&(Ue={...Ue,...T}),Xe.push(Ue)}return Xe}return(le&&le.columns)??n},[T,n,t,le]),_e=d.useMemo(()=>(le&&le.sizes)??N,[le,N]),ue=d.useCallback(et=>{if(_(et.width),be(et.height),O){const Xe=Object.keys(O).map(Number).sort((Ze,Ue)=>Ze-Ue).find(Ze=>et.width<=Ze)??null;Xe!==H&&(Ce(O[Xe]),te(Xe))}},[O,H]),He=d.useContext($a.theme),ze=d.useRef(0);return d.useEffect(()=>{if(!ze.current)F&&F(ne);else{const et=K.getState();K.init({data:t,columns:Ae,split:E||et.split,sizes:_e||et.sizes,selectedRows:u||et.selectedRows,dynamic:w,tree:D,sortMarks:P||et.sortMarks,filterValues:X||et.filterValues,undo:z,reorder:x,_skin:He,_select:f})}ze.current++},[K,t,Ae,E,_e,u,w,D,P,X,z,x,He,f,F,ne]),ze.current===0&&K.init({data:t,columns:Ae,split:E||{left:0},sizes:_e||{},selectedRows:u||[],dynamic:w,tree:D,sortMarks:P||{},filterValues:X||{},undo:z,reorder:x,_skin:He,select:f}),d.useImperativeHandle(Z,()=>({...ne}),[ne]),i.jsx(js.Provider,{value:ne,children:i.jsx(Fv,{words:Pv,optional:!0,children:i.jsx(VR,{header:g,footer:y,overlay:b,rowStyle:r,columnStyle:o,cellStyle:c,onReorder:A,multiselect:h,autoRowHeight:k,clientWidth:$,clientHeight:ie,responsiveLevel:H,resize:ue,hotkeys:I})})})});Rv(ss);const za=d.createContext(null),Hv=d.createContext(null),zv=d.createContext(null);function YR({children:t}){const n=d.useContext($a.i18n),r=d.useMemo(()=>n.getGroup("filemanager"),[n]),o=d.useContext(za),[c]=Zs(o,"panels"),u=Tt(o,"activePanel"),f=c[u].path,[h,g]=d.useState(null),[y,w]=d.useState(null),[b,x]=d.useState(""),[A,k]=d.useState(""),[N,E]=d.useState(!1);function D(){const P=b.trim();if(!P){E(!0);return}h.add?o.exec("create-file",{file:{...h.item,name:P},parent:f}):A!==P&&o.exec("rename-file",{id:h.item.id,name:P}),T()}function T(){g(null),E(null),k(""),x("")}function F(){o.exec("delete-files",{ids:y.selected}),w(null)}const O=d.useMemo(()=>({showPrompt(P){const z=P.item.name||(P.item.type==="folder"?r("New folder"):`${r("New file")}.txt`);k(z),x(z),g({...P})},showConfirm(P){w({...P})}}),[r]);return i.jsxs(Hv.Provider,{value:O,children:[i.jsx(YN,{children:t}),h?i.jsx(sv,{title:r(`Enter ${h.item.type} name`),onConfirm:D,onCancel:T,children:i.jsx(Lv,{error:N,select:!0,focus:!0,value:b,onChange:({value:P})=>x(P)})}):null,y?i.jsx(sv,{title:r("Are you sure you want to delete these items:"),onConfirm:F,onCancel:()=>w(null),children:y.selected?i.jsx("ul",{className:"wx-gq7BMzEP wx-list",children:y.selected.map((P,z)=>i.jsx("li",{children:P},z))}):null}):null]})}let Dw={"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 XR(t){const n=t.lastIndexOf("."),r=n>0&&n<t.length-1?Math.min(10,t.length-n):Math.min(5,t.length),o=t.slice(0,-r),c=t.slice(-r);return[o,c]}function ZR({item:t}){const n=d.useContext(za),r=d.useContext($a.i18n).getGroup("filemanager"),o=d.useContext(za).templates,[c]=Zs(n,"panels"),u=Tt(n,"activePanel"),f=Tt(n,"mode"),h=c[u].selected,g=d.useMemo(()=>o.preview(t,214,163),[o,t]),y=d.useMemo(()=>o.icon(t,"big"),[o,t]),[w,b]=d.useMemo(()=>XR(t.name),[t.name]);return i.jsx(i.Fragment,{children:t.id==="/wx-filemanager-parent-link"?f!=="search"?i.jsx("div",{className:"wx-GAOa4kDV wx-back-item",children:i.jsxs("div",{className:`wx-GAOa4kDV wx-back ${t.navigation?"wx-selected":""}`,"data-id":Ha("/wx-filemanager-parent-link"),children:[i.jsx("i",{className:"wx-GAOa4kDV wxi-arrow-left"}),i.jsx("span",{children:r("Back to parent folder")})]})}):null:i.jsxs("div",{className:`wx-GAOa4kDV wx-item ${h?.length&&h.indexOf(t.id)>=0?"wx-selected":""}`,"data-id":Ha(t.id),children:[g?i.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-preview",children:i.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:r("A miniature file preview"),src:g})}):y?i.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-icon",children:i.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:"",src:y})}):i.jsx("div",{className:"wx-GAOa4kDV wx-preview",children:i.jsx("i",{className:`wx-GAOa4kDV wxi-${t.type}`})}),t.type==="folder"?i.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[i.jsxs("div",{className:"wx-GAOa4kDV wx-folder-name",children:[i.jsx("span",{className:"wx-GAOa4kDV wx-type",children:r("Folder")}),i.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[i.jsx("span",{children:w}),i.jsx("span",{children:b})]})]}),i.jsx("div",{"data-action-id":Ha(t.id),className:"wx-GAOa4kDV wx-more",children:i.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]}):i.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[i.jsx("div",{className:"wx-GAOa4kDV wx-file-name",children:i.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[i.jsx("span",{children:w}),i.jsx("span",{children:b})]})}),i.jsx("div",{"data-action-id":Ha(t.id),className:"wx-GAOa4kDV wx-more",children:i.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]})]})})}function JS(){const t=d.useContext(za),n=d.useContext($a.i18n),r=d.useMemo(()=>n.getGroup("filemanager"),[n]),[o]=Zs(t,"panels"),c=Tt(t,"activePanel"),u=Tt(t,"mode"),f=o[c]._files,h=o[c].selected,g=o[c].path,y=o[c]._crumbs,w=o[c]._selectNavigation,b=d.useCallback((T,F)=>{const O=F&&(F.ctrlKey||F.metaKey),P=F&&F.shiftKey;if(T==="/wx-filemanager-parent-link"){if(h.length&&(O||P))return;t.exec("select-file",{type:"navigation"});return}let z=T==="body"&&F?null:T;const I=F.target.className.indexOf("wx-more")!==-1||F.target.className.indexOf("wxi-dots-v")!==-1;setTimeout(()=>{t.exec("select-file",{id:z,toggle:O&&!I,range:P&&!I,panel:c})},1)},[t,h,c]),x=d.useCallback(()=>{y.length>1&&t.exec("set-path",{id:y[y.length-2].id,panel:c,selected:[y[y.length-1].id]})},[t,y,c]),A=d.useCallback(T=>{if(T==="/wx-filemanager-parent-link")return x();u==="search"&&t.exec("filter-files",{text:""});const F=f.find(O=>O.id===T);F&&(F.type=="folder"?t.exec("set-path",{id:F.id,panel:c}):t.exec("open-file",{id:F.id}))},[t,x,u,f,c]),k=d.useCallback((T,F)=>{(!h?.length||!h.filter(O=>O?.id===T).length>0)&&b(T,F)},[h,b]),N=d.useMemo(()=>g!=="/"?[{id:"/wx-filemanager-parent-link",name:r("Back to parent folder"),navigation:w},...f]:f,[g,r,w,f]),E=d.useRef(null),D=d.useRef();return d.useEffect(()=>{E.current&&(D.current?(D.current.click=b,D.current._dblclick=A,D.current.context=k):(D.current={click:b,dblclick:T=>D.current._dblclick(T),_dblclick:A,context:k},yd(E.current,D.current)))},[b,A,k]),u=="search"&&!N.length?i.jsx("div",{className:"wx-iyjASZCY wx-not-found",children:i.jsx("div",{className:"wx-iyjASZCY wx-not-found-text",children:r("Looks like nothing is here")})}):i.jsx("div",{tabIndex:0,className:"wx-iyjASZCY "+("wx-cards"+(g!=="/"&&u!=="search"?" wx-has-back-link":"")),"data-id":Ha("body"),ref:E,children:N.map(T=>i.jsx(ZR,{item:T},T.id))})}function Xc({name:t="",spin:n=!1,onClick:r}){return i.jsx("i",{"data-menu-ignore":"true",className:`wx-uwcvNSAG wx-icon wxi-${t} ${n?"wx-spin":""} ${r?"wx-clickable":""}`,onClick:()=>{r&&r()}})}function JR(){const t=d.useContext($a.i18n).getGroup("filemanager"),n=d.useContext(za),r=Tt(n,"activePanel"),[o]=Zs(n,"panels"),c=d.useMemo(()=>o[r]._crumbs,[o,r]);function u(){n.exec("filter-files",{text:""})}return i.jsxs("div",{className:"wx-GDJvtROw wx-search",children:[i.jsxs("div",{className:"wx-GDJvtROw wx-toolbar",children:[i.jsx("div",{className:"wx-GDJvtROw wx-back-icon",children:i.jsx(Xc,{name:"angle-left",onClick:u})}),i.jsxs("div",{className:"wx-GDJvtROw wx-text",children:[t("Search results in")," ",Array.isArray(c)&&c.map((f,h)=>i.jsxs(d.Fragment,{children:[h?"/":null,f.id=="/"?t(f.name):f.name]},h))]})]}),i.jsx(JS,{})]})}function vg({narrowMode:t,extraInfo:n}){const r=d.useContext(za),{preview:o,icon:c}=r.templates,u=d.useContext($a.i18n),f=d.useMemo(()=>u.getGroup("filemanager"),[u]),h=d.useMemo(()=>fd("%D, %d %F %Y, %H:%i",u.getRaw().calendar),[u]),[g,y]=Zs(r,"panels"),w=Tt(r,"activePanel"),b=Tt(r,"preview"),x=Tt(r,"search"),A=d.useMemo(()=>{const I=g&&w!=null&&g[w]?._selected?.length||0;return x&&!I},[x,y,w]),k=d.useMemo(()=>{const I=g&&w!=null?g[w]:null;return I?A?I._files:I._selected:[]},[A,y,w]),N=d.useCallback((I,X)=>(I?`${I} ${f(I>1?"folders":"folder")} `:"")+(X?`${X} ${f(X>1?"files":"file")}`:""),[f]),E=d.useCallback(()=>{r.exec("show-preview",{mode:!b})},[r,b]),D=d.useCallback(I=>I.type==="folder"?f("Folder"):I.ext||f("Unknown file"),[f]),T=d.useMemo(()=>{let I,X,se,Z,G,K,me,V;if(k.length===1&&!A){X=k[0],I=X.name;const ne=o(X,400,500);ne?(se=ne,Z=""):(Z=c(X,"big"),se=""),G=X.type!=="folder"}else{if(X=G=null,I="",k.length){let ne=0,$=0,_=0,ie=[],be;k.forEach(te=>{typeof te.size>"u"&&(be=!0,ne=void 0),be||(ne+=te.size),ie.push(D(te)),te.type==="folder"?$++:_++});const H=new Set(ie);K=H.size>1?f("multiple"):[...H][0],me=N($,_),V=ne,A||(I=f("Multiple files"))}Z=c({type:A?"search":k.length?"multiple":"none"},"big"),se=""}return{name:I,item:X,previewSrc:se,iconSrc:Z,showDownloadIcon:G,type:K,totalCount:me,totalSize:V}},[k,A,o,c,f,D,N]),F=d.useCallback(()=>{r.exec("download-file",{id:k[0].id})},[r,k]),O=d.useCallback(async I=>{if(!n||!I)return null;try{return await n(I)}catch(X){return console.log(X),null}},[n]),[P,z]=d.useState(null);return d.useEffect(()=>{let I=!1;return z(null),Promise.resolve(O(T.item)).then(X=>{I||z(X)}).catch(()=>{I||z(null)}),()=>{I=!0}},[O,T.item]),i.jsx("div",{className:"wx-O0BTtRrH wx-wrapper",children:k&&k.length?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"wx-O0BTtRrH wx-preview",children:[i.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[i.jsx("div",{className:"wx-O0BTtRrH wx-name",children:T.name}),i.jsxs("div",{className:"wx-O0BTtRrH wx-icons",children:[T.showDownloadIcon?i.jsx(Xc,{name:"download",onClick:F}):null,t?i.jsx(Xc,{name:"close",onClick:E}):null]})]}),T.previewSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:i.jsx("img",{src:T.previewSrc,alt:f("A miniature file preview")})}):T.iconSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:i.jsx("img",{src:T.iconSrc,alt:f("A miniature file preview")})}):i.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:T.item?i.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${T.item.type}`}):i.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${A?"search":"file-multiple-outline"}`})})]}),i.jsxs("div",{className:"wx-O0BTtRrH wx-info-panel",children:[i.jsx("div",{className:"wx-O0BTtRrH wx-title",children:f(A?"Found":"Information")}),i.jsxs("div",{className:"wx-O0BTtRrH wx-list",children:[T.item?i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Type")}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:D(T.item)}),typeof T.item.size<"u"?i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Size")}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:Zf(T.item.size)})]}):null,i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Date")}),i.jsxs("span",{className:"wx-O0BTtRrH wx-value",children:[h(T.item.date)," "]})]}):i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Count")}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:T.totalCount}),i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Type")}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:T.type}),typeof T.totalSize<"u"?i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Size")}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:Zf(T.totalSize)})]}):null]}),P?Object.entries(P).map(([I,X])=>i.jsxs(hv.Fragment,{children:[i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:I}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:X})]},I)):null]})]})]}):i.jsxs("div",{className:"wx-O0BTtRrH wx-no-info-panel",children:[i.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[i.jsx("div",{className:"wx-O0BTtRrH wx-name",children:T.name}),i.jsx("div",{className:"wx-O0BTtRrH wx-icons",children:t?i.jsx(Xc,{name:"close",onClick:E}):null})]}),i.jsx("div",{className:"wx-O0BTtRrH wx-no-info-wrapper",children:i.jsxs("div",{className:"wx-O0BTtRrH wx-no-info",children:[T.previewSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:i.jsx("img",{src:T.previewSrc,alt:f("A miniature file preview")})}):T.iconSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:i.jsx("img",{src:T.iconSrc,alt:f("A miniature file preview")})}):i.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:i.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${A?"search":"message-question-outline"}`})}),i.jsx("span",{className:"wx-O0BTtRrH wx-text",children:A?"":f("Select file or folder to view details")})]})})]})})}function e0({panel:t}){const n=d.useContext(za),r=d.useContext($a.i18n),o=d.useMemo(()=>r.getGroup("filemanager"),[r]),[c,u]=Zs(n,"panels"),f=d.useMemo(()=>c[t]._files,[u,t]),h=d.useMemo(()=>c[t]._crumbs||[],[u,t]);function g(k){const N=Ov(k,h);n.exec("set-path",{id:k,panel:t,...N&&{selected:[N]}})}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 x=d.useRef(null),A=d.useRef();return d.useEffect(()=>{A.current?A.current.click=g:(A.current={click:g},yd(x.current,A.current))},[g]),i.jsxs("div",{className:"wx-SNY5LTYx wx-breadcrumbs","data-menu-ignore":"true",ref:x,children:[i.jsx("div",{className:"wx-SNY5LTYx wx-refresh-icon",children:i.jsx(Xc,{name:"refresh",spin:!!y,onClick:b})}),h.map((k,N)=>i.jsxs(hv.Fragment,{children:[N?i.jsx(Xc,{name:"angle-right"}):null,i.jsx("div",{className:"wx-SNY5LTYx wx-item","data-id":Ha(k.id),"data-menu-ignore":"true",children:k.id=="/"?o(k.name):k.name})]},N))]})}function ej({row:t}){const n=d.useContext($a.i18n),[r]=d.useState(()=>n.getGroup("filemanager")),o=d.useContext(za).templates,[c]=d.useState(()=>o.icon(t,"small"));return i.jsx("div",{className:"wx-qgAqG6sL wx-name-cell",children:t.id==="/wx-filemanager-parent-link"?i.jsxs(i.Fragment,{children:[i.jsx("i",{className:"wx-qgAqG6sL wxi-arrow-left"}),i.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",r("Back to parent folder")]})]}):i.jsxs(i.Fragment,{children:[c?i.jsx("img",{className:"wx-qgAqG6sL wx-icon",alt:"",src:c,height:"24px",width:"24px"}):i.jsx("i",{className:`wx-qgAqG6sL wxi-${t.type}`}),i.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",t.name," "]})]})})}function t0({children:t}){const n=d.useContext(za),r=Tt(n,"activePanel"),o=d.useContext(zv),c=d.useRef(null);let u=d.useRef({});return u.current.drop=()=>{const f=c.current,h=aN(f,"data-panel");h&&h!=r&&n.exec("set-active-panel",{panel:h*1})},u.current.dragEnter=()=>{const f=c.current;f&&f.classList.toggle("wx-active")},u.current.dragLeave=()=>{const f=c.current;f&&f.classList.toggle("wx-active")},d.useEffect(()=>{const f=c.current;return o.droparea(f,u.current)},[]),i.jsx("div",{className:"wx-LT9X7tb7 wx-upload-area",ref:c,children:t})}function lv({panel:t,active:n=!1,onClick:r,onContextMenu:o}){const c=d.useContext(za),u=d.useContext($a.i18n),f=d.useMemo(()=>u.getGroup("filemanager"),[u]),h=d.useMemo(()=>fd("%d %M %Y",u.getRaw().calendar),[u]),[g]=Zs(c,"panels"),y=g[t].selected,w=g[t].path,b=g[t]._crumbs,x=g[t]._sorts,A=g[t]._selectNavigation,k=g[t]._files,N=d.useMemo(()=>[{id:"name",header:f("Name"),flexgrow:3,sort:!0,resize:!0,cell:ej},{id:"size",header:f("Size"),width:100,sort:!0,resize:!0,template:K=>typeof K=="number"?Zf(K):""},{id:"date",header:f("Date"),width:120,sort:!0,resize:!0,template:K=>K?h(K):""}],[f,h]),E=d.useRef(null),D=d.useRef(null),T=d.useMemo(()=>A?["/wx-filemanager-parent-link"]:[...y],[A,y]);function F(K,me){if(me&&me.target&&me.target.className&&me.target.className.indexOf("wx-grip")!==-1)return;const V=me&&(me.ctrlKey||me.metaKey),ne=me&&me.shiftKey;if(K==="/wx-filemanager-parent-link"){if(y.length&&(V||ne))return;c.exec("select-file",{type:"navigation"});return}let $=K==="body"&&me?null:K;!E.current&&!D.current?c.exec("select-file",{id:$,toggle:V,range:ne,panel:t}):(E.current=null,D.current=null)}function O(){b.length>1&&c.exec("set-path",{id:b[b.length-2].id,panel:t,selected:[b[b.length-1].id]})}function P(K){if(K==="/wx-filemanager-parent-link")return O();const me=k.find(V=>V.id===K);me&&(me.type==="folder"?c.exec("set-path",{id:me.id,panel:t}):c.exec("open-file",{id:me.id}))}function z(K){const me=K.key,V=x[w];let ne=V?"asc":"desc";V&&V.key===me&&(ne=V.order==="asc"?"desc":"asc"),c.exec("sort-files",{key:me,order:ne,panel:t,path:w})}function I(K){K.intercept("sort-rows",me=>(E.current=!0,z(me),!1)),K.intercept("select-row",()=>!1),K.on("resize-column",()=>D.current=!0),K.intercept("hotkey",()=>!1)}const X=d.useMemo(()=>w!=="/"?[{id:"/wx-filemanager-parent-link",name:f("Back to parent folder")},...k]:k,[w,k,f]),se=d.useMemo(()=>{if(X&&x&&x[w]){const{key:K,order:me}=x[w];return{[K]:{order:me}}}},[X,x,w]),Z=d.useRef(null),G=d.useRef();return d.useEffect(()=>{G.current?(G.current.click=F,G.current._dblclick=P):(G.current={click:F,dblclick:K=>G.current._dblclick(K),_dblclick:P},yd(Z.current,G.current))},[F,P]),i.jsxs("div",{onClick:r,onContextMenu:o,className:"wx-SSaVhET7 wx-wrapper",children:[i.jsx(e0,{panel:t}),i.jsx("div",{"data-id":Ha("body"),className:`wx-SSaVhET7 wx-list ${n?"wx-active":""}`,ref:Z,children:i.jsx(t0,{children:i.jsx(QR,{init:I,data:X,columns:N,selectedRows:T,columnStyle:()=>"wx-SSaVhET7 wx-each-cell",sizes:{rowHeight:42,headerHeight:42},sortMarks:se})})})]})}function tj(){const t=d.useContext(za),n=Tt(t,"activePanel");function r(o){t.exec("set-active-panel",{panel:o})}return i.jsxs("div",{className:"wx-L55BfJa2 wx-panels","data-id":Ha("body"),children:[i.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":0,children:i.jsx(lv,{panel:0,active:n==0,onClick:()=>r(0),onContextMenu:()=>r(0)})}),i.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":1,children:i.jsx(lv,{panel:1,active:n==1,onClick:()=>r(1),onContextMenu:()=>r(1)})})]})}function n0({folderIcon:t=!1,folder:n={}}){const r=d.useContext(za),[o,c]=Zs(r,"panels"),u=Tt(r,"activePanel"),f=d.useMemo(()=>o[u].path,[c,u]),h=d.useContext($a.i18n),g=d.useMemo(()=>h.getGroup("filemanager"),[h]),y=d.useMemo(()=>!!n.data?.find(A=>A.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]),x=n.open;return i.jsxs(i.Fragment,{children:[i.jsxs("li",{"data-id":Ha(n.id),className:`wx-NYfhvGIt wx-folder${f===n.id?" wx-selected":""}`,style:{paddingLeft:`${b}px`},children:[y?i.jsx("i",{className:`wx-NYfhvGIt wx-toggle wxi-${x?"angle-down":"angle-right"}`,"data-action":"toggle"}):i.jsx("span",{className:"wx-NYfhvGIt wx-toggle-placeholder"}),i.jsx("i",{className:"wx-NYfhvGIt "+(t||"wxi-folder")}),i.jsxs("span",{className:"wx-NYfhvGIt wx-name",children:[" ",w," "]})]}),x&&n.data&&n.data.length&&y?i.jsx(i.Fragment,{children:n.data.map(A=>A.type==="folder"?i.jsx(n0,{folder:A},A.id):null)}):null]})}function nj(){const t=d.useContext(za),[n,r]=Zs(t,"data"),[o,c]=Zs(t,"panels"),u=Tt(t,"activePanel"),f=d.useMemo(()=>o[u]._crumbs,[c,u]),h=d.useCallback(A=>{t.exec("open-tree-folder",{id:A,mode:!n.byId(A).open})},[t,r]),g=d.useCallback(A=>{const k=Ov(A,f);t.exec("set-path",{id:A,panel:u,...k&&{selected:[k]}})},[t,f,u]),[y,w]=d.useState([]);d.useEffect(()=>{w(n.byId(0).data)},[r]);const b=d.useRef(null),x=d.useRef();return d.useEffect(()=>{x.current?(x.current.click=g,x.current.toggle=h):(x.current={click:g,toggle:h},yd(b.current,x.current))},[g,h]),i.jsx("ul",{ref:b,className:"wx-LyHJ6R6A",children:y.map(A=>A.type==="folder"?i.jsx(n0,{folder:A},A.id):null)})}function aj(){const t=d.useContext(za),n=d.useContext($a.i18n),r=d.useMemo(()=>n.getGroup("filemanager"),[n]),o=Tt(t,"drive"),c=o?o.used:"",u=o?o.total:"";return c&&u?i.jsxs("div",{className:"wx-DetSyKGG wx-drive",children:[i.jsx("progress",{value:c,max:u,className:"wx-DetSyKGG wx-progress"}),i.jsxs("p",{children:[Zf(c)," ",r("of")," ",Zf(u)," ",r("used")]})]}):null}function rj({option:t}){const n=d.useContext($a.i18n).getGroup("filemanager"),r=d.useContext(zv),o=d.useCallback(()=>{r.open({})},[r]);return i.jsx("div",{className:"wx-9XiKcxq5 wx-upload-button",onClick:o,children:i.jsx("span",{children:n(t.text)})})}function sj({readonly:t,menuOptions:n}){const r=d.useContext($a.i18n).getGroup("filemanager"),{showPrompt:o}=d.useContext(Hv);d.useEffect(()=>{CT("upload",rj)},[]);function c({action:f}){f&&(f.id==="add-file"?o({item:{type:"file",size:0,date:new Date},add:!0}):f.id==="add-folder"&&o({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 i.jsxs("div",{className:"wx-FlucfALM wx-wrapper",children:[!t&&i.jsx("div",{className:"wx-FlucfALM wx-button",children:i.jsx(MT,{options:u,at:"bottom-fit",onClick:c,children:i.jsx(Wf,{type:"primary block",children:r("Add New")})})}),i.jsx("div",{className:"wx-FlucfALM wx-tree",children:i.jsx(nj,{})}),i.jsx(aj,{})]})}function ij({value:t="",onSearch:n}){const[r,o]=FS(t),c=d.useContext($a.i18n).getGroup("filemanager"),u=d.useRef(null),f=d.useMemo(()=>r!==""?"wxi-close":"wxi-search",[r]);function h(y){const w=y.target.value;o(w),n&&n({value:w})}function g(){o(""),u.current&&u.current.focus(),n&&n({value:""})}return i.jsxs("div",{className:"wx-lUZMtgT1 wx-search-input",children:[i.jsx("i",{className:`wx-lUZMtgT1 wx-icon ${f}`,onClick:g}),i.jsx("input",{type:"text",className:"wx-lUZMtgT1 wx-text",ref:u,value:r,onInput:h,placeholder:c("Search")})]})}function oj({narrowMode:t=!1,onShowTree:n}){const r=d.useContext(za),o=d.useContext($a.i18n).getGroup("filemanager"),c=Tt(r,"mode"),u=Tt(r,"preview"),f=Tt(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 i.jsxs("div",{className:"wx-5PZQQztG wx-toolbar",children:[i.jsxs("div",{className:"wx-5PZQQztG wx-left "+(t?"wx-left-narrow":""),children:[t?c==="panels"||c==="search"?null:i.jsx("div",{className:"wx-5PZQQztG wx-sidebar-icon","data-id":Ha("toggle-tree"),children:i.jsx(Xc,{onClick:()=>n&&n(),name:"subtask"})}):i.jsx("div",{className:"wx-5PZQQztG wx-name",children:o("Files")}),i.jsx(ij,{onSearch:w,value:f})]}),i.jsxs("div",{className:"wx-5PZQQztG wx-right",children:[t?null:i.jsx("div",{className:"wx-5PZQQztG wx-preview-icon",children:i.jsx(XN,{onClick:y,value:u,children:i.jsx("i",{className:"wx-5PZQQztG wxi-eye"})})}),i.jsx("div",{className:"wx-5PZQQztG wx-modes",children:i.jsx(WN,{value:c,options:h,onChange:g})})]})]})}function lj(){const t=d.useContext(za),n=Tt(t,"activePanel");return i.jsxs("div",{className:"wx-NwohNJzN wx-wrapper",children:[i.jsx(e0,{panel:n}),i.jsx(t0,{children:i.jsx(JS,{})})]})}function cj({readonly:t=!1,menuOptions:n,extraInfo:r}){const o=d.useRef(null),c=d.useRef(null),[u,f]=d.useState(void 0),[h,g]=d.useState(void 0),[y,w]=d.useState(!1),b=US(),x=d.useContext(za),{showPrompt:A,showConfirm:k}=d.useContext(Hv),N=d.useContext($a.i18n),E=d.useMemo(()=>N.getGroup("filemanager"),[N]),D=Tt(x,"mode"),T=Tt(x,"preview"),F=Tt(x,"activePanel"),[O,P]=Zs(x,"panels"),z=d.useMemo(()=>(O&&F!=null?O[F]:null)?.selected??[],[P,F]),I=d.useMemo(()=>(O&&F!=null?O[F]:null)?.path,[P,F]),[X,se]=d.useState([]);d.useEffect(()=>{const H=o.current;if(!H)return;const te=new ResizeObserver(le=>{const Ce=le[0]?.borderBoxSize?.[0]?.inlineSize;typeof Ce=="number"&&g(Ce<768)});return te.observe(H),()=>{te.disconnect()}},[]);const Z=d.useCallback(()=>{w(H=>!H)},[]),G=d.useCallback(H=>{h&&Xf(H)!=="toggle-tree"&&w(!1)},[h]);d.useEffect(()=>{const H=c.current;if(H)return Vi(H,G).destroy},[G]),d.useEffect(()=>{const H=c.current;if(!H)return;const te=new ResizeObserver(()=>{H&&f(H.clientWidth)});return te.observe(H),H&&f(H.clientWidth),()=>{te.disconnect()}},[]);const K=d.useMemo(()=>({icon:"wxi-eye",text:"Preview",id:"preview"}),[]),me=d.useCallback(H=>{let te=h?[K]:[];return H==="file"&&(te=[...te,...n().filter(le=>le.id==="download")]),te},[h,K,n]),V=d.useRef(null),ne=d.useCallback((H,te,le)=>{const Ce=le?[te.id]:z;switch(H){case"download":x.exec("download-file",{id:te.id});break;case"copy":case"move":V.current={action:H,ids:Ce};break;case"paste":V.current&&x.exec(V.current.action==="copy"?"copy-files":"move-files",{ids:V.current.ids,target:te?.type==="folder"?te.id:I});break;case"rename":A({item:te});break;case"delete":k({selected:Ce});break;case"preview":x.exec("show-preview",{mode:!T});break}},[x,z,I,A,k,T]),$=d.useCallback(()=>O?.[F],[O,F]);d.useEffect(()=>{const H=o.current;if(!H)return;const te=fT(H,{api:x,menuOptions:t?me:n,performAction:ne,getPanel:$});return()=>{typeof te=="function"?te():te&&typeof te.destroy=="function"&&te.destroy()}},[x,t,me,n,ne,$]);const _=d.useCallback((H,te)=>{const le=H?x.getFile(H):null,Ce=te.target.closest(".tree-item.folder");let Ae;if(t)Ae=me(le?.type);else{switch(H){case"body":Ae=n(H);break;default:if(le)if(!Ce&&z.length>1)Ae=h?[K,...n("multiselect")]:n("multiselect");else if(H==="/")Ae=n("folder",le).filter(_e=>_e.id==="paste");else{const _e=n(le.type,le);_e&&(Ae=h?[K,..._e]:_e)}}D==="search"&&(Ae=Ae?.filter(_e=>_e.id!=="paste"))}if(le?.id&&(!z.length||!z.some(_e=>_e===le.id))&&!Ce&&x.exec("select-file",{id:le.id}),Ae?.length)return Ae.forEach(_e=>{Ce&&(_e.hotkey=""),_e.text&&(_e.text=E(_e.text)),_e.hotkey&&(_e.subtext=_e.hotkey)}),se(Ae),le||{}},[x,t,me,n,z,h,K,D,E]),ie=d.useCallback(H=>{const{action:te,context:le}=H;te&&ne(te.id,le,!te.hotkey)},[ne]);async function be(H){await Promise.resolve();const{name:te,size:le}=H.file;x.exec("create-file",{file:{name:te,size:le,date:new Date,file:H.file},parent:I})}return i.jsx("div",{className:"wx-RJbNonjJ wx-filemanager wx-flex",ref:o,"data-menu-ignore":"false",children:h&&T?i.jsx("div",{className:"wx-RJbNonjJ wx-info-narrow",children:i.jsx(vg,{narrowMode:h,extraInfo:r})}):i.jsxs(i.Fragment,{children:[i.jsx(oj,{narrowMode:h,onShowTree:Z}),i.jsx(AT,{dataKey:"id",at:"point",options:X,resolver:_,onClick:ie,children:i.jsxs($S,{dataKey:"actionId",options:X,resolver:_,onClick:ie,children:[i.jsx(ET,{data:b,apiOnly:!0,uploadURL:be}),i.jsx(zv.Provider,{value:b,children:i.jsx("div",{className:"wx-RJbNonjJ wx-content-wrapper wx-flex",children:D!=="panels"&&D!=="search"?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"wx-RJbNonjJ "+["wx-sidebar",h?"wx-sidebar-narrow":"",y?"wx-sidebar-visible":""].filter(Boolean).join(" "),ref:c,children:i.jsx(sj,{readonly:t,menuOptions:n})}),i.jsxs("div",{className:"wx-RJbNonjJ wx-content",style:{width:`calc(100% - ${u||0}px - 10px)`},children:[i.jsx("div",{className:`wx-RJbNonjJ wx-content-item${T?"":"-fit"}`,"data-id":Ha("body"),children:D==="table"?i.jsx(lv,{panel:F}):i.jsx(lj,{})}),T?i.jsx("div",{className:"wx-RJbNonjJ wx-info",children:i.jsx(vg,{extraInfo:r})}):null]})]}):i.jsxs(i.Fragment,{children:[i.jsx("div",{className:`wx-RJbNonjJ wx-content-item${T?"":"-fit"}`,children:D==="panels"?i.jsx(tj,{}):i.jsx(JR,{})}),T?i.jsx("div",{className:"wx-RJbNonjJ wx-info",children:i.jsx(vg,{extraInfo:r})}):null]})})})]})})]})})}const uj=t=>t.split("-").map(n=>n?n.charAt(0).toUpperCase()+n.slice(1):"").join("");function dj(t,n){const{type:r,ext:o}=t;if(r==="folder")return!1;let c;return r&&r!=="file"&&Dw[r]?c=r:o?c=Dw[o]?o:"file":c="unknown",`https://cdn.svar.dev/icons/filemanager/vivid/${n}/${c}.svg`}const fj=d.forwardRef(function(t,n){const{data:r=[],mode:o="cards",drive:c=null,preview:u=!1,panels:f=null,activePanel:h=0,readonly:g=!1,menuOptions:y=cT,extraInfo:w=null,init:b=null,icons:x=dj,previews:A=null,...k}=t,N=d.useRef();N.current=k;const E=d.useMemo(()=>new lT(OS),[]),D=d.useMemo(()=>E.in,[E]),T=d.useRef(null);T.current===null&&(T.current=new DS((P,z)=>{const I="on"+uj(P);N.current&&N.current[I]&&N.current[I](z)}),D.setNext(T.current));const F=d.useMemo(()=>({getState:E.getState.bind(E),getReactiveState:E.getReactive.bind(E),getStores:()=>({data:E}),exec:D.exec,setNext:P=>(T.current=T.current.setNext(P),T.current),intercept:D.intercept.bind(D),on:D.on.bind(D),detach:D.detach.bind(D),getFile:E.getFile.bind(E),serialize:E.serialize.bind(E),templates:{preview:A||(()=>null),icon:x==="simple"?(()=>null):x}}),[E,D]),O=d.useRef(0);return d.useEffect(()=>{if(!O.current)b&&b(F);else{const P=E.getState();E.init({data:r,mode:o,drive:c,preview:u,panels:f||P.panels||[],activePanel:h})}O.current++},[E,r,o,c,u,f,h,b,F]),O.current===0&&E.init({data:r,mode:o,drive:c,preview:u,panels:f||[],activePanel:h}),d.useImperativeHandle(n,()=>({...F}),[F]),i.jsx(za.Provider,{value:F,children:i.jsx(Fv,{words:Pv,optional:!0,children:i.jsx(YR,{children:i.jsx(cj,{readonly:g,menuOptions:y,extraInfo:w})})})})});function mj({fonts:t=!0,children:n}){return n?i.jsx(vw,{fonts:t,children:n}):i.jsx(vw,{fonts:t})}Rv(ss);function $v(t,n){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Hub ${n} response.`);return t}function nm(t,n,r){const o=$v(t,r);if(!Array.isArray(o[n]))throw new Error(`Invalid Hub ${r} response: ${n} must be an array.`);return o[n]}function pj(t,n,r){const o=$v(t,r);if(!o[n]||typeof o[n]!="object"||Array.isArray(o[n]))throw new Error(`Invalid Hub ${r} response: ${n} must be an object.`);return o[n]}async function hj(t,n=!1){return nm(await rt(`/api/remote/filesystem/roots${n?"?refresh=1":""}`,void 0,t),"roots","filesystem roots")}async function yg(t,n){const r=await rt(`/api/remote/filesystem/entries?id=${encodeURIComponent(t)}`,void 0,n);return{folder:pj(r,"folder","filesystem entries"),entries:nm(r,"entries","filesystem entries")}}async function gj(t,n){return rt("/api/remote/filesystem/selection/scan",{method:"POST",body:JSON.stringify({itemIds:t})},n)}async function vj(t,n,r,o){return rt("/api/remote/files/from-hub",{method:"POST",body:JSON.stringify({itemIds:t,deviceIds:n,remoteDirectory:r})},o)}async function yj(t,n=!1){const r=await rt(`/api/remote/files/jobs?active=${n?"1":"0"}`,void 0,t);return{jobs:nm(r,"jobs","file transfer jobs")}}async function bj(t,n){return rt(`/api/remote/files/jobs/${encodeURIComponent(t)}`,void 0,n)}async function wj(t,n){return rt(`/api/remote/files/jobs/${encodeURIComponent(t)}/cancel`,{method:"POST"},n)}async function Iw(t){return nm(await rt("/api/remote/filesystem/shared-folders",void 0,t),"folders","shared folders")}async function xj(t,n){return rt("/api/remote/filesystem/shared-folders",{method:"POST",body:JSON.stringify({sourceId:t})},n)}async function Sj(t,n,r){return rt(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)},r)}async function Cj(t,n){return rt(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}`,{method:"DELETE"},n)}async function kj(t,n,r,o){const c=await rt(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}/sync`,{method:"POST",body:JSON.stringify({deviceIds:n,remoteDirectory:r})},o),u=$v(c,"shared folder sync");return{ok:u.ok===!0,jobs:nm(c,"jobs","shared folder sync"),files:Number(u.files||0),totalBytes:Number(u.totalBytes||0)}}function Mj(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 Lw(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,o=0;for(;r>=1024&&o<n.length-1;)r/=1024,o+=1;return`${r.toFixed(o===0||r>=100?0:1)} ${n[o]}`}function Np(t){return t.driveType==="network"?"network":t.driveType==="removable"?"removable":"local"}function Aj(t){const n=t.filter(r=>Np(r)==="local");return n.find(r=>/\bC:/i.test(`${r.name} ${r.displayPath||""}`))||n[0]||t[0]||null}function Nj({hubUrl:t,roots:n,loading:r,error:o,onRefreshRoots:c,onImportFiles:u,onImportFolder:f,onSelectionChange:h,onShareItem:g,onAddSyncFolder:y,onNotice:w}){const b=d.useRef(null),x=d.useRef("/"),A=d.useRef(0),k=d.useRef([]),N=d.useRef(new Map),[E,D]=d.useState(null),[T,F]=d.useState([]),[O,P]=d.useState([]),[z,I]=d.useState(0),[X,se]=d.useState(null),[Z,G]=d.useState(!1),[K,me]=d.useState(""),[V,ne]=d.useState(new Set),$=n.find(Y=>Y.id===E)||null,_=T[T.length-1]||null,ie=$?_?.svarPath||`/${$.name}`:null,be=ie;d.useEffect(()=>{k.current=T,x.current=be||"/"},[be,T]);const H=d.useMemo(()=>(N.current.clear(),!$||!be||T.length===0?[]:(T.forEach(Y=>N.current.set(Y.svarPath,Y.hubId)),[...T.map((Y,Se)=>({id:Y.svarPath,parent:Se===0?"/":T[Se-1].svarPath,type:"folder",name:Y.name,date:Y.modifiedAt?new Date(Y.modifiedAt):void 0,lazy:!1})),...O.map(Y=>{const Se=`${be}/${Y.name}`;return N.current.set(Se,Y.id),{id:Se,parent:be,name:Y.name,type:Y.type==="file"?"file":"folder",...Y.type==="file"?{size:Y.size}:{},date:Y.modifiedAt?new Date(Y.modifiedAt):void 0,lazy:Y.type!=="file"&&Y.hasChildren===!0,displayPath:Y.displayPath,locked:Y.locked,driveType:Y.driveType,totalBytes:Y.totalBytes,freeBytes:Y.freeBytes}})])),[$,O,be,T]),te=Y=>N.current.get(String(Y))||String(Y),le=Y=>Mj({...Y,id:te(String(Y.id)),parent:te(String(Y.parent))}),Ce=async(Y,Se)=>{const ye=Y[Y.length-1];if(!ye)return;const je=++A.current;G(!0),me("");try{const $e=await yg(ye.hubId,t);if(je!==A.current)return;if(!Array.isArray($e.entries))throw new Error("Invalid Hub filesystem entries response.");const B={...ye,displayPath:$e.folder.displayPath||ye.displayPath,modifiedAt:$e.folder.modifiedAt||ye.modifiedAt},lt=[...Y.slice(0,-1),B];k.current=lt,F(lt),P($e.entries),I(Nt=>Nt+1)}catch($e){if(je!==A.current)return;console.error("[LiveDesk FS] folder navigation failed",{folderId:ye.hubId,error:$e}),me($e instanceof Error?`${Se}: ${$e.message}`:`${Se}: Unable to read this folder.`)}finally{je===A.current&&G(!1)}},Ae=async Y=>{const Se={svarPath:`/${Y.name}`,hubId:Y.id,name:Y.name,displayPath:Y.displayPath,modifiedAt:Y.modifiedAt},ye=++A.current;D(Y.id),k.current=[Se],F([Se]),x.current=Se.svarPath,P([]),me(""),G(!0),se(Y.id),ne(je=>{const $e=new Set(je);return $e.delete(Y.id),$e});try{const je=await yg(Y.id,t);if(ye!==A.current)return;if(!Array.isArray(je.entries))throw new Error("Invalid Hub filesystem entries response.");const $e={...Se,displayPath:je.folder.displayPath||Se.displayPath,modifiedAt:je.folder.modifiedAt||Se.modifiedAt};k.current=[$e],F([$e]),P(je.entries),I(B=>B+1)}catch(je){if(ye!==A.current)return;console.error("[LiveDesk FS] getEntries failed",{rootId:Y.id,error:je}),ne($e=>new Set($e).add(Y.id)),me(je instanceof Error?`${Y.name}: ${je.message}`:`${Y.name}: Unable to read this drive.`),w(je instanceof Error?`${Y.name}: ${je.message}`:`${Y.name}: Unable to read this drive.`)}finally{ye===A.current&&(se(null),G(!1))}},_e=Y=>{const Se=k.current;Y<0||Y>=Se.length||Y===Se.length-1||Ce(Se.slice(0,Y+1),Se[Y].name)},ue=(Y,Se)=>{if(Y.type!=="folder")return;const ye=k.current,je=ye.findIndex(B=>B.svarPath===Se);if(je<0)return;const $e={svarPath:`${Se}/${Y.name}`,hubId:Y.id,name:Y.name,displayPath:Y.displayPath,modifiedAt:Y.modifiedAt};Ce([...ye.slice(0,je+1),$e],Y.name)},He=()=>_e(k.current.length-2),ze=Y=>{if(Y.key!=="Enter"&&Y.code!=="Enter"&&Y.code!=="NumpadEnter"||Y.target?.closest('button, input, textarea, [contenteditable="true"]'))return;const ye=b.current;if(!ye)return;const je=ye.getState().panels?.flatMap(B=>B.selected||[])||[];if(je.length!==1)return;const $e=ye.getFile(String(je[0]));$e?.type==="folder"&&(Y.preventDefault(),Y.stopPropagation(),ue(le($e),String($e.parent||x.current)))};d.useEffect(()=>{const Y=n.find(Se=>Se.id===E)||Aj(n);if(ne(Se=>new Set([...Se].filter(ye=>n.some(je=>je.id===ye)))),!Y){D(null),k.current=[],F([]),P([]);return}Ae(Y)},[n]);const et=Y=>{b.current=Y,Y.on("request-data",async({id:Se})=>{const ye=String(Se),je=te(ye);try{const $e=await yg(je,t);if(!Array.isArray($e.entries))throw new Error("Invalid Hub filesystem entries response.");const B=$e.entries.map(lt=>{const Nt=`${ye}/${lt.name}`;return N.current.set(Nt,lt.id),{id:Nt,parent:ye,name:lt.name,type:lt.type==="file"?"file":"folder",...lt.type==="file"?{size:lt.size}:{},date:lt.modifiedAt?new Date(lt.modifiedAt):void 0,lazy:lt.type!=="file"&&lt.hasChildren===!0,displayPath:lt.displayPath,locked:lt.locked,driveType:lt.driveType,totalBytes:lt.totalBytes,freeBytes:lt.freeBytes}});await Y.exec("provide-data",{id:ye,data:B})}catch($e){console.error("[LiveDesk FS] nested getEntries failed",{id:je,error:$e}),w($e instanceof Error?$e.message:"Unable to read this folder.")}}),Y.intercept("set-path",({id:Se})=>{const ye=String(Se),je=k.current.findIndex(B=>B.svarPath===ye);if(je>=0)return _e(je),!1;const $e=Y.getFile(ye);if($e?.type==="folder")return ue(le($e),String($e.parent||x.current)),!1}),Y.intercept("open-file",()=>!1),Y.on("select-file",()=>{window.setTimeout(()=>{const je=(Y.getState().panels?.flatMap($e=>$e.selected||[])||[]).map($e=>Y.getFile($e)).filter(Boolean).map($e=>le($e));h(je.map($e=>$e.id),je)},0)})},Xe=(Y,Se)=>{const ye=Se?le(Se):null,je=()=>{const $e=ye?.type==="file"?String(Se?.parent||x.current):String(Se?.id||x.current);b.current?.exec("request-data",{id:$e})};return Y==="body"?[{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:je},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>w("Select a file or folder to view its properties.")}]:Y==="multiselect"?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>{(b.current?.getState().panels?.flatMap(B=>B.selected||[])||[]).forEach(B=>{const lt=b.current?.getFile(B);lt&&g(le(lt))})}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:je}]:ye?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>g(ye)},...ye.type==="folder"?[{id:"sync",text:"Add folder to Sync",icon:"mdi mdi-folder-sync-outline",handler:()=>y(ye)}]:[],{id:"copy-path",text:"Copy path",icon:"mdi mdi-content-copy",handler:()=>{Sp(ye.displayPath||ye.name)}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:je},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>w(`${ye.name}
175
- ${ye.displayPath||""}`)}]:[]},Ze=async()=>{try{await c()}catch(Y){w(Y instanceof Error?Y.message:"Unable to refresh Hub drives.")}},Ue=[{id:"local",label:"Local drives",icon:qc,roots:n.filter(Y=>Np(Y)==="local")},{id:"removable",label:"Removable drives",icon:qC,roots:n.filter(Y=>Np(Y)==="removable")},{id:"network",label:"Network drives",icon:gv,roots:n.filter(Y=>Np(Y)==="network")}];return i.jsxs("section",{className:"hub-file-explorer-panel","aria-label":"Hub file explorer",children:[i.jsxs("div",{className:"hub-file-explorer-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Hub file explorer"}),i.jsxs("strong",{children:[i.jsx(qc,{size:16})," Browse files on this Hub"]})]}),i.jsxs("div",{className:"hub-file-explorer-heading-actions",children:[i.jsx("button",{className:"icon-button",onClick:u,title:"Import files from this browser",type:"button",children:i.jsx(Tx,{size:16})}),i.jsx("button",{className:"icon-button",onClick:f,title:"Import folder from this browser",type:"button",children:i.jsx(WC,{size:16})}),i.jsx("button",{className:"icon-button",onClick:()=>{Ze()},title:"Refresh drives",type:"button",children:i.jsx(hd,{size:16})})]})]}),r?i.jsxs("div",{className:"hub-file-explorer-state",children:[i.jsx(qc,{size:24}),i.jsx("strong",{children:"Connecting to LiveDesk Hub file system..."})]}):o?i.jsxs("div",{className:"hub-file-explorer-state error",role:"alert",children:[i.jsx(Ui,{size:24}),i.jsx("strong",{children:o})]}):i.jsxs("div",{className:"hub-file-explorer-content",children:[i.jsxs("aside",{className:"hub-file-explorer-drive-sidebar","aria-label":"Hub drives",children:[i.jsxs("div",{className:"hub-drive-sidebar-title",children:[i.jsx(qc,{size:15}),i.jsx("strong",{children:"This PC"})]}),Ue.map(Y=>Y.roots.length>0&&i.jsxs("section",{className:"hub-drive-group",children:[i.jsxs("h3",{children:[i.jsx(Y.icon,{size:13}),Y.label]}),i.jsx("div",{className:"hub-drive-list",children:Y.roots.map(Se=>{const ye=Y.icon,je=V.has(Se.id)||Se.locked===!0;return i.jsxs("button",{className:`hub-drive-item ${E===Se.id?"active":""} ${je?"unavailable":""}`,onClick:()=>{Ae(Se)},"aria-pressed":E===Se.id,type:"button",children:[i.jsx("span",{className:"hub-drive-item-icon",children:i.jsx(ye,{size:16})}),i.jsxs("span",{className:"hub-drive-item-copy",children:[i.jsx("strong",{children:Se.name}),i.jsx("small",{children:Se.displayPath||Se.name}),i.jsxs("em",{children:[Lw(Se.freeBytes||0)," free / ",Lw(Se.totalBytes||0)]})]}),X===Se.id?i.jsx(yi,{className:"hub-drive-item-status spin",size:15}):je?i.jsx(ub,{className:"hub-drive-item-status",size:15}):null]},Se.id)})})]},Y.id)),n.length===0&&i.jsxs("div",{className:"hub-drive-sidebar-empty",children:[i.jsx(Ui,{size:17}),i.jsx("span",{children:"No drives available."})]})]}),i.jsxs("div",{className:"hub-file-explorer-browser",children:[i.jsxs("div",{className:"hub-file-explorer-navigation",children:[i.jsx("nav",{className:"hub-file-explorer-breadcrumbs","aria-label":"Current Hub folder",children:T.map((Y,Se)=>i.jsxs("span",{className:"hub-file-explorer-breadcrumb-item",children:[Se>0&&i.jsx(vv,{size:13,"aria-hidden":"true"}),i.jsx("button",{className:`hub-file-explorer-breadcrumb ${Se===T.length-1?"current":""}`,onClick:()=>_e(Se),"aria-current":Se===T.length-1?"location":void 0,type:"button",children:Y.name})]},Y.svarPath))}),i.jsxs("div",{className:"hub-file-explorer-navigation-actions",children:[Z&&i.jsx(yi,{className:"hub-file-explorer-loading-icon spin",size:15,"aria-label":"Loading folder"}),i.jsx("button",{className:"icon-button",onClick:He,disabled:T.length<=1||Z,title:"Back to parent folder",type:"button",children:i.jsx(xx,{size:16})})]})]}),K&&i.jsxs("div",{className:"hub-file-explorer-folder-error",role:"alert",children:[i.jsx(ub,{size:15}),i.jsx("span",{children:K})]}),i.jsx("div",{className:"hub-file-explorer-svar",onKeyDownCapture:ze,children:i.jsx(mj,{fonts:!1,children:i.jsx(fj,{data:H,panels:ie?[{path:ie,selected:[]}]:void 0,readonly:!0,mode:"table",preview:!1,init:et,icons:"simple",menuOptions:Xe},`${$?.id||"no-root"}:${z}`)})})]})]})]})}class Tj 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?i.jsxs("section",{className:"file-share-error-boundary",role:"alert",children:[i.jsx($p,{size:24}),i.jsx("strong",{children:"Share Files could not be opened."}),i.jsx("span",{children:this.state.error.message||"An unexpected file explorer error occurred."}),i.jsxs("button",{className:"text-button",onClick:this.props.onRetry,type:"button",children:[i.jsx(hd,{size:15})," Retry"]})]}):this.props.children}}function Rj(t){return t.deviceName||t.hostname||t.deviceId}function jj({devices:t,mode:n,selectedIds:r,onModeChange:o,onToggle:c}){const u=new Set(r);return i.jsxs("section",{className:"distribution-targets",children:[i.jsxs("div",{className:"file-share-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Target"}),i.jsx("strong",{children:n==="all"?`${t.length} connected`:`${r.length} selected`})]}),i.jsxs("div",{className:"file-share-tabs compact","aria-label":"File transfer targets",children:[i.jsxs("button",{className:n==="all"?"active":"",onClick:()=>o("all"),type:"button",children:[i.jsx(Kf,{size:14})," All connected"]}),i.jsxs("button",{className:n==="selected"?"active":"",onClick:()=>o("selected"),type:"button",children:[i.jsx(Ba,{size:14})," Selected"]})]})]}),i.jsx("div",{className:"file-share-device-list","aria-label":"Connected Client targets",children:t.length===0?i.jsx("div",{className:"file-share-empty-inline",children:"No connected Clients."}):t.map(f=>{const h=n==="all"||u.has(f.deviceId);return i.jsxs("label",{className:`file-share-device-option ${h?"selected":""}`,children:[i.jsx("input",{type:"checkbox",checked:h,disabled:n==="all",onChange:()=>c(f.deviceId)}),i.jsx(Ba,{size:20,"aria-hidden":"true"}),i.jsxs("span",{children:[i.jsx("strong",{children:Rj(f)}),i.jsxs("small",{children:["Slot ",f.slotNumber?String(f.slotNumber).padStart(3,"0"):"-"," / ",f.platform||"unknown OS"]})]}),i.jsx(Oa,{size:17,"aria-hidden":"true"})]},f.deviceId)})})]})}function Ej(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,o=0;for(;r>=1024&&o<n.length-1;)r/=1024,o+=1;return`${r.toFixed(o===0||r>=100?0:1)} ${n[o]}`}function Dj({folders:t,loading:n,busy:r,canSync:o,onSyncAll:c,onSync:u,onToggleAuto:f,onRemove:h,onAdd:g}){return i.jsxs("section",{className:"file-share-sync-panel",children:[i.jsxs("div",{className:"file-share-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Hub folders"}),i.jsx("strong",{children:"Continuous sync"})]}),i.jsxs("button",{className:"text-button compact",onClick:c,disabled:r||!o||t.length===0,type:"button",children:[i.jsx(xp,{size:15})," ",r?"Syncing":"Sync all"]})]}),n?i.jsx("div",{className:"file-share-empty-state",children:"Loading Hub sync folders..."}):t.length===0?i.jsxs("button",{className:"file-share-empty-state interactive",onClick:g,type:"button",children:[i.jsx(xp,{size:28}),i.jsx("strong",{children:"Add a selected Hub folder"}),i.jsx("span",{children:"Hub keeps the manifest and can sync while this browser is closed."})]}):i.jsx("div",{className:"file-share-sync-list",children:t.map(y=>i.jsxs("article",{className:`file-share-sync-row state-${y.status}`,children:[i.jsx("div",{className:"file-share-sync-icon",children:i.jsx(xp,{size:19})}),i.jsxs("div",{className:"file-share-sync-info",children:[i.jsx("strong",{children:y.name}),i.jsx("span",{children:y.displayPath}),i.jsxs("small",{children:[y.fileCount," files / ",Ej(y.totalBytes)," · ",y.lastSyncedAt?`Last sync ${Ox(y.lastSyncedAt)} ago`:y.message||"Not synced yet"]})]}),i.jsxs("label",{className:"file-share-auto-sync",children:[i.jsx("input",{type:"checkbox",checked:y.autoSync,onChange:()=>f(y)}),i.jsx("span",{children:"Auto"})]}),i.jsxs("button",{className:"text-button compact",onClick:()=>u(y),disabled:r||!o||y.status==="syncing",type:"button",children:[i.jsx(hd,{size:14})," Sync now"]}),i.jsx("button",{className:"icon-button",onClick:()=>h(y),title:"Remove sync folder",type:"button",children:i.jsx(Rx,{size:15})})]},y.id))})]})}function Ij(t){const r=(t.targetMode==="all"?t.devices.map(o=>o.deviceId):t.selectedTargetIds).length>0;return i.jsxs("aside",{className:"file-share-distribution-panel",children:[i.jsxs("div",{className:"file-share-distribution-head",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Distribution"}),i.jsx("strong",{children:"Hub → Clients"})]}),i.jsx(Vf,{size:18})]}),i.jsxs("div",{className:"file-share-tabs",role:"tablist","aria-label":"Distribution mode",children:[i.jsx("button",{className:t.tab==="send"?"active":"",onClick:()=>t.onTabChange("send"),role:"tab","aria-selected":t.tab==="send",type:"button",children:"Send"}),i.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"?i.jsxs(i.Fragment,{children:[i.jsx(jj,{devices:t.devices,mode:t.targetMode,selectedIds:t.selectedTargetIds,onModeChange:t.onTargetModeChange,onToggle:t.onTargetToggle}),i.jsxs("label",{className:"file-share-destination",children:[i.jsx("span",{children:"Destination folder"}),i.jsxs("div",{children:[i.jsx(dd,{size:15}),i.jsx("input",{value:t.remoteDirectory,onChange:o=>t.onRemoteDirectoryChange(o.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),i.jsx("small",{children:"Blank uses Desktop/LiveDeskFiles."})]}),i.jsxs("div",{className:"file-share-selection-summary",children:[i.jsx("span",{children:"Selected"}),i.jsx("strong",{children:t.selectedSummary})]}),i.jsxs("button",{className:"file-share-share-button",onClick:t.onShare,disabled:!t.canShare,type:"button",children:[i.jsx(Vf,{size:17})," Share selected"]}),i.jsxs("button",{className:"file-share-secondary-button",onClick:t.onAddSync,disabled:!t.canAddSync,type:"button",children:[i.jsx(dd,{size:16})," Add selected folder to Sync"]})]}):i.jsx(Dj,{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 Lj(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,o=0;for(;r>=1024&&o<n.length-1;)r/=1024,o+=1;return`${r.toFixed(o===0||r>=100?0:1)} ${n[o]}`}function _w(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(cv(t.state)?100:99,n))}function Fw(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 cv(t){return["completed","partially-failed","failed","cancelled"].includes(t)}function _j({hubUrl:t,devices:n,localFeatureAccess:r,upgradeNotice:o,remoteDirectory:c,onRemoteDirectoryChange:u,targetMode:f,selectedTargetIds:h,onTargetModeChange:g,onTargetToggle:y,filePickerRef:w,folderPickerRef:b,onBrowserFileImport:x,onBrowserFolderImport:A,onNotice:k,onTransferChange:N}){const E=Array.isArray(n)?n:[],[D,T]=d.useState([]),[F,O]=d.useState(!0),[P,z]=d.useState(""),[I,X]=d.useState([]),[se,Z]=d.useState([]),[G,K]=d.useState(null),[me,V]=d.useState(!1),[ne,$]=d.useState([]),[_,ie]=d.useState(!0),[be,H]=d.useState(!1),[te,le]=d.useState("send"),[Ce,Ae]=d.useState([]),_e=d.useRef(new Set),ue=d.useRef(!1),He=d.useMemo(()=>f==="all"?E.map(ke=>ke.deviceId):h.filter(ke=>E.some(qe=>qe.deviceId===ke)),[E,h,f]),ze=Ce.find(ke=>!cv(ke.state)),et=se.length===1&&se[0].type==="folder"?se[0]:null,Xe=se.length===0?"Select files or folders from the Hub explorer.":me?"Calculating selection size...":G?`${G.files} files, ${G.folders} folders · ${Lj(G.totalBytes)}`:`${se.length} item${se.length===1?"":"s"} selected`,Ze=ke=>{N({id:ke.jobId,state:ke.state,progress:_w(ke),message:Fw(ke)})},Ue=d.useCallback(async()=>{const ke=await hj(t,!0);return T(ke),z(""),ke},[t]),Y=async()=>{if(!ue.current){ue.current=!0;try{const qe=(await yj(t,!0)).jobs||[],Ye=await Promise.all([..._e.current].map(async pe=>{try{return await bj(pe,t)}catch{return null}})),_t=[...qe,...Ye.filter(Boolean)],tt=[...new Map(_t.map(pe=>[pe.jobId,pe])).values()];Ae(tt),tt.forEach(Ze),tt.filter(pe=>cv(pe.state)).forEach(pe=>_e.current.delete(pe.jobId))}catch{}finally{ue.current=!1}}};d.useEffect(()=>{let ke=!0;O(!0),z(""),Promise.all([Ue(),Iw(t).then(Ye=>{ke&&$(Ye)})]).catch(Ye=>{ke&&(z(Ye instanceof Error?"Hub file system is unavailable. Make sure LiveDesk Hub is running on this computer.":"Hub file system is unavailable."),k(Ye instanceof Error?Ye.message:"Hub file system is unavailable."))}).finally(()=>{ke&&(O(!1),ie(!1))}),Y();const qe=window.setInterval(()=>{Y()},800);return()=>{ke=!1,window.clearInterval(qe)}},[t,Ue]),d.useEffect(()=>{if(I.length===0){K(null);return}let ke=!1;return V(!0),gj(I,t).then(qe=>{ke||K(qe)}).catch(qe=>{ke||k(qe instanceof Error?qe.message:"Unable to calculate selected size.")}).finally(()=>{ke||V(!1)}),()=>{ke=!0}},[t,I.join("|")]);const Se=(ke,qe)=>{X(ke),Z(qe)},ye=ke=>{ke.forEach(qe=>_e.current.add(qe.jobId)),Ae(qe=>[...new Map([...qe,...ke].map(Ye=>[Ye.jobId,Ye])).values()]),ke.forEach(Ze)},je=async()=>{if(!r){k(o);return}if(I.length===0){k("Select files or folders from the Hub explorer.");return}if(He.length===0){k("Choose at least one connected Client.");return}if(ze){k("A Hub transfer is already running.");return}try{const ke=await vj(I,He,c.trim(),t);_e.current.add(ke.jobId),k("Hub transfer queued."),await Y()}catch(ke){k(ke instanceof Error?ke.message:"Unable to start Hub transfer.")}},$e=async ke=>{const qe=ke||et;if(!qe||qe.type!=="folder"){k("Select one folder to add it to Sync.");return}try{const Ye=await xj(qe.id,t);$(_t=>[..._t.filter(tt=>tt.id!==Ye.folder.id),Ye.folder]),le("sync"),k(`${qe.name} is ready for Hub sync.`)}catch(Ye){k(Ye instanceof Error?Ye.message:"Unable to add the Hub folder to Sync.")}},B=async ke=>{if(He.length===0){k("Choose at least one connected Client.");return}H(!0),$(qe=>qe.map(Ye=>Ye.id===ke.id?{...Ye,status:"syncing"}:Ye));try{const qe=await kj(ke.id,He,c.trim(),t);ye(qe.jobs||[]),k(qe.jobs?.length?"Hub sync queued.":"No changed files to sync.");const Ye=await Iw(t);$(Ye)}catch(qe){k(qe instanceof Error?qe.message:"Unable to sync the Hub folder."),$(Ye=>Ye.map(_t=>_t.id===ke.id?{..._t,status:"error",message:"Sync failed"}:_t))}finally{H(!1)}},lt=async()=>{H(!0);try{for(const ke of ne)await B(ke)}finally{H(!1)}},Nt=async ke=>{try{const qe=await Sj(ke.id,{autoSync:!ke.autoSync},t);$(Ye=>Ye.map(_t=>_t.id===ke.id?qe.folder:_t))}catch(qe){k(qe instanceof Error?qe.message:"Unable to update auto sync.")}},Ht=async ke=>{try{await Cj(ke.id,t),$(qe=>qe.filter(Ye=>Ye.id!==ke.id))}catch(qe){k(qe instanceof Error?qe.message:"Unable to remove the sync folder.")}};return i.jsxs("section",{className:"livedesk-file-explorer",children:[i.jsx("input",{ref:w,className:"hidden-file-input",type:"file",multiple:!0,onChange:ke=>{ke.currentTarget.files&&x(ke.currentTarget.files),ke.currentTarget.value=""}}),i.jsx("input",{ref:b,className:"hidden-file-input",type:"file",multiple:!0,webkitdirectory:"",directory:"",onChange:ke=>{ke.currentTarget.files&&A(ke.currentTarget.files),ke.currentTarget.value=""}}),i.jsx("div",{className:"file-share-workspace",children:i.jsxs(Tj,{onRetry:()=>window.location.reload(),children:[i.jsx(Nj,{hubUrl:t,roots:D,loading:F,error:P,onRefreshRoots:Ue,onImportFiles:()=>w.current?.click(),onImportFolder:()=>b.current?.click(),onSelectionChange:Se,onShareItem:ke=>{X([ke.id]),Z([ke]),le("send")},onAddSyncFolder:ke=>{X([ke.id]),Z([ke]),$e(ke)},onNotice:k}),i.jsx(Ij,{devices:E,targetMode:f,selectedTargetIds:h,onTargetModeChange:g,onTargetToggle:y,remoteDirectory:c,onRemoteDirectoryChange:u,selectedEntries:se,selectedSummary:Xe,canShare:r&&!ze&&I.length>0&&He.length>0&&!me,onShare:()=>{je()},canAddSync:!!et,onAddSync:()=>{$e()},tab:te,onTabChange:le,folders:ne,foldersLoading:_,syncBusy:be,onSyncAll:()=>{lt()},onSync:ke=>{B(ke)},onToggleAuto:ke=>{Nt(ke)},onRemove:ke=>{Ht(ke)},onAddFolder:()=>{$e()}})]})}),ze&&i.jsx("footer",{className:"file-share-workspace-footer",children:i.jsxs("span",{children:[Fw(ze)," · ",_w(ze),"% ",i.jsx("button",{className:"icon-button",onClick:()=>{wj(ze.jobId,t).then(ke=>{Ae(qe=>qe.map(Ye=>Ye.jobId===ke.jobId?ke:Ye)),Ze(ke)})},title:"Cancel transfer",type:"button",children:i.jsx(vr,{size:14})})]})})]})}const Fj=d.forwardRef(function({value:n,onChange:r,onSubmit:o,onOpenSuggestedTasks:c,suggestedOpen:u=!1,suggestedTaskCount:f,disabled:h=!1,placeholder:g="Ask LiveDesk to work across your machines...",compact:y=!1},w){return i.jsxs("form",{className:"agents-composer",onSubmit:b=>{b.preventDefault(),o()},children:[i.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:c,disabled:h,children:i.jsx(GC,{size:17})}),i.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}),i.jsxs("button",{className:"agents-run-button",type:"submit",disabled:h||!n.trim(),children:[h?i.jsx(yi,{className:"spin",size:16}):i.jsx(Vf,{size:16}),h?"Running":"Run"]})]})}),Pj=["read","processControl","serviceControl","applicationControl","fileRead","fileWrite","fileDelete","shell","script","softwareInstall","network","systemPower","systemConfiguration","userAccount"];function Op(t){return t.deviceName?.trim()||t.hostname?.trim()||t.deviceId}function Bp(t){return t.connected!==!0?!1:t.synthetic===!0?!0:!t.channels||t.channels.control===!0}function Oj(t){return t==="running"||t==="completed"||t==="failed"||t==="cancelled"?t:"queued"}function Bj(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 Hj(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Rs(t){return typeof t=="number"&&Number.isFinite(t)?t:null}function mp(t){const n=Rs(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 zj(t){const n=Rs(t);return n===null?"":`${Math.round((n<=1?n:n/100)*100)}%`}function $j(t){return!t||/^(?:[\w .-]+ )?collected(?:\.)?$/i.test(t.trim())?"":t.trim()}function Hp(t,n){if(n.error)return n.error;const r=Hj(n.data),o=$j(n.result||"");if(!r)return o||n.stage||n.status;if(t==="system.health"){const c=typeof r.machine=="string"?r.machine:"",u=mp(r.freeMemoryBytes),f=mp(r.totalMemoryBytes),h=Rs(r.totalMemoryBytes)&&Rs(r.freeMemoryBytes)!==null?`${Math.round(Rs(r.freeMemoryBytes)/Rs(r.totalMemoryBytes)*100)}% RAM free`:"";return[c,u&&f?`RAM ${u}/${f}`:"",h,typeof r.platform=="string"?r.platform:""].filter(Boolean).join(" · ")||o||n.status}if(t==="disk.status"){const c=typeof r.root=="string"?r.root:"",u=mp(r.freeBytes),f=Rs(r.totalBytes)&&Rs(r.freeBytes)!==null?`${Math.round(Rs(r.freeBytes)/Rs(r.totalBytes)*100)}% free`:"";return[c,u&&`${u} free`,f].filter(Boolean).join(" · ")||o||n.status}if(t==="gpu.status"){const c=typeof r.name=="string"&&r.name?r.name:"No GPU detected",u=zj(r.usageRatio),f=Rs(r.temperatureC)!==null?`${Math.round(Rs(r.temperatureC))}°C`:"",h=mp(r.freeMemoryBytes);return[c,u&&`GPU ${u}`,f,h&&`${h} free`].filter(Boolean).join(" · ")||o||n.status}if(t==="process.list"){const c=Rs(r.count);return c!==null?`${c} matching process${c===1?"":"es"}`:o||n.status}if(t==="network.status"){const c=Array.isArray(r.adapters)?r.adapters.length:null;return c!==null?`${c} active adapter${c===1?"":"s"}`:o||n.status}return o||n.stage||n.status}function Pw(t,n){const r=Hp(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 Uj({state:t,operation:n}){const r=t.status==="completed"?qi:t.status==="failed"||t.status==="cancelled"?vr:t.status==="running"?yi:jx,o=t.status==="running"?t.stage||"Working":t.status==="completed"?n?Hp(n,t):t.result||"Completed":t.status==="failed"?t.error||"Failed":t.status==="cancelled"?"Cancelled":"Queued";return i.jsxs("div",{className:`agent-target-row status-${t.status}`,"data-agent-target-id":t.deviceId,children:[i.jsx("span",{className:"agent-target-status","aria-hidden":"true",children:i.jsx(r,{size:15})}),i.jsx("strong",{children:t.deviceName}),i.jsx("span",{className:"agent-target-state",children:t.status[0].toUpperCase()+t.status.slice(1)}),i.jsx("small",{children:o})]})}function qj({operation:t,states:n,status:r,onCancel:o,onRetry:c,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(F=>F.status==="completed").length,failed:n.filter(F=>F.status==="failed").length,running:n.filter(F=>F.status==="running").length,queued:n.filter(F=>F.status==="queued").length,cancelled:n.filter(F=>F.status==="cancelled").length}),[n]),x=n.filter(F=>Pw(t,F)),A=x.filter(F=>F.status==="completed").length,k=b.failed>0,N=x.length>0,E=n.filter(F=>y==="issues"?Pw(t,F):y==="running"?F.status==="running"||F.status==="queued":y==="completed"?F.status==="completed":y==="failed"?F.status==="failed":!0),D=N&&!f||r==="completed-with-failures"?"Completed with issues":r[0]?.toUpperCase()+r.slice(1),T=n.filter(F=>F.status==="completed").map(F=>Hp(t,F)).filter(Boolean).filter((F,O,P)=>P.indexOf(F)===O).slice(0,2);return i.jsxs("section",{className:"agent-task-block","aria-label":"Task execution",children:[i.jsxs("div",{className:"agent-task-head",children:[i.jsxs("div",{children:[i.jsx("span",{children:"LiveDesk Agent"}),i.jsx("strong",{children:Bj(t)})]}),i.jsx("span",{className:`agent-task-status status-${N?"completed-with-failures":r}`,children:D})]}),i.jsxs("div",{className:"agent-task-summary","aria-label":"Task summary",children:[i.jsxs("strong",{children:[b.total," targets"]}),i.jsxs("span",{className:"summary-completed",children:[b.completed," completed"]}),b.running>0&&i.jsxs("span",{className:"summary-running",children:[b.running," running"]}),b.queued>0&&i.jsxs("span",{children:[b.queued," queued"]}),k&&i.jsxs("span",{className:"summary-failed",children:[b.failed," failed"]}),A>0&&i.jsxs("span",{className:"summary-cancelled",children:[A," warning"]}),b.cancelled>0&&i.jsxs("span",{className:"summary-cancelled",children:[b.cancelled," cancelled"]})]}),T.length>0&&i.jsxs("div",{className:"agent-task-result-preview",title:T.join(" · "),children:[i.jsx("span",{children:"Result"}),T.join(" · ")]}),i.jsx("div",{className:"agent-target-chips","aria-label":"Target status overview",children:n.map((F,O)=>{const P=F.status==="completed"?"✓":F.status==="failed"?"×":F.status==="cancelled"?"!":F.status==="running"?"…":"·";return i.jsxs("span",{className:`agent-target-chip status-${F.status}`,title:`${F.deviceName}: ${Hp(t,F)}`,"aria-label":`${O+1}. ${F.deviceName}: ${F.status}`,children:[i.jsx("b",{children:String(O+1).padStart(2,"0")}),i.jsx("span",{children:P})]},F.deviceId)})}),n.length>0&&i.jsx("div",{className:"agent-task-details-toggle",children:i.jsxs("button",{type:"button",onClick:()=>g(F=>!F),"aria-expanded":h,children:[h?i.jsx(VC,{size:14}):i.jsx(Ex,{size:14}),h?"Hide details":"Show details"]})}),h&&i.jsxs("div",{className:"agent-task-details",children:[i.jsx("div",{className:"agent-task-filters",role:"tablist","aria-label":"Task result filter",children:["all","issues","running","completed","failed"].map(F=>i.jsx("button",{className:y===F?"active":"",onClick:()=>w(F),role:"tab","aria-selected":y===F,type:"button",children:F==="all"?"All":F==="issues"?"Issues only":F[0].toUpperCase()+F.slice(1)},F))}),i.jsx("div",{className:"agent-task-rows",children:E.length>0?E.map(F=>i.jsx(Uj,{operation:t,state:F},F.deviceId)):i.jsx("small",{className:"agent-task-no-results",children:"No targets match this filter."})})]}),(f||k)&&i.jsxs("div",{className:"agent-task-actions",children:[f&&o&&i.jsxs("button",{onClick:o,disabled:u,type:"button",children:[i.jsx(KC,{size:14})," Cancel"]}),!f&&k&&c&&i.jsxs("button",{onClick:c,disabled:u,type:"button",children:[i.jsx(Lg,{size:14})," Retry failed"]})]})]})}function Wj(t){try{return JSON.stringify(t,null,2).slice(0,6e3)}catch{return"{}"}}function Gj({approval:t,busy:n=!1,onApprove:r,onReject:o}){return i.jsxs("article",{className:"agent-approval-card","aria-label":"Agent approval required",children:[i.jsxs("div",{className:"agent-approval-head",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Approval required"}),i.jsx("strong",{children:t.toolName})]}),i.jsx("span",{className:`agent-approval-risk risk-${t.risk}`,children:t.risk})]}),i.jsx("p",{children:t.description}),i.jsx("pre",{children:Wj(t.arguments)}),i.jsxs("small",{children:["Permission: ",t.permissionMode," · Scope: selected devices only · Expires in 5 minutes"]}),i.jsxs("div",{className:"agent-approval-actions",children:[i.jsxs("button",{className:"reject",disabled:n,onClick:o,type:"button",children:[i.jsx(vr,{size:14})," Reject"]}),i.jsxs("button",{disabled:n,onClick:()=>r("once"),type:"button",children:[i.jsx(qi,{size:14})," Once"]}),i.jsx("button",{disabled:n,onClick:()=>r("same-action-this-run"),type:"button",children:"Allow same action"}),i.jsx("button",{disabled:n,onClick:()=>r("category-this-run"),type:"button",children:"Allow category"})]}),i.jsxs("div",{className:"agent-approval-scope",children:[i.jsx($p,{size:13})," Approval is bound to this run, tool, arguments, selected devices, and policy hash."]})]})}function Vj(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 Kj({items:t,onCancel:n,onRetry:r,busyBatchId:o,approvals:c,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),x=d.useRef(!0),A=d.useRef(""),k=t[t.length-1];return d.useLayoutEffect(()=>{const N=b.current;N&&(k?.type==="user"&&k.id!==A.current&&(x.current=!0),A.current=k?.id||"",x.current&&(N.scrollTop=N.scrollHeight))},[c,t,k?.id,k?.type,g?.message,g?.stage]),i.jsxs("section",{className:"agents-conversation","aria-live":"polite",ref:b,onScroll:N=>{const E=N.currentTarget;x.current=E.scrollHeight-E.scrollTop-E.clientHeight<72},children:[c.filter(N=>N.status==="pending").map(N=>i.jsx(Gj,{approval:N,busy:h===N.approvalId,onApprove:E=>u(N,E),onReject:()=>f(N)},N.approvalId)),t.length===0&&i.jsxs("div",{className:"agents-empty-conversation",children:[i.jsx("strong",{children:y}),i.jsx("span",{children:w})]}),t.map(N=>{if(N.type==="task"){const E=N;return i.jsx(qj,{operation:E.operation,states:E.states,status:E.status,onCancel:()=>n(E.batchId,E.agentRunId),onRetry:()=>r(E.batchId),busy:o===E.batchId},E.id)}return i.jsxs("article",{className:`agents-message ${N.type}`,children:[i.jsx("span",{children:N.type==="user"?"You":"LiveDesk Agent"}),i.jsx("p",{children:N.text})]},N.id)}),g&&i.jsxs("article",{className:"agents-message agent agents-progress-message",role:"status",children:[i.jsxs("span",{children:[i.jsx(yi,{"aria-hidden":"true",size:15}),Vj(g.stage)]}),i.jsx("p",{children:g.message})]})]})}const Ow=["Recommended","Health & capacity","Processes & services","Files & configuration","Software & automation","Network & connectivity","Power & maintenance","Troubleshooting & recovery"],ia=["windows","macos","linux"],Bl={"system.health":{label:"system health",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ia},"gpu.status":{label:"GPU status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ia},"disk.status":{label:"disk status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ia},"process.list":{label:"process inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ia},"service.status":{label:"service inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ia},"diagnostics.collect":{label:"diagnostics collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ia},"process.control":{label:"process control",permissionCategory:"processControl",readOnly:!1,risk:"high",supportedPlatforms:ia},"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:ia},"application.close":{label:"application close",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:ia},"file.read":{label:"file reading",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:ia},"file.write":{label:"file writing",permissionCategory:"fileWrite",readOnly:!1,risk:"high",supportedPlatforms:ia},"file.delete":{label:"file deletion",permissionCategory:"fileDelete",readOnly:!1,risk:"critical",supportedPlatforms:ia},"file.list":{label:"directory listing",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:ia},"command.run":{label:"command execution",permissionCategory:"shell",readOnly:!1,risk:"critical",supportedPlatforms:ia},"script.run":{label:"script execution",permissionCategory:"script",readOnly:!1,risk:"high",supportedPlatforms:ia},"software.install":{label:"software installation",permissionCategory:"softwareInstall",readOnly:!1,risk:"high",supportedPlatforms:ia},"network.status":{label:"network inspection",permissionCategory:"network",readOnly:!0,risk:"low",supportedPlatforms:ia},"system.power":{label:"power control",permissionCategory:"systemPower",readOnly:!1,risk:"critical",supportedPlatforms:ia},"system.configure":{label:"system configuration",permissionCategory:"systemConfiguration",readOnly:!1,risk:"critical",supportedPlatforms:ia},"logs.collect":{label:"log collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ia}};new Set(Object.keys(Bl));const Qj={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","문제해결","복구","장애"]},Bw=["low","medium","high","critical"];function Yj(t){return t.reduce((n,r)=>{const o=Bl[r].risk;return Bw.indexOf(o)>Bw.indexOf(n)?o:n},"low")}function Xj(t){return ia.filter(n=>t.every(r=>Bl[r].supportedPlatforms.includes(n)))}function ot(t,n,r,o,c,u,f={}){const h=f.description||o,g=c.flatMap(w=>w.split(".")),y=[...new Set([...Qj[n],...u,...g])];return{id:t,category:n,title:r,prompt:o,description:h,requiredOperations:c,risk:f.risk||Yj(c),targetSupport:f.targetSupport||"single-or-multiple",supportedPlatforms:f.supportedPlatforms||Xj(c),keywords:y,recommended:f.recommended??!1,enabled:!0}}const a0=[ot("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}),ot("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}),ot("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}),ot("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}),ot("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}),ot("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}),ot("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}),ot("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}),ot("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","높은 사용량"]),ot("health-uptime","Health & capacity","Review Client uptime","Show uptime, boot time, and current system health for the target Clients.",["system.health"],["uptime","boot","가동시간"]),ot("health-gpu-temperature","Health & capacity","Check GPU temperature","Check GPU temperature and thermal warnings on the current targets.",["gpu.status"],["thermal","temperature","발열"]),ot("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"]),ot("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","디스크"]),ot("health-gpu-compare","Health & capacity","Compare GPU capacity","Compare GPU model, memory, temperature, and utilization across the current targets.",["gpu.status"],["compare","graphics","capacity"]),ot("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","경고"]),ot("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"]),ot("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","실행 중"]),ot("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"]),ot("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"}),ot("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"}),ot("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"}),ot("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"}),ot("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","서비스 상태"]),ot("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"}),ot("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"}),ot("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","구성"]),ot("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"]),ot("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"}),ot("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"}),ot("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"]),ot("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"}),ot("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"}),ot("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"]}),ot("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"]}),ot("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"]}),ot("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"}),ot("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"}),ot("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"}),ot("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"]),ot("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"}),ot("network-adapter-status","Network & connectivity","Check network adapters","Show adapter state, address, and link information for the current targets.",["network.status"],["adapter","ethernet","wifi","네트워크 상태"]),ot("network-disconnected","Network & connectivity","Find disconnected targets","Find current targets with disconnected or degraded network adapters.",["network.status"],["disconnected","offline","연결 끊김"]),ot("network-link-speed","Network & connectivity","Check link speed","Report network link speed and duplex information for the current targets.",["network.status"],["speed","bandwidth","duplex"]),ot("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"]),ot("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"]),ot("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"]),ot("network-compare","Network & connectivity","Compare target connectivity","Compare adapter state, addresses, and link speed across the current targets.",["network.status"],["compare","inventory","connectivity"]),ot("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"]),ot("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"}),ot("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"}),ot("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"}),ot("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"}),ot("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"}),ot("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"}),ot("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"}),ot("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"}),ot("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"}),ot("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"}),ot("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"}),ot("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"}),ot("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"}),ot("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"}),ot("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"}),ot("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","장애 보고서"])],bg={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 Zj(t,n){return t==="safe-auto"?bg:t==="full-access"?{...bg,processControl:"allow",serviceControl:"allow",applicationControl:"allow",fileDelete:"allow",shell:"allow",script:"allow",softwareInstall:"allow",systemPower:"allow",systemConfiguration:"allow"}:t==="custom"&&n?n:{...bg,processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileWrite:"ask",network:"ask"}}function Jj(t,n,r){const o=Zj(n,r),c=t.requiredOperations.map(u=>o[Bl[u].permissionCategory]);if(c.includes("deny")){const u=t.requiredOperations.find(f=>o[Bl[f].permissionCategory]==="deny");return{state:"blocked",label:"Blocked",reason:`This task requires ${Bl[u].label}, which is blocked by the current permission policy.`}}return c.includes("ask")?{state:"approval",label:"Approval required",reason:"This task requires approval before the requested changes can reach a Client."}:t.requiredOperations.every(u=>Bl[u].readOnly)?{state:"read-only",label:"Read only"}:n==="full-access"?{state:"full-access",label:"Full Access"}:{state:"auto",label:"Auto allowed"}}function eE(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 tE(t,n,r){const o=new Set(r);return t.filter(c=>c.connected&&(n==="all"||n==="auto"||o.has(c.deviceId)))}function nE(t,n){const r=eE(t.platform);if(!r||!n.supportedPlatforms.includes(r))return!1;const o=t.capabilities?.agentTools;return!Array.isArray(o)||o.length===0?n.requiredOperations.every(c=>Bl[c].readOnly):n.requiredOperations.every(c=>o.includes(c))}function r0(t,n,r,o,c,u){const f=Jj(t,c,u),h=tE(n,r,o),g=h.map(A=>A.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(A=>nE(A,t)),b=w.map(A=>A.deviceId),x=g.filter(A=>!b.includes(A));return w.length===0?{...y,unsupportedDeviceIds:x,reason:"No current target supports the required platform and client capabilities."}:{...y,available:!0,availableDeviceIds:b,unsupportedDeviceIds:x}}function aE(t,n,r,o,c,u){return t.filter(f=>f.enabled&&r0(f,n,r,o,c,u).available).length}const wg="livedesk.agentPromptRecent",xg="livedesk.agentPromptFavorites",rE={Recommended:zl,"Health & capacity":Vc,"Processes & services":ZC,"Files & configuration":XC,"Software & automation":Nx,"Network & connectivity":gv,"Power & maintenance":Aa,"Troubleshooting & recovery":YC};function Hw(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 pp(t,n){try{window.localStorage.setItem(t,JSON.stringify(n))}catch{}}function Sg(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 sE(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 iE(t,n,r){if(!r.trim())return!0;const o=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(o)}function oE(t){return`permission-${t}`}function lE(t){return t==="low"?"Low risk":t==="medium"?"Medium risk":t==="high"?"High risk":"Critical risk"}function cE(t){return t==="windows"?"Windows":t==="macos"?"macOS":"Linux"}function uE({devices:t,targetMode:n,selectedIds:r,permissionMode:o,customCategories:c,onSelectPrompt:u,onClose:f}){const[h,g]=d.useState(""),[y,w]=d.useState("all"),[b,x]=d.useState(()=>Hw(wg)),[A,k]=d.useState(()=>Hw(xg)),[N,E]=d.useState(0),[D,T]=d.useState(""),F=d.useRef(null),O=d.useRef(null),P=d.useMemo(()=>a0.filter(ne=>ne.enabled),[]),z=d.useMemo(()=>new Map(P.map(ne=>[ne.id,r0(ne,t,n,r,o,c)])),[c,t,o,r,n,P]),I=d.useMemo(()=>[...z.values()].filter(ne=>ne.available).length,[z]),X=d.useMemo(()=>t.filter(ne=>ne.connected&&(n==="all"||n==="auto"||r.includes(ne.deviceId))).length,[t,r,n]),se=d.useMemo(()=>{const ne=P.filter($=>iE($,z.get($.id),h));return y==="recent"?b.map($=>ne.find(_=>_.id===$)).filter($=>!!$):y==="favorites"?A.map($=>ne.find(_=>_.id===$)).filter($=>!!$):y==="all"?ne:ne.filter($=>{const _=z.get($.id);return y==="read-only"?_.state==="read-only":y==="auto"?_.state==="auto":y==="approval"?_.state==="approval":y==="full-access"?_.state==="full-access":y==="available"?_.available:y==="unavailable"?!_.available:$.category===y})},[z,A,y,b,h,P]),Z=d.useMemo(()=>y!=="all"?[{category:Sg(y),templates:se}]:Ow.map(ne=>({category:ne,templates:se.filter($=>$.category===ne)})).filter(ne=>ne.templates.length>0),[y,se]);d.useEffect(()=>{E(ne=>Math.min(ne,Math.max(0,se.length-1)))},[se.length]),d.useEffect(()=>{pp(wg,b)},[b]),d.useEffect(()=>{pp(xg,A)},[A]),d.useEffect(()=>{O.current?.focus();const ne=_=>{_.target instanceof Node&&!F.current?.contains(_.target)&&f()},$=_=>{_.key==="Escape"&&(_.preventDefault(),f())};return document.addEventListener("pointerdown",ne),document.addEventListener("keydown",$),()=>{document.removeEventListener("pointerdown",ne),document.removeEventListener("keydown",$)}},[f]);const G=ne=>{const $=z.get(ne.id);if(!$.available){T($.reason||"This task is not available for the current targets and permission policy.");return}const _=[ne.id,...b.filter(ie=>ie!==ne.id)].slice(0,10);x(_),pp(wg,_),u(ne.prompt),f()},K=ne=>{k($=>{const _=$.includes(ne)?$.filter(ie=>ie!==ne):[ne,...$];return pp(xg,_),_})},me=ne=>{ne.key==="ArrowDown"?(ne.preventDefault(),E($=>Math.min($+1,Math.max(0,se.length-1)))):ne.key==="ArrowUp"?(ne.preventDefault(),E($=>Math.max($-1,0))):ne.key==="Enter"&&se[N]&&(ne.preventDefault(),G(se[N]))};let V=-1;return i.jsxs("section",{className:"agents-suggested-tasks",ref:F,"aria-label":"Suggested tasks",children:[i.jsxs("header",{className:"agents-suggested-header",children:[i.jsxs("div",{children:[i.jsxs("span",{className:"agents-suggested-title",children:[i.jsx(zl,{size:15})," Suggested tasks"]}),i.jsxs("small",{children:[I," available · ",P.length," total. Choose a task, edit it, then run it."]})]}),i.jsx("button",{className:"agents-suggested-close",type:"button","aria-label":"Close suggested tasks",onClick:f,children:i.jsx(vr,{size:16})})]}),i.jsxs("label",{className:"agents-suggested-search",children:[i.jsx(QC,{size:15,"aria-hidden":"true"}),i.jsx("input",{ref:O,value:h,onChange:ne=>g(ne.target.value),onKeyDown:me,placeholder:"Search tasks...","aria-label":"Search suggested tasks"})]}),i.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",...Ow].map(ne=>{const $=ne==="recent"?Mx:ne==="favorites"?_g:ne==="all"?zl:ne==="available"?Oa:ne==="unavailable"?Dx:ne==="read-only"||ne==="auto"||ne==="approval"||ne==="full-access"?Aa:rE[ne];return i.jsxs("button",{className:y===ne?"active":"",type:"button",title:Sg(ne),"aria-label":Sg(ne),"aria-pressed":y===ne,onClick:()=>{w(ne),E(0),T("")},children:[i.jsx($,{size:12})," ",sE(ne)]},ne)})}),D&&i.jsx("div",{className:"agents-suggested-notice",role:"status",children:D}),i.jsxs("div",{className:"agents-suggested-list",role:"listbox","aria-label":"Suggested tasks",children:[Z.map(ne=>i.jsxs("div",{className:"agents-suggested-group",children:[i.jsx("strong",{children:ne.category}),ne.templates.map($=>{V+=1;const _=V===N,ie=A.includes($.id),be=z.get($.id),H=be.availableDeviceIds.length+be.unsupportedDeviceIds.length||X,te=be.available?`Available on ${be.availableDeviceIds.length} of ${H} target${H===1?"":"s"}`:`Unavailable: ${be.reason||"not supported by the current targets"}`;return i.jsxs("div",{className:`agents-suggested-item ${_?"active":""} ${be.available?"":"unavailable"}`,children:[i.jsxs("button",{className:"agents-suggested-prompt",type:"button",role:"option","aria-selected":_,"aria-disabled":!be.available,onClick:()=>G($),children:[i.jsx("span",{children:$.title}),i.jsx("small",{className:"agents-suggested-description",children:$.description}),i.jsxs("span",{className:"agents-suggested-meta",children:[i.jsx("em",{children:$.category}),i.jsx("em",{className:oE(be.state),children:be.label}),i.jsx("em",{className:`risk-${$.risk}`,children:lE($.risk)}),i.jsx("em",{children:$.supportedPlatforms.map(cE).join(" · ")}),i.jsx("em",{className:be.available?"availability-ok":"availability-unavailable",children:te}),be.available&&be.unsupportedDeviceIds.length>0&&i.jsxs("em",{className:"availability-warning",children:["Unsupported on ",be.unsupportedDeviceIds.length]})]})]}),i.jsx("button",{className:`agents-suggested-favorite ${ie?"favorite":""}`,type:"button","aria-label":ie?`Remove ${$.title} from favorites`:`Add ${$.title} to favorites`,"aria-pressed":ie,onClick:()=>K($.id),children:i.jsx(_g,{size:14,fill:ie?"currentColor":"none"})})]},$.id)})]},ne.category)),se.length===0&&i.jsx("p",{className:"agents-suggested-empty",children:"No tasks match this search or current filter."})]})]})}function dE({devices:t,mode:n,selectedIds:r,onModeChange:o,onToggle:c,permissionMode:u,onPermissionModeChange:f}){const h=t.filter(Bp),g=r.filter(y=>h.some(w=>w.deviceId===y)).length;return i.jsxs("section",{className:"agents-target-picker","aria-label":"Agent targets",children:[i.jsxs("div",{className:"agents-target-toolbar",children:[i.jsx("span",{className:"agents-section-label",children:"Targets"}),i.jsxs("div",{className:"agents-target-modes",children:[i.jsxs("button",{className:n==="all"?"active":"",onClick:()=>o("all"),type:"button",children:[i.jsx(Kf,{size:14})," All connected ",i.jsx("small",{children:h.length})]}),i.jsxs("button",{className:n==="selected"?"active":"",onClick:()=>o("selected"),type:"button",children:[i.jsx(qi,{size:14})," Selected ",g]}),i.jsxs("button",{className:n==="auto"?"active":"",onClick:()=>o("auto"),type:"button",children:[i.jsx(zl,{size:14})," Auto"]}),i.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[i.jsx(Kf,{size:14})," Group ",i.jsx("small",{children:"Soon"})]})]}),i.jsxs("label",{className:`agents-permission-picker permission-${u}`,children:[i.jsx($p,{size:14}),i.jsx("span",{children:"Permission"}),i.jsxs("select",{value:u,onChange:y=>f(y.target.value),"aria-label":"Agent permission mode",children:[i.jsx("option",{value:"ask",children:"Ask"}),i.jsx("option",{value:"safe-auto",children:"Safe Auto"}),i.jsx("option",{value:"full-access",children:"Full Access"}),i.jsx("option",{value:"custom",children:"Custom"})]}),i.jsx(Ex,{size:13,"aria-hidden":"true"})]})]}),i.jsx("div",{className:"agents-target-list",children:t.length===0?i.jsx("span",{className:"agents-target-empty",children:"No Clients discovered."}):t.map(y=>{const w=Bp(y),b=n==="all"||n==="auto"?w:r.includes(y.deviceId);return i.jsxs("label",{className:`agents-target-option ${b?"selected":""} ${w?"":"offline"}`,children:[i.jsx("input",{type:"checkbox",checked:b,disabled:!w||n!=="selected",onChange:()=>c(y.deviceId)}),i.jsx("span",{className:"agents-target-icon",children:i.jsx(Ba,{size:15})}),i.jsxs("span",{children:[i.jsx("strong",{children:Op(y)}),i.jsx("small",{children:w?"Ready":y.connected?"Agent reconnecting":"Offline"})]}),b&&i.jsx(qi,{className:"agents-target-check",size:15,"aria-hidden":"true"})]},y.deviceId)})})]})}const fE=800,zw=5e3;function mE(){return typeof document>"u"||document.visibilityState==="visible"}function pE(t){return typeof document>"u"?()=>{}:(document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t))}function $w({poll:t,onResult:n,onError:r,intervalMs:o=fE,isVisible:c=mE,subscribeVisibility:u=pE,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,x=null,A=null;const k=()=>{x!==null&&(h(x),x=null)},N=()=>{!w||!c()||x!==null||y.current||(x=f(()=>{x=null,E()},o))},E=()=>{if(!w||!c()||y.current)return y.current;const O=++b,P=g();A=P;const z=jp(y,()=>t(P.signal));return z.then(I=>{w&&O===b&&!P.signal.aborted&&n?.(I)},I=>{w&&O===b&&!P.signal.aborted&&r?.(I)}).finally(()=>{A===P&&(A=null),w&&c()&&N()}).catch(()=>{}),z},D=async()=>{if(!w)throw new Error("LiveDesk Agent polling owner is closed.");k(),b+=1;const O=y.current;if(A&&!A.signal.aborted&&A.abort(new Error("LiveDesk Agent polling was superseded by an explicit refresh.")),O)try{await O}catch{}if(!(!w||!c()))return k(),E()},F=u(()=>{if(k(),!c()){b+=1,A&&!A.signal.aborted&&A.abort(new Error("LiveDesk Agent polling paused while hidden."));return}E()});return E(),{refresh:D,stop(){w&&(w=!1,b+=1,k(),F?.(),A&&!A.signal.aborted&&A.abort(new Error("LiveDesk Agent polling owner closed.")))}}}async function hE(t,n){return rt("/api/settings/agent/run",{method:"POST",body:JSON.stringify(n)},t)}async function gE(t,n,r={}){return rt(`/api/settings/agent/runs/${encodeURIComponent(n)}`,r,t)}async function vE(t,n){return rt(`/api/settings/agent/runs/${encodeURIComponent(n)}/cancel`,{method:"POST",body:JSON.stringify({})},t)}async function yE(t){return rt("/api/settings/agent/runs/cancel-all",{method:"POST",body:JSON.stringify({})},t)}async function bE(t,n,r,o){return rt(`/api/settings/agent/runs/${encodeURIComponent(n)}/approvals/${encodeURIComponent(r)}/approve`,{method:"POST",body:JSON.stringify({scope:o})},t)}async function wE(t,n,r,o="User rejected this action."){return rt(`/api/settings/agent/runs/${encodeURIComponent(n)}/approvals/${encodeURIComponent(r)}/reject`,{method:"POST",body:JSON.stringify({reason:o})},t)}async function xE(t,n,r){return rt(`/api/settings/agent/policies/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify({categories:r})},t)}async function SE(t,n){return rt("/api/settings/agent/summary",{method:"POST",body:JSON.stringify(n)},t)}async function CE(t,n,r={}){return rt(`/api/remote/tasks/${encodeURIComponent(n)}`,r,t)}async function kE(t,n){return rt(`/api/remote/tasks/${encodeURIComponent(n)}/cancel`,{method:"POST",body:JSON.stringify({})},t)}async function ME(t,n){return rt(`/api/remote/tasks/${encodeURIComponent(n)}/retry`,{method:"POST",body:JSON.stringify({failedOnly:!0})},t)}function od(t){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Cg(t,n){const r=new Map(n.map(o=>[o.deviceId,Op(o)]));return t.results.map(o=>({deviceId:o.deviceId,deviceName:o.deviceName||r.get(o.deviceId)||o.deviceId,status:Oj(o.status),stage:o.stage||(o.status==="running"?"Checking processes":void 0),result:o.result,data:o.data,error:o.error,sequence:Number.isSafeInteger(o.sequence)?o.sequence:0}))}function AE(t,n){const r=new Map(n.map(o=>[o.deviceId,o]));return t.map(o=>{const c=r.get(o.deviceId);return!c||c.sequence<=o.sequence?o:c})}function NE(t,n){const r=n.filter(u=>u.status==="completed"),o=n.filter(u=>u.status==="failed");if(t.operation==="process.list"){const f=`${r.filter(h=>{const g=h.result||"";return!/not running|no process/i.test(g)&&/running|online|found/i.test(g)}).length}대에서 요청한 프로세스가 실행 중입니다.`;return o.length>0?`${f}
176
- ${o.map(h=>`${h.deviceName}는 ${h.error||"응답하지 않았습니다."}`).join(`
177
- `)}`:f}return o.length>0?`${r.length}대 완료, ${o.length}대 실패했습니다.`:`${r.length}대 작업이 완료되었습니다.`}const TE={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 RE(t){return t==="safe-auto"?"Safe Auto":t==="full-access"?"Full Access":t==="custom"?"Custom":"Ask"}function jE(t){return t.replace(/([A-Z])/g," $1").replace(/^./,n=>n.toUpperCase())}function EE(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 Uw({hubUrl:t,devices:n,launchRequest:r,variant:o="page",selectedDeviceIds:c=[]}){const u=o==="dock",[f,h]=d.useState(u?c.length>0?"selected":"auto":"all"),[g,y]=d.useState(c),[w,b]=d.useState("auto"),[x,A]=d.useState(""),[k,N]=d.useState([]),[E,D]=d.useState(""),[T,F]=d.useState(""),[O,P]=d.useState(""),[z,I]=d.useState("safe-auto"),[X]=d.useState("custom-default"),[se,Z]=d.useState(TE),[G,K]=d.useState([]),[me,V]=d.useState(""),[ne,$]=d.useState(!1),[_,ie]=d.useState(null),[be,H]=d.useState(!1),[te,le]=d.useState(""),[Ce,Ae]=d.useState(!1),[_e,ue]=d.useState(null),He=d.useRef(null),ze=d.useRef(null),et=d.useRef(null),Xe=d.useRef(new Set),Ze=d.useRef(new Set),Ue=d.useRef(new Set),Y=d.useMemo(()=>n.filter(Bp).map(ee=>ee.deviceId),[n]),Se=d.useMemo(()=>aE(a0,n,f,g,z,se),[se,n,z,g,f]);d.useEffect(()=>{u&&y(c)},[u,c]),d.useEffect(()=>{r?.deviceId&&(h("selected"),y([r.deviceId]),A(r.instruction),Ae(!1),window.requestAnimationFrame(()=>{He.current?.focus(),He.current?.setSelectionRange(r.instruction.length,r.instruction.length)}))},[r]);const ye=d.useCallback(ee=>{const he=Cg(ee,n);if(N(Fe=>Fe.map(fe=>fe.type==="task"&&fe.batchId===ee.batchId?{...fe,states:AE(fe.states,he),status:ee.status}:fe)),!["running","queued"].includes(ee.status)&&!Xe.current.has(ee.batchId)){Xe.current.add(ee.batchId);const Fe=od("agent-summary");N(fe=>[...fe,{type:"agent",id:Fe,text:NE(ee,he)}]),ee.operation&&SE(t,{instruction:ee.instructionPreview,operation:ee.operation,total:he.length,completed:he.filter(fe=>fe.status==="completed").length,failed:he.filter(fe=>fe.status==="failed").length,results:he.map(fe=>({deviceName:fe.deviceName,status:fe.status,result:fe.result,error:fe.error}))}).then(fe=>{!fe.ok||!fe.summary||N(xe=>xe.map(nt=>nt.type==="agent"&&nt.id===Fe?{...nt,text:fe.summary}:nt))}).catch(()=>{}),D(fe=>fe===ee.batchId?"":fe)}},[n,t]),je=d.useCallback((ee,he)=>{Ue.current.has(ee.batchId)||(Ue.current.add(ee.batchId),N(Fe=>[...Fe,{type:"task",id:od("task"),batchId:ee.batchId,agentRunId:he,operation:ee.operation||"diagnostics.collect",instruction:ee.instructionPreview,states:Cg(ee,n),status:ee.status}])),ye(ee)},[n,ye]),$e=d.useCallback((ee,he)=>{for(const fe of he.taskBatches||[])je(fe,ee);K(he.approvals||[]);const Fe=["running","queued","waiting-approval"].includes(he.status);if(ue(Fe?{runId:ee,stage:he.stage||he.status,message:he.progressMessage||(he.status==="waiting-approval"?"Review the requested action to continue.":"Codex is preparing the answer.")}:fe=>fe?.runId===ee?null:fe),!Fe&&!Ze.current.has(ee)){Ze.current.add(ee);const fe=[he.error,he.errorMessage].filter(Boolean).join(" — "),xe=he.finalResponse?.trim()||(he.status==="cancelled"?"Codex 작업을 취소했습니다.":fe?`Codex 작업이 완료되지 않았습니다: ${fe}`:"Codex 작업이 완료되었습니다.");N(nt=>[...nt,{type:he.status==="failed"?"error":"agent",id:od("agent-run-result"),text:xe}])}},[je]),B=d.useCallback(async ee=>{const he=ze.current;if(!(!he||he.id!==ee))try{return await he.owner.refresh()}catch(Fe){if(ze.current!==he)return;throw Fe}},[]);d.useEffect(()=>{if(!T){ze.current=null;return}const ee=T,he=$w({poll:fe=>gE(t,ee,{signal:fe,timeoutMs:zw}),onResult:fe=>{$e(ee,fe),["running","queued","waiting-approval"].includes(fe.status)||(F(xe=>xe===ee?"":xe),H(!1))},onError:fe=>{le(fe instanceof Error?fe.message:String(fe))}}),Fe={id:ee,owner:he};return ze.current=Fe,()=>{he.stop(),ze.current===Fe&&(ze.current=null)}},[T,t,$e]),d.useEffect(()=>{if(!E){et.current=null;return}const ee=E,he=$w({poll:fe=>CE(t,ee,{signal:fe,timeoutMs:zw}),onResult:fe=>{ye(fe),["running","queued"].includes(fe.status)||D(xe=>xe===ee?"":xe)},onError:fe=>{le(fe instanceof Error?fe.message:String(fe))}}),Fe={id:ee,owner:he};return et.current=Fe,()=>{he.stop(),et.current===Fe&&(et.current=null)}},[E,t,ye]);const lt=async(ee="",he,Fe=!1)=>{const fe=(ee||x).trim();if(!fe||E||T)return;const xe=he||(f==="all"||f==="auto"?Y:g.filter(dt=>Y.includes(dt)));if(xe.length===0){le("Select at least one connected Client.");return}if(z==="full-access"&&!be&&!Fe){ie({instruction:fe,targetIds:xe});return}if(N(dt=>[...dt,{type:"user",id:od("user"),text:fe}]),A(""),Ae(!1),le(""),xe.length===0){N(dt=>[...dt,{type:"error",id:od("no-targets"),text:"연결된 대상 장비를 하나 이상 선택해 주세요."}]);return}const ct=w==="ask"?`Read-only request. Inspect and answer without changing Client state.
178
-
179
- ${fe}`:w==="plan"?`Plan only. Produce a safe execution plan, but do not change Client state.
180
-
181
- ${fe}`:w==="execute"?`Execute this request within the configured LiveDesk approval policy.
182
-
183
- ${fe}`:fe,ft=f==="auto"?`Auto target selection is enabled. Inspect the allowed Clients and use only the most suitable target or targets for this request.
184
-
185
- ${ct}`:ct;try{if(z==="custom"){const Dt=await xE(t,X,se);if(!Dt.ok)throw new Error(Dt.error||"Custom Agent policy could not be saved.")}const dt=await hE(t,{instruction:ft,deviceIds:xe,permissionMode:z,customPolicyId:X});if(!dt.ok||!dt.runId)throw new Error(dt.error||"Codex Agent run could not be started.");K(dt.approvals||[]),ue({runId:dt.runId,stage:dt.stage||dt.status||"queued",message:dt.progressMessage||"Codex request queued on the Hub."}),F(dt.runId)}catch(dt){N(Dt=>[...Dt,{type:"error",id:od("codex-run-error"),text:EE(dt)}])}},Nt=async(ee,he)=>{V(ee.approvalId);try{const Fe=await bE(t,ee.runId,ee.approvalId,he);if(!Fe.ok)throw new Error(Fe.error||"Agent approval could not be applied.");await B(ee.runId)}catch(Fe){le(Fe instanceof Error?Fe.message:String(Fe))}finally{V("")}},Ht=async ee=>{V(ee.approvalId);try{const he=await wE(t,ee.runId,ee.approvalId);if(!he.ok)throw new Error(he.error||"Agent approval could not be rejected.");await B(ee.runId)}catch(he){le(he instanceof Error?he.message:String(he))}finally{V("")}},ke=async(ee,he)=>{P(ee);try{if(he){const fe=await vE(t,he);for(const xe of fe.taskBatches||[])ye(xe);F(xe=>xe===he?"":xe),ue(xe=>xe?.runId===he?null:xe);return}const Fe=await kE(t,ee);ye(Fe),D(fe=>fe===ee?"":fe)}catch(Fe){le(Fe instanceof Error?Fe.message:String(Fe))}finally{P("")}},qe=async()=>{if(!(ne||!E&&!T)){$(!0);try{const ee=await yE(t);if(!ee.ok)throw new Error(ee.error||"모든 Agent 작업을 취소하지 못했습니다.");D(""),F(""),ue(null),K([]),N(he=>he.map(Fe=>Fe.type==="task"&&["queued","running"].includes(Fe.status)?{...Fe,status:"cancelled",states:Fe.states.map(fe=>["queued","running"].includes(fe.status)?{...fe,status:"cancelled",stage:"Cancelled",error:"Cancelled by user."}:fe)}:Fe))}catch(ee){le(ee instanceof Error?ee.message:String(ee))}finally{$(!1)}}},Ye=async ee=>{P(ee);try{const he=await ME(t,ee);if(!he.ok||!he.batch||!he.batchId)throw new Error(he.error||"재시도하지 못했습니다.");Xe.current.delete(he.batchId),N(Fe=>Fe.map(fe=>fe.type==="task"&&fe.batchId===ee?{...fe,batchId:he.batchId,states:Cg(he.batch,n),status:he.batch.status}:fe)),D(he.batchId)}catch(he){le(he instanceof Error?he.message:String(he))}finally{P("")}},_t=ee=>{A(ee),Ae(!1),window.requestAnimationFrame(()=>He.current?.focus())},tt=d.useMemo(()=>n.filter(Bp),[n]),pe=d.useMemo(()=>tt.filter(ee=>g.includes(ee.deviceId)),[tt,g]),Ne=f==="auto"?`Auto · ${tt.length} available`:f==="all"?`All ${tt.length} computers`:pe.length===1?Op(pe[0]):`${pe.length} selected`,Be=f==="auto"?"LiveDesk chooses the best computer for each task.":f==="all"?"The Agent may coordinate every connected computer.":pe.length>0?pe.map(Op).join(" · "):"Select one or more computers on the Wall.",Oe=f==="selected"&&pe.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"],We=f==="selected"?pe.length>0?"What should this computer do?":"Choose a computer or use Auto.":f==="all"?"Use all your computers together.":"What should LiveDesk handle?",Rt=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 i.jsxs("section",{className:`agents-page ${u?"agents-dock-console":""}`,children:[u&&i.jsxs("header",{className:"agent-console-header",children:[i.jsxs("div",{className:"agent-console-title",children:[i.jsx("span",{className:"agent-console-mark",children:i.jsx(zl,{size:16})}),i.jsxs("div",{children:[i.jsx("small",{children:"Hub Codex Agent"}),i.jsx("strong",{children:"Command Console"})]}),i.jsx("i",{children:"Ready"})]}),i.jsxs("section",{className:"agent-console-target","aria-label":"Agent target scope",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Target"}),i.jsx("strong",{children:Ne}),i.jsx("small",{children:Be})]}),i.jsxs("div",{className:"agent-console-target-modes",children:[i.jsxs("button",{className:f==="selected"?"active":"",onClick:()=>h("selected"),type:"button",children:[i.jsx(qi,{size:12})," Selected"]}),i.jsxs("button",{className:f==="all"?"active":"",onClick:()=>h("all"),type:"button",children:[i.jsx(Kf,{size:12})," All"]}),i.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[i.jsx(Kf,{size:12})," Group"]}),i.jsxs("button",{className:f==="auto"?"active":"",onClick:()=>h("auto"),type:"button",children:[i.jsx(zl,{size:12})," Auto"]})]})]}),i.jsx("div",{className:"agent-console-interaction-modes","aria-label":"Agent interaction mode",children:["auto","ask","plan","execute"].map(ee=>i.jsxs("button",{className:w===ee?"active":"",onClick:()=>b(ee),type:"button",children:[ee==="auto"?i.jsx(zl,{size:12}):ee==="execute"?i.jsx(Ba,{size:12}):null,ee[0].toUpperCase()+ee.slice(1)]},ee))})]}),i.jsxs("div",{className:"agents-workspace",children:[(E||T)&&i.jsxs("div",{className:"agents-page-status",children:[i.jsxs("span",{children:[Y.length," Clients · ",RE(z)]}),i.jsx("button",{type:"button",className:"agents-stop-all",onClick:()=>{qe()},disabled:ne,children:ne?"Stopping…":"Stop all"})]}),_&&i.jsx("div",{className:"agents-permission-modal-backdrop",role:"presentation",children:i.jsxs("section",{className:"agents-permission-modal",role:"dialog","aria-modal":"true","aria-labelledby":"full-access-title",children:[i.jsx("span",{className:"agents-permission-modal-icon",children:i.jsx($p,{size:20})}),i.jsx("h3",{id:"full-access-title",children:"Confirm Full Access"}),i.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."}),i.jsxs("div",{className:"agents-permission-modal-actions",children:[i.jsx("button",{type:"button",onClick:()=>ie(null),children:"Cancel"}),i.jsx("button",{type:"button",className:"danger",onClick:()=>{const ee=_;ie(null),H(!0),lt(ee.instruction,ee.targetIds,!0)},children:"Run with Full Access"})]})]})}),te&&i.jsx("div",{className:"agents-error",role:"alert",children:te}),i.jsx(Kj,{items:k,onCancel:ke,onRetry:Ye,busyBatchId:O,approvals:G,onApprove:Nt,onReject:Ht,busyApprovalId:me,progress:_e,emptyTitle:u?We:void 0,emptyBody:u?Rt:void 0}),u&&k.length===0&&!_e&&i.jsx("div",{className:"agent-console-suggestions","aria-label":"Suggested Agent commands",children:Oe.map(ee=>i.jsx("button",{type:"button",onClick:()=>_t(ee),children:ee},ee))}),i.jsxs("div",{className:"agents-composer-shell",children:[Ce&&i.jsx(uE,{devices:n,targetMode:f,selectedIds:g,permissionMode:z,customCategories:se,onSelectPrompt:_t,onClose:()=>Ae(!1)}),i.jsx(Fj,{ref:He,value:x,onChange:A,onSubmit:()=>{lt()},onOpenSuggestedTasks:()=>Ae(ee=>!ee),suggestedOpen:Ce,suggestedTaskCount:Se,disabled:!!E||!!T,placeholder:u?"Tell LiveDesk what outcome you want...":void 0,compact:u})]})]}),!u&&i.jsxs("aside",{className:"agents-target-sidebar","aria-label":"Agent targets and permissions",children:[i.jsx(dE,{devices:n,mode:f,selectedIds:g,onModeChange:h,onToggle:ee=>y(he=>he.includes(ee)?he.filter(Fe=>Fe!==ee):[...he,ee]),permissionMode:z,onPermissionModeChange:ee=>{I(ee),ee!=="full-access"&&H(!1)}}),z==="custom"&&i.jsxs("section",{className:"agents-custom-policy","aria-label":"Custom Agent permissions",children:[i.jsxs("div",{className:"agents-custom-policy-head",children:[i.jsxs("div",{children:[i.jsx("span",{className:"agents-section-label",children:"Custom policy"}),i.jsx("strong",{children:"Choose what Codex may do automatically."})]}),i.jsx("span",{children:"Denied actions never reach a device."})]}),i.jsx("div",{className:"agents-custom-policy-grid",children:Pj.map(ee=>i.jsxs("label",{children:[i.jsx("span",{children:jE(ee)}),i.jsxs("select",{value:se[ee],onChange:he=>Z(Fe=>({...Fe,[ee]:he.target.value})),children:[i.jsx("option",{value:"allow",children:"Allow automatically"}),i.jsx("option",{value:"ask",children:"Ask every time"}),i.jsx("option",{value:"deny",children:"Deny"})]})]},ee))})]})]})]})}function s0(t){return{type:t.type,deviceIds:t.deviceIds,monitorIndex:t.monitorIndex,label:t.label}}async function i0(t){try{return(await t.json()).error||`${t.status} ${t.statusText}`}catch{return`${t.status} ${t.statusText}`}}async function o0(t,n,r){const o=encodeURIComponent(JSON.stringify({kind:n.kind,fileName:n.fileName,mimeType:t.type||"application/octet-stream",durationMs:n.durationMs,target:s0(n.target)})),c=await fetch(`${Vl(r)}/api/captures?metadata=${o}`,{method:"POST",headers:{"Content-Type":t.type||"application/octet-stream"},body:t,cache:"no-store"});if(!c.ok)throw new Error(await i0(c));return await c.json()}async function DE(t,n){return await rt("/api/capture-sessions",{method:"POST",body:JSON.stringify({...t,target:s0(t.target)})},n)}async function IE(t,n,r,o){const c=await fetch(`${Vl(o)}/api/capture-sessions/${encodeURIComponent(t)}/chunks/${n}`,{method:"PUT",headers:{"Content-Type":r.type||"application/octet-stream"},body:r,cache:"no-store"});if(!c.ok)throw new Error(await i0(c));return await c.json()}async function LE(t,n,r){return await rt(`/api/capture-sessions/${encodeURIComponent(t)}/finalize`,{method:"POST",body:JSON.stringify({durationMs:n})},r)}async function qw(t,n){await rt(`/api/capture-sessions/${encodeURIComponent(t)}`,{method:"DELETE"},n)}async function _E(t){return await rt("/api/captures",void 0,t)}function Ww(t,n){return`${Vl(n)}/api/captures/${encodeURIComponent(t)}/content`}async function FE(t,n){return await rt(`/api/captures/${encodeURIComponent(t)}`,{method:"DELETE"},n)}function PE({hubUrl:t,onToast:n}){const[r,o]=d.useState([]),[c,u]=d.useState(!0),f=d.useCallback(async()=>{u(!0);try{o((await _E(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=Ww(g.id,t);if(navigator.share)try{await navigator.share({title:g.fileName,url:y});return}catch{}window.open(y,"_blank","noopener,noreferrer")};return i.jsxs("section",{className:"capture-gallery",children:[i.jsxs("header",{children:[i.jsxs("div",{children:[i.jsx("span",{className:"settings-eyebrow",children:"Capture Gallery"}),i.jsx("h2",{children:"Saved captures"})]}),i.jsxs("button",{className:"text-button",onClick:()=>{f()},type:"button",children:[i.jsx(hd,{size:15})," Refresh"]})]}),c?i.jsx("p",{className:"settings-help",children:"Loading captures..."}):r.length===0?i.jsx("p",{className:"settings-help",children:"No captures saved yet."}):i.jsx("div",{className:"capture-gallery-grid",children:r.map(g=>{const y=Ww(g.id,t);return i.jsxs("article",{className:"capture-gallery-card",children:[g.mimeType.startsWith("image/")?i.jsx("img",{src:y,alt:g.target.label}):i.jsx("video",{src:y,controls:!0,preload:"metadata"}),i.jsxs("div",{className:"capture-gallery-card-body",children:[i.jsx("strong",{children:g.fileName}),i.jsxs("small",{children:[g.target.label," · ",new Date(g.createdAt).toLocaleString()," · ",Math.ceil(g.sizeBytes/1024)," KB"]}),i.jsxs("div",{children:[i.jsx("button",{className:"icon-button",title:"Open","aria-label":"Open",onClick:()=>window.open(y,"_blank","noopener,noreferrer"),type:"button",children:i.jsx(JC,{size:15})}),i.jsx("a",{className:"icon-button",title:"Download","aria-label":"Download",href:`${y}?download=1`,download:g.fileName,children:i.jsx(mv,{size:15})}),i.jsx("button",{className:"icon-button",title:"Share","aria-label":"Share",onClick:()=>{h(g)},type:"button",children:i.jsx(ek,{size:15})}),i.jsx("button",{className:"icon-button danger",title:"Delete","aria-label":"Delete",onClick:()=>{window.confirm(`Delete ${g.fileName}?`)&&FE(g.id,t).then(()=>f()).catch(w=>n(w instanceof Error?w.message:String(w)))},type:"button",children:i.jsx(Rx,{size:15})})]})]})]},g.id)})})]})}function hp(t){if(!t)return"";const n=Math.max(0,Math.floor((Date.now()-t)/1e3)),r=Math.floor(n/3600),o=Math.floor(n%3600/60),c=n%60;return r>0?`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}:${String(c).padStart(2,"0")}`:`${String(o).padStart(2,"0")}:${String(c).padStart(2,"0")}`}function Gw({controller:t,compact:n=!1,onFirstRollingUse:r,onError:o}){const{state:c,settings:u,videoSupported:f}=t,h=async b=>{try{await b()}catch(x){o?.(x instanceof Error?x.message:String(x))}},g=async()=>{if(u.rollingEnabled){t.setRollingEnabled(!1);return}(r?await r():window.confirm(`Keep the most recent 30 seconds in memory temporarily?
186
- Nothing is saved until you press Save Last 30s.`))&&t.setRollingEnabled(!0)},y=c.recording?`Stop recording · ${hp(c.recordingStartedAt)}`:`Start recording · ${c.targetLabel}`,w=c.timelapse?`Stop timelapse · ${hp(c.timelapseStartedAt)}`:`Start timelapse · ${u.timelapseIntervalSeconds}s interval`;return i.jsxs("div",{className:`capture-toolbar ${n?"compact":""} ${c.recording?"recording-active":""}`,"aria-label":"Capture actions",children:[i.jsx("button",{className:"capture-action","aria-label":`Take screenshot · ${c.targetLabel}`,title:`Take screenshot · ${c.targetLabel}`,disabled:c.busy,onClick:()=>{h(t.takeScreenshot)},type:"button",children:i.jsx(tk,{size:17})}),i.jsx("button",{className:`capture-action ${c.recording?"active":""}`,"aria-label":y,title:y,disabled:!f||c.busy||c.timelapse,onClick:()=>{h(c.recording?t.stopRecording:t.startRecording)},type:"button",children:c.recording?i.jsxs(i.Fragment,{children:[i.jsx(db,{size:14,fill:"currentColor"}),i.jsx("span",{children:hp(c.recordingStartedAt)})]}):i.jsx(jx,{size:18})}),i.jsxs("button",{className:"capture-action","aria-label":c.bufferEnabled?`Save last 30 seconds · ${c.bufferSeconds}s ready`:"Enable Last 30s memory buffer",title:c.bufferEnabled?`Save last 30 seconds · ${c.bufferSeconds}s ready`:"Enable Last 30s memory buffer",disabled:!f||c.recording||c.timelapse||c.busy||c.bufferEnabled&&c.bufferSeconds<1,onClick:()=>c.bufferEnabled?void h(t.saveLast30Seconds):void g(),type:"button",children:[i.jsx(nk,{size:17}),i.jsx("small",{children:"30s"})]}),i.jsx("button",{className:`capture-action ${c.timelapse?"timelapse-active":""}`,"aria-label":w,title:w,disabled:!f||c.busy||c.recording,onClick:()=>{h(c.timelapse?t.stopTimelapse:t.startTimelapse)},type:"button",children:c.timelapse?i.jsxs(i.Fragment,{children:[i.jsx(db,{size:14,fill:"currentColor"}),i.jsx("span",{children:hp(c.timelapseStartedAt)})]}):i.jsx(ak,{size:17})})]})}function l0({state:t}){return t==="ok"?i.jsx(Oa,{size:15,"aria-hidden":"true"}):i.jsx(Dx,{size:15,"aria-hidden":"true"})}function Vw({active:t,refreshing:n,onClick:r}){return i.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?i.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):i.jsx(rk,{size:18,"aria-hidden":"true"})})}function Kw({active:t,refreshing:n,onClick:r}){return i.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?i.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):i.jsx(Sx,{size:18,"aria-hidden":"true"})})}function Qw({active:t,refreshing:n,onClick:r}){return i.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?i.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):i.jsx(Wi,{size:18,"aria-hidden":"true"})})}function c0({items:t,mode:n="remote"}){return i.jsx("span",{className:`remote-status-lines mode-${n}`,role:"status","aria-label":n==="debug"?"Debug status":"Remote status",children:t.map(r=>i.jsxs("span",{className:`remote-status-line state-${r.state}`,title:r.detail,children:[i.jsx(l0,{state:r.state}),i.jsxs("span",{children:[i.jsx("strong",{children:r.label}),i.jsx("small",{children:r.detail})]})]},r.id))})}function OE({items:t,collectedAt:n,onClose:r}){return i.jsxs("section",{className:"remote-status-dialog hub-status-dialog",role:"dialog","aria-modal":"false","aria-labelledby":"hub-status-dialog-title",children:[i.jsxs("header",{children:[i.jsx("span",{className:"remote-status-dialog-mark","aria-hidden":"true",children:i.jsx(Wi,{size:19})}),i.jsxs("span",{children:[i.jsx("small",{children:"Hub measurements"}),i.jsx("h2",{id:"hub-status-dialog-title",children:"Hub Status"})]}),i.jsx("button",{type:"button",onClick:r,title:"Close Hub status","aria-label":"Close Hub status",children:i.jsx(vr,{size:17})})]}),i.jsx("p",{children:"LiveDesk collects these Hub and browser signals continuously. This check refreshed the latest snapshot instead of starting a one-time benchmark."}),i.jsx("div",{className:"remote-status-dialog-list",children:t.map(o=>i.jsxs("article",{className:`remote-status-dialog-row state-${o.state}`,children:[i.jsx(l0,{state:o.state}),i.jsxs("span",{children:[i.jsx("strong",{children:o.label}),i.jsx("small",{children:o.detail})]})]},o.id))}),i.jsxs("footer",{children:["Checked ",new Date(n).toLocaleTimeString()]})]})}const BE=/(nvenc|videotoolbox|qsv|quick\s*sync|amf|vaapi|v4l2m2m|mediafoundation|h264_mf)/i,HE=/(libx264|openh264|software|cpu)/i,uv=2,zE=256,Fc=new Map,At=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 an(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Uv(t,n){let r=t;for(const o of String(n).split(".")){if(!r||typeof r!="object")return;r=r[o]}return r}function bt(t,...n){for(const r of n){const o=Uv(t,r);if(o==null||o==="")continue;const c=Number(o);if(Number.isFinite(c))return c}}function It(t,...n){for(const r of n){const o=Uv(t,r);if(typeof o=="string"&&o.trim())return o.trim()}return""}function u0(t,...n){for(const r of n){const o=Uv(t,r);if(typeof o=="boolean")return o;if(o===1||o==="1"||String(o).toLowerCase()==="true")return!0;if(o===0||o==="0"||String(o).toLowerCase()==="false")return!1}}function bi(t,...n){const r=bt(t,...n);if(r!==void 0)return Math.max(0,Math.min(1,r>1?r/100:r))}function Qe(t,n,r,o){return{id:t,state:n,label:r,detail:o}}function d0(t){const n=an(t),r=bt(n,"helperCount"),o=bt(n,"helperOwnedIoTaskCount"),c=bt(n,"helperUndisposedProcessCount"),u=bt(n,"helperOwnedExitObserverCount"),f=bt(n,"helperQuarantineCount"),h=bt(n,"utilityQuarantineCount"),g=bt(n,"utilityOwnedIoTaskCount"),y=bt(n,"utilityUndisposedProcessCount"),w=Number(bt(n,"helperDisposeFailureCount")||0),b=Number(bt(n,"utilityDisposeFailureCount")||0),x=Math.max(0,Number(r||0)),A=Number(o||0),k=Number(c||0),N=Number(u||0),E=Math.max(0,Number(f||0)),D=Math.max(0,Number(h||0)),T=Number(g||0),F=Number(y||0),O=[o,c,u,f,h,g,y].every(I=>I!==void 0),P=O&&(A<0||k<0||N<0||k!==x||N!==0||x===0&&A!==0||x>0&&A===0),z=O&&(T<0||F<0||F!==D||T!==D*2);return{telemetryAvailable:O,helperOwnedIoTaskCount:A,helperUndisposedProcessCount:k,helperOwnedExitObserverCount:N,helperQuarantineCount:E,helperDisposeFailureCount:w,helperLastDisposeFailure:It(n,"helperLastDisposeFailure"),helperLedgerMismatch:P,utilityQuarantineCount:D,utilityOwnedIoTaskCount:T,utilityUndisposedProcessCount:F,utilityQuarantinePids:Array.isArray(n.utilityQuarantinePids)?n.utilityQuarantinePids.map(I=>Number(I)).filter(I=>Number.isSafeInteger(I)&&I>0):[],utilityQuarantineProfiles:Array.isArray(n.utilityQuarantineProfiles)?n.utilityQuarantineProfiles.map(I=>String(I||"").trim()).filter(Boolean).slice(0,4):[],utilityQuarantineStartCount:Math.max(0,Number(bt(n,"utilityQuarantineStartCount")||0)),utilityQuarantineStopCount:Math.max(0,Number(bt(n,"utilityQuarantineStopCount")||0)),utilityDisposeFailureCount:b,utilityLastDisposeFailure:It(n,"utilityLastDisposeFailure"),utilityLedgerMismatch:z,historicalCleanupFailure:w!==0||b!==0,currentProblem:E>0||D>0||P||z}}function f0({key:t,sampleId:n,mismatch:r}){if(!t)return{count:0,confirmed:!1};if(!r)return Fc.delete(t),{count:0,confirmed:!1};const o=String(n||"").trim();if(!o)return{count:0,confirmed:!1};const c=Gf(o),u=Fc.get(t);if(u?.sampleId===o)return{count:u.count,confirmed:u.count>=uv};const f=u&&c!==void 0&&u.sampleEpochMs!==void 0&&c>u.sampleEpochMs,h=u&&f?u.count+1:1;return!Fc.has(t)&&Fc.size>=zE&&Fc.delete(Fc.keys().next().value),Fc.set(t,{sampleId:o,sampleEpochMs:c,count:h}),{count:h,confirmed:h>=uv}}function Gf(t){const n=Date.parse(String(t||""));return Number.isFinite(n)&&n>0?n:void 0}function Yw(t){return`${(Math.max(0,Number(t||0))/1024**3).toFixed(1)} GB`}function _l(t){const n=Number(t);return Number.isFinite(n)?`${(Math.max(0,n)/1024**2).toFixed(0)} MB`:"-"}function Fl(t){const n=Number(t);return Number.isFinite(n)?`${(Math.max(0,n)*100).toFixed(1)}%`:"-"}function gp(t){const n=Number(t);return Number.isFinite(n)?`${Math.max(0,n).toFixed(1)}%`:"-"}function $E(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 m0(t){const n=an(t),r=It(n,"controlTransport").toLowerCase();return r==="encrypted-rendezvous-relay"||/relay/.test(r)?"encrypted-rendezvous-relay":r==="direct-tcp"||/direct|tcp/.test(r)?"direct-tcp":""}function Xw(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 UE(t){const n=m0(t);return n==="encrypted-rendezvous-relay"?Qe("control-transport","ok","Control connection: Encrypted rendezvous relay","Commands and remote input use the end-to-end encrypted rendezvous relay."):n==="direct-tcp"?Qe("control-transport","ok","Control connection: Direct TCP","Commands and remote input use the direct Hub connection."):Qe("control-transport","warning","Control connection is not identified","Waiting for Direct TCP or encrypted rendezvous relay status.")}function qE(t,n){const r=an(t),o=an(n),c=m0(r);if(c==="encrypted-rendezvous-relay"){const u=It(o,"state")||(o.connected===!0?"registered":"unknown"),f=Xw(It(o,"endpoint"))||Xw(It(r,"relayEndpoint")),h=r.connected!==!0||o.connected===!1||/(connecting|reconnect|failed|error|degraded|unavailable|disabled)/.test(u);return Qe("debug-control-transport",h?"warning":"ok",`Encrypted rendezvous relay control · ${u}`,[`endpoint ${f||"-"}`,`state ${u}`,`reconnect ${Math.max(0,Number(o.reconnectCount||0))}`,`handshake ${Math.max(0,Number(o.handshakeCount||0))}`,`peers ${Math.max(0,Number(o.peerCount||0))}`,It(o,"lastError")].filter(Boolean).join(" · "))}if(c==="direct-tcp"){const u=It(r,"remoteAddress"),f=bt(r,"remotePort"),h=u?`${u}${f?`:${f}`:""}`:"-";return Qe("debug-control-transport",r.connected===!0?"ok":"warning","Direct TCP control",`peer ${h} · protocol ${It(r,"protocol")||"-"} v${bt(r,"protocolVersion")??"-"} · input ${an(r.channels).input===!1?"shared control channel":"dedicated channel"}`)}return Qe("debug-control-transport","warning","Control transport is not identified","No Direct TCP or encrypted rendezvous relay metadata is available.")}function p0(t,n){const r=Number(t?.browserReceivedEpochMs);return Number.isFinite(r)&&r>0?Math.max(0,n-r):Number.POSITIVE_INFINITY}function h0(t,n,r){const o=an(n?.frameTransport),c=It(t,"frameTransportChangedAt"),u=It(o,"changedAt"),f=Gf(c),h=Gf(u),g=h!==void 0&&(f===void 0||h>f),y=g?o:t,w=g?t:o,b=It(t,"transport").toLowerCase(),x=It(y,g?"active":"frameTransportActive")||It(w,g?"frameTransportActive":"active"),A=It(y,g?"protocol":"frameTransportProtocol")||It(w,g?"frameTransportProtocol":"protocol"),N=(g?It(o,"videoTransport","activeTransport")||[x,A].filter(Boolean).join("-")||It(t,"videoTransport"):It(t,"videoTransport")||It(o,"videoTransport","activeTransport")||[x,A].filter(Boolean).join("-")).toLowerCase(),E=/(?:^|[-_])ws(?:$|[-_])|websocket/.test(N)||/(?:^|[-_])ws(?:$|[-_])|websocket/.test(b),T=/relay/.test(N)||/relay/.test(b)?"encrypted-relay":/p2p|udp/.test(N)||b==="udp-p2p"?"p2p-udp":/direct|tcp|ws|websocket/.test(N)||b==="binary"||E?E?"direct-ws":"direct-tcp":"",F=(It(y,g?"state":"frameTransportState")||It(w,g?"frameTransportState":"state")||(T?"active":"")).toLowerCase(),O=It(y,g?"reason":"frameTransportReason")||It(w,g?"frameTransportReason":"reason"),P=g?u||c:c||u,z=Gf(P),I=z===void 0?void 0:Math.max(0,r-z),X=I===void 0?"":I<1e3?"changed now":I<6e4?`changed ${Math.round(I/1e3)}s ago`:I<36e5?`changed ${Math.round(I/6e4)}m ago`:`changed ${P}`,se=g?o.switchCount??t?.frameTransportSwitchCount:t?.frameTransportSwitchCount??o.switchCount,Z=g?o.tcpFailureCount??t?.frameTransportTcpFailureCount:t?.frameTransportTcpFailureCount??o.tcpFailureCount,G=g?typeof o.p2pReady=="boolean"?o.p2pReady:t?.frameTransportP2pReady===!0:typeof t?.frameTransportP2pReady=="boolean"?t.frameTransportP2pReady:o.p2pReady===!0;return{rawTransport:b,videoTransport:T,state:F,reason:O,changedAt:P,changedLabel:X,switchCount:Math.max(0,Number(se??0)||0),tcpFailureCount:Math.max(0,Number(Z??0)||0),p2pReady:G}}function WE(t,n,r){const o=h0(t,n,r),c=/(connecting|recovering|failed|error|degraded|unavailable)/.test(o.state);if(o.videoTransport==="encrypted-relay")return Qe("transport",c?"warning":"ok",c?"Encrypted TCP relay fallback needs attention":"Encrypted TCP relay fallback",c?`End-to-end encrypted TCP relay is ${o.state||"not ready"}; open Debug Status for the technical reason${o.changedLabel?` · ${o.changedLabel}`:""}.`:`End-to-end encrypted TCP relay fallback is active${o.changedLabel?` · ${o.changedLabel}`:""}.`);if(o.videoTransport==="p2p-udp")return Qe("transport",c?"warning":"ok",c?"P2P video connection needs attention":"P2P video connection",c?`Encrypted UDP P2P is ${o.state||"not ready"}; open Debug Status for the technical reason${o.changedLabel?` · ${o.changedLabel}`:""}.`:`Encrypted UDP P2P fallback is active${o.changedLabel?` · ${o.changedLabel}`:""}.`);if(o.videoTransport==="direct-tcp"||o.videoTransport==="direct-ws"){const u=o.videoTransport==="direct-ws"?"WebSocket":"TCP";return Qe("transport",c?"warning":"ok",c?"Direct video connection needs attention":"Direct video connection",c?`Direct ${u} to Hub is ${o.state||"not ready"}; open Debug Status for the technical reason${o.changedLabel?` · ${o.changedLabel}`:""}.`:`Direct ${u} to Hub is active${o.changedLabel?` · ${o.changedLabel}`:""}.`)}return Qe("transport","warning","Video transport is not identified",o.reason||"Waiting for Direct TCP, encrypted UDP P2P, or encrypted TCP relay transport data.")}const GE=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 g0(t){const r=String(t?.platformProfile||"").toLowerCase().includes("macos-screencapturekit"),o=Number(t?.nativeCaptureTelemetryVersion)>=5&&GE.every(u=>bt(t,u)!==void 0)&&typeof t?.nativeOutputQueueAwaitingKeyFrame=="boolean"&&t?.nativeCopyTelemetryAvailable===!0,c=t?.nativeCaptureTelemetryAvailable===!0&&t?.nativeCaptureResourceTelemetryAvailable===!0&&o;return{required:r,available:c,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 VE(t){const n=String(t?.frameMode||t?.mode||t?.codec||"").toLowerCase(),r=[t?.hardwareEncoder,t?.platformProfile].filter(Boolean).join(" · "),o=u0(t,"nativeEncoderHardwareAccelerated"),c=t?.nativeEncoderHardwareAccelerationKnown===!0||o!==void 0,u=g0(t);return!t||!/h264/.test(n)?Qe("encoder","warning","Video encoder unavailable","Waiting for an H.264 frame."):u.required&&!u.available?Qe("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)?Qe("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?Qe("encoder","warning","Hardware H.264 encoding is under load",`${u.coalesced} current-window frame(s) were coalesced while the encoder was busy.`):c&&o===!1?Qe("encoder","warning","H.264 hardware acceleration is not active",`${r||"Native encoder"} is running without confirmed hardware acceleration.`):c&&o===!0?Qe("encoder","ok","Hardware H.264 encoding",`${r||"Native encoder"} · hardware acceleration confirmed`):BE.test(r)?Qe("encoder","ok","Hardware H.264 encoding",r):HE.test(r)?Qe("encoder","warning","Software H.264 encoding",`${r||"CPU encoder"} may limit frame rate.`):Qe("encoder","warning","H.264 encoder not identified",r||"The Client has not reported its active encoder profile.")}function KE({device:t,frame:n,receiveStat:r,paintStat:o,codec:c,selectedMonitorIndex:u=0,control:f=!1,controlInputReady:h=!1,controlBinding:g,hubRelay:y,capturePaused:w=!1,capturePauseConfirmed:b=!0,capturePauseError:x="",clientHeartbeatMs:A=5e3,now:k=Date.now()}={}){const N=an(t),E=an(N.status),D=an(o?.lastInfo),T=[],F=p0(n,k);T.push(UE(N)),T.push(w?b?Qe("connection","ok","Video capture is paused","Client screen capture and video encoder shutdown were confirmed by the Client."):Qe("connection","warning","Video stop needs attention",String(x||"The Hub is blocking video restart, but the Client did not confirm screen capture and video encoder shutdown.")):N.connected===!0&&F<=At.frameAgeWarningMs?Qe("connection","ok","Video connection is current",`${Math.round(F)}ms since the latest frame.`):Qe("connection","warning",N.connected===!0?"Video frame is stale":"Client is offline",N.connected===!0&&Number.isFinite(F)?`${Math.round(F)}ms since the latest frame.`:String(N.lastDisconnectReason||"No current Client session."))),T.push(WE(n,E,k)),T.push(VE(n));const O=d0(E.capture),P=an(E.capture),z=f0({key:`${String(N.deviceId||N.id||"")}:capture-cleanup`,sampleId:It(P,"sampledAt"),mismatch:O.helperLedgerMismatch||O.utilityLedgerMismatch});(O.helperQuarantineCount>0||O.utilityQuarantineCount>0||z.confirmed)&&T.push(Qe("capture-cleanup","warning","Video capture cleanup needs attention",`capture quarantine ${O.helperQuarantineCount} · utility quarantine ${O.utilityQuarantineCount} · owned I/O ${O.helperOwnedIoTaskCount+O.utilityOwnedIoTaskCount} · exit observers ${O.helperOwnedExitObserverCount} · undisposed processes ${O.helperUndisposedProcessCount+O.utilityUndisposedProcessCount}`));const I=Math.max(0,Number(n?.requestedFps||n?.effectiveFps||0)),X=Math.max(0,Number(r?.framesPerSecond||0));Math.max(0,Number(n?.sourceGapMs||0));const se=Math.max(0,Number(n?.nativeCaptureFps||0)),Z=Math.max(0,Number(n?.nativeEncodedFps||0)),G=Math.max(0,Number(n?.nativeCaptureSampleCount||0)),K=Math.max(0,Number(n?.nativeCaptureTelemetryVersion||0)),me=bt(n,"nativeCaptureTelemetryAgeMs"),ne=Math.max(0,Number(me||0))+(Number.isFinite(F)?F:0),$=K<2||me!==void 0&&ne<=At.nativeTelemetryStaleMs,_=Math.max(0,Number(n?.nativeBackpressureSkippedFrameCount||0)),ie=Math.max(0,Number(n?.nativeIdleSkippedFrameCount||0)),be=n?.nativeCaptureTelemetryAvailable===!0&&G>0&&$,H=bt(n,"captureP95Ms","captureAverageMs","captureStageMs"),te=Math.max(0,Number(H||0)),le=n?.captureTimingAvailable===!0&&I>0&&Number(r?.sampleMs||0)>0&&H!==void 0,Ce=le||be,Ae=Math.max(At.minimumCaptureBudgetMs,I>0?1e3/I*At.captureBudgetMultiplier:0),_e=I>0?1e3/I:100,ue=I>0&&se>=I*At.receiveRatioWarning,He=Z>0&&Z<I*At.receiveRatioWarning,ze=be&&ue&&He&&Z>=1&&ie>=Math.max(10,se*.6)&&_===0,et=be&&I>0&&(se<I*At.receiveRatioWarning||!ze&&Z>0&&Z<I*At.receiveRatioWarning),Xe=be?et:le&&te>Ae;T.push(Ce?Xe?Qe("capture","warning","Screen capture cannot keep target speed",be?`${se.toFixed(1)} native capture · ${Z.toFixed(1)} encoded · ${I||"?"} requested fps`:`${te?`capture p95 ${Math.round(te)}ms`:"capture timing unavailable"} · ${X.toFixed(1)}/${I||"?"} fps`):Qe("capture","ok","Screen capture speed is healthy",be?`${se.toFixed(1)} native capture · ${Z.toFixed(1)} encoded · ${I||"?"} requested fps${ze?" · idle optimized":""}`:`${te?`capture p95 ${Math.round(te)}ms`:"no slow capture reported"}${I?` · ${X.toFixed(1)}/${I} fps`:""}`):Qe("capture","warning","Screen capture data is still collecting","A current frame-rate and capture-time sample is required."));const Ze=bt(n,"hubPacketTransitAgeMs"),Ue=Math.max(0,Number(Ze||0)),Y=Math.max(0,Number(n?.agentSendGapMs||0)),Se=Math.max(0,Number(n?.agentSendDurationMs||0)),ye=!$E(N.remoteAddress),je=bi(E,"network.usageRatio"),$e=bt(E,"network.latencyMs"),B=(je??0)>=At.networkUsageWarningRatio||($e??0)>=At.networkLatencyWarningMs,lt=n?.hubClientQueueTelemetryAvailable===!0||bt(n,"hubClientDropped")!==void 0&&bt(n,"hubClientQueueDepth")!==void 0&&bt(n,"hubClientQueueLimit")!==void 0&&bt(n,"hubClientBufferedBytes")!==void 0,Nt=lt?Math.max(0,Number(n?.hubClientQueueDepth||0)):0,Ht=lt?Math.max(0,Number(n?.hubClientQueueLimit||0)):0,ke=lt&&Ht>0&&Nt>=Ht,qe=Ze!==void 0&&Number(r?.sampleMs||0)>0,Ye=!ze&&I>0&&Number(r?.sampleMs||0)>0&&X<I*At.deliveryRatioWarning,_t=!ze&&Y>Math.max(At.networkDelayWarningMs,_e*3),tt=Ue>At.networkDelayWarningMs||_t||Se>At.networkDelayWarningMs||Ye||F>At.frameAgeWarningMs||B||ke;T.push(qe?tt||ye?Qe("network","warning",ye?"External network route may add delay":B?"Client network adapter needs attention":ke?"Hub browser video queue needs attention":"Video delivery is uneven",[Ue?`${Math.round(Ue)}ms Hub-to-browser`:"",Y?`${Math.round(Y)}ms Client send gap`:"",Se?`${Math.round(Se)}ms Client send time`:"",Ye?`${X.toFixed(1)} of ${I} requested fps`:"",$e!==void 0?`${Math.round($e)}ms Client network latency`:"",je!==void 0?`${Math.round(je*100)}% Client link use`:"",lt&&Ht>0?`Hub queue ${Nt}/${Ht}`:"",ye?String(N.remoteAddress||"external route"):""].filter(Boolean).join(" · ")||"Frame delivery is not current."):Qe("network","ok","Network delivery is healthy",`${Math.round(Ue)}ms Hub-to-browser · ${ze?`idle optimized at ${Z.toFixed(1)} fps`:"the current video rate is on target."}`):Qe("network","warning","Network delivery data is still collecting","A calibrated Hub-to-browser transit sample is required."));const pe=bi(E,"cpu.usageRatio","cpu.usedRatio","cpu.percent"),Ne=bi(E,"memory.usedRatio","usedMemRatio"),Be=bi(E,"gpu.usageRatio"),Oe=bi(E,"gpu.memory.usedRatio"),We=bt(E,"gpu.temperatureC","thermal.gpuC"),Rt=pe!==void 0&&Ne!==void 0,ee=Gf(N.lastStatusAt),he=ee===void 0?Number.POSITIVE_INFINITY:Math.max(0,k-ee),Fe=Math.max(At.minimumClientStatusFreshMs,Math.max(1e3,Number(A||0))*At.clientStatusFreshMultiplier),fe=he<=Fe,xe=(pe??0)>=At.cpuWarningRatio||(Ne??0)>=At.memoryWarningRatio||(Be??0)>=At.gpuWarningRatio||(Oe??0)>=At.gpuMemoryWarningRatio||(We??0)>=At.gpuTemperatureWarningC;T.push(Rt?fe?xe?Qe("computer","warning",(Be??0)>=At.gpuWarningRatio||(Oe??0)>=At.gpuMemoryWarningRatio||(We??0)>=At.gpuTemperatureWarningC?"Client GPU is under load":"Client computer is under load",[`CPU ${Math.round(pe*100)}%`,`memory ${Math.round(Ne*100)}%`,Be!==void 0?`GPU ${Math.round(Be*100)}%`:"",Oe!==void 0?`GPU memory ${Math.round(Oe*100)}%`:"",We!==void 0?`GPU ${Math.round(We)}C`:""].filter(Boolean).join(" · ")):Qe("computer","ok","Client computer has working capacity",[`CPU ${Math.round(pe*100)}%`,`memory ${Math.round(Ne*100)}%`,Be!==void 0?`GPU ${Math.round(Be*100)}%`:""].filter(Boolean).join(" · ")):Qe("computer","warning","Client performance snapshot is stale",Number.isFinite(he)?`The latest CPU and memory report is ${Math.round(he/1e3)} seconds old.`:"No current Client performance heartbeat has been received."):Qe("computer","warning","Client performance data is unavailable","CPU and memory telemetry have not been reported yet."));const nt=Number(n?.monitorIndex),ct=Number.isInteger(nt)&&nt===Number(u),ft=an(N.channels),dt=an(N.capabilities),Dt=ft.input!==!1&&dt.remoteInput!==!1&&dt.accessibilityPermission!==!1,Yt=dt.screenRecordingPermission!==!1,cn=an(g),Xt=!f||String(n?.sessionId||"")&&String(n?.sessionId||"")===String(cn.sessionId||"")&&String(n?.commandId||"")&&String(n?.commandId||"")===String(cn.commandId||"")&&Number(n?.captureGeneration||0)>0&&Number(n?.captureGeneration||0)===Number(cn.captureGeneration||0)&&Number(n?.monitorIndex)===Number(cn.monitorIndex),oa=!f||h&&Xt;T.push(ct&&oa&&Dt&&Yt?Qe("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"}.`):Qe("display","warning",Yt?Dt?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(nt)?nt+1:"not available"}.`));const Na=an(c),Pn=Array.isArray(Na.canvases)?an(Na.canvases[0]):{},Wn=Math.max(0,Number(o?.decoderInputFps||0)),la=Math.max(0,Number(o?.decoderOutputFps||0)),Pe=Wn>0&&Number(o?.sampleMs||r?.sampleMs||0)>0,at=X>0&&Number(r?.sampleMs||0)>0&&Number(o?.sampleMs||0)>0&&Wn<X*At.decoderInputRatioWarning,ht=Wn>0?la/Wn:0,Zt=It(Pn,"configuredAcceleration","requestedAcceleration")||It(D,"h264DecodeAcceleration"),bn=It(Pn,"softwareFallbackReason"),Es=!!bn||Zt==="prefer-software";return T.push(at?Qe("decoder","warning","Browser decoder input is dropping frames",`${X.toFixed(1)} received / ${Wn.toFixed(1)} decoder input / ${la.toFixed(1)} output fps.`):Pe?Es||ht<At.decoderOutputRatioWarning?Qe("decoder","warning",Es?"Browser is using software H.264 fallback":"Browser decoder output is slow",`${bn||String(D.decoderLabel||Zt||"decoder")} · ${Wn.toFixed(1)} in / ${la.toFixed(1)} out fps.`):Qe("decoder","ok",Zt==="prefer-hardware"?"Browser requests hardware H.264":"Browser H.264 path is responsive",`${Wn.toFixed(1)} in / ${la.toFixed(1)} out fps. Chrome does not expose definitive hardware acceptance.`):Qe("decoder","warning","Browser decoder data is still collecting","Decoder input and output samples are required before this path can be marked healthy.")),T}function Hi(t){const n=String(t||"").trim();return n?n.length<=14?n:`${n.slice(0,6)}…${n.slice(-5)}`:"-"}function yn(t,n=1){const r=Number(t);return Number.isFinite(r)?r.toFixed(n):"-"}function QE({device:t,frame:n,receiveStat:r,paintStat:o,codec:c,selectedMonitorIndex:u=0,control:f=!1,controlInputReady:h=!1,controlBinding:g,hubRelay:y,now:w=Date.now()}={}){const b=an(t),x=an(b.status),A=an(x.runtimeProcess),k=an(x.capture),N=d0(k),E=an(g),D=an(o?.lastInfo),T=an(c),F=Array.isArray(T.canvases)?an(T.canvases[0]):{},O=[],P=Number(u),z=Number(n?.monitorIndex),I=Number.isInteger(z)&&z===P,X=Number(n?.captureGeneration||0),se=Number(E.captureGeneration||0),Z=!f||I&&String(n?.sessionId||"")===String(E.sessionId||"")&&String(n?.commandId||"")===String(E.commandId||"")&&X>0&&X===se,G=Math.max(0,Number(n?.requestedFps||n?.effectiveFps||0)),K=Math.max(0,Number(r?.framesPerSecond||0)),me=Math.max(0,Number(o?.framesPerSecond||0)),V=Math.max(0,Number(o?.decoderInputFps||0)),ne=Math.max(0,Number(o?.decoderOutputFps||0)),$=Number(r?.sampleMs||0)>0&&Number(o?.sampleMs||0)>0,_=G>0&&$&&Math.min(K,me||K,ne||K)<G*At.deliveryRatioWarning,ie=Math.max(0,Number(n?.sourceGapMs||0)),be=Math.max(0,Number(n?.agentSendGapMs||0)),H=Math.max(0,Number(n?.agentSendDurationMs||0)),te=Math.max(0,Number(n?.agentSendDurationFrameSeq||0)),le=Math.max(0,Number(n?.agentQueueBeforePaceMs||0)),Ce=Math.max(0,Number(n?.agentFrameAgeMs||0)),Ae=bt(n,"hubPacketTransitAgeMs"),_e=Math.max(0,Number(n?.droppedByAgent||0)),ue=Math.max(0,Number(n?.hubIngressDropped||0)),He=n?.hubClientQueueTelemetryAvailable===!0||bt(n,"hubClientDropped")!==void 0&&bt(n,"hubClientQueueDepth")!==void 0&&bt(n,"hubClientQueueLimit")!==void 0&&bt(n,"hubClientBufferedBytes")!==void 0,ze=He?Math.max(0,Number(n?.hubClientDropped||0)):0,et=He?Math.max(0,Number(n?.hubClientQueueDepth||0)):0,Xe=He?Math.max(0,Number(n?.hubClientQueueLimit||0)):0,Ze=He?Math.max(0,Number(n?.hubClientBufferedBytes||0)):0,Ue=Math.max(0,Number(n?.udpIncompleteFrames||0)),Y=_e+ue+ze,Se=p0(n,w),ye=It(F,"configuredAcceleration","requestedAcceleration")||It(D,"h264DecodeAcceleration"),je=It(F,"softwareFallbackReason"),$e=Math.max(0,Number(T.hardwareReleaseGeneration||0)),B=Math.max(0,Number(T.hardwareRecoveryProbeCount||0)),lt=Number(T.lastHardwareRecoveryProbeAt),Nt=Number.isFinite(lt)&&lt>0?Math.max(0,w-lt):void 0,Ht=`hardware releases ${$e} · recovery probes ${B} · last probe ${Nt===void 0?"-":`${Math.round(Nt)}ms ago`}`,ke=$&&K>0&&V<K*At.decoderInputRatioWarning,qe=h0(n,x,w),Ye=It(b,"deviceId")||It(n,"deviceId"),_t=It(n,"sessionId")||It(b,"sessionId"),tt=It(b,"productVersion")||It(x,"productVersion","runtime.productVersion"),pe=It(b,"agentVersion")||It(x,"agentVersion","runtime.agentVersion"),Ne=bt(b,"pid","runtimePid")??bt(x,"pid","runtimePid","process.pid"),Be=bt(A,"pid"),Oe=bi(A,"cpuUsageRatio"),We=bt(A,"cpuCorePercent"),Rt=bt(A,"workingSetBytes"),ee=bt(A,"privateMemoryBytes"),he=Math.max(Rt||0,ee||0),Fe=(Be??0)>0&&(Rt??0)>0,fe=Fe&&(Ne??0)>0&&Be!==Ne,xe=(Oe??0)>=At.runtimeProcessCpuWarningRatio||he>=At.runtimeProcessMemoryWarningBytes,nt=bi(x,"cpu.usageRatio"),ct=bi(x,"memory.usedRatio","usedMemRatio"),ft=Math.max(0,Number(bt(k,"videoStreamCount")||0)),dt=Math.max(0,Number(bt(k,"audioStreamCount")||0)),Dt=bt(k,"helperCount"),Yt=Math.max(0,Number(Dt||0)),cn=bt(k,"helperMaxConcurrent"),Xt=Math.max(Yt,Number(cn||0)),oa=Array.isArray(k.helperPids)?k.helperPids.map(Ea=>Number(Ea)).filter(Ea=>Number.isSafeInteger(Ea)&&Ea>0):[],Na=Array.isArray(k.helperProfiles)?k.helperProfiles.map(Ea=>String(Ea||"").trim()).filter(Boolean).slice(0,4):[],Pn=bi(k,"helperCpuUsageRatio"),Wn=bt(k,"helperCpuCorePercent"),la=bt(k,"helperWorkingSetBytes"),Pe=bt(k,"helperPrivateMemoryBytes"),q=Math.max(la||0,Pe||0),at=Math.max(0,Number(bt(k,"helperStartCount")||0)),ht=Math.max(0,Number(bt(k,"helperStopCount")||0)),Zt=Dt!==void 0,bn=Zt&&at>=ht&&at-ht!==Yt,Es=Yt>1||Xt>1||ft>1||bn||N.currentProblem,Ua=Zt&&(ft>0&&Yt===0||ft===0&&Yt>0),de=f0({key:Ye&&_t?`${Ye}:${_t}`:"",sampleId:It(k,"sampledAt"),mismatch:Ua}),De=Ua&&!de.confirmed,Ke=Es||de.confirmed,wt=(Pn??0)>=At.captureHelperCpuWarningRatio||q>=At.captureHelperMemoryWarningBytes,Jt=!!(Ye&&_t&&tt&&pe&&(Ne??0)>0),Ft=n?.nativeCaptureTelemetryAvailable===!0,mt=Math.max(0,Number(n?.nativeCaptureTelemetryVersion||0)),Pt=mt>=2,xt=g0(n),mn=!xt.required||xt.available,na=bt(n,"nativeCaptureTelemetryAgeMs"),On=Math.max(0,Number(na||0))+(Number.isFinite(Se)?Se:0),rn=na===void 0?"-":`${Math.round(On)}ms`,br=!Pt||na!==void 0&&On<=At.nativeTelemetryStaleMs,wr=Ft&&!br,Ot=u0(n,"nativeEncoderHardwareAccelerated"),Rn=n?.nativeEncoderHardwareAccelerationKnown===!0||Ot!==void 0,Bn=It(n,"nativeEncoderHardwareQueryStatus"),Za=Bn==="0"?"confirmed":Bn,va=Math.max(0,Number(n?.nativeCaptureDisplayId||0)),xr=Math.max(0,Number(n?.nativeCaptureFps||0)),Ja=Math.max(0,Number(n?.nativeCompressionOutputCount||0)),is=Math.max(0,Number(n?.nativeCompressionFps||0)),Ta=Math.max(0,Number(n?.nativeEncodedFps||0)),un=Pt||Ja>0?is:Ta,er=Math.max(0,Number(n?.nativeCaptureSampleCount||0)),Ds=Math.max(0,Number(n?.nativeEncodableFrameCount||0)),_o=Math.max(0,Number(n?.nativeSkippedFrameCount||0)),os=Math.max(0,Number(n?.nativeEncodedFrameCount||0)),Js=Math.max(0,Number(n?.nativeEncodeFramesInFlight||0)),Ki=xt.pending,Ln=xt.timestampOwners,Fo=xt.timestampOwnerHighWatermark,Jc=xt.coalesced,Wr=Math.max(0,Number(n?.nativeBackpressureSkippedFrameCount||0)),ei=xt.pendingReplaced,St=Math.max(0,Number(n?.nativeIdleSkippedFrameCount||0)),Gn=xt.vtActive,ls=xt.vtHighWatermark,en=Math.max(0,Number(n?.nativeOutputQueueDepth||0)),Qi=Math.max(0,Number(n?.nativeOutputQueueBytes||0)),Po=xt.outputOldestAgeMs,ti=Math.max(0,Number(n?.nativeOutputQueueHighWatermark||0)),Kl=Math.max(0,Number(n?.nativeOutputQueueDroppedCount||0)),Wt=n?.nativeOutputQueueAwaitingKeyFrame===!0,Ra=xt.nativeAndPipeResidenceAgeMs,tr=xt.handoffDropped,ni=xt.handoffRecoveryRequests,Vn=xt.handoffOldestAgeMs,Sr=Js>2||Ki>1||Ln>2||Fo>2||Jc>0||Js>=2&&Wr>0,qa=xt.required&&xt.available&&(Gn!==1||ls>1||Ln>2||Fo>2),Ql=en>=3||Qi>=6*1024*1024||Po>120||Kl>0||Wt||Ra>250||tr>0||ni>0||Vn>120,Oo=`in-flight ${Js}/2 · backpressure skipped ${Wr} · idle skipped ${St} · stdout queue ${en} AU/${Math.round(Qi/1024)} KB/${Math.round(Po)}ms · HWM ${ti} · dropped ${Kl} · awaiting key ${Wt?"yes":"no"} · native+pipe ${Math.round(Ra)}ms · handoff ${Math.round(Vn)}ms/drop ${tr}/recovery ${ni}`,Yl=`pending ${Ki}/1; timestamp owners ${Ln}/2 (HWM ${Fo}); coalesced ${Jc}; pending replaced ${ei}; VideoToolbox ${Gn} active/HWM ${ls}`,Yi=xt.available&&xt.annexBAllocations>0&&xt.annexBPayloadCopies>=xt.annexBAllocations&&xt.annexBPayloadCopiedBytes>0&&xt.pipePayloadAllocations>0&&xt.pipePayloadCopies>=xt.pipePayloadAllocations&&xt.pipePayloadCopiedBytes>0,Cr=`Annex-B allocation/copy ${xt.annexBAllocations}/${xt.annexBPayloadCopies} (${Math.round(xt.annexBPayloadCopiedBytes/1024)} KB) · pipe allocation/read ${xt.pipePayloadAllocations}/${xt.pipePayloadCopies} (${Math.round(xt.pipePayloadCopiedBytes/1024)} KB)`,cs=Ft&&er>0&&br,Xi=G>0?1e3/G:100,us=G>0&&xr>=G*At.receiveRatioWarning,ai=un>0&&un<G*At.receiveRatioWarning,Gt=cs&&us&&ai&&un>=1&&Ta>=1&&St>=Math.max(10,xr*.6)&&Wr===0,ja=_&&!Gt,nr=!Gt&&be>Math.max(At.networkDelayWarningMs,Xi*3),pn=cs&&G>0&&xr<G*At.receiveRatioWarning,ds=cs&&!Gt&&xr>0&&(Pt&&un<=0||un>0&&un<xr*At.receiveRatioWarning),xn=cs&&Ja>0&&un>0&&Ta<un*At.receiveRatioWarning,kr=wr?"Native capture telemetry is stale":mn?qa?"VideoToolbox encoder ownership needs attention":cs?pn?"Native screen capture is below request":ds||Sr?"VideoToolbox compression is behind capture":xn||Ql?"Native stdout delivery is backpressured":Ot===!1?"Native hardware encoder is unavailable":"Native capture or encoder needs attention":"Native capture telemetry is unavailable":"Native encoder resource telemetry is unavailable";O.push(qE(b,y)),O.push(Jt?Qe("debug-runtime","ok",`LiveDesk ${tt} · Agent ${pe}`,`pid ${Ne} · session ${Hi(_t)} · device ${Hi(Ye)}`):Qe("debug-runtime","warning","Runtime identity is incomplete",`LiveDesk ${tt||"-"} · Agent ${pe||"-"} · pid ${Ne??"-"} · session ${Hi(_t)} · device ${Hi(Ye)}`)),O.push(Fe&&!fe&&!xe?Qe("debug-process-load","ok","RemoteFast process load is healthy",`pid ${Be} · CPU ${Fl(Oe)} machine / ${gp(We)} core · RSS ${_l(Rt)} · private ${_l(ee)} · system CPU ${Fl(nt)} · memory ${Fl(ct)}`):Qe("debug-process-load","warning",Fe?fe?"RemoteFast process identity does not match":"RemoteFast process load needs attention":"RemoteFast process telemetry is collecting",`runtime pid ${Be??"-"} · reported pid ${Ne??"-"} · CPU ${Fl(Oe)} machine / ${gp(We)} core · RSS ${_l(Rt)} · private ${_l(ee)} · system CPU ${Fl(nt)} · memory ${Fl(ct)}`)),O.push(n?Qe("debug-frame","ok",`Frame #${Number(n.frameSeq||0)} · ${String(n.streamPurpose||(f?"control":"wall"))}`,`stream ${Hi(n.streamId)} · ${n.width||0}x${n.height||0} · ${Math.round(Number(n.byteLength||0)/1024)} KB · age ${Number.isFinite(Se)?Math.round(Se):"-"}ms`):Qe("debug-frame","warning","No current frame",`Device ${Hi(b.deviceId)} has not produced a frame.`));const Wa=/(connecting|recovering|failed|error|degraded|unavailable)/.test(qe.state);O.push(qe.videoTransport&&!Wa?Qe("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(" · ")):Qe("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(" · "))),O.push(I?Qe("debug-monitor","ok",`Monitor selected ${P+1} · frame ${z+1}`,`reported ${Number(n?.monitorCount||0)||"?"} displays · generation ${X||"-"}`):Qe("debug-monitor","warning",`Monitor mismatch: selected ${P+1} · frame ${Number.isInteger(z)?z+1:"-"}`,`reported ${Number(n?.monitorCount||0)||"?"} displays · generation ${X||"-"}`)),O.push(Z&&(!f||h)?Qe("debug-binding","ok",f?"Control generation is bound":"Wall capture generation is current",`session ${Hi(n?.sessionId)} · command ${Hi(n?.commandId)} · generation ${X||"-"}`):Qe("debug-binding","warning",f?"Control generation is not bound":"Wall capture generation is unavailable",`frame ${Hi(n?.commandId)}/${X||"-"} · expected ${Hi(E.commandId)}/${se||"-"} · input ${h?"ready":"waiting"}`)),O.push($&&!ja?Qe("debug-cadence","ok",`Cadence ${yn(K)} rx · ${yn(me)} paint · ${yn(ne)} decode`,`requested ${yn(G)} · decoder input ${yn(V)} fps · receive p95 ${yn(r?.p95IntervalMs)}ms${Gt?" · idle optimized":""}`):Qe("debug-cadence","warning",$?"Frame cadence is below request":"Frame cadence sample is collecting",`requested ${yn(G)} · receive ${yn(K)} · paint ${yn(me)} · decode ${yn(ne)} fps`)),O.push(cs&&mn&&!pn&&!ds&&!xn&&!Sr&&!qa&&!Ql&&Ot!==!1?Qe("debug-native-capture","ok",`Native capture ${yn(xr)} fps · compress ${yn(un)} fps · stdout ${yn(Ta)} fps${Gt?" · idle optimized":""}`,`telemetry v${mt||1} · age ${rn} · hardware ${Rn?Ot?"yes":"no":"unknown"}${Za?` (${Za})`:""} · display ${va||"-"} · capture samples ${er} · encodable ${Ds} · skipped ${_o} · compression outputs ${Ja} · stdout written ${os} · ${Oo} · encoded AU output gap ${Math.round(ie)}ms`):Qe("debug-native-capture","warning",kr,`telemetry ${Ft?`v${mt||1}`:"no"} · age ${rn} · hardware ${Rn?Ot?"yes":"no":"unknown"}${Za?` (${Za})`:""} · display ${va||"-"} · capture ${yn(xr)} fps · compress ${yn(un)} fps · stdout ${yn(Ta)} fps · capture samples ${er} · encodable ${Ds} · skipped ${_o} · compression outputs ${Ja} · stdout written ${os} · ${Oo} · encoded AU output gap ${Math.round(ie)}ms`)),xt.required&&(O.push(mn&&!Sr&&!qa?Qe("debug-native-resource","ok","VideoToolbox resource ownership is bounded",Yl):Qe("debug-native-resource","warning",mn?qa?"VideoToolbox session ownership is not exclusive":"VideoToolbox encode lane is coalescing":"VideoToolbox resource telemetry is unavailable",Yl)),O.push(mn&&Yi?Qe("debug-native-copy","ok","Capture copy accounting is current",Cr):Qe("debug-native-copy","warning",mn?"Capture copy accounting needs attention":"Capture copy accounting is unavailable",Cr))),O.push(Zt&&!Ke&&!wt?Qe("debug-capture-ownership","ok",De?"Capture ownership transition is settling":Yt>0?"Capture helper ownership is exclusive":"Capture helpers are idle",`video ${ft} · audio ${dt} · helpers ${Yt} (max ${Xt||"-"}) · pid ${oa.join(",")||"-"} · profile ${Na.join(", ")||"-"} · CPU ${Fl(Pn)} machine / ${gp(Wn)} core · RSS ${_l(la)} · private ${_l(Pe)} · starts ${at} / stops ${ht}${De?` · mismatch samples ${de.count}/${uv}`:""}`):Qe("debug-capture-ownership","warning",Zt?Yt>1||Xt>1?"Duplicate capture helpers detected":Ke?"Capture stream and helper ownership do not match":"Capture helper load needs attention":"Capture process telemetry is collecting",`video ${ft} · audio ${dt} · helpers ${Yt} (max ${Xt||"-"}) · pid ${oa.join(",")||"-"} · profile ${Na.join(", ")||"-"} · CPU ${Fl(Pn)} machine / ${gp(Wn)} core · RSS ${_l(la)} · private ${_l(Pe)} · starts ${at} / stops ${ht}`));const fs=`helper I/O ${N.helperOwnedIoTaskCount} | exit observers ${N.helperOwnedExitObserverCount} | undisposed ${N.helperUndisposedProcessCount} | quarantine ${N.helperQuarantineCount} | dispose failures ${N.helperDisposeFailureCount} | utility I/O ${N.utilityOwnedIoTaskCount} | undisposed ${N.utilityUndisposedProcessCount} | quarantine ${N.utilityQuarantineCount} | utility pid ${N.utilityQuarantinePids.join(",")||"-"} | profile ${N.utilityQuarantineProfiles.join(", ")||"-"} | utility starts ${N.utilityQuarantineStartCount} / stops ${N.utilityQuarantineStopCount} | dispose failures ${N.utilityDisposeFailureCount}${N.helperLastDisposeFailure?` | helper last ${N.helperLastDisposeFailure}`:""}${N.utilityLastDisposeFailure?` | utility last ${N.utilityLastDisposeFailure}`:""}`;O.push(N.telemetryAvailable&&!N.currentProblem&&!N.historicalCleanupFailure?Qe("debug-capture-cleanup","ok",Yt>0?"Capture cleanup ownership is exact":"Capture cleanup is idle",fs):Qe("debug-capture-cleanup","warning",N.telemetryAvailable?N.currentProblem?"Capture cleanup is quarantined or mismatched":"Capture cleanup recorded a disposal failure":"Capture cleanup telemetry is collecting",fs)),O.push(He?Y===0&&Ue===0&&(Xe<=0||et<Xe)&&!nr&&H<=At.networkDelayWarningMs&&Ce<=At.networkDelayWarningMs&&(Ae===void 0||Ae<=At.networkDelayWarningMs)?Qe("debug-delivery","ok","Delivery counters are clear",`encoded AU output gap ${Math.round(ie)}ms · Client send gap ${Math.round(be)}ms · Client send time ${Math.round(H)}ms (frame ${te||"-"}) · Agent queue ${Math.round(le)}ms · Agent age ${Math.round(Ce)}ms · Agent drop ${_e} · Hub transit ${Ae===void 0?"-":Math.round(Ae)}ms · Hub ingress drop ${ue} · browser queue drop ${ze} (${et}/${Xe||"-"}) · buffered ${Math.round(Ze/1024)} KB · UDP incomplete ${Ue}${Gt?" · idle optimized":""}`):Qe("debug-delivery","warning","Delivery counters show loss or delay",`encoded AU output gap ${Math.round(ie)}ms · Client send gap ${Math.round(be)}ms · Client send time ${Math.round(H)}ms (frame ${te||"-"}) · Agent queue ${Math.round(le)}ms · Agent age ${Math.round(Ce)}ms · Agent drop ${_e} · Hub transit ${Ae===void 0?"-":Math.round(Ae)}ms · Hub ingress drop ${ue} · browser queue drop ${ze} (${et}/${Xe||"-"}) · buffered ${Math.round(Ze/1024)} KB · UDP incomplete ${Ue}`):Qe("debug-delivery","warning","Browser queue counters are available in Hub Status",`encoded AU output gap ${Math.round(ie)}ms · Client send gap ${Math.round(be)}ms · Agent drop ${_e} · Hub ingress drop ${ue} · per-browser lane counters are intentionally collected outside video packets.`));const Zi=bt(n,"captureP95Ms");return O.push(n?.captureTimingAvailable===!0&&Zi!==void 0?Qe("debug-capture","ok",`Capture p95 ${yn(Zi)}ms · avg ${yn(n?.captureAverageMs)}ms`,`stage ${yn(n?.captureStageMs)}ms · slow ${Number(n?.slowFrameCount||0)} · helper restart ${Number(n?.captureHelperRestarts||0)} · source skip ${Number(n?.captureSourceSkipped||0)}`):cs&&Pt?Qe("debug-capture","ok","Capture latency is not instrumented; native cadence is current",`ScreenCaptureKit ${yn(xr)} fps · VideoToolbox ${yn(un)} fps · stdout ${yn(Ta)} fps · telemetry age ${rn}`):Qe("debug-capture","warning","Capture timing sample is unavailable",`stage ${yn(n?.captureStageMs)}ms · helper restart ${Number(n?.captureHelperRestarts||0)} · source serial ${Number(n?.captureSourceSerial||0)}`)),O.push(!je&&ye!=="prefer-software"&&!ke?Qe("debug-decoder","ok",`Decoder ${ye||"acceleration unknown"}`,`${String(n?.frameMode||n?.codec||"-")} · ${String(n?.hardwareEncoder||"-")} · ${String(n?.platformProfile||"-")} · ${Ht}`):Qe("debug-decoder","warning",ke?"Decoder input is losing received frames":"Decoder software fallback is active",ke?`${yn(K)} received / ${yn(V)} decoder input / ${yn(ne)} output fps · ${Ht}`:`${je||ye||"software"} · ${yn(V)} in / ${yn(ne)} out fps · ${Ht}`)),O}function YE({status:t,deviceDiagnostics:n=[],codec:r,browser:o,frameStats:c}={}){const u=an(t),f=an(u.diagnostics),h=an(f.system),g=an(f.network),y=an(r),w=an(o),b=Array.isArray(n)?n:[],x=b.reduce((Ce,Ae)=>Ce+(Array.isArray(Ae)&&Ae.some(_e=>_e?.state==="warning")?1:0),0),A=bi(h,"cpuUsageRatio","processCpuRatio"),k=bi(h,"memoryUsedRatio"),N=bt(h,"totalMemoryBytes"),E=bt(h,"cpuLogicalCores")??bt(w,"hardwareConcurrency"),D=bt(w,"deviceMemory"),T=(E??0)>0&&A!==void 0&&k!==void 0&&(N??0)>0,F=(N??0)>0&&N<At.hubMinimumTotalMemoryBytes,O=(D??0)>0&&D<At.hubMinimumBrowserMemoryGb,P=(E??0)>0&&E<4||(A??0)>=At.cpuWarningRatio||(k??0)>=At.memoryWarningRatio||F||O,z=Math.max(0,Number(y.activeSoftwareFallbackCount??y.softwareFallbackCount??0)),I=Math.max(0,Number(y.activeDecoderCount||0)),X=Math.max(0,Number(c?.bytesPerSecond||0)*8/1e6),se=bt(g,"externalDeviceCount"),Z=It(g,"route"),G=se!==void 0&&!!Z,K=(se??0)>0||Z==="external",me=an(u.frameLanes),V=an(me.packetFanout),ne=["packetBuilds","metadataSerializations","payloadCopyOperations","fanoutEligibleSubscribers"].every(Ce=>bt(V,Ce)!==void 0),$=Array.isArray(me.clients)?me.clients.map(an):[],_=bt(me,"clientCount")!==void 0&&Array.isArray(me.clients)&&ne,ie=$.some(Ce=>{const Ae=Math.max(0,Number(Ce.queueDepth||0)),_e=Math.max(0,Number(Ce.queueLimit||0)),ue=Math.max(0,Number(Ce.queuedBytes||0)),He=Math.max(0,Number(Ce.queueByteLimit||0));return Math.max(0,Number(Ce.droppedPackets||0))>0||_e>0&&Ae>=_e||He>0&&ue>=He||Array.isArray(Ce.backpressuredDeviceIds)&&Ce.backpressuredDeviceIds.length>0}),be=Math.max(0,Number(V.packetBuilds||0)),H=Math.max(0,Number(V.metadataSerializations||0)),te=Math.max(0,Number(V.payloadCopyOperations||0)),le=Math.max(0,Number(V.fanoutEligibleSubscribers||0));return[u.started&&!u.lastError?Qe("hub-runtime","ok","Hub runtime is ready",`${u.connectedDeviceCount||0} Clients connected.`):Qe("hub-runtime","warning","Hub runtime needs attention",String(u.lastError||"Hub is not ready.")),T?P?Qe("hub-computer","warning",F?"Hub has limited system memory":O?"Browser reports limited memory capacity":"Hub computer may limit remote performance",[`${E||"?"} logical cores`,`${Yw(N)} RAM`,D!==void 0?`${D} GB browser memory class`:"",`CPU ${A===void 0?"?":Math.round(A*100)}%`,`memory ${k===void 0?"?":Math.round(k*100)}%`].filter(Boolean).join(" · ")):Qe("hub-computer","ok","Hub computer capacity is healthy",`${E||"?"} logical cores · ${Yw(N)} RAM · CPU ${A===void 0?"not reported":`${Math.round(A*100)}%`}.`):Qe("hub-computer","warning","Hub performance data is unavailable","Logical-core, CPU, used-memory, and total-memory telemetry are required."),I<=0?Qe("hub-codec","warning","No active browser H.264 decoder to check","Open Wall or Control and wait for a video frame."):z>0?Qe("hub-codec","warning","Some browser decoders use software fallback",`${I} active H.264 decoders · ${z} software fallbacks. Chrome does not expose definitive hardware acceptance.`):Qe("hub-codec","ok","All active streams request hardware H.264",`${I} active decoders. Chrome hardware acceptance is inferred from health, not directly exposed.`),_?ie?Qe("hub-frame-lanes","warning","A Hub browser video lane needs attention",`${$.length}/${me.clientCount||0} lanes reported · packet builds ${be} · metadata serializations ${H} · payload copies ${te} · fanout deliveries ${le}.`):Qe("hub-frame-lanes","ok","Hub browser video lanes are bounded",`${$.length}/${me.clientCount||0} lanes reported · packet builds ${be} · metadata serializations ${H} · payload copies ${te} · fanout deliveries ${le}.`):Qe("hub-frame-lanes","warning","Hub browser queue data is unavailable","Per-browser queue, drop, buffered-byte, and packet-allocation evidence is required."),x>0?Qe("hub-clients","warning",`${x} Clients need attention`,"Open the matching Wall slot lines for the exact cause."):Qe("hub-clients","ok","Connected Clients report healthy remote paths",`${b.length} Client reports checked.`),Qe("hub-network",!G||K||X>120?"warning":"ok",G?K?`${se} Clients use an external network route`:X>120?"Hub receive load is high":"Hub receive load is within range":"Hub network route data is unavailable",G?`${Z.toUpperCase()} route · ${X.toFixed(X>=10?0:1)} Mbps received by this browser.`:"The Hub has not reported LAN/external route classification yet.")]}async function XE(t,n={}){const r=t.filter(b=>b.canvas&&b.canvas.width>0&&b.canvas.height>0),o=Math.max(320,n.maxWidth||1920),c=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(o/u),g=Math.floor(c/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 x=r[b],A=b%u,k=Math.floor(b/u),N=A*h,E=k*g,D=x.canvas,T=Math.min(h/D.width,g/D.height),F=Math.max(1,Math.floor(D.width*T)),O=Math.max(1,Math.floor(D.height*T)),P=N+Math.floor((h-F)/2),z=E+Math.floor((g-O)/2);w.drawImage(D,P,z,F,O),n.includeLabels!==!1&&(w.fillStyle="rgba(4, 10, 20, .74)",w.fillRect(N,E+g-28,h,28),w.fillStyle="#f8fafc",w.fillText(x.label,N+9,E+g-9))}return y}function ZE(t){return t?.signature||"none"}function JE(t){return t?.label||"No capture target"}function Zw(t){return{...t,deviceIds:[...t.deviceIds],sourceCanvas:t.sourceCanvas||null}}function eD(){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 tD(t){return t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function nD(t){return`LiveDesk_${t.type==="wall"||t.type==="selection"?"Wall":`${tD(t.label)}_Monitor-${Number(t.monitorIndex||0)+1}`}_${eD()}.png`}async function aD(t,n,r){const o=await new Promise((u,f)=>t.toBlob(h=>h?u(h):f(new Error("Screenshot could not be encoded.")),"image/png")),c=await o0(o,{kind:"screenshot",fileName:nD(n),target:n},r);try{await navigator.clipboard.write([new ClipboardItem({"image/png":o})])}catch{}return c.capture}function v0(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(n=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(n))||""}function rD(t,n){const r=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","_"),o=n.label.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,70)||"Wall";return t==="timelapse"?`LiveDesk_Timelapse_${o}_${r}.webm`:`LiveDesk_Recording_${o}_${r}.webm`}async function y0(t){if(typeof MediaRecorder>"u"||typeof t.canvas.captureStream!="function")throw new Error("This browser does not support video recording.");const n=v0();if(!n)throw new Error("This browser does not support WebM recording.");const r=t.kind||"recording",o=await DE({kind:r,fileName:rD(r,t.target),mimeType:n,target:t.target},t.hubUrl),c=t.canvas.captureStream(t.frameRequests?0:t.fps),u=new MediaRecorder(c,{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 x=h++;w=w.then(()=>IE(o.sessionId,x,b.data,t.hubUrl).then(()=>{})).catch(A=>{y=y||(A instanceof Error?A:new Error(String(A))),t.onError?.(y)})},u.onerror=()=>{y=new Error("Video recording stopped unexpectedly."),t.onError?.(y)},u.start(1e3),{requestFrame:()=>{c.getVideoTracks()[0]?.requestFrame?.()},stop:async()=>{if(!g){if(g=!0,await new Promise(b=>{u.addEventListener("stop",()=>b(),{once:!0}),u.stop()}),c.getTracks().forEach(b=>b.stop()),await w,y)throw await qw(o.sessionId,t.hubUrl).catch(()=>{}),y;await LE(o.sessionId,Math.max(0,performance.now()-f),t.hubUrl)}},cancel:async()=>{g||(g=!0,u.stop(),c.getTracks().forEach(b=>b.stop()),await qw(o.sessionId,t.hubUrl).catch(()=>{}))}}}class sD{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 o=v0();if(!o)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:o,videoBitsPerSecond:3e6}),this.startedAt=performance.now(),this.recorder.ondataavailable=c=>{if(!c.data.size)return;const u=performance.now();for(this.segments.push({blob:c.data,at:u}),this.totalBytes+=c.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 o=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 o0(o,{kind:"last-30s",fileName:u,target:n,durationMs:Math.min(3e4,this.segments.length*1e3)},r)}}async function iD(t,n,r,o,c){const u=await y0({canvas:t,target:n,kind:"timelapse",fps:30,frameRequests:!0,hubUrl:o,onError:c});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 b0="livedesk.captureSettings";function oD(){const t={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const n=JSON.parse(localStorage.getItem(b0)||"null");return{...t,...n&&typeof n=="object"?n:{}}}catch{return t}}function lD(t){const[n,r]=d.useState(oD),[o,c]=d.useState(0),[u,f]=d.useState(0),[h,g]=d.useState(0),[y,w]=d.useState(!1),b=d.useRef(void 0),x=d.useRef(!1),A=d.useRef(""),k=d.useRef(null),N=d.useRef(null),E=d.useRef(null),D=d.useRef(null),T=d.useRef(new sD),F=t.sourceRegistry.resolveCurrentTarget(),O=ZE(F),P=JE(F),z=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;d.useEffect(()=>{if(localStorage.setItem(b0,JSON.stringify(n)),!x.current)return;const ie=JSON.stringify(n);ie!==A.current&&(A.current=ie,rt("/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(be=>{b.current=Number(be.revision||b.current||0)}).catch(()=>{}))},[t.hubUrl,n]),d.useEffect(()=>{let ie=!0;return rt("/api/settings",void 0,t.hubUrl).then(be=>{if(!ie)return;const H=be.settings?.filesAudio||{},te=typeof H.rollingBufferEnabled=="boolean"?H.rollingBufferEnabled:n.rollingEnabled,le=H.recordingQuality==="high"?"high":"standard",Ce=[5,10,30,60].includes(Number(H.timelapseIntervalSeconds))?Number(H.timelapseIntervalSeconds):n.timelapseIntervalSeconds,Ae=typeof H.includeRemoteCursor=="boolean"?H.includeRemoteCursor:n.includeRemoteCursor,_e={rollingEnabled:te,recordingQuality:le,timelapseIntervalSeconds:Ce,includeRemoteCursor:Ae};b.current=Number(be.revision||0),A.current=JSON.stringify(_e),x.current=!0,r(_e)}).catch(()=>{x.current=!0}),()=>{ie=!1}},[t.hubUrl]);const I=d.useCallback(async ie=>{if(ie.sourceCanvas&&ie.sourceCanvas.width>0&&ie.sourceCanvas.height>0)return{target:Zw(ie),canvas:ie.sourceCanvas,cleanup:()=>{}};const be=await t.sourceRegistry.composeWall(ie.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let H=!1;const te=window.setInterval(async()=>{if(H)return;const le=await t.sourceRegistry.composeWall(ie.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0}).catch(()=>null);!le||H||((be.width!==le.width||be.height!==le.height)&&(be.width=le.width,be.height=le.height),be.getContext("2d")?.drawImage(le,0,0))},100);return{target:Zw(ie),canvas:be,cleanup:()=>{H=!0,window.clearInterval(te)}}},[t.sourceRegistry]);d.useEffect(()=>{const ie=T.current;if(!n.rollingEnabled||!F||!z){ie.stop(),g(0);return}let be=!1,H=null;return(async()=>{try{if(H=await I(F),be)return;await ie.start(H.canvas,H.target);const le=window.setInterval(()=>g(Math.round(ie.seconds)),500),Ce=()=>{window.clearInterval(le),H?.cleanup()};ie.__cleanup=Ce}catch(le){be||t.onToast(le instanceof Error?le.message:String(le))}})(),()=>{be=!0,ie.stop(),ie.__cleanup?.(),ie.__cleanup=void 0,g(0)}},[I,t.onToast,n.rollingEnabled,O,z]);const X=d.useCallback(ie=>r(be=>({...be,rollingEnabled:ie})),[]),se=d.useCallback(ie=>r(be=>({...be,recordingQuality:ie})),[]),Z=d.useCallback(ie=>r(be=>({...be,timelapseIntervalSeconds:ie})),[]),G=d.useCallback(async()=>{const ie=t.sourceRegistry.resolveCurrentTarget();if(!ie)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);let be=null;try{be=await I(ie),await aD(be.canvas,be.target,t.hubUrl),t.onToast("Screenshot saved")}finally{be?.cleanup(),w(!1)}},[I,t.hubUrl,t.onToast,t.sourceRegistry]),K=d.useCallback(async()=>{if(E.current)throw new Error("Stop the timelapse before recording.");const ie=t.sourceRegistry.resolveCurrentTarget();if(!ie)throw new Error("화면이 준비된 후 다시 시도하세요.");const be=await I(ie),H=await y0({canvas:be.canvas,target:be.target,fps:ie.type==="control"?30:15,hubUrl:t.hubUrl,onError:te=>t.onToast(te.message)});N.current=be.cleanup,k.current=H,c(Date.now()),t.onToast("Recording started")},[I,t.hubUrl,t.onToast,t.sourceRegistry]),me=d.useCallback(async()=>{const ie=k.current;if(ie){w(!0);try{await ie.stop(),t.onToast("Recording saved")}finally{k.current=null,N.current?.(),N.current=null,c(0),w(!1)}}},[t.onToast]),V=d.useCallback(async()=>{if(k.current||E.current)throw new Error("Last 30s is unavailable during a recording.");const ie=t.sourceRegistry.resolveCurrentTarget();if(!ie)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);try{await T.current.save(ie,t.hubUrl),t.onToast("Last 30 seconds saved")}finally{w(!1)}},[t.hubUrl,t.onToast,t.sourceRegistry]),ne=d.useCallback(async()=>{if(k.current)throw new Error("Stop the recording before starting a timelapse.");const ie=t.sourceRegistry.resolveCurrentTarget();if(!ie)throw new Error("화면이 준비된 후 다시 시도하세요.");const be=await I(ie),H=await iD(be.canvas,be.target,n.timelapseIntervalSeconds,t.hubUrl,te=>t.onToast(te.message));D.current=be.cleanup,E.current=H,f(Date.now()),t.onToast("Timelapse started")},[I,t.hubUrl,t.onToast,t.sourceRegistry,n.timelapseIntervalSeconds]),$=d.useCallback(async()=>{const ie=E.current;if(ie){w(!0);try{await ie.stop(),t.onToast("Timelapse saved")}finally{E.current=null,D.current?.(),D.current=null,f(0),w(!1)}}},[t.onToast]);return d.useEffect(()=>{const ie=be=>{!k.current&&!E.current||(be.preventDefault(),be.returnValue="")};return window.addEventListener("beforeunload",ie),()=>window.removeEventListener("beforeunload",ie)},[]),d.useEffect(()=>()=>{T.current.stop(),k.current?.cancel(),E.current?.cancel(),N.current?.(),D.current?.()},[]),{state:d.useMemo(()=>({recording:!!k.current,recordingStartedAt:o,timelapse:!!E.current,timelapseStartedAt:u,bufferSeconds:h,bufferEnabled:n.rollingEnabled,busy:y,targetLabel:P}),[h,y,o,n.rollingEnabled,P,u]),settings:n,videoSupported:z,targetKey:O,setRollingEnabled:X,setRecordingQuality:se,setTimelapseInterval:Z,takeScreenshot:G,startRecording:K,stopRecording:me,saveLast30Seconds:V,startTimelapse:ne,stopTimelapse:$}}const cD=120,uD=999,Ff=5,Pf=30,dD=Number.POSITIVE_INFINITY,w0="livedesk.remoteDirectory",dv="livedesk.localHubAccessEnabled",fD="livedesk.streamSettings",mD=18,pD="livedesk.controlStreamSettings",hD=10,x0="livedesk.wallCadence",S0="livedesk.wallMonitorSelections",C0=2,kg=512*1024,fv="".trim(),k0="".trim(),Jw="livedesk-adsense-script",Mg=!!fv&&!!k0,gD=Object.freeze([{code:"ShiftLeft",label:"Shift"},{code:"ControlLeft",label:"Ctrl"},{code:"AltLeft",label:"Alt"},{code:"MetaLeft",label:"Win"}]),vD=1e3/60,Ag=1500,yD=650,bD=1800,wD=650,xD=2500,Ng=1500,ex=15e3,tx=120,nx=100,ax=20,SD=6e4,CD=6e4,rx=240,kD=1024,MD=640,AD=360,sx="Connected LiveDesk clients are updating in batches. Hub will restart after every target reconnects on the requested versions.",vp="LiveDesk is replacing the Hub and verifying the requested version.",yp=5*6e4,ND=5e3,TD=8e3;function Pc({label:t,tooltip:n,disabled:r=!1,active:o=!1,danger:c=!1,pressed:u,onClick:f,children:h}){return i.jsx("span",{className:`manual-action-tooltip ${r?"disabled":""}`.trim(),"data-tooltip":n,children:i.jsx("button",{className:`manual-action ${o?"active":""} ${c?"danger":""}`.trim(),onClick:f,disabled:r,"aria-label":t,"aria-pressed":u,type:"button",children:h})})}function RD(t,n){if(n.deviceId!==t.deviceId)return!1;const r=Number(n.browserReceivedEpochMs);if(!Number.isFinite(r)||r<t.startedAtEpochMs)return!1;const o=Number(n.monitorIndex);if(Number.isFinite(o)&&Math.floor(o)!==t.monitorIndex)return!1;const c=String(n.frameMode||n.mode||"").trim().toLowerCase();return!c||c===t.frameMode}const Oc={free:{name:"Free",price:"$0",limit:Ff,audience:"Personal trial",note:"5 devices with a standard ad banner."},ltd:{name:"Plus",price:"$79 LTD",ltd:"$79 LTD",limit:Pf,audience:"Creators and homelabs",note:"30 devices, no ads, personal use."},pro:{name:"Pro",price:"$199 LTD",ltd:"$199 LTD",limit:dD,audience:"Business and studios",note:"Commercial use and larger Client walls."}},jD={"mode3-h264-hw":30};function ix(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}},o=r(t),c=r(n);if(!o||!c)return!1;for(let f=0;f<3;f+=1){if(o.core[f]>c.core[f])return!0;if(o.core[f]<c.core[f])return!1}if(o.prerelease.length===0||c.prerelease.length===0)return o.prerelease.length===0;const u=Math.max(o.prerelease.length,c.prerelease.length);for(let f=0;f<u;f+=1){const h=o.prerelease[f],g=c.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 ED=512;function pa(t,n){return`${t}:${n}`}function zi(t){return[t.deviceId,t.sessionId||"",t.streamId||"",t.commandId||"",Number(t.captureGeneration||0),Number(t.monitorIndex??-1),t.streamPurpose||""].join("|")}const DD={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:jD["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},ID={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:30,maxWidth:3840,maxHeight:2160,quality:75,showScreenStatus:!1},ox={maxWidth:3840,maxHeight:2160};function Lf(t,n){if(t.length===0)return 0;const r=[...t].sort((c,u)=>c-u),o=Math.max(0,Math.min(r.length-1,Math.ceil(r.length*n)-1));return r[o]}function M0(t,n){t.push(n),t.length>rx&&t.splice(0,t.length-rx)}function bp(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 lx(t,n,r){if(t.lastAt!==void 0){const o=Math.max(0,n-t.lastAt);t.intervalCount+=1,t.intervalSumMs+=o,t.minIntervalMs=Math.min(t.minIntervalMs,o),t.maxIntervalMs=Math.max(t.maxIntervalMs,o),M0(t.intervalSamplesMs,o)}if(t.lastFrameSeq!==void 0){const o=r-t.lastFrameSeq;o!==1&&(t.seqGapCount+=1,t.maxSeqGap=Math.max(t.maxSeqGap,Math.abs(o)))}t.lastAt=n,t.lastFrameSeq=r}function cx(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 ux(t){return!t||t.seqGapCount<=0?"none":`${t.seqGapCount} gaps / max ${t.maxSeqGap}`}function LD(t){return Number.isFinite(t)?String(t):"30+"}const A0=[1,2,5,8,12,20,30],dx={large:{maxWidth:1920,maxHeight:1080},medium:{maxWidth:1280,maxHeight:720},list:{maxWidth:960,maxHeight:540}},vi={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},fx=2200,_D=8e3,FD=3500,PD=7e3,OD=2,BD=7e3,HD=2600,zD=4200,$D=750,UD=2,mx=4200;function px(t,n){return Math.min(3e4,t*2**Math.min(3,Math.max(0,n)))}function Tp(t,n){const r=t.capabilities?.[n];return typeof r=="boolean"?r:/^(1|true|yes|on)$/i.test(String(r||"").trim())}function qr(t){return t.deviceName||t.hostname||t.deviceId}function qD(){return"npx -y --prefer-online livedesk@latest client"}function WD(){return"npx -y --prefer-online livedesk@latest"}function GD(){try{return localStorage.getItem(w0)||""}catch{return""}}function VD(){try{return localStorage.getItem(dv)==="1"}catch{return!1}}function ld(t){try{t?localStorage.setItem(dv,"1"):localStorage.removeItem(dv)}catch{}}function wi(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Uc(t){const n=wi(t.status),r=wi(n.screens),o=wi(t.capabilities),c=wi(t.latestLiveFrame),u=wi(t.activeLiveStream),h=[n.monitorCount,n.screenCount,r.count,o.monitorCount,o.screenCount,c.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 Hl(t){const n=Number(t);return Number.isFinite(n)&&n>0?Math.floor(n):0}function N0(t){const n=wi(t.status),o=[wi(n.screens).displays,n.displays,n.monitors];for(const c of o)if(!(!Array.isArray(c)||c.length===0))return c.map(u=>wi(u));return[]}function qv(t,n){const r=N0(t),o=r.find(g=>Number(g.index)===n)||r[n]||r[0]||{},c=Hl(o.width),u=Hl(o.height),f=[o.name,o.displayName,o.deviceName,o.id].find(g=>typeof g=="string"&&g.trim()),h=typeof f=="string"?f.trim():`Display ${n+1}`;return{index:n,name:h,width:c,height:u,primary:o.primary===!0||o.isPrimary===!0}}function KD(t){const n=Uc(t);return Array.from({length:n},(r,o)=>qv(t,o))}function QD(t){const n=N0(t);if(n.length===0)return"";const r=n.map((o,c)=>{const u=Number(o.index),f=[o.name,o.displayName,o.deviceName,o.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):c,typeof f=="string"?f.trim().toLowerCase():"",h(o.left),h(o.top),h(o.width),h(o.height),o.primary===!0||o.isPrimary===!0]}).sort((o,c)=>o[0]-c[0]);return JSON.stringify(r)}function YD(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 T0(t,n){const r=qv(t,n);if(r.width>0&&r.height>0)return{width:r.width,height:r.height};const o=wi(t.status),c=Hl(o.screenWidth||o.width),u=Hl(o.screenHeight||o.height);return c>0&&u>0?{width:c,height:u}:null}function R0(t){if(!t)return null;const n=Hl(t.sourceWidth)||Hl(t.width),r=Hl(t.sourceHeight)||Hl(t.height);return n>0&&r>0?{width:n,height:r}:null}function XD(t,n,r){const u=((typeof n?.monitorIndex=="number"?Of(n.monitorIndex,Math.max(1,n.monitorCount||1)):r)===r?R0(n):null)||T0(t,r);return u?Math.max(.25,Math.min(4,u.width/u.height)):16/9}const wp=16/9;function Of(t,n){const r=Math.max(1,Math.min(64,Math.floor(Number(n)||1))),o=Math.floor(Number(t));return Number.isFinite(o)?Math.max(0,Math.min(r-1,o)):0}function Ys(t,n){return F1(n,Uc(t),t.platform)}function ZD(){try{const t=localStorage.getItem(S0);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)!==C0||!r||typeof r!="object"||Array.isArray(r))return{selections:{},topologyFingerprints:{}};const o={},c={};for(const[u,f]of Object.entries(r)){const h=u.trim(),g=wi(f),y=g.monitorIndex,w=Math.floor(Number(y));if(!h||!Number.isFinite(w))continue;o[h]=Math.max(0,Math.min(63,w));const b=typeof g.topologyFingerprint=="string"?g.topologyFingerprint.trim():"";b&&(c[h]=b)}return{selections:o,topologyFingerprints:c}}catch{return{selections:{},topologyFingerprints:{}}}}function JD(t,n){try{const r=Object.fromEntries(Object.entries(t).map(([o,c])=>[o,{monitorIndex:c,topologyFingerprint:n[o]||""}]));localStorage.setItem(S0,JSON.stringify({version:C0,selections:r}))}catch{}}function eI(){return{...DD}}function tI(t){try{localStorage.setItem(fD,JSON.stringify({...t,version:mD}))}catch{}}function nI(){return{...ID}}function aI(t){try{localStorage.setItem(pD,JSON.stringify({...t,version:hD}))}catch{}}function rI(){try{return localStorage.getItem(x0)==="slow"?"slow":"fast"}catch{return"fast"}}function sI(t){try{localStorage.setItem(x0,t)}catch{}}function Tg(t,n){return t.length!==n.length?!1:t.every((r,o)=>r===n[o])}function Rg(t){return[...new Set(t.filter(Boolean))].sort()}function iI(t){return vi.fallbackVisibleCounts[t]||vi.fallbackVisibleCounts.large}function hx(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 o=dx[n]||dx.large;return{maxWidth:Math.min(t.maxWidth,o.maxWidth),maxHeight:Math.min(t.maxHeight,o.maxHeight)}}function oI(t,n=vi.minFps){const r=[...A0].sort((c,u)=>c-u),o=Math.max(n,Math.floor(t/2));return[...r].reverse().find(c=>c<t&&c>=n)||o}function lI(t,n){return[...A0].sort((o,c)=>o-c).find(o=>o>t&&o<=n)||n}function Bf(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,o=0;for(;r>=1024&&o<n.length-1;)r/=1024,o+=1;const c=o===0||r>=100?0:1;return`${r.toFixed(c)} ${n[o]}`}function gx(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 jg(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`${gx(r)} / ${gx(t)}`}function cI(t){const n=new Uint8Array(t),r=32768;let o="";for(let c=0;c<n.length;c+=r){const u=n.subarray(c,c+r);o+=String.fromCharCode(...u)}return btoa(o)}function vx(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 uI(t){return t===1?"middle":t===2?"right":"left"}function yx(t,...n){for(const r of n){const o=t?.[r];if(typeof o=="string"&&o.trim())return o.trim()}return""}function bx(t){const n=Number(t);return Number.isInteger(n)&&n>=1&&n<=uD?n:0}const dI={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function fI(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 o=t==="critical"?"critical":"warn",c=n.find(f=>f.state===o)||n.find(f=>f.state==="critical"||f.state==="warn");if(!c)return t==="critical"?"Issue":"Check";const u=dI[c.id]||c.label;return c.value&&c.value!=="-"?`${u} ${c.value}`:u}function j0(t,n){const r=n.split(".");let o=t;for(const c of r){if(o==null)return;if(Array.isArray(o)){const u=Number(c);o=Number.isInteger(u)?o[u]:void 0;continue}if(typeof o=="object"){o=o[c];continue}return}return o}function ea(t,...n){for(const r of n){const o=j0(t,r),c=Number(o);if(Number.isFinite(c))return c}}function $i(t,...n){for(const r of n){const o=j0(t,r);if(typeof o=="string"&&o.trim())return o.trim();if(typeof o=="number"&&Number.isFinite(o))return String(o)}return""}function Eo(t){const n=Number(t);if(Number.isFinite(n))return Math.max(0,Math.min(1,n>1?n/100:n))}function Eg(t,n){if(!(typeof t!="number"||typeof n!="number"||!Number.isFinite(t)||!Number.isFinite(n)||t<=0))return Eo((t-Math.max(0,n))/t)}function cd(t){return t===void 0?"-":`${Math.round(t*100)}%`}function Dg(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 Bc(t,n=.92,r=.78){return t===void 0?"unknown":t>=n?"critical":t>=r?"warn":"good"}function mI(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 E0(t){const n=t.status||{},r=ea(n,"cpu.cores","cpuCores","processorCount"),o=ea(n,"loadavg.0","cpu.load1"),c=Eo(ea(n,"cpu.usedRatio","cpu.usageRatio","cpu.ratio","cpu.usedPct","cpu.usagePct","cpu.percent")??(r&&o!==void 0?o/Math.max(1,r):void 0)),u=ea(n,"memory.totalBytes","totalMem"),f=ea(n,"memory.freeBytes","freeMem"),h=Eo(ea(n,"memory.usedRatio","memory.usedPct","usedMemRatio"))??Eg(u,f),g=ea(n,"disk.totalBytes","rootDisk.totalBytes","storage.totalBytes"),y=ea(n,"disk.freeBytes","rootDisk.freeBytes","storage.freeBytes"),w=Eo(ea(n,"disk.usedRatio","disk.usedPct","rootDisk.usedRatio","storage.usedRatio"))??Eg(g,y),b=ea(n,"thermal.cpuC","temperatureC","cpu.temperatureC","gpu.temperatureC"),x=Eo(ea(n,"gpu.usedRatio","gpu.usageRatio","gpu.usedPct","gpu.usagePct","gpu.percent","accelerators.gpu.usageRatio")),A=$i(n,"gpu.name","gpu.model","accelerators.gpu.name"),k=ea(n,"gpu.memory.totalBytes","gpu.totalMemoryBytes","gpu.vramTotalBytes"),N=ea(n,"gpu.memory.freeBytes","gpu.freeMemoryBytes","gpu.vramFreeBytes"),E=Eo(ea(n,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??Eg(k,N),D=ea(n,"gpu.temperatureC","thermal.gpuC"),T=Eo(ea(n,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),F=$i(n,"npu.name","npu.model","accelerators.npu.name"),O=ea(n,"npu.tops","npu.topsInt8","accelerators.npu.tops"),P=ea(n,"network.rxMbps","network.receiveMbps","network.downMbps"),z=ea(n,"network.txMbps","network.transmitMbps","network.upMbps"),I=ea(n,"network.latencyMs","network.rttMs"),X=Eo(ea(n,"network.usedRatio","network.usageRatio","network.saturationRatio")),se=$i(n,"network.link","network.interface","network.name"),Z=Math.max(b??Number.NEGATIVE_INFINITY,D??Number.NEGATIVE_INFINITY),G=Number.isFinite(Z)?Z:void 0,K=G===void 0?void 0:Eo((G-35)/60),me=b!==void 0&&D!==void 0?`CPU ${Math.round(b)}° · GPU ${Math.round(D)}°`:b!==void 0?`CPU ${Math.round(b)}°`:D!==void 0?`GPU ${Math.round(D)}°`:"-",V=$i(n,"workload.role","role","lane")||(Tp(t,"taskDispatch")?"Command-ready Client":"Local machine"),ne=$i(t.latestTask,"status")||$i(n,"workload.status")||"idle",$=$i(t.latestTask,"title","instructionPreview")||$i(n,"workload.title"),_=$i(t.latestTask,"resultSummary","error","instructionPreview")||$i(n,"workload.summary"),ie=Date.parse(t.lastSeenAt||t.connectedAt||""),be=Number.isFinite(ie)?Date.now()-ie:0;let H="online";t.connected?be>5*6e4?H="stale":(b??0)>=86||(D??0)>=88||(c??0)>=.94||(x??0)>=.96||(E??0)>=.96||(T??0)>=.96||(h??0)>=.94||(w??0)>=.94||(I??0)>=200||ne==="failed"?H="critical":(b??0)>=78||(D??0)>=80||(c??0)>=.82||(x??0)>=.86||(E??0)>=.88||(T??0)>=.86||(h??0)>=.82||(w??0)>=.86||(I??0)>=80?H="warn":["queued","running","targeted"].includes(ne)&&(H="busy"):H="offline";const te=[{id:"cpu",label:"CPU",value:cd(c),detail:r?`${r} cores`:o!==void 0?`load ${o.toFixed(1)}`:"not reported",ratio:c,state:Bc(c,.92,.78)},{id:"memory",label:"RAM",value:cd(h),detail:jg(u,f),ratio:h,state:Bc(h,.92,.78)},{id:"disk",label:"DISK",value:cd(w),detail:jg(g,y),ratio:w,state:Bc(w,.92,.82)},{id:"gpu",label:"GPU",value:cd(x),detail:A||(k&&N!==void 0?`${Bf(N)} VRAM free`:D!==void 0?`${Math.round(D)}C`:"not reported"),ratio:x,state:D!==void 0&&D>=88?"critical":D!==void 0&&D>=80?"warn":Bc(x,.96,.86)},{id:"vram",label:"VRAM",value:cd(E),detail:jg(k,N),ratio:E,state:Bc(E,.96,.88)},{id:"npu",label:"NPU",value:T!==void 0?cd(T):O!==void 0?`${Math.round(O)} TOPS`:"-",detail:F||(O!==void 0?"neural engine":"not reported"),ratio:T,state:Bc(T,.96,.86)},{id:"temp",label:"TEMP",value:me,detail:`uptime ${mI(ea(n,"uptimeSec"))}`,ratio:K,state:G===void 0?"unknown":G>=86?"critical":G>=78?"warn":"good"},{id:"network",label:"NET",value:Dg(P)||(I!==void 0?`${Math.round(I)}ms`:se||"-"),detail:Dg(z)?`${Dg(z)} up`:se||"not reported",ratio:X,state:I!==void 0&&I>=200?"critical":I!==void 0&&I>=80?"warn":Bc(X,.9,.75)}];return{state:H,label:fI(H,te,ne),role:V,taskLabel:$||(ne==="idle"?"idle":ne),taskStatus:ne,taskSummary:_,metrics:te}}const pI=[{id:"slow",label:"Slow",fps:av("slow")},{id:"fast",label:"Fast",fps:av("fast")}],hI=[{id:"list",label:"List"},{id:"medium",label:"Small"},{id:"large",label:"Large"}],gI=[{id:"sync-server",label:"Hub",icon:Wi,accent:"blue",tooltip:"hub"},{id:"wall",label:"Wall",icon:sk,accent:"blue",tooltip:"wall"},{id:"control",label:"Control",icon:Fg,accent:"red",tooltip:"control"},{id:"share-files",label:"Share Files",icon:xp,accent:"green",tooltip:"share-files"},{id:"agents",label:"Agents",icon:Pg,accent:"violet",tooltip:"agents"}],vI=[{id:"doc",label:"Doc",icon:Rp,accent:"amber"},{id:"support",label:"Support",icon:Hf,accent:"violet"},{id:"pricing",label:"Pricing",icon:zf,accent:"green"}];function yI(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 Un(t){return yI(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 Hc(t){return t.map(n=>Un(n))}function hr(t){return{languageName:t.languageName,languageLabel:t.languageLabel,eyebrow:t.eyebrow,title:Un(t.title),intro:Un(t.intro),sections:[{title:Un(t.managerTitle),body:Un(t.managerBody),points:Hc(t.managerPoints)},{title:Un(t.clientTitle),body:Un(t.clientBody),points:Hc(t.clientPoints)},{title:Un(t.syncTitle),body:Un(t.syncBody),points:Hc(t.syncPoints)},...t.agentTitle&&t.agentBody&&t.agentPoints?[{title:Un(t.agentTitle),body:Un(t.agentBody),points:Hc(t.agentPoints)}]:[],{title:Un(t.platformTitle),body:Un(t.platformBody),points:Hc(t.platformPoints)}],sync:{title:Un(t.syncTitle),body:Un(t.syncBody),points:Hc(t.syncPoints)},firewall:{title:Un(t.firewallTitle),body:Un(t.firewallBody),points:Hc(t.firewallPoints)},commands:{title:Un(t.commandsTitle),body:Un(t.commandsBody),manager:Un(t.managerCommandLabel),primary:Un(t.clientCommandLabel),slot:Un(t.slotCommandLabel),manual:Un(t.manualCommandLabel)}}}const pd={ko:hr({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:hr({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:hr({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":hr({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":hr({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:hr({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:hr({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:hr({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":hr({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:hr({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:hr({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:hr({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:hr({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:hr({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:hr({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:hr({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ı"})},bI=Object.entries(pd).map(([t,n])=>({id:t,label:n.languageName}));function wI(){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(pd[n])return n;if(r.startsWith("zh-tw")||r.startsWith("zh-hk"))return"zh-TW";if(r.startsWith("pt"))return"pt-BR";const o=r.split("-")[0];if(pd[o])return o}return"en"}function xI({index:t}){const n=t+1;return i.jsx("article",{className:"device-tile placeholder-tile","aria-label":`Empty slot ${n}`,children:i.jsxs("div",{className:"tile-screen","aria-hidden":"true",children:[i.jsx("span",{className:"slot-grid","aria-hidden":"true"}),i.jsxs("span",{className:"empty-screen",children:[i.jsx(Ba,{size:24}),i.jsxs("strong",{children:["Slot ",String(n).padStart(3,"0")]})]})]})})}function SI({entry:t,slotNumber:n}){return i.jsx("article",{className:"device-tile offline-wall-tile","aria-label":`${t.label} offline in slot ${n}`,children:i.jsxs("div",{className:"tile-screen","aria-hidden":"true",children:[i.jsx("span",{className:"slot-grid","aria-hidden":"true"}),i.jsxs("span",{className:"offline-screen",children:[i.jsx(Ba,{size:28}),i.jsx("strong",{children:t.label}),i.jsx("em",{children:"Offline"}),i.jsxs("small",{children:["Slot ",String(n).padStart(3,"0"),t.platform?` · ${t.platform}`:""]})]})]})})}const D0=["cpu","gpu","memory","vram","network","disk","temp"];function CI({entry:t,slotNumber:n}){return i.jsxs("div",{className:"wall-device-list-row offline-layout-row",role:"row","aria-label":`${t.label} offline`,children:[i.jsxs("span",{className:"wall-device-name",role:"gridcell",children:[i.jsx("span",{className:"wall-device-icon","aria-hidden":"true",children:i.jsx(Ba,{size:17})}),i.jsxs("span",{children:[i.jsx("strong",{children:t.label}),i.jsxs("small",{children:["Slot ",String(n).padStart(3,"0"),t.platform?` · ${t.platform}`:""]})]})]}),i.jsxs("span",{className:"wall-device-list-status state-offline",role:"gridcell",children:[i.jsx("i",{"aria-hidden":"true"}),i.jsx("strong",{children:"Offline"})]}),D0.map(r=>i.jsxs("span",{className:"wall-device-list-metric state-unknown",role:"gridcell",children:[i.jsx("strong",{children:"-"}),i.jsx("small",{children:"offline"})]},r))]})}function kI({device:t,slotNumber:n,selected:r,updateIndicator:o,remoteDiagnostics:c,diagnosticsMode:u="remote",onSelect:f,onOpenControl:h}){const g=E0(t),y=new Map(g.metrics.map(b=>[b.id,b])),w=o?.label||g.label;return i.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:[i.jsxs("span",{className:"wall-device-name",role:"gridcell",children:[i.jsx("span",{className:"wall-device-icon","aria-hidden":"true",children:i.jsx(Ba,{size:17})}),i.jsxs("span",{children:[i.jsx("strong",{children:qr(t)}),i.jsxs("small",{children:["Slot ",String(n).padStart(3,"0"),t.platform?` · ${t.platform}`:"",t.arch?` · ${t.arch}`:""]})]}),r&&i.jsx(qi,{size:16,strokeWidth:3,"aria-label":"Selected"})]}),i.jsxs("span",{className:`wall-device-list-status state-${g.state} ${o?`update-${o.state}`:""}`,role:"gridcell",title:o?.error||w,children:[i.jsx("i",{"aria-hidden":"true"}),i.jsx("strong",{children:w})]}),D0.map(b=>{const x=y.get(b);return i.jsxs("span",{className:`wall-device-list-metric state-${x?.state||"unknown"}`,role:"gridcell",title:x?`${x.label}: ${x.value} · ${x.detail}`:"Not reported",children:[i.jsx("strong",{children:x?.value||"-"}),i.jsx("small",{children:x?.detail||"not reported"}),x?.ratio!==void 0&&i.jsx("i",{style:{width:`${Math.round(x.ratio*100)}%`},"aria-hidden":"true"})]},b)}),c&&i.jsx("span",{className:"wall-device-list-diagnostics",role:"gridcell",children:i.jsx(c0,{items:c,mode:u})})]})}function MI(t){if(!t)return!1;const n=String(t.platform||"").trim().toLowerCase();return Do(n)&&t.capabilities?.screenRecordingPermission===!1}function Do(t){const n=String(t||"").trim().toLowerCase();return n==="macos"||n==="darwin"||n==="mac"||n==="macosx"}function AI(t){const n=String(t||"").trim().toLowerCase();return n==="linux"||n.startsWith("linux ")}function wx({device:t,frame:n,selected:r,controlEnabled:o,showStatus:c,monitorIndex:u,monitorCount:f,onSelect:h,onFocusDevice:g,onOpenControl:y,onCycleMonitor:w,onCanvasReady:b,sendInput:x,remoteModifierState:A,updateIndicator:k,presentationReady:N,showPresentationSpinner:E=!1,remoteDiagnostics:D,diagnosticsMode:T="remote"}){const F=d.useRef(null),O=d.useRef(null),P=d.useRef(0),z=d.useRef(null),I=E0(t),X=["cpu","gpu","memory","vram"].map(ue=>I.metrics.find(He=>He.id===ue)).filter(ue=>!!ue),se=Av(u),Z=f>1,G=N??!!n,K=MI(t)&&!G,me=E&&t.connected&&!G&&!K,V=XD(t,n,se),ne=V>=wp?100:V/wp*100,$=V>=wp?wp/V*100:100,_={"--screen-aspect":V.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,ne)).toFixed(3)}%`,"--screen-content-height":`${Math.max(1,Math.min(100,$)).toFixed(3)}%`},ie=d.useCallback(ue=>{F.current=ue,b(t.deviceId,ue)},[t.deviceId,b]),be=ue=>{const He=ue.currentTarget.getBoundingClientRect();return N1(ue.clientX,ue.clientY,He)},H=ue=>j1(ue,A),te=d.useCallback(()=>{z.current!==null&&(window.cancelAnimationFrame(z.current),z.current=null)},[]),le=d.useCallback(()=>{const ue=O.current;if(!ue)return;O.current=null;const He=Number(ue.input.normalizedX),ze=Number(ue.input.normalizedY);if(!Number.isFinite(He)||!Number.isFinite(ze))return;x(t.deviceId,{...ue.input,normalizedX:He,normalizedY:ze})&&(P.current=performance.now())},[t.deviceId,x]),Ce=d.useCallback(()=>{z.current===null&&(z.current=window.requestAnimationFrame(()=>{z.current=null,le()}))},[le]);d.useEffect(()=>()=>{te(),O.current=null},[te]);const Ae=(ue,He)=>{if(!o)return;const ze={type:He,monitorIndex:se,...be(ue),button:uI(ue.button),...H(ue)};if(He==="pointermove"){const et=performance.now();O.current={input:ze},et-P.current>=vD&&(te(),le()),Ce();return}O.current&&(te(),le()),x(t.deviceId,ze)},_e=d.useCallback(ue=>{const He=document.activeElement;He instanceof HTMLElement&&ue.contains(He)&&He.classList.contains("monitor-cycle-button")&&He.blur()},[]);return i.jsx("article",{className:`device-tile ${r?"selected":""} ${t.connected?"online":"offline"}`,"data-live-device-id":t.deviceId,style:_,children:i.jsxs("div",{className:`tile-screen ${G?"has-frame":"is-empty"}`,role:"button",tabIndex:o?-1:0,"aria-pressed":r,onClick:ue=>{ue.target instanceof Element&&ue.target.closest(".monitor-cycle")||o||h()},onKeyDown:ue=>{ue.target instanceof Element&&ue.target.closest(".monitor-cycle")||o||(ue.key==="Enter"||ue.key===" ")&&(ue.preventDefault(),h())},onDoubleClick:ue=>{ue.target instanceof Element&&ue.target.closest(".monitor-cycle")||(ue.preventDefault(),y())},onPointerLeave:ue=>_e(ue.currentTarget),children:[i.jsx("span",{className:`screen-content ${G?"has-frame":"is-empty"}`,children:i.jsx("canvas",{ref:ie,className:`remote-canvas ${G?"has-frame":"is-empty"}`,"data-monitor-index":se,tabIndex:o?0:-1,onPointerDown:ue=>{o&&(ue.preventDefault(),ue.stopPropagation(),g(),ue.currentTarget.focus(),ue.currentTarget.setPointerCapture(ue.pointerId),Ae(ue,"pointerdown"))},onPointerMove:ue=>{o&&ue.preventDefault(),Ae(ue,"pointermove")},onPointerLeave:ue=>{o&&(Ae(ue,"pointermove"),te(),le())},onPointerUp:ue=>{o&&(ue.preventDefault(),ue.stopPropagation(),Ae(ue,"pointerup"),ue.currentTarget.hasPointerCapture(ue.pointerId)&&ue.currentTarget.releasePointerCapture(ue.pointerId))},onPointerCancel:ue=>{ue.currentTarget.hasPointerCapture(ue.pointerId)&&ue.currentTarget.releasePointerCapture(ue.pointerId)},onWheel:ue=>{o&&(ue.preventDefault(),x(t.deviceId,{type:"wheel",monitorIndex:se,...be(ue),deltaX:ue.deltaX,deltaY:ue.deltaY,...H(ue)}))},onContextMenu:ue=>o&&ue.preventDefault()},`${t.deviceId}:monitor:${se}`)}),!G&&i.jsx("span",{className:"empty-screen",children:i.jsx(Ba,{size:26})}),i.jsx("span",{className:"wall-device-title",title:qr(t),children:qr(t)}),me&&i.jsxs("span",{className:"wall-presentation-loading",role:"status","aria-live":"polite",children:[i.jsx("span",{className:"wall-presentation-spinner","aria-hidden":"true"}),i.jsx("strong",{children:"Preparing video"})]}),K&&i.jsxs("span",{className:"wall-presentation-loading permission-required",role:"status","aria-live":"polite",children:[i.jsx(Aa,{size:24,"aria-hidden":"true"}),i.jsx("strong",{children:"Screen Recording permission required"}),i.jsx("small",{children:"Allow the terminal app on this Mac, then restart LiveDesk."})]}),k&&i.jsxs("span",{className:`wall-update-status state-${k.state}`,role:"status","aria-live":"polite",title:k.error||k.label,children:[k.state==="updated"?i.jsx(Oa,{size:20,"aria-hidden":"true"}):k.state==="failed"?i.jsx(vr,{size:22,"aria-hidden":"true"}):k.state==="offline"?i.jsx(zp,{size:22,"aria-hidden":"true"}):i.jsx("span",{className:"wall-update-spinner","aria-hidden":"true"}),i.jsx("strong",{children:k.label}),k.error?i.jsx("small",{children:k.error}):null]}),c&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:`tile-health-pill state-${I.state}`,children:I.label}),i.jsx("span",{className:"tile-metrics","aria-label":`${qr(t)} status`,children:X.map(ue=>i.jsxs("span",{className:`tile-metric state-${ue.state}`,children:[i.jsx("b",{children:ue.label}),i.jsx("em",{children:ue.value}),ue.ratio!==void 0&&i.jsx("i",{style:{width:`${Math.round(ue.ratio*100)}%`}})]},ue.id))})]}),D&&i.jsx(c0,{items:D,mode:T}),Z&&i.jsxs("span",{className:"monitor-cycle","aria-label":`${qr(t)} display ${se+1} of ${f}`,onPointerDown:ue=>ue.stopPropagation(),onClick:ue=>ue.stopPropagation(),onDoubleClick:ue=>ue.stopPropagation(),children:[i.jsx("button",{className:"monitor-cycle-button previous",onClick:ue=>{ue.preventDefault(),ue.stopPropagation(),w(-1),ue.currentTarget.blur()},title:"Previous display",type:"button",children:i.jsx(Ix,{size:18})}),i.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",se+1,"/",f]}),i.jsx("button",{className:"monitor-cycle-button next",onClick:ue=>{ue.preventDefault(),ue.stopPropagation(),w(1),ue.currentTarget.blur()},title:"Next display",type:"button",children:i.jsx(vv,{size:18})})]}),r&&i.jsx("span",{className:"device-selection-check","aria-hidden":"true",children:i.jsx(qi,{size:23,strokeWidth:3.5})})]})})}function NI({visible:t}){return d.useEffect(()=>{if(!t||!Mg)return;if(!document.getElementById(Jw)){const r=document.createElement("script");r.id=Jw,r.async=!0,r.crossOrigin="anonymous",r.src=`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${encodeURIComponent(fv)}`,document.head.appendChild(r)}const n=window.setTimeout(()=>{try{window.adsbygoogle=window.adsbygoogle||[],window.adsbygoogle.push({})}catch{}},120);return()=>window.clearTimeout(n)},[t]),t?i.jsxs("aside",{className:`free-ad-banner ${Mg?"adsense-ready":"house-ad"}`,"aria-label":"Advertisement",children:[i.jsx("span",{className:"ad-label",children:"Advertisement"}),Mg?i.jsx("ins",{className:"adsbygoogle livedesk-ad-unit",style:{display:"block"},"data-ad-client":fv,"data-ad-slot":k0,"data-ad-format":"auto","data-full-width-responsive":"true"}):i.jsxs("div",{className:"house-ad-copy",children:[i.jsx("strong",{children:"Sponsored placement"}),i.jsx("span",{children:"Mini PCs, GPUs, NAS, networking, and developer tools."})]})]}):null}function TI({runtimeBaseUrl:t=""}){const{session:n,loading:r}=i1(),{target:o,error:c,refresh:u}=l1(n),f=d.useMemo(()=>{if(!o?.active)return null;const p=o.expires_at?Date.parse(o.expires_at):Number.POSITIVE_INFINITY;return Number.isFinite(p)&&p<=Date.now()?null:o},[o]),h=d.useMemo(()=>Ab(f),[f]),g=t.trim().replace(/\/+$/,""),y=d.useMemo(()=>[...new Set([g,...h,qn].filter(Boolean))],[h,g]),[w,b]=d.useState(VD),x=d.useMemo(()=>y.some(p=>!!Uf(p)),[y]),A=!x||w,{status:k,devices:N,error:E,refresh:D,hubBaseUrl:T}=o1(y,A),{entitlement:F,licensed:O,loading:P,error:z,refresh:I}=c1(n),[X,se]=d.useState([]),[Z,G]=d.useState(""),[K,me]=d.useState(""),[V,ne]=d.useState(""),[$,_]=d.useState(""),[ie,be]=d.useState(""),[H,te]=d.useState("idle"),[le,Ce]=d.useState(!1),[Ae,_e]=d.useState(null),ue=d.useRef(null),[He,ze]=d.useState(""),et=d.useRef("");et.current=$;const[Xe,Ze]=d.useState(!1),[Ue,Y]=d.useState([]),Se=d.useRef(null),[ye,je]=d.useState(!1),$e=d.useRef(""),B=d.useRef(new Map),lt=d.useRef(0),Nt=d.useRef(!1),Ht=d.useRef(""),ke=d.useRef(null);ke.current||(ke.current=O1());const qe=d.useRef(document.visibilityState==="visible"),[Ye,_t]=d.useState({}),tt=d.useRef({}),pe=d.useRef(new Set),Ne=d.useRef(new Map),Be=d.useRef(new Map),[Oe,We]=d.useState({}),Rt=d.useMemo(()=>new Set(Object.keys(Ye)),[Ye]),ee=d.useCallback((p,S)=>{if(!p)return;const C={...tt.current};S?C[p]=S:delete C[p],tt.current=C,_t(C)},[]),he=d.useCallback((p,S)=>{p&&We(C=>{if(!!C[p]===S)return C;const R={...C};return S?R[p]=!0:delete R[p],R})},[]),Fe=d.useCallback((p,S)=>{p&&Be.current.set(p,{paused:S,expiresAt:Date.now()+TD})},[]),[fe,xe]=d.useState(""),[nt,ct]=d.useState(""),[ft,dt]=d.useState(!1),Dt=d.useRef(null),Yt=d.useRef(null);d.useEffect(()=>{fe==="auth"&&n?.access_token&&xe("")},[fe,n?.access_token]);const[cn,Xt]=d.useState(""),[oa,Na]=d.useState(null),Pn=d.useRef(null),Wn=d.useRef(0),la=d.useCallback((p,S,C)=>{const R=String(p||"").trim();if(Xt(R),Pn.current!==null&&(window.clearTimeout(Pn.current),Pn.current=null),!R){Na(null);return}const j=++Wn.current;if(Na({id:j,message:R,tone:S}),!C)return;const U=window.setTimeout(()=>{Na(W=>W?.id===j?null:W),Pn.current===U&&(Pn.current=null)},5e3);Pn.current=U},[]),Pe=d.useCallback((p,S="info")=>{la(p,S,!0)},[la]),q=d.useCallback(p=>{la(p,"progress",!1)},[la]),at=d.useCallback(async(p,S)=>{const C=String(n?.user?.id||"").trim();if(!C)throw new Error("Sign in before saving a Wall layout.");const R=++wr.current,j=Yc(S);mn(!0);try{const{data:U,error:W}=await Et.from("livedesk_wall_layouts").upsert({user_id:C,is_locked:p,slots:j},{onConflict:"user_id"}).select("is_locked, slots, revision, updated_at").single();if(W)throw W;return R===wr.current&&(wt(U?.is_locked===!0),Ft(Yc(U?.slots))),U}finally{R===wr.current&&mn(!1)}},[n?.user?.id]);d.useEffect(()=>{const p=String(n?.user?.id||"").trim(),S=++wr.current;if(!p){wt(!1),Ft([]),Pt(!1);return}let C=!1;return Pt(!0),(async()=>{const{data:R,error:j}=await Et.from("livedesk_wall_layouts").select("is_locked, slots, revision, updated_at").eq("user_id",p).maybeSingle();C||S!==wr.current||(j?(Pe(`Wall layout could not be loaded: ${j.message}`,"error"),wt(!1),Ft([])):(wt(R?.is_locked===!0),Ft(Yc(R?.slots))),Pt(!1))})(),()=>{C=!0}},[n?.user?.id,Pe]),d.useEffect(()=>()=>{Pn.current!==null&&window.clearTimeout(Pn.current)},[]);const[ht,Zt]=d.useState(()=>typeof window<"u"&&window.location.pathname.startsWith("/support")?"support":"wall");d.useEffect(()=>{const p=()=>{Zt(window.location.pathname.startsWith("/support")?"support":S=>S==="support"?"wall":S)};return window.addEventListener("popstate",p),()=>window.removeEventListener("popstate",p)},[]);const[bn,Es]=d.useState("large"),[Ua,de]=d.useState(rI),De=av(Ua),[Ke,wt]=d.useState(!1),[Jt,Ft]=d.useState([]),[mt,Pt]=d.useState(!1),[xt,mn]=d.useState(!1),[na,wn]=d.useState(""),[On,rn]=d.useState(0),br=d.useRef(""),wr=d.useRef(0),[Ot,Rn]=d.useState(!1),[Bn,Za]=d.useState(!1),[va,xr]=d.useState(!1),[Ja,is]=d.useState(!1),[Ta,un]=d.useState(Date.now),er=d.useRef(null);d.useEffect(()=>()=>{er.current!==null&&window.clearTimeout(er.current)},[]);const[Ds,_o]=d.useState(wI),[os,Js]=d.useState(!1),[Ki,Ln]=d.useState(!1),[Fo,Jc]=d.useState(!1),[Wr,ei]=d.useState(GD),[St]=d.useState(eI),[Gn]=d.useState(nI),[ls]=d.useState(ZD),[en,Qi]=d.useState(ls.selections),Po=d.useRef({...ls.topologyFingerprints}),ti=d.useRef({}),Kl=d.useRef({...ls.selections}),[Wt,Ra]=d.useState(null),[tr,ni]=d.useState([]),[Vn,Sr]=d.useState(De),[qa,Ql]=d.useState(""),[Oo,Yl]=d.useState(0),[Yi,Cr]=d.useState(0),[cs,Xi]=d.useState(0),[us,ai]=d.useState(()=>new Set),Gt=d.useRef(new Map),ja=d.useRef(new Map),nr=d.useRef(new Map),pn=d.useRef(new Map),ds=d.useRef(new Map),xn=d.useRef(new Set),kr=d.useRef(new Map),Wa=d.useRef(new Map),fs=d.useRef(new WeakMap),Zi=d.useRef(new WeakMap),Ea=d.useRef(""),Da=d.useRef(null),Bo=d.useRef(Promise.resolve()),Ji=d.useRef(0),eo=d.useRef(null),Mr=d.useRef(null),Xl=d.useRef(""),Ar=d.useRef(new Map),Si=d.useRef(null),Zl=d.useRef(0),ri=d.useRef(new Map),bd=d.useRef(typeof window<"u"&&new URLSearchParams(window.location.search).get("livedeskTransmissionProbe")==="1"),eu=d.useRef(new Map),wd=d.useRef([]),xd=d.useRef(0),[tu,Sd]=d.useState({}),Ci=d.useRef(new Map),[nu,Ho]=d.useState({}),au=d.useRef(null),[Cd,Ga]=d.useState(!1),Jl=d.useRef(null),th=d.useRef(0),si=d.useRef(null),am=d.useRef(new Map),ms=d.useRef(null),Gr=d.useRef(null),Nr=d.useRef(null),ec=d.useRef(!1),rm=d.useRef(0),Kn=d.useRef(0),ca=d.useRef(""),zo=d.useRef(Promise.resolve()),$o=d.useRef(""),yt=d.useRef(null),Tr=d.useRef(""),ki=d.useRef(null),to=d.useRef(0),Uo=d.useRef(""),Rr=d.useRef(new Map),no=d.useRef(new Map),ru=d.useRef(performance.now()),qo=d.useRef(new Map),Mi=d.useRef(new Map),Ai=d.useRef(new Map),Is=d.useRef(new Map),Ni=d.useRef(new Map),ps=d.useRef(document.visibilityState==="visible"),jr=d.useRef(1),su=d.useRef([]),[Va,kd]=d.useState(document.visibilityState==="visible"),[Ti,sm]=d.useState(0),Wo=d.useRef(0),tc=d.useRef(0),iu=d.useRef(0),ou=d.useRef(0),Md=d.useRef(0),Ad=d.useRef(new Map),lu=d.useRef([]),ar=d.useRef(new Map),Go=d.useRef(new Map),Ls=d.useRef(new Map),nc=d.useRef(new Set),ao=d.useCallback(p=>bA(fs.current,p),[]),ro=d.useCallback(p=>Sv(Zi.current,p),[]),ii=d.useCallback((p,S)=>Ob(Zi.current,p,S),[]),aa=d.useCallback(p=>{const S=Pb(fs.current,p);return Pb(Zi.current,p),S},[]),hs=d.useCallback((p,S)=>Ob(fs.current,p,S),[]),cu=d.useCallback(p=>Mr.current===p?!0:[Gt.current,ja.current,nr.current,pn.current,Ar.current].some(C=>Array.from(C.values()).some(R=>R===p)),[]),Qn=d.useCallback(p=>{p&&(aa(p),nc.current.add(p),SA(p,{isCurrent:cu,dispose:ad,schedule:S=>queueMicrotask(()=>{try{S()}finally{nc.current.delete(p)}})}))},[cu,aa]),rr=d.useCallback(p=>(aa(p),Vp(p,ad)),[aa]),Nd=d.useCallback(()=>{const p=Mr.current,S=[...nc.current];Mr.current=null,nc.current.clear(),fs.current=new WeakMap,Zi.current=new WeakMap,Wa.current.clear(),Xl.current="",xA([Gt.current,ja.current,nr.current,pn.current,Ar.current],[p,...S],ad),Si.current=null,Zl.current=0,ds.current.clear(),xn.current.clear(),kr.current.clear(),ri.current.clear(),eu.current.clear(),wd.current.length=0,Ci.current.clear(),pe.current.clear()},[]);d.useEffect(()=>()=>{Nd()},[Nd]);const jn=d.useCallback((p,S)=>{const C=pa(p,S),R=performance.now();Rr.current.delete(C),no.current.delete(C),qo.current.delete(C),Ni.current.delete(C),Ls.current.delete(C),Ci.current.delete(C),ri.current.delete(C),Ho(j=>{if(!Object.prototype.hasOwnProperty.call(j,C))return j;const U={...j};return delete U[C],U}),Sd(j=>{if(!Object.prototype.hasOwnProperty.call(j,C))return j;const U={...j};return delete U[C],U}),p==="control"?(Mi.current.delete(C),Ai.current.set(C,R)):Is.current.set(C,R)},[]),[Vr,_s]=d.useState(null),[im,oi]=d.useState(!1),[nh,om]=d.useState([]),[so,ah]=d.useState("all"),[Vo,Td]=d.useState([]),[rh,sh]=d.useState(!1),[lm,gs]=d.useState(!0),ac=d.useRef(null),Er=d.useRef(null),Ko=d.useRef(null),Rd=d.useRef(null),uu=d.useRef(!1),Qo=d.useRef(!1),rc=d.useRef(!1),Fs=d.useRef(0),Ps=d.useRef(0),Kr=d.useRef(0),Ka=d.useRef(0),du=d.useRef(0),Ia=d.useRef(""),Yo=ht==="settings",Os=ht==="pricing",jd=ht==="doc",sc=ht==="support",vs=ht==="share-files",ic=ht==="agents",Xo=!Yo&&!Os&&!jd&&!sc&&!vs&&!ic,Ct=ht==="control",Bs=Va&&ht==="wall",Dr=d.useRef(Bs);Dr.current=Bs;const Qr=Va&&(ht==="wall"||Ct),ys=d.useRef(Qr);ys.current=Qr;const bs=Va&&(Ct||Bs),io=d.useRef({active:Qr,epoch:jr.current});io.current.active!==Qr&&(jr.current+=1,io.current={active:Qr,epoch:jr.current}),d.useEffect(()=>{Xo||(Rn(!1),Za(!1),xr(!1))},[Xo]);const Mt=St.frameMode==="mode4-h264-atlas",En=ie||Gn.frameMode,ws=En!=="mode3-h264-hw"?Math.min(30,Gn.fps):Gn.fps,Qa=N.find(p=>p.deviceId===K),Hs=Qa?.platform,li=Qa?Ys(Qa,en[Qa.deviceId]):0,oc=Qa?qv(Qa,li):null,fu=AI(Hs)?{maxWidth:1280,maxHeight:720}:ox,mu=En!=="mode3-h264-hw"?{maxWidth:1920,maxHeight:1080}:ox,lc={maxWidth:Math.min(mu.maxWidth,fu.maxWidth,Gn.maxWidth),maxHeight:Math.min(mu.maxHeight,fu.maxHeight,Gn.maxHeight)},_n={maxWidth:oc?.width?Math.min(lc.maxWidth,oc.width):lc.maxWidth,maxHeight:oc?.height?Math.min(lc.maxHeight,oc.height):lc.maxHeight};d.useEffect(()=>{if(k?.started){if(!n?.access_token){rt("/api/remote/license",{method:"DELETE"},T).catch(()=>{});return}rt("/api/remote/license/sync",{method:"POST",headers:{Authorization:`Bearer ${n.access_token}`}},T).catch(p=>{console.warn("[LiveDesk] Hub license sync failed",p)})}},[F?.updated_at,T,n?.access_token,k?.started]),d.useEffect(()=>{!n?.access_token||!k?.started||k.runtimeRole!=="hub"||!k.deviceId||(async()=>{try{const{data:p,error:S}=await Et.rpc("register_livedesk_device",{p_device_id:k.deviceId,p_device_name:k.deviceName||k.deviceId,p_role:"hub",p_assigned_hub_id:null,p_platform:navigator.platform||navigator.userAgent,p_os_version:navigator.userAgent,p_app_version:k.managerVersion||k.managerPackage||""}),C=Array.isArray(p)?p[0]:p;(S||C?.ok===!1)&&console.warn("[LiveDesk] Hub device role registration failed",S||C?.reason||"unknown-error")}catch(p){console.warn("[LiveDesk] Hub device role registration failed",p)}})()},[n?.access_token,k?.deviceId,k?.deviceName,k?.managerPackage,k?.managerVersion,k?.runtimeRole,k?.started]),d.useEffect(()=>{!n?.access_token||!n.refresh_token||!k?.started||k.runtimeRole!=="hub"||rc.current||(rc.current=!0,rt("/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}})},T||qn).then(p=>{p.hostTarget?.ok===!1&&console.warn("[LiveDesk] Hub host target publish is waiting for a valid Hub role:",p.hostTarget.error||"unknown-error"),D()}).catch(p=>{console.warn("[LiveDesk] Hub session sync failed:",p)}).finally(()=>{rc.current=!1}))},[T,D,n?.access_token,n?.expires_at,n?.refresh_token,n?.user?.email,n?.user?.id,k?.runtimeRole,k?.started]);const Je=d.useMemo(()=>N.filter(p=>p.connected),[N]);d.useEffect(()=>{const p={...tt.current},S=Date.now();let C=!1;We(R=>{const j={...R};let U=!1;for(const W of N){const oe=String(W.liveCapturePause?.token||"").trim(),ae=Be.current.get(W.deviceId);if(ae)if((ae.paused?!!oe:!oe)||ae.expiresAt<=S)Be.current.delete(W.deviceId);else continue;const J=!!oe&&(W.liveCapturePause?.captureStopConfirmed!==!0||W.liveCapturePause?.phase==="stop-unconfirmed");!!j[W.deviceId]!==J&&(U=!0,J?j[W.deviceId]=!0:delete j[W.deviceId])}return U?j:R});for(const R of N){const j=String(R.liveCapturePause?.token||"").trim(),U=String(p[R.deviceId]||""),W=Be.current.get(R.deviceId);if(W)if((W.paused?!!j:!j)||W.expiresAt<=S)Be.current.delete(R.deviceId);else continue;j&&j!==U?(p[R.deviceId]=j,C=!0):!j&&U&&(delete p[R.deviceId],Ne.current.delete(R.deviceId),C=!0)}C&&(tt.current=p,_t(p))},[N]);const Bt=so==="all"?Je.length:Vo.filter(p=>Je.some(S=>S.deviceId===p)).length,Ri=d.useMemo(()=>Je.reduce((p,S)=>Math.max(p,bx(S.slotNumber)),0),[Je]),ya=Math.max(cD,Je.length,Ri),Zo=d.useMemo(()=>{const p=Array(ya).fill(null),S=[];for(const C of Je){const R=bx(C.slotNumber);R>0&&R<=ya&&!p[R-1]?p[R-1]=C:S.push(C)}for(const C of S){const R=p.findIndex(j=>!j);R<0?p.push(C):p[R]=C}return p},[Je,ya]),La=d.useMemo(()=>Ke?Y1({connectedDevices:Je,entries:Jt,minimumSlotCount:ya}):Zo.map((p,S)=>({slotNumber:S+1,device:p,saved:null,offline:!1,persisted:!1})),[Je,Zo,ya,Jt,Ke]),pu=d.useMemo(()=>La.map(p=>p.device),[La]),Ed=d.useMemo(()=>La.filter(p=>!!p.device||!!p.saved),[La]),Jo=d.useCallback(async()=>{const p=Ke,S=Jt,C=Q1(Zo);wt(!0),Ft(C);try{await at(!0,C),Pe("Current Wall layout is locked and saved to your account.","success")}catch(R){wt(p),Ft(S),Pe(`Wall layout could not be saved: ${R instanceof Error?R.message:String(R)}`,"error")}},[at,Zo,Pe,Jt,Ke]),oo=d.useCallback(async()=>{const p=Ke,S=Jt;wt(!1),Ft([]);try{await at(!1,[]),Pe("Saved Wall layout released. Client slot order is active again.","success")}catch(C){wt(p),Ft(S),Pe(`Wall layout could not be released: ${C instanceof Error?C.message:String(C)}`,"error")}},[at,Pe,Jt,Ke]),Dd=d.useCallback((p,S)=>{!Ke||!p||(br.current=p,wn(p),S.dataTransfer.effectAllowed="move",S.dataTransfer.setData("text/plain",p))},[Ke]),ji=d.useCallback(()=>{br.current="",wn(""),rn(0)},[]),Id=d.useCallback(async p=>{const S=br.current;if(!Ke||!S||p<=0){ji();return}const C=Jt,R=X1(La,S,p);if(ji(),JSON.stringify(R)!==JSON.stringify(xS(La))){Ft(R);try{await at(!0,R)}catch(j){Ft(C),Pe(`Wall position could not be saved: ${j instanceof Error?j.message:String(j)}`,"error")}}},[ji,at,Pe,Jt,Ke,La]),zs=d.useMemo(()=>Je.map(p=>p.deviceId),[Je]),sr=d.useMemo(()=>new Set(X),[X]),Dn=d.useMemo(()=>Je.filter(p=>sr.has(p.deviceId)),[Je,sr]),ir=d.useMemo(()=>N.find(p=>p.deviceId===Z)||Dn[0]||null,[N,Z,Dn]),ba=d.useMemo(()=>N.find(p=>p.deviceId===K)||null,[K,N]),or=ba?Ys(ba,en[ba.deviceId]):0,Ie=Ct?ba:ir,cc=d.useMemo(()=>new Set(Vo),[Vo]),lo=d.useMemo(()=>so==="all"?Je.map(p=>p.deviceId):Je.filter(p=>cc.has(p.deviceId)).map(p=>p.deviceId),[Je,cc,so]),wa=Ie?Tp(Ie,"control"):!1,el=Do(Ie?.platform)&&(Ie?.capabilities?.controlPermission===!1||Ie?.capabilities?.accessibilityPermission===!1),Yr=Ie?Tp(Ie,"audio")||Tp(Ie,"remoteAudio"):!1,tl=(Array.isArray(Ie?.capabilities?.agentTools)?Ie.capabilities.agentTools.map(String):[]).includes("system.power"),Yn=O?F?.plan==="pro"?"pro":"ltd":"free",Hn=Oc[Yn],uc=Hn.limit,lr=d.useMemo(()=>new Set(z1(Je,uc)),[uc,Je]),dc=!Ie||lr.has(Ie.deviceId),Ld=Yn==="free",Vt=dc,xs=Yn==="ltd"?`Plus includes up to ${Pf} Clients. Upgrade to Pro for commercial use and larger walls.`:`Free includes up to ${Ff} Clients. Upgrade to Plus for ${Pf} devices and no ads.`,ih=Yn==="free",$s=Vt&&!!Ie&&wa,cm=Vt&&!!Ie&&Yr,nl=d.useMemo(()=>Ct?Ie?[Ie]:[]:Dn.length>0?Dn:Ie?[Ie]:[],[Ie,Dn,Ct]),ra=d.useMemo(()=>nl.filter(p=>lr.has(p.deviceId)),[lr,nl]),al=ra.some(p=>String(Ye[p.deviceId]||"").startsWith("pending:")||Oe[p.deviceId]===!0),rl=!(ra.length>0&&ra.every(p=>{const S=String(Ye[p.deviceId]||"");return!!S&&!S.startsWith("pending:")&&Oe[p.deviceId]!==!0}))||al,ci=d.useMemo(()=>pu.filter(p=>!!p?.connected).slice(0,iI(bn)).map(p=>p.deviceId),[pu,bn]),sl=d.useMemo(()=>Qr?Bs?Mt||bn==="list"?zs:St.visibleOnlyLive?tr.length>0?tr:ci:zs:lu.current.length>0?lu.current:zs:[],[ci,Mt,tr,St.visibleOnlyLive,zs,Qr,Bs,bn]),Ir=d.useMemo(()=>Rg(sl.filter(p=>lr.has(p))),[lr,sl]);lu.current=Ir;const Lr=d.useMemo(()=>Ir.filter(p=>p!==qa&&!Rt.has(p)),[Rt,Ir,qa]),fc=d.useMemo(()=>new Map(Je.map(p=>[p.deviceId,p.platform])),[Je]),il=d.useMemo(()=>Object.fromEntries(Je.map(p=>[p.deviceId,String(p.sessionId||"").trim()])),[Je]),_a=$1(Mt,Ir.length),Xn=d.useMemo(()=>Mt?Lr.filter(p=>jf({mode4Enabled:Mt,directMode4WallEnabled:_a,isMac:Do(fc.get(p))})==="atlas"):[],[_a,Mt,fc,Lr]),cr=d.useMemo(()=>Lr.filter(p=>jf({mode4Enabled:Mt,directMode4WallEnabled:_a,isMac:Do(fc.get(p))})==="direct"),[_a,Mt,fc,Lr]),Fd=d.useMemo(()=>{const p=St.autoStartLive?Lr.map(S=>pa("wall",S)):[];return bs&&Vt&&V&&lr.has(V)&&(H==="connecting"||H==="active"||H==="warm")&&p.push(pa("control",V)),[...new Set(p)].sort()},[bs,V,H,Vt,lr,St.autoStartLive,Lr]);d.useEffect(()=>{const p=new Set(Ir);ai(S=>{let C=!1;const R=new Set;for(const j of S)p.has(j)?R.add(j):C=!0;return C?R:S})},[Ir]);const ol=d.useMemo(()=>{const p=j=>Je.find(U=>U.deviceId===j)||null,S=j=>{const U=p(j);return U?Ys(U,en[j]):0},C=(j,U=S(j))=>j===V&&(H==="connecting"||H==="active"||H==="warm")?pn.current.get(j)||ja.current.get(j)||null:Mt?Ar.current.get(j)||Gt.current.get(j)||null:Gt.current.get(j)||null,R=(j,U=S(j))=>{const W=p(j);return`${W?qr(W):j} · Monitor ${U+1}`};return{resolveCurrentTarget(){if(Ct&&ba){const ae=or;return{type:"control",deviceIds:[ba.deviceId],monitorIndex:ae,label:`${qr(ba)} · Monitor ${ae+1}`,sourceCanvas:C(ba.deviceId,ae),signature:`control:${ba.deviceId}:${ae}:${Gn.frameMode}`}}const j=Dn.map(ae=>ae.deviceId).filter(ae=>Lr.includes(ae)),U=ir&&Lr.includes(ir.deviceId)?ir.deviceId:"",W=j.length>0?j:U?[U]:Lr,oe=j.length===0&&!U;if(W.length===0)return null;if(W.length===1){const ae=W[0],J=S(ae);return{type:oe?"wall":j.length>1?"selection":"device",deviceIds:W,monitorIndex:J,label:oe?"Wall":R(ae,J),sourceCanvas:oe?null:C(ae,J),signature:`${oe?"wall":"device"}:${ae}:${J}:${Mt?"atlas":"direct"}`}}return{type:j.length>1?"selection":"wall",deviceIds:W,label:j.length>1?`${W.length} selected Clients`:"Wall",sourceCanvas:null,signature:`${j.length>1?"selection":"wall"}:${W.join(",")}:${bn}`}},getDeviceCanvas:C,composeWall(j,U={}){return XE(j.map(W=>{const oe=S(W);return{deviceId:W,label:R(W,oe),canvas:C(W,oe)}}),U)}}},[Je,ba,V,H,Gn.frameMode,Gt,Mt,en,or,Dn,Ct,Lr,ir,bn]),ll=lD({hubUrl:T,sourceRegistry:ol,onToast:Pe}),ui=d.useMemo(()=>bs&&Vt&&V&&lr.has(V)&&(H==="connecting"||H==="active"||H==="warm")?[V]:[],[bs,V,H,Vt,lr]),co=d.useMemo(()=>Rg([...Ir,...ui]),[ui,Ir]),uo=d.useMemo(()=>hx(St,bn),[St,bn]),Us=d.useMemo(()=>hx(St,"large"),[St]),_r=U1({mode4Enabled:Mt,directMode4WallEnabled:_a,adaptiveFps:Vn,directDeviceCount:cr.length,adaptive:St.adaptiveLoadShedding}),hu=G1({deviceCount:Xn.length,targetFps:Vn,adaptive:St.adaptiveLoadShedding});Mt&&Xn.length>0;const Fa=d.useCallback((p,S,C)=>{if(p.width<=0||p.height<=0)return!1;const R=C?Math.min(1,C.maxWidth/p.width,C.maxHeight/p.height):1,j=Math.max(1,Math.round(p.width*R)),U=Math.max(1,Math.round(p.height*R));(S.width!==j||S.height!==U)&&(S.width=j,S.height=U);const W=S.getContext("2d",{alpha:!1});return W?(W.imageSmoothingEnabled=!0,W.imageSmoothingQuality="low",W.drawImage(p,0,0,p.width,p.height,0,0,S.width,S.height),!0):!1},[]),cl=d.useCallback((p,S)=>{const C=Math.max(0,Number(S.clientWidth||0)),R=Math.max(0,Number(S.clientHeight||0)),j=Math.max(1,Number(window.devicePixelRatio||1)),U=C>0&&R>0?{maxWidth:Math.ceil(C*j),maxHeight:Math.ceil(R*j)}:void 0;return Fa(p,S,U)},[Fa]),ul=d.useCallback((p,S)=>{if(!bd.current)return;const C=`${p}:${S.deviceId}`,R=eu.current.get(C)||{bindingKey:"",totalPaints:0,lastPaintAt:0,lastFrameSeq:0};R.bindingKey=zi(S),R.totalPaints+=1,R.lastPaintAt=performance.now(),R.lastFrameSeq=Number(S.frameSeq||0),eu.current.set(C,R);const j=++xd.current,U={sequence:j,scope:p,deviceId:S.deviceId,bindingKey:R.bindingKey,frameSeq:R.lastFrameSeq,paintedAt:R.lastPaintAt};wd.current[(j-1)%ED]=U},[]),xa=d.useCallback(p=>{p&&ai(S=>{if(S.has(p))return S;const C=new Set(S);return C.add(p),C})},[]),Sa=d.useCallback(p=>{p&&ai(S=>{if(!S.has(p))return S;const C=new Set(S);return C.delete(p),C})},[]),Ss=d.useCallback((p,S)=>{if(!S||S.width<=0||S.height<=0)return!1;const C=document.createElement("canvas");if(C.width=S.width,C.height=S.height,!Fa(S,C))return Qn(C),!1;const R=nr.current.get(p);return nr.current.set(p,C),R&&R!==C&&rr(R),xa(p),!0},[xa,Fa,rr,Qn]),Zn=d.useCallback(p=>{wA(nr.current,p,ad)},[]),dl=d.useCallback((p,S)=>{const C=nr.current.get(p),R=Gt.current.get(p)===S||Ar.current.get(p)===S;return tt.current[p]?(Zn(p),!1):!C||!R||C.width<=0||C.height<=0?!1:Fa(C,S)?!0:(Zn(p),!1)},[Fa,Zn]),Fr=d.useCallback((p,S=!1,C)=>{if(tt.current[p]||!xn.current.has(p))return!1;const R=performance.now(),U=1e3/Math.max(1,Math.min(De,ta.controlWallReuseMaxFps,ws)),W=kr.current.get(p)||0;if(!S&&W>0&&R+2<W)return!1;const oe=pn.current.get(p)||ja.current.get(p),ae=Gt.current.get(p)||Ar.current.get(p);if(!oe||!ae)return!1;const J=Math.max(0,Number(ae.clientWidth||0)),Ge=Math.max(0,Number(ae.clientHeight||0)),Le=Math.max(1,Number(window.devicePixelRatio||1)),st=J>0&&Ge>0?{maxWidth:Math.min(uo.maxWidth,Math.ceil(J*Le)),maxHeight:Math.min(uo.maxHeight,Math.ceil(Ge*Le))}:uo;if(!Fa(oe,ae,st))return!1;let zt=(S||W<=0?R:W)+U;for(;zt<=R+2;)zt+=U;return kr.current.set(p,zt),C&&ae.isConnected&&ul("wall-reuse-visible",C),xa(p),Zn(p),!0},[ws,uo,xa,Fa,ul,Zn,De]);d.useEffect(()=>{Ea.current=qa},[qa]);const Ei=d.useCallback((p,S)=>{const C=si.current;if(!C||C.deviceId!==p)return;const R=Date.now();am.current.set(p,{...C,source:S,completedAtEpochMs:R,durationMs:Math.max(0,performance.now()-C.startedAt)}),si.current=null},[]),um=d.useCallback((p,S)=>{const C=Gt.current.get(p);if(S&&C&&C!==S&&Ss(p,C),S){if(Gt.current.set(p,S),C&&C!==S&&Qn(C),tt.current[p]){Zn(p),rr(S),Sa(p);return}nr.current.get(p)&&dl(p,S)&&xa(p),Fr(p,!0);return}if(C&&ys.current&&lu.current.includes(p)){Ss(p,C),Gt.current.delete(p),Qn(C);return}Gt.current.delete(p),Zn(p),Qn(C),Sa(p)},[Sa,xa,Fr,dl,Ss,rr,Zn,Qn]),dm=d.useCallback((p,S)=>{const C=ja.current.get(p);if(S){ja.current.set(p,S),C&&C!==S&&Qn(C);const R=V===p&&le?pn.current.get(p):null;R&&cl(R,S)&&p===K&&(Ei(p,"warm-reuse"),Ga(!0));return}ja.current.delete(p),Qn(C)},[Ei,K,V,le,cl,Qn]),di=d.useCallback((p,S,C)=>{const R=performance.now(),j=pa(p,C.deviceId);let U=C;if(p==="control"&&C.visualChanged){const ae=String(S.inputFeedbackEventId||""),J=Number(S.inputFeedbackInputSeq||0),Ge=Number(S.inputFeedbackIssuedAtEpochMs||0),Le=Number(S.browserReceivedEpochMs||0),st=ar.current.get(C.deviceId)||"",zt=Ge>0?Math.max(0,Date.now()-Ge):Number.POSITIVE_INFINITY;if(ae.length>0&&J>0&&ae!==st&&zt<=Ng){const $t=Go.current.get(C.deviceId)||[];$t.push(zt),$t.length>tx&&$t.splice(0,$t.length-tx),Go.current.set(C.deviceId,$t),U={...C,inputFeedbackSeq:J,inputFeedbackMs:zt,inputFeedbackAt:R,inputFeedbackExact:!0,inputFeedbackEventId:ae,inputFeedbackInputType:S.inputFeedbackInputType,inputFeedbackInputToFrameMs:Le>0?Math.max(0,Le-Ge):void 0,inputFeedbackFrameToPaintMs:Le>0?Math.max(0,Date.now()-Le):void 0,inputFeedbackAgentApplyMs:S.inputFeedbackAgentApplyMs,inputFeedbackApplyToCaptureMs:S.inputFeedbackApplyToCaptureMs,inputFeedbackSampleCount:$t.length,inputFeedbackP50Ms:Lf($t,.5),inputFeedbackP95Ms:Lf($t,.95)},ar.current.set(C.deviceId,ae),Ad.current.set(C.deviceId,J)}else if(!ae){const $t=g1(C.deviceId),ln=Ad.current.get(C.deviceId)||0,hn=$t?R-$t.sentAt:Number.POSITIVE_INFINITY;$t&&$t.inputSeq>ln&&hn<=Ng&&(U={...C,inputFeedbackSeq:$t.inputSeq,inputFeedbackMs:Math.max(0,hn),inputFeedbackAt:R,inputFeedbackExact:!1},Ad.current.set(C.deviceId,$t.inputSeq))}}no.current.set(j,R);const W=ri.current.get(j)||{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},oe=zi(S);W.bindingKey!==oe&&(W.bindingKey=oe,W.lastAt=void 0,W.lastFrameSeq=void 0,W.sampleChangedFrames=0,W.sampleDecoderInputBase=Number(C.decoderInputCount||0),W.sampleDecoderOutputBase=Number(C.decoderOutputCount||0),bp(W,R)),p==="control"&&U.inputFeedbackMs===void 0&&W.lastInfo?.inputFeedbackMs!==void 0&&W.lastInfo.inputFeedbackAt!==void 0&&R-W.lastInfo.inputFeedbackAt<=Ng&&(U={...U,inputFeedbackSeq:W.lastInfo.inputFeedbackSeq,inputFeedbackMs:W.lastInfo.inputFeedbackMs,inputFeedbackAt:W.lastInfo.inputFeedbackAt,inputFeedbackExact:W.lastInfo.inputFeedbackExact,inputFeedbackEventId:W.lastInfo.inputFeedbackEventId,inputFeedbackInputType:W.lastInfo.inputFeedbackInputType,inputFeedbackInputToFrameMs:W.lastInfo.inputFeedbackInputToFrameMs,inputFeedbackFrameToPaintMs:W.lastInfo.inputFeedbackFrameToPaintMs,inputFeedbackAgentApplyMs:W.lastInfo.inputFeedbackAgentApplyMs,inputFeedbackApplyToCaptureMs:W.lastInfo.inputFeedbackApplyToCaptureMs,inputFeedbackSampleCount:W.lastInfo.inputFeedbackSampleCount,inputFeedbackP50Ms:W.lastInfo.inputFeedbackP50Ms,inputFeedbackP95Ms:W.lastInfo.inputFeedbackP95Ms}),W.totalFrames+=1,W.sampleFrames+=1,lx(W,R,U.frameSeq),U.visualChanged&&(W.totalChangedFrames+=1,W.sampleChangedFrames+=1),W.lastInfo=U,ri.current.set(j,W)},[]),fo=d.useCallback((p,S)=>{if(tt.current[p.deviceId]||Ea.current===p.deviceId)return;di("wall",p,S),p.kind==="live"&&(xa(p.deviceId),Zn(p.deviceId));const C=le&&V===p.deviceId;Ea.current!==p.deviceId&&!C&&(xn.current.delete(p.deviceId),kr.current.delete(p.deviceId))},[V,le,xa,di,Zn]),Pd=d.useCallback((p,S)=>{if(tt.current[p.deviceId]||$n(Nr.current,yt.current)||!dg(p,yt.current))return;di("control",p,S),ze(W=>W&&"");const C=pn.current.get(p.deviceId),R=ja.current.get(p.deviceId);let j=!1;C&&C.width>0&&C.height>0&&(R&&Ct&&p.deviceId===K&&(j=cl(C,R),j&&ul("control-visible",p)),ds.current.set(p.deviceId,{...p,payload:new Uint8Array(0),byteLength:0}),xn.current.add(p.deviceId),p.deviceId===V&&(Ce(!0),te(W=>W==="connecting"?"active":W)),Fr(p.deviceId,!1,p));const U=Jl.current;!U||!RD(U,p)||!j||(Ei(p.deviceId,"fresh-frame"),Ga(!0))},[Ei,K,V,Fr,cl,di,ul,Ct]),Di=d.useCallback((p,S)=>{const C=performance.now(),R=pa(p,S.deviceId);Rr.current.set(R,C),Ls.current.delete(R),p==="control"?Mi.current.delete(R):Is.current.delete(R);const j=Ci.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:[]},U=zi(S);if(j.bindingKey!==U&&(j.bindingKey=U,j.lastAt=void 0,j.lastFrameSeq=void 0,j.lastContentHash=void 0,j.sampleBytes=0,j.sampleH264Frames=0,j.sampleTinyFrames=0,j.sampleRepeatedFrames=0,j.sourceSendIntervalsMs.length=0,bp(j,C)),j.totalFrames+=1,j.sampleFrames+=1,j.sampleBytes+=Math.max(0,Number(S.byteLength||0)),String(S.frameMode||S.mode||S.codec||S.mimeType||"").toLowerCase().includes("h264")){j.sampleH264Frames+=1,Number(S.byteLength||0)<=kD&&(j.sampleTinyFrames+=1);const J=String(S.contentHash||"");J&&j.lastContentHash===J&&(j.sampleRepeatedFrames+=1),j.lastContentHash=J}const ae=Number(S.agentSendGapMs||0);ae>0&&ae<1e3&&M0(j.sourceSendIntervalsMs,ae),j.lastFrame=$c(S),lx(j,C,S.frameSeq),Ci.current.set(R,j)},[]);d.useEffect(()=>{const p=new Set(Fd);for(const R of ri.current.keys())p.has(R)||ri.current.delete(R);for(const R of Ci.current.keys())p.has(R)||Ci.current.delete(R);const S=R=>{const j=Object.entries(R).filter(([U])=>p.has(U));return j.length===Object.keys(R).length?R:Object.fromEntries(j)};if(Sd(S),Ho(S),p.size===0)return;const C=window.setInterval(()=>{const R=performance.now(),j={},U={};for(const W of p){const oe=ri.current.get(W);if(oe){const Le=Math.max(1,R-oe.sampleStartedAt);j[W]={bindingKey:oe.bindingKey||"",totalFrames:oe.totalFrames,totalChangedFrames:oe.totalChangedFrames,framesPerSecond:oe.sampleFrames*1e3/Le,changedFramesPerSecond:oe.sampleChangedFrames*1e3/Le,averageIntervalMs:oe.intervalCount>0?oe.intervalSumMs/oe.intervalCount:0,minIntervalMs:Number.isFinite(oe.minIntervalMs)?oe.minIntervalMs:0,maxIntervalMs:oe.maxIntervalMs,p95IntervalMs:Lf(oe.intervalSamplesMs,.95),intervalCount:oe.intervalCount,seqGapCount:oe.seqGapCount,maxSeqGap:oe.maxSeqGap,decoderInputFps:Math.max(0,(Number(oe.lastInfo?.decoderInputCount||0)-oe.sampleDecoderInputBase)*1e3/Le),decoderOutputFps:Math.max(0,(Number(oe.lastInfo?.decoderOutputCount||0)-oe.sampleDecoderOutputBase)*1e3/Le),sampleMs:Le,lastInfo:oe.lastInfo},oe.sampleDecoderInputBase=Number(oe.lastInfo?.decoderInputCount||0),oe.sampleDecoderOutputBase=Number(oe.lastInfo?.decoderOutputCount||0),oe.sampleChangedFrames=0,bp(oe,R)}const ae=Ci.current.get(W);if(!ae)continue;const J=Math.max(1,R-ae.sampleStartedAt),Ge=ae.lastFrame?$c(ae.lastFrame):void 0;ae.lastFrame=Ge,U[W]={totalFrames:ae.totalFrames,framesPerSecond:ae.sampleFrames*1e3/J,averageIntervalMs:ae.intervalCount>0?ae.intervalSumMs/ae.intervalCount:0,minIntervalMs:Number.isFinite(ae.minIntervalMs)?ae.minIntervalMs:0,maxIntervalMs:ae.maxIntervalMs,p95IntervalMs:Lf(ae.intervalSamplesMs,.95),intervalCount:ae.intervalCount,seqGapCount:ae.seqGapCount,maxSeqGap:ae.maxSeqGap,averageFrameBytes:ae.sampleFrames>0?ae.sampleBytes/ae.sampleFrames:0,tinyFrameRatio:ae.sampleH264Frames>0?ae.sampleTinyFrames/ae.sampleH264Frames:0,repeatedFrameRatio:ae.sampleH264Frames>0?ae.sampleRepeatedFrames/ae.sampleH264Frames:0,sourceSendAverageMs:ae.sourceSendIntervalsMs.length>0?ae.sourceSendIntervalsMs.reduce((Le,st)=>Le+st,0)/ae.sourceSendIntervalsMs.length:0,sourceSendP95Ms:Lf(ae.sourceSendIntervalsMs,.95),sourceSendSampleCount:ae.sourceSendIntervalsMs.length,sampleMs:J,lastFrame:Ge},ae.sampleBytes=0,ae.sampleH264Frames=0,ae.sampleTinyFrames=0,ae.sampleRepeatedFrames=0,ae.sourceSendIntervalsMs.length=0,bp(ae,R)}Sd(j),Ho(U)},1e3);return au.current=C,()=>{window.clearInterval(C),au.current===C&&(au.current=null)}},[Fd]);const gu=d.useCallback(p=>{const S=p.deviceId,C=zi(p);if(tt.current[S]||Ea.current===S||p.currentGenerationVerified!==!0||Wa.current.get(S)!==C)return;Di("wall",p);const R=Gt.current.get(S);if(!R)return;const j=ao(R),U=ro(R),W=()=>Gt.current.get(S)!==R||!hs(R,j)||!!tt.current[S]||Ea.current===S||Wa.current.get(S)!==C,oe=()=>W()||!ii(R,U),ae=V1(Mt,St.h264DecodeAcceleration);cg(R,p,oe,fo,ae.acceleration,ae.latencyMode,W).catch(()=>{})},[ao,ii,hs,ro,fo,Mt,Di,St.h264DecodeAcceleration]),ur=d.useCallback(p=>{const S=p.deviceId;if(tt.current[S]||$n(Nr.current,yt.current)||!dg(p,yt.current))return;Di("control",p);let C=pn.current.get(S);C||(C=document.createElement("canvas"),C.setAttribute("aria-hidden","true"),pn.current.set(S,C));const R=C,j=$c(p),U=ao(R),W=ro(R),oe=()=>pn.current.get(S)!==R||!hs(R,U)||!!tt.current[S]||!dg(j,yt.current),ae=()=>oe()||!ii(R,W),J=et.current;cg(R,p,ae,Pd,Gn.h264DecodeAcceleration,"interactive",oe).catch(Ge=>{et.current!==J||pn.current.get(S)!==R||!ii(R,W)||oe()||V!==S||ze(Ge instanceof Error?Ge.message:String(Ge||"Control H.264 decode failed"))})},[ao,ii,hs,ro,V,Gn.h264DecodeAcceleration,Pd,Di]),Xr=d.useCallback(p=>{const S=Mr.current;Mr.current=p,S&&S!==p&&Qn(S),Wo.current=0,tc.current=0,iu.current=0,ou.current=0,Md.current=0,Zl.current=0},[Qn]),Pr=d.useCallback(()=>{const p=new Set,S=Mr.current,C=Si.current;if(!S||!C||S.width<=0||S.height<=0||Zl.current!==C.layoutVersion)return p;for(const R of C.tiles){if(tt.current[R.deviceId])continue;const j=Ar.current.get(R.deviceId);if(!j||R.width<=0||R.height<=0)continue;const U=Math.max(1,Math.round(R.width)),W=Math.max(1,Math.round(R.height)),oe=MD,ae=AD;(j.width!==oe||j.height!==ae)&&(j.width=oe,j.height=ae);const J=j.getContext("2d",{alpha:!1});if(J){J.imageSmoothingEnabled=!0,J.imageSmoothingQuality="high";try{J.drawImage(S,Math.round(R.x),Math.round(R.y),U,W,0,0,oe,ae),p.add(R.deviceId)}catch{}}}return p},[]),Od=d.useCallback((p,S)=>{const C=Ar.current.get(p);if(S&&C&&C!==S&&Ss(p,C),S){if(Ar.current.set(p,S),C&&C!==S&&Qn(C),tt.current[p]){Zn(p),rr(S),Sa(p);return}nr.current.get(p)&&dl(p,S)&&xa(p),window.requestAnimationFrame(()=>{Pr().has(p)&&Zn(p)}),window.requestAnimationFrame(()=>Fr(p,!0));return}Ar.current.delete(p),Zn(p),Qn(C),Sa(p)},[Sa,xa,Pr,Fr,dl,Ss,rr,Zn,Qn]),Bd=d.useCallback((p,S)=>{iu.current=performance.now(),Zl.current=Number(p.layoutVersion||0),Pr();const C=Si.current?.tiles||[],R=C.length>0?Math.round(p.byteLength/C.length):p.byteLength;for(const j of C){if(tt.current[j.deviceId])continue;const U={...p,deviceId:j.deviceId,width:j.width,height:j.height,sourceWidth:j.width,sourceHeight:j.height,byteLength:R};fo(U,{...S,deviceId:j.deviceId,width:j.width,height:j.height,byteLength:R}),Ea.current===j.deviceId&&Fr(j.deviceId,!0)}},[fo,Pr,Fr]),Ii=d.useCallback(p=>{const S=performance.now();Wo.current<=0&&(Wo.current=S),tc.current=S;const C=Mr.current;if(!C)return;const R=zi(p);Xl.current!==R&&(Xl.current=R,aa(C));const j=ao(C),U=ro(C),W=()=>Mr.current!==C||Xl.current!==R||!hs(C,j),oe=()=>W()||!ii(C,U),ae=Si.current?.tiles||[],J=ae.length>0?Math.round(p.byteLength/ae.length):p.byteLength;for(const Ge of ae)tt.current[Ge.deviceId]||Di("wall",{...p,deviceId:Ge.deviceId,width:Ge.width,height:Ge.height,sourceWidth:Ge.width,sourceHeight:Ge.height,byteLength:J});cg(C,p,oe,Bd,void 0,"smooth",W).catch(()=>{})},[ao,ii,hs,ro,Bd,Di,aa]),dr=d.useCallback(p=>{if(p.streamPurpose!=="wall"||tt.current[p.deviceId])return;const S=zi(p);Wa.current.get(p.deviceId)!==S&&(Wa.current.set(p.deviceId,S),aa(Gt.current.get(p.deviceId)))},[aa]),zn=d.useMemo(()=>({fps:_r,maxWidth:Us.maxWidth,maxHeight:Us.maxHeight,quality:St.quality,mode:Mt?"mode3-h264-hw":St.frameMode,frameMode:Mt?"mode3-h264-hw":St.frameMode,streamPurpose:"wall",forceRestart:Ti>0,forceRestartToken:Ti>0?`document-presentation-resume-${Ti}`:"",restartReason:Ti>0?"document-presentation-resume":"",connectionSessionIds:il,monitorSelections:en,onFrame:gu,onStreamReady:dr}),[il,_r,Ti,gu,dr,Mt,en,St,Us]),mc=d.useCallback(p=>{const S=yt.current;if(tt.current[p.deviceId]||!S||$n(Nr.current,S)||S.deviceId!==p.deviceId||p.deviceId!==V||p.streamPurpose!=="control"||p.monitorIndex!==or)return;const C=Je.find(j=>j.deviceId===p.deviceId);if(!C?.sessionId||C.sessionId!==p.sessionId)return;const R=ue.current;(!R||zi(R)!==zi(p))&&aa(pn.current.get(p.deviceId)),yt.current=rp(S.deviceId,S.transitionGeneration,p),ue.current=p,_e(p),te(j=>j==="connecting"?"active":j)},[Je,V,aa,or]);d.useEffect(()=>{aa(pn.current.get(V)),ue.current=null;const p=yt.current;p&&p.deviceId===V&&(yt.current=rp(p.deviceId,p.transitionGeneration,{sessionId:p.sessionId,monitorIndex:or})),_e(null)},[V,$,En,aa,or]);const Zr=$?`${$}-monitor-${or}`:"",jt=d.useMemo(()=>({fps:ws,maxWidth:_n.maxWidth,maxHeight:_n.maxHeight,quality:Gn.quality,mode:En,frameMode:En,streamPurpose:"control",forceRestart:Zr!=="",forceRestartToken:Zr,restartReason:Zr?"control-session-or-monitor-change":"",connectionSessionIds:il,monitorSelections:en,onFrame:ur,onStreamReady:mc}),[il,Zr,Gn.quality,ur,ws,En,_n.maxHeight,_n.maxWidth,mc,en]),{frames:sn,state:An,error:pc,stats:Jr,restartLive:qs}=Gb(cr,St.autoStartLive&&cr.length>0,T,zn);d.useEffect(()=>{const p=new Set(cr);for(const S of Wa.current.keys())p.has(S)||(Wa.current.delete(S),aa(Gt.current.get(S)))},[cr,aa]);const{frame:fi,layout:Cs,state:Li,stats:oh,refreshInputs:In}=x1(Xn,Mt&&St.autoStartLive&&Xn.length>0,T,{fps:ta.atlasOutputFps,inputFps:hu,width:1920,height:1080,tileWidth:Us.maxWidth,tileHeight:Us.maxHeight,captureDeviceIds:Xn,connectionSessionIds:il,monitorSelections:en,onFrame:Ii});d.useEffect(()=>{Si.current=Cs,Cs&&window.requestAnimationFrame(Pr)},[Cs,Pr]),d.useEffect(()=>{if(!Mt||Li!=="open"){Wo.current=0,tc.current=0,iu.current=0;return}const p=window.setInterval(()=>{const S=Mr.current,C=performance.now();if(!S||document.visibilityState!=="visible"||C-ru.current<Ag)return;const R=tc.current,j=Wo.current;if(R<=0||j<=0||C-R>500)return;const U=iu.current||j,W=C-U;if(W>=bD&&C-Md.current>=xD){rd(S)&&(Md.current=C,ou.current=C);return}W>=yD&&C-ou.current>=wD&&mA(S)&&(ou.current=C)},250);return()=>window.clearInterval(p)},[Li,Mt]);const{frames:mo,state:hc,error:fl,stats:fm,restartLive:vu,reconnectLive:yu}=Gb(ui,ui.length>0,T,jt);d.useEffect(()=>{const p=Kl.current,S=new Set([...Object.keys(p),...Object.keys(en)]);for(const C of S){const R=Math.max(0,Math.floor(Number(p[C])||0)),j=Math.max(0,Math.floor(Number(en[C])||0));R!==j&&(Wa.current.delete(C),aa(Gt.current.get(C)),aa(pn.current.get(C)),aa(Ar.current.get(C)),jn("wall",C),jn("control",C),rd(Gt.current.get(C)||null),rd(pn.current.get(C)||null))}S.size>0&&(aa(Mr.current),rd(Mr.current)),Kl.current={...en}},[en,jn,aa]);const po=d.useMemo(()=>{const p=(C,R)=>{const j=Je.find(W=>W.deviceId===C),U=j?Ys(j,en[C]):0;return!Number.isFinite(Number(R.monitorIndex))||Number(R.monitorIndex)===U},S=new Map;for(const[C,R]of sn.entries())p(C,R)&&S.set(C,R);if(Mt&&fi&&Xn.length>0){const C=new Map((Cs?.tiles||[]).map(j=>[j.deviceId,j])),R=Math.max(1,C.size);for(const j of Xn){const U=C.get(j);U&&S.set(j,{...fi,deviceId:j,width:U.width,height:U.height,sourceWidth:U.width,sourceHeight:U.height,byteLength:Math.round(fi.byteLength/R)})}}for(const[C,R]of mo.entries())p(C,R)&&S.set(C,R);for(const C of sl){if(!xn.current.has(C)||S.has(C))continue;const R=ds.current.get(C);R&&p(C,R)&&S.set(C,R)}return S},[fi,Cs,Je,mo,Xn,Mt,en,sn,sl,cs]),gc=Ct&&ui.length>0?hc:Xn.length>0?Li:An,ua=Ct&&ui.length>0?fm:Xn.length>0?oh:Jr;d.useCallback((p,S="browser-stale")=>{const C=qs(p,S),R=vu(p,S);return C||R},[vu,qs]),d.useEffect(()=>{Mt&&Xn.length>0&&!Ct&&In()},[Xn.length,Mt,In,Ct]);const Nn=d.useCallback((p,S,C)=>{const R=S==="control"?pn.current.get(p)||null:Gt.current.get(p)||null;if(!R||!rd(R))return!1;const j=performance.now();return Ni.current.set(pa(S,p),j),!0},[]),ho=d.useCallback(p=>{if(En!=="mode3-h264-hw"||!V||ie)return!1;const S=Je.find(oe=>oe.deviceId===V)||ba,C=String(S?.platform||"").toLowerCase();if(!["win32","windows","win32nt"].includes(C))return!1;const R="mode5-lzo-delta",j=pa("control",V),U=performance.now();Ai.current.set(j,U),Rr.current.delete(j),no.current.delete(j),qo.current.delete(j),Mi.current.delete(j),Ls.current.delete(j),rd(pn.current.get(V)||null),yu([V],"control-decode-fallback"),be(R),_(`control-${R}-fallback-${V}-${Date.now()}`),Ce(!1),Ga(!1);const W=p==="no first frame"||p==="control-first-frame-timeout";return ze(oe=>oe||(W?`Control frame transport timeout; retrying Control with Mode 5 (${p})`:`H.264 decode failed; retrying Control with Mode 5 (${p})`)),te("connecting"),!0},[Je,ba,V,ie,En,yu]);d.useEffect(()=>{const p=Ct?ba:null;if(p){Jl.current={deviceId:p.deviceId,monitorIndex:or,frameMode:En,startedAtEpochMs:Date.now()},Ga(V===p.deviceId&&le);return}Jl.current=null,Ga(!1)},[ba?.sessionId,K,V,le,En,or,Ct]);const ml=d.useCallback(async(p,S)=>{const C=String(S.streamId||"").trim(),R=String(S.streamPurpose||"").trim(),j=String(S.sessionId||"").trim(),U=String(S.commandId||"").trim(),W=Number(S.captureGeneration||0),oe=Number(S.monitorIndex??-1);if(!C||!["wall","atlas"].includes(R)||!j||!U||!Number.isSafeInteger(W)||W<=0||!Number.isSafeInteger(oe)||oe<0)throw new Error("wall-start-owner-incomplete");const ae=performance.now()+3e3;for(;;){const J=await rt(`/api/remote/devices/${encodeURIComponent(p)}/live/stop`,{method:"POST",body:JSON.stringify({streamId:C,streamPurpose:R,expectedSessionId:j,expectedCommandId:U,expectedCaptureGeneration:W,expectedMonitorIndex:oe,requireNoPresentationOwner:!0,reason:"wall-start-presentation-revoked"})},T);if(J?.ok===!1)throw new Error(J.error||"revoked-wall-start-stop-failed");if(J?.captureStopConfirmed===!0||J?.alreadyStopped===!0||J?.staleOwner===!0)return J;if(J?.presentationOwnerActive===!0||J?.retainedForPresentation===!0){if(ps.current&&ys.current)return J;if(performance.now()<ae){await new Promise(Ge=>window.setTimeout(Ge,50));continue}throw new Error("revoked-wall-start-presentation-owner-did-not-release")}throw new Error("revoked-wall-start-stop-unconfirmed")}},[T]),Ws=d.useCallback(async p=>{if(tt.current[p])throw new Error("LIVE_CAPTURE_PAUSED");if(!ps.current||!ys.current)return{ok:!0,skipped:!0,reason:"wall-capture-owner-hidden"};const S=jr.current,C=N.find(W=>W.deviceId===p);jf({mode4Enabled:Mt,directMode4WallEnabled:_a,isMac:Do(C?.platform)});const R=C?Ys(C,en[p]):0,j={fps:Mt?_r:Vn,maxWidth:Us.maxWidth,maxHeight:Us.maxHeight,quality:St.quality,mode:Mt?"mode3-h264-hw":St.frameMode,frameMode:Mt?"mode3-h264-hw":St.frameMode,streamPurpose:"wall",monitorIndex:R},U=await rt(`/api/remote/devices/${encodeURIComponent(p)}/live/start`,{method:"POST",body:JSON.stringify(j)},T);if(U?.ok===!1)throw new Error(U.error||"wall-stream-start-failed");return S!==jr.current||!ps.current||!ys.current?(await ml(p,U),{...U,skipped:!0,reason:"wall-presentation-owner-revoked",compensated:!0}):U},[Vn,hu,N,_a,_r,T,Mt,en,ml,St.frameMode,St.quality,Us.maxHeight,Us.maxWidth]),bu=d.useCallback(async p=>{const S=N.find(R=>R.deviceId===p);jf({mode4Enabled:Mt,directMode4WallEnabled:_a,isMac:Do(S?.platform)});const C=await rt(`/api/remote/devices/${encodeURIComponent(p)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"wall",reason:"control-active"})},T);if(C?.ok===!1)throw new Error(C.error||"wall-stream-stop-failed");return C},[N,_a,T,Mt]),Gs=d.useCallback(async(p,S="control-session-stop")=>{const C=await rt(`/api/remote/devices/${encodeURIComponent(p)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"control",reason:S})},T);if(C?.ok===!1)throw new Error(C.error||"control-stream-stop-failed");return C},[T]),Ca=d.useCallback((p,S={})=>{Nr.current?.deviceId===p&&(Nr.current=null);const C=pn.current.get(p);if(C){const j=nr.current.has(p)||Gt.current.has(p)||Ar.current.has(p);S.preservePresentation!==!1&&!j&&Ss(p,C),pn.current.delete(p),Qn(C)}const R=ja.current.get(p);R&&ad(R),ds.current.delete(p),xn.current.delete(p),kr.current.delete(p)},[Ss,rr,Qn]),pl=d.useCallback(p=>{const S=[pa("wall",p),pa("control",p)];for(const C of S){const R=Ci.current.get(C);R?.lastFrame&&(R.lastFrame=$c(R.lastFrame))}Ho(C=>{let R=!1;const j={...C};for(const U of S){const W=C[U];!W?.lastFrame||W.lastFrame.payload.byteLength===0||(j[U]={...W,lastFrame:$c(W.lastFrame)},R=!0)}return R?j:C})},[]),vc=d.useCallback(p=>{Wa.current.delete(p),Zn(p),Ca(p,{preservePresentation:!1});const S=new Set;for(const C of[ja.current.get(p),Gt.current.get(p),Ar.current.get(p)])C&&S.add(C);for(const C of S)rr(C);Sa(p),V===p&&(Jl.current=null,Ga(!1),Ce(!1)),pe.current.add(p),pl(p)},[Sa,V,rr,Ca,pl,Zn]);d.useEffect(()=>{const p=new Set(Object.keys(Ye));for(const S of p)pe.current.has(S)||vc(S);for(const S of pe.current)p.has(S)||pe.current.delete(S)},[vc,Ye]);const go=d.useCallback(p=>{const S=nw(Bo.current,p);return Bo.current=S.tail,S.result},[]),Or=d.useCallback(p=>{const S=nw(zo.current,p);return zo.current=S.tail,S.result},[]),Br=d.useCallback(p=>{Da.current=p,Ji.current=0;const S=p?.deviceId||"";Ea.current=S,Ql(S),S&&xn.current.add(S)},[]),vo=d.useCallback(p=>go(async()=>{if(tt.current[p.deviceId])return!1;const S=Da.current;return!$n(S,p)||!sp(p.deviceId,p,yt.current)?!1:(await Ws(p.deviceId),$n(Da.current,p)&&Br(null),!0)}),[Br,go,Ws]),Hd=d.useCallback((p,S,C)=>go(async()=>{const R=Da.current;if($n(R,p))return C.stoppedWallDeviceId=p.deviceId,!0;if(R)if(tt.current[R.deviceId])$n(Da.current,R)&&Br(null);else{if(!sp(R.deviceId,R,yt.current))return!1;await Ws(R.deviceId),$n(Da.current,R)&&Br(null)}if(!S())return!1;if(await bu(p.deviceId),C.stoppedWallDeviceId=p.deviceId,!S()){if(sp(C.stoppedWallDeviceId,p,yt.current))try{await Ws(C.stoppedWallDeviceId)}catch(j){throw Br(p),j}finally{C.stoppedWallDeviceId=""}return!1}return ad(Gt.current.get(p.deviceId)||null),Br(p),!0}),[Br,go,Ws,bu]),yc=d.useCallback(async(p,S)=>{if(S.stoppedWallDeviceId){if($n(Da.current,p)){try{await vo(p)}catch(C){Pe(C instanceof Error?C.message:String(C))}finally{S.stoppedWallDeviceId=""}return}await go(async()=>{if(!S.stoppedWallDeviceId||!sp(S.stoppedWallDeviceId,p,yt.current))return;const C=S.stoppedWallDeviceId;try{await Ws(C)}catch(R){Br(p),Pe(R instanceof Error?R.message:String(R))}finally{S.stoppedWallDeviceId=""}})}},[Br,go,vo,Pe,Ws]),fr=d.useCallback(async(p,S,C={})=>{const R=C.allowStopFailure===!0,j=C.resumeWall!==!1;try{await Gs(p.deviceId,S)}catch(U){if(!R)throw U}if(!$n(yt.current,p))return!1;if(yt.current=null,ue.current=null,_e(null),Ca(p.deviceId),Ce(!1),_(""),be(""),ze(""),ne(U=>U===p.deviceId?"":U),!j)return $n(Da.current,p)&&Br(null),!0;try{await vo(p)}catch(U){Pe(U instanceof Error?U.message:String(U))}return!0},[Br,Ca,vo,Pe,Gs]),mm=(Va&&Ct&&Vt&&K&&!Rt.has(K)&&Je.find(p=>p.deviceId===K)||null)?.deviceId||"";d.useEffect(()=>{$o.current=mm},[mm]),d.useEffect(()=>{const p=K&&Je.find(U=>U.deviceId===K)||null;if(!Va||!Ct||!Vt||!p){ca.current&&(++Kn.current,ca.current="");return}if(tt.current[p.deviceId]){ca.current&&(++Kn.current,ca.current=""),V===p.deviceId&&te("paused");return}if(Tr.current){if(Tr.current===p.deviceId)return;Tr.current=""}if(V===p.deviceId&&(H==="active"||H==="warm"||H==="connecting")){te(U=>U==="warm"?"active":U);return}if(ca.current===p.deviceId)return;const S=++Kn.current,C=rp(p.deviceId,S,{sessionId:p.sessionId,monitorIndex:or});ca.current=p.deviceId;const R={stoppedWallDeviceId:""},j=()=>S===Kn.current&&$o.current===C.deviceId;Or(async()=>{if(!j())return;const U=yt.current;if(U){te("stopping");try{await fr(U,"control-session-switch")}catch(ae){j()&&(te("error"),Pe(ae instanceof Error?ae.message:String(ae)));return}if(!j()){yt.current||te("idle");return}}try{if(!await Hd(C,j,R)||!j()){await yc(C,R),yt.current||te("idle");return}}catch(ae){await yc(C,R),j()&&(te("error"),Pe(ae instanceof Error?ae.message:String(ae)));return}if(!j()){await yc(C,R);return}yt.current=C,Nr.current=null,Tr.current="",ki.current=null,to.current=0,Uo.current="",R.stoppedWallDeviceId="";const W=pa("control",C.deviceId),oe=`control-session-${S}-${C.deviceId}`;Ai.current.set(W,performance.now()),Rr.current.delete(W),no.current.delete(W),Ls.current.delete(W),Mi.current.delete(W),be(""),ze(""),_(oe),ne(C.deviceId),Ce(!1),te("connecting")}).catch(U=>{j()&&(te("error"),Pe(U instanceof Error?U.message:String(U)))}).finally(()=>{Kn.current===S&&ca.current===C.deviceId&&(ca.current="")})},[Je,K,V,H,Va,Or,Vt,Hd,yc,or,Pe,Ct,fr,Ye]),d.useEffect(()=>{if(!V||Je.some(C=>C.deviceId===V))return;const p=V;++Kn.current,ca.current="";const S=yt.current;te("stopping"),Or(async()=>{S&&S.deviceId===p?await fr(S,"control-device-disconnected",{allowStopFailure:!0}):(Ca(p),ne(C=>C===p?"":C)),yt.current||te("idle")})},[Je,V,Or,Ca,fr]),d.useEffect(()=>{if(Gr.current!==null&&(window.clearTimeout(Gr.current),Gr.current=null),!Bs||Ct||!V||tt.current[V]||H!=="connecting"&&H!=="active"&&H!=="warm")return;const p=V,S=yt.current;if(!S||S.deviceId!==p)return;const C=window.setTimeout(()=>{Gr.current===C&&(Gr.current=null);const R=yt.current;if($o.current||tt.current[p]||!$n(R,S))return;Nr.current=S;const j=++Kn.current;ca.current="",te("stopping"),Or(async()=>{if(j!==Kn.current||$o.current||!$n(yt.current,S)){$n(Nr.current,S)&&(Nr.current=null),$n(yt.current,S)&&$o.current===p&&te("active");return}try{await fr(S,"control-session-wall-downshift")}catch(U){$n(Nr.current,S)&&(Nr.current=null),j===Kn.current&&!$o.current&&$n(yt.current,S)&&(te("active"),Pe(U instanceof Error?U.message:String(U)));return}Nr.current=null,j===Kn.current&&!yt.current&&te("idle")})},CD);return Gr.current=C,()=>{Gr.current===C&&(window.clearTimeout(C),Gr.current=null)}},[V,H,Or,Pe,Ct,fr,Ye,Bs]);const bc=d.useCallback(p=>{if(rm.current===p)return;rm.current=p;const S=yt.current,C=S?.deviceId||V,R=++Kn.current;ca.current="",ue.current=null,ec.current=!0,_e(null),Ce(!1),Ga(!1),C&&(jn("control",C),Ca(C,{preservePresentation:!1}),te("stopping"),Or(async()=>{if(S&&S.deviceId===C)try{await fr(S,"control-session-document-hidden",{resumeWall:!1})}catch(j){!ps.current&&jr.current===p&&(te("error"),Pe(j instanceof Error?j.message:String(j)));return}else Ca(C,{preservePresentation:!1}),ne(j=>j===C?"":j);!yt.current&&Kn.current===R&&te("idle")}))},[V,Or,Ca,jn,Pe,fr]);d.useEffect(()=>{if(ms.current!==null&&(window.clearTimeout(ms.current),ms.current=null),!V||H==="idle"||H==="paused"||H==="error")return;if(!Va){bc(jr.current);return}if(H==="stopping"||bs){V&&bs&&H==="connecting"&&(ec.current=!1),V&&bs&&ec.current&&(H==="warm"||H==="active")&&(ec.current=!1,ue.current=null,_e(null),Ce(!1),Ga(!1),jn("control",V),_(`control-presentation-resume-${Date.now()}-${V}`),te("connecting"));return}ue.current=null,ec.current=!0,_e(null),Ce(!1),Ga(!1),te(S=>S==="idle"||S==="stopping"?S:"warm");const p=V;return Ca(p,{preservePresentation:!1}),ms.current=window.setTimeout(()=>{ms.current=null,++Kn.current,ca.current="";const S=yt.current;te("stopping"),Or(async()=>{if(S&&S.deviceId===p)try{await fr(S,"control-session-warm-timeout")}catch(C){te("error"),Pe(C instanceof Error?C.message:String(C));return}else Ca(p),ne(C=>C===p?"":C);yt.current||te("idle")})},SD),()=>{ms.current!==null&&(window.clearTimeout(ms.current),ms.current=null)}},[bs,V,H,Va,Or,Ca,bc,jn,Pe,fr]),d.useEffect(()=>()=>{ms.current!==null&&window.clearTimeout(ms.current),Gr.current!==null&&(window.clearTimeout(Gr.current),Gr.current=null),Nr.current=null},[]);const wc=d.useCallback(()=>{const p=new Set(su.current),S=yt.current?.deviceId||"";V&&p.add(V),S&&p.add(S),su.current=[];for(const R of p){Wa.current.delete(R),Zn(R),Ca(R,{preservePresentation:!1});for(const j of[Gt.current.get(R),ja.current.get(R),Ar.current.get(R)])j&&rr(j);Sa(R),jn("wall",R),jn("control",R),pl(R)}const C=Mr.current;C&&rr(C),Xl.current="",Si.current=null,Zl.current=0},[Sa,V,rr,Ca,pl,Zn,jn]);d.useEffect(()=>{if(Va){su.current=[...co];return}wc()},[Va,co,wc]),d.useEffect(()=>{const p=Da.current,S=yt.current;if(!Bs||!p||tt.current[p.deviceId]||S&&S.deviceId===p.deviceId){Ji.current=0;return}const C=Ji.current,R=Math.min(5e3,500*2**Math.min(C,4)),j=window.setTimeout(()=>{eo.current===j&&(eo.current=null);const U=Da.current;!Dr.current||!U||tt.current[U.deviceId]||!$n(U,p)||(Ji.current=C+1,vo(U).catch(W=>{Pe(W instanceof Error?W.message:String(W)),$n(Da.current,U)&&!yt.current&&Yl(oe=>oe+1)}))},R);return eo.current=j,()=>{window.clearTimeout(j),eo.current===j&&(eo.current=null)}},[H,vo,Pe,Bs,Oo,qa]);const hl=V&&Je.find(p=>p.deviceId===V)||null,gl=!!(Ct&&Xe&&H==="active"&&le&&hl?.sessionId&&Ae?.deviceId===hl.deviceId&&Ae.sessionId===hl.sessionId&&Ae.streamPurpose==="control"&&Ae.commandId&&Ae.captureGeneration>0&&Ae.monitorIndex===or),{state:wu,sendInput:zd,stats:ks,error:$d}=S1(Va&&$s&&gl,T),xu=hl?.deviceId||"",Ud=hl?.sessionId||"",Su=Ae?.commandId||"",_i=Number(Ae?.captureGeneration||0),qd=Number(Ae?.monitorIndex||0),yo=d.useCallback((p,S)=>!ps.current||!gl||!xu||!Ud||!Su||_i<=0||p!==xu?!1:zd(p,{...S,monitorIndex:qd,controlSessionId:Ud,controlCommandId:Su,captureGeneration:_i}),[gl,_i,Su,xu,qd,Ud,zd]),Hr=Va&&ps.current&&gl&&wu==="open",Wd={shiftKey:Ue.includes("ShiftLeft"),ctrlKey:Ue.includes("ControlLeft"),altKey:Ue.includes("AltLeft"),metaKey:Ue.includes("MetaLeft")},zr=d.useCallback(p=>ke.current.enqueueStop(p),[]),bo=d.useCallback(p=>ke.current.enqueueStart(p),[]),ka=d.useCallback((p,S=Ht.current)=>(Nt.current=p,Ht.current=p?String(S||""):"",lt.current+=1,lt.current),[]),es=d.useCallback((p,S,C)=>B1({generation:p,currentGeneration:lt.current,enabled:Nt.current,deviceId:S,currentDeviceId:Ht.current,documentVisible:ps.current,presentationVisible:qe.current,streamId:C,currentStreamId:B.current.get(S)||""}),[]),$r=d.useCallback(async(p,S,C)=>{if(!S)return{ok:!0,alreadyStopped:!0,captureStopConfirmed:!0,noExactOwner:!0};const j=await(W=>rt(`/api/remote/devices/${encodeURIComponent(p)}/audio/stop`,{method:"POST",body:JSON.stringify({...W?{streamId:W}:{},reason:C})},T))(S),U=H1(j);if(U.staleOwner)return j;if(!U.confirmed)throw new Error(j?.error||"Remote audio capture stop was not confirmed.");return j},[T]),Cu=d.useCallback(async(p,S)=>{const C=await rt(`/api/remote/devices/${encodeURIComponent(p)}/audio/stop`,{method:"POST",body:JSON.stringify({reason:S})},T);if(C?.ok===!1||C?.captureStopConfirmed!==!0&&C?.alreadyStopped!==!0)throw new Error(C?.error||"Remote audio stop-all was not confirmed.");return C},[T]),pm=d.useCallback(p=>{const S=lt.current,C=B.current.get(p)||"";return zr(()=>$r(p,C,"remote-audio-automatic-restart")).then(()=>bo(async()=>{if(S!==lt.current||!Nt.current||Ht.current!==p||!ps.current||!qe.current||!Vt||!Yr||($e.current||Ie?.deviceId||"")!==p)return"";const R=`audio-restart-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;if(B.current.set(p,R),!es(S,p,R))return B.current.delete(p),"";const j=await rt(`/api/remote/devices/${encodeURIComponent(p)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:R,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},T);if(j?.ok===!1)throw B.current.get(p)===R&&B.current.delete(p),new Error(j.error||"Remote audio restart failed.");return es(S,p,R)?R:(await $r(p,R,"remote-audio-stale-restart-compensation"),B.current.get(p)===R&&B.current.delete(p),"")}))},[bo,zr,Vt,T,es,Yr,Ie?.deviceId,$r]),ku=Ie?.deviceId&&B.current.get(Ie.deviceId)||"",hm=d.useCallback(async(p,S,C)=>{ka(!1),je(!1),await zr(()=>$r(p,S,C)),B.current.get(p)===S&&B.current.delete(p)},[zr,ka,$r]),{state:Mu,lastFrame:xc,stats:Sn,error:Au}=M1(Ie?.deviceId||"",Va&&cm&&ye,T,Ti,Ot||Bn||bd.current,ku,pm,hm),Nu=d.useRef(new Map);d.useEffect(()=>{const p=[["hub",E],["registry",c],["license",z],["wall-stream",pc],["control-stream",fl],["control-decode",He],["remote-input",$d],["remote-audio",Au]];for(const[S,C]of p){const R=String(C||"").trim();if(S==="hub"&&Wt?.requiresHubRestart&&Wt.stage==="updating"){Nu.current.delete(S);continue}if(!R){Nu.current.delete(S);continue}Nu.current.get(S)!==R&&(Nu.current.set(S,R),Pe(R))}},[Au,He,fl,E,$d,z,c,Pe,pc,Wt]);const vl=Ie?.deviceId||"",Gd=Ie?Ys(Ie,en[vl]):0;d.useEffect(()=>{if(!Xe||!$s||!Hr||!vl)return;const p=D1(),S=vl,C=Gd,R=Le=>{if(!Le)return!1;const st=yo(S,{...Le,monitorIndex:C});return!st&&Le.type!=="keyboard.reset"&&(p.reset("browser-input-send-rejected"),Y([])),st},j=(Le,st)=>{const zt=Le.target,Cn=zt?.tagName?.toLowerCase(),$t=zt?.isContentEditable||Cn==="input"||Cn==="textarea"||Cn==="select",ln=p.isPressed(Le);if($t&&(st==="keydown"||!ln))return;const hn=p.event(Le,st);hn&&(Le.preventDefault(),Le.stopPropagation(),R(hn))},U=Le=>j(Le,"keydown"),W=Le=>j(Le,"keyup"),oe=(Le,st=!1)=>{const zt=p.reset(Le,st);zt&&(R(zt),Y([]))};Se.current=Le=>{const st=p.snapshot().latchedCodes.includes(Le),zt=p.modifier(Le,!st);zt&&(R(zt),Y(Cn=>st?Cn.filter($t=>$t!==Le):[...Cn.filter($t=>$t!==Le),Le]))};const ae=()=>oe("browser-window-blur"),J=()=>oe("browser-page-hidden"),Ge=()=>{document.visibilityState==="hidden"&&oe("browser-document-hidden")};return window.addEventListener("keydown",U,!0),window.addEventListener("keyup",W,!0),window.addEventListener("blur",ae),window.addEventListener("pagehide",J),document.addEventListener("visibilitychange",Ge),()=>{window.removeEventListener("keydown",U,!0),window.removeEventListener("keyup",W,!0),window.removeEventListener("blur",ae),window.removeEventListener("pagehide",J),document.removeEventListener("visibilitychange",Ge),Se.current=null,oe("control-keyboard-owner-changed",!0)}},[$s,Hr,vl,Gd,Xe,yo]);const Vd=d.useCallback(p=>{qe.current=p;const S=$e.current||Ie?.deviceId||"";if(!ye||!S)return;const C=ka(Nt.current,S);if(!p){const j=B.current.get(S)||"";zr(async()=>{await $r(S,j,"remote-audio-document-hidden")}).catch(U=>{($e.current||Ie?.deviceId||"")===S&&(ka(!1),B.current.delete(S),je(!1),Pe(U instanceof Error?U.message:String(U)))});return}const R=`audio-presentation-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;B.current.set(S,R),bo(async()=>{if(!es(C,S,R)||!Vt||!Yr||($e.current||Ie?.deviceId||"")!==S)return;const j=await rt(`/api/remote/devices/${encodeURIComponent(S)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:R,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},T);if(j?.ok===!1)throw new Error(j.error||"Remote audio presentation resume failed.");es(C,S,R)||(await $r(S,R,"remote-audio-stale-presentation-compensation"),B.current.get(S)===R&&B.current.delete(S))}).catch(j=>{ps.current&&C===lt.current&&(ka(!1),B.current.delete(S),je(!1),Pe(j instanceof Error?j.message:String(j)))})},[ye,bo,zr,ka,Vt,T,es,Yr,Ie?.deviceId,Pe,$r]);d.useEffect(()=>{const p=j=>{const U=ps.current;j!==U&&(ps.current=j,jr.current+=1,io.current={active:j&&ys.current,epoch:jr.current},j||(wc(),bc(jr.current)),Vd(j),kd(j),j&&!U&&(sm(W=>W+1),ru.current=performance.now()))},S=()=>{p(document.visibilityState==="visible")},C=()=>p(!1),R=()=>S();return document.addEventListener("visibilitychange",S),window.addEventListener("pagehide",C),window.addEventListener("pageshow",R),()=>{document.removeEventListener("visibilitychange",S),window.removeEventListener("pagehide",C),window.removeEventListener("pageshow",R)}},[wc,bc,Vd]),d.useEffect(()=>{if(!V||H!=="connecting"&&H!=="active"&&H!=="warm"||hc!=="open")return;const p=V,S=pa("control",p),C=window.setInterval(()=>{const R=performance.now();if(document.visibilityState!=="visible"||R-ru.current<Ag)return;const j=Rr.current.get(S)||0,U=no.current.get(S)||0,W=qo.current.get(S)||0,oe=Ai.current.get(S)||R;Ai.current.has(S)||Ai.current.set(S,oe);const ae=j<=0,J=ae?R-oe>_D:R-j>fx,Ge=j>0&&(U<=0||R-U>fx);if(!J&&Ge){const Cn=Ni.current.get(S)||0;R-Cn>=mx&&Nn(p,"control","decoder-paint-stale");return}if(!J)return;const Le=Mi.current.get(S)||0;if(Le>0){if(R-Le<PD)return;Mi.current.delete(S)}const st=Ls.current.get(S)||0;if(st>=OD){if(ho(ae?"no first frame":"stale stream"))return;Ce(!1),Ga(!1),Tr.current=p,te("error");return}if(R-W<px(FD,st))return;vu([p],ae?"control-first-frame-timeout":"control-receive-stale")&&(qo.current.set(S,R),Mi.current.set(S,R),Ai.current.set(S,R),Ls.current.set(S,st+1))},650);return()=>window.clearInterval(C)},[hc,V,H,ho,Nn,vu]),d.useEffect(()=>{!He||V&&tt.current[V]||En!=="mode3-h264-hw"||ho(He)||(Ce(!1),Ga(!1),Tr.current=yt.current?.deviceId||"",te("error"))},[He,V,En,ho]),d.useEffect(()=>{!Ct||!V||tt.current[V]||!fl||(Tr.current=V,te(p=>p==="error"?p:"error"))},[fl,V,Ct]),d.useEffect(()=>{if(H!=="error")return;const p=yt.current;if(!p)return;Tr.current=p.deviceId,$n(ki.current,p)||(ki.current=p,to.current=0);const S=to.current,C=S===0?0:Math.min(5e3,500*2**Math.min(S-1,4)),R=window.setTimeout(()=>{$n(yt.current,p)&&(++Kn.current,ca.current="",te("stopping"),Or(async()=>{if($n(yt.current,p))try{if(!await fr(p,"control-session-terminal-error"))return;ki.current=null,to.current=0,Uo.current===p.deviceId?(Uo.current="",Tr.current="",te("idle")):te("error")}catch(j){if(!$n(yt.current,p))return;to.current+=1,Pe(j instanceof Error?j.message:String(j)),te("error"),Cr(U=>U+1)}}))},C);return()=>window.clearTimeout(R)},[H,Yi,Or,Pe,fr]);const wo=d.useCallback(p=>{if(!p||Tr.current!==p)return!1;const S=yt.current;return++Kn.current,ca.current="",to.current=0,S&&S.deviceId===p?(Uo.current=p,ki.current=null,te("error"),Cr(C=>C+1),!0):(Uo.current="",Tr.current="",ki.current=null,te("idle"),!0)},[]);d.useEffect(()=>{if(An!=="open"||!St.autoStartLive||cr.length===0)return;const p=window.setInterval(()=>{const S=performance.now();if(document.visibilityState!=="visible"||S-ru.current<Ag)return;const C=1e3/Math.max(1,_r||De||1),R=Math.max(HD,Math.ceil(C*4)),j=[];for(const U of cr){if(j.length>=UD)break;const W=pa("wall",U),oe=Rr.current.get(W)||0,ae=oe<=0,J=Is.current.get(W)||S;if(Is.current.has(W)||Is.current.set(W,J),ae&&S-J<=BD)continue;const Ge=qo.current.get(W)||0,Le=no.current.get(W)||0,st=ae||S-oe>R,zt=!ae&&(Le<=0||S-Le>R);if(!st&&zt){const $t=Ni.current.get(W)||0;S-$t>=mx&&Nn(U,"wall","decoder-paint-stale");continue}if(!st)continue;const Cn=Ls.current.get(W)||0;S-Ge>=px(zD,Cn)&&j.push(U)}if(j.length>0&&qs(j,j.some(U=>(Rr.current.get(pa("wall",U))||0)<=0)?"wall-first-frame-timeout":"wall-frame-stale"))for(const U of j){const W=pa("wall",U);qo.current.set(W,S),Is.current.set(W,S),Rr.current.delete(W),no.current.delete(W),Ls.current.set(W,(Ls.current.get(W)||0)+1)}},$D);return()=>window.clearInterval(p)},[_r,cr,Nn,qs,St.autoStartLive,De,An]),d.useEffect(()=>{Sr(De),Fs.current=Date.now(),Ps.current=0,Kr.current=0,Ka.current=0,du.current=0,Ia.current=""},[De,St.frameMode,St.adaptiveLoadShedding]),d.useEffect(()=>{YM({h264DecodeAcceleration:St.h264DecodeAcceleration})},[St.h264DecodeAcceleration]),d.useEffect(()=>{if(!Vt||Ct||bn==="list"||!St.visibleOnlyLive){ni([]);return}const p=ac.current;if(!p||typeof IntersectionObserver>"u"){ni(ci);return}const S=Array.from(p.querySelectorAll("[data-live-device-id]"));if(S.length===0){ni([]);return}const C=new Map,R=()=>{const U=Rg(S.map(W=>String(W.dataset.liveDeviceId||"")).filter(W=>(C.get(W)||0)>0));ni(W=>Tg(W,U)?W:U)},j=new IntersectionObserver(U=>{for(const W of U){const oe=String(W.target.dataset.liveDeviceId||"");oe&&C.set(oe,W.isIntersecting?W.intersectionRatio||.01:0)}R()},{root:null,rootMargin:vi.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return S.forEach(U=>j.observe(U)),R(),()=>j.disconnect()},[ci,Vt,Ct,pu,St.visibleOnlyLive,bn]),d.useEffect(()=>{if(!St.adaptiveLoadShedding||!St.autoStartLive||cr.length===0){Kr.current=0,Ka.current=0,du.current=0,Ia.current="";return}const p=De;if(An!=="open"||Jr.sampleMs<500||Jr.lastUpdatedAt<=0||du.current===Jr.lastUpdatedAt)return;du.current=Jr.lastUpdatedAt;const S=Date.now(),C=cr.map(Le=>({deviceId:Le,receive:nu[pa("wall",Le)],paint:tu[pa("wall",Le)]}));if(!C.every(({receive:Le,paint:st})=>{const zt=Le?.lastFrame,Cn=Math.max(0,Number(zt?.requestedFps||0)),$t=zt?zi(zt):"";return W1({receiveSampleMs:Number(Le?.sampleMs||0),paintSampleMs:Number(st?.sampleMs||0),currentGenerationVerified:zt?.currentGenerationVerified===!0,frameRequestedFps:Cn,adaptiveFps:Vn})&&st?.bindingKey===$t})){Kr.current=0,Ka.current=0,Ps.current=0;return}const j=[Vn,...C.map(({deviceId:Le,receive:st})=>`${Le}:${zi(st.lastFrame)}`).sort()].join("|");if(Ia.current!==j){Ia.current=j,Kr.current=S,Ka.current=0,Ps.current=0;return}if(!Kr.current){Kr.current=S,Ka.current=0;return}if(S-Kr.current<vi.downshiftStableSampleMs)return;const U=C.reduce((Le,{receive:st})=>Le+Math.max(0,Number(st?.framesPerSecond||0)),0),W=C.reduce((Le,{receive:st})=>Le+Math.max(0,Number(st?.framesPerSecond||0))*Math.max(0,Number(st?.averageFrameBytes||0)),0),oe=C.reduce((Le,{paint:st})=>Le+Math.max(0,Number(st?.framesPerSecond||0)),0),ae=Math.max(0,...C.map(({receive:Le})=>Number(Le?.maxIntervalMs||0))),J=Math.max(0,...C.map(({paint:Le})=>Number(Le?.p95IntervalMs||0))),Ge=q1({directDeviceCount:cr.length,requestedFps:Vn,measuredFramesPerSecond:U,measuredPaintFramesPerSecond:oe,measuredBytesPerSecond:W,maxBytesPerSecond:vi.maxWallBytesPerSecond,worstReceiveGapMs:ae,worstPaintP95Ms:J,maxFrameGapMs:vi.maxFrameGapMs});if(Ge.overloaded){if(Ps.current=0,Ka.current+=1,Ka.current<vi.downshiftConsecutiveSamples)return;const Le=vi.minFps;if(S-Fs.current>=vi.downshiftCooldownMs&&Vn>Le){const st=Math.max(Le,oI(Vn,Le));st<Vn&&(Sr(st),Fs.current=S,Kr.current=0,Ka.current=0)}return}if(Ka.current=0,!Ge.healthyForRecovery||Vn>=p){Ge.healthyForRecovery||(Ps.current=0);return}if(!Ps.current){Ps.current=S;return}if(S-Ps.current>=vi.recoveryCooldownMs){const Le=Math.min(p,lI(Vn,p));Le>Vn&&(Sr(Le),Fs.current=S,Ps.current=0,Kr.current=0,Ka.current=0)}},[Vn,cr.length,cr,tu,nu,An,Jr.lastUpdatedAt,Jr.sampleMs,St.adaptiveLoadShedding,St.autoStartLive,St.frameMode,De]),d.useEffect(()=>{const p=new URLSearchParams(window.location.search).get("checkout");if(p==="success"){Pe("Checkout returned. Waiting for Dodo confirmation."),I();const S=window.setInterval(()=>{I()},4e3),C=window.setTimeout(()=>{window.clearInterval(S)},45e3);return()=>{window.clearInterval(S),window.clearTimeout(C)}}p==="cancelled"&&Pe("Checkout cancelled.")},[I]),d.useEffect(()=>{!Vt&&Xe&&Ze(!1),!Vt&&ye&&(ka(!1),je(!1))},[ye,Xe,ka,Vt]),d.useEffect(()=>{ye&&(!Ie||!Yr)&&(ka(!1),je(!1))},[ye,ka,Yr,Ie]),d.useEffect(()=>{const p=Ie?.deviceId||"",S=$e.current;if($e.current=p,!S||S===p)return;const C=ka(ye,p),R=p?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";p&&ye&&B.current.set(p,R);let j=!0;const U=B.current.get(S)||"";return(async()=>{try{await zr(async()=>{await $r(S,U,"remote-audio-device-switch"),B.current.delete(S)}),await bo(async()=>{if(!j||!es(C,p,R)||!p||!Vt||!Yr)return;const W=await rt(`/api/remote/devices/${encodeURIComponent(p)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:R,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},T);if(W.ok===!1)throw new Error(W.error||"Remote audio start failed.");es(C,p,R)||(await $r(p,R,"remote-audio-stale-device-switch-compensation"),B.current.get(p)===R&&B.current.delete(p))})}catch(W){j&&(ka(!1),B.current.delete(p),je(!1),Pe(W instanceof Error?W.message:String(W)))}})(),()=>{j=!1}},[ye,bo,zr,ka,Vt,T,es,Yr,Ie?.deviceId,$r]),d.useEffect(()=>{const p=Je.map(j=>j.deviceId),S=new Set(p),C=new Map(Je.map(j=>[j.deviceId,j])),R=new Map;for(const j of Je){const U=QD(j);if(!U)continue;const W=wi(j.status),oe=[j.lastStatusAt,W.capturedAt,W.collectedAt,W.timestamp,W.updatedAt].find(J=>typeof J=="string"&&J.trim()),ae=L1(ti.current[j.deviceId],U,oe);ae&&(ti.current[j.deviceId]=ae,R.set(j.deviceId,ae),wS({platform:j.platform,topologyFingerprint:U,consecutiveTopologySamples:ae.consecutiveSamples})&&(Po.current[j.deviceId]=U))}for(const j of Object.keys(ti.current))S.has(j)||delete ti.current[j];se(j=>{const U=j.filter(W=>S.has(W));return Tg(j,U)?j:U}),G(j=>j&&S.has(j)?j:""),me(j=>j&&S.has(j)?j:""),Qi(j=>{let U=!1;const W={};for(const[oe,ae]of Object.entries(j)){const J=C.get(oe);if(!J){W[oe]=ae;continue}const Ge=R.get(oe)||ti.current[oe],Le=_1({requestedIndex:ae,monitorCount:Uc(J),platform:J.platform,topologyFingerprint:Ge?.fingerprint||"",consecutiveTopologySamples:Ge?.consecutiveSamples||0});W[oe]=Le,Le!==ae&&(U=!0)}return U?W:j}),Td(j=>{const U=j.filter(W=>S.has(W));return Tg(j,U)?j:U})},[Je,ya]),d.useEffect(()=>{om([]),gs(!1)},[Fr]),d.useEffect(()=>{!vs||so!=="selected"||Vo.length>0||Dn.length===0||Td(Dn.map(p=>p.deviceId))},[Dn,Vo.length,so,vs]),d.useEffect(()=>{try{localStorage.setItem(w0,Wr)}catch{}},[Wr]),d.useEffect(()=>{tI(St)},[St]),d.useEffect(()=>{aI(Gn)},[Gn]),d.useEffect(()=>{JD(en,Po.current)},[Je,en]);const Tu=d.useCallback(async()=>{const p=new Set(y);p.add(qn);try{const U=await rt("/api/remote/status",void 0,qn);Ab({endpoint:U.agentEndpoint,endpoint_candidates:[...U.agentEndpointCandidates||[],...U.hostTargetEndpointCandidates||[]]}).forEach(W=>p.add(W))}catch{}const S=[...p].sort((U,W)=>{const oe=ae=>{const J=Uf(ae);return J==="local"?0:J==="loopback"?1:2};return oe(U)-oe(W)||U.localeCompare(W)});let C=!1,R="",j=!1;try{for(const U of S){const W=Uf(U);try{if(await rt("/api/health",void 0,U),W==="local")return b(!0),ld(!0),U;W==="loopback"&&(C=!0,R=U)}catch{W==="local"&&(j=!0)}}return C?(j&&Pe("LiveDesk Hub is reachable on this PC, but not through the LAN address yet. Restart LiveDesk Hub to bind 5179 on the network."),b(!0),ld(!0),R||qn):(b(!1),ld(!1),"")}catch{return b(!1),ld(!1),""}},[y]),yl=async()=>{if(xe("auth"),Ln(!1),await Tu(),window.liveDesk?.auth?.signInWithGoogle){const C=await window.liveDesk.auth.signInWithGoogle();C?.ok===!1&&(Pe(C.error||"LiveDesk could not open the system browser for Google sign-in."),xe(""));return}const{data:p,error:S}=await Et.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}/callback`}});S&&(Pe(S.message),xe(""))},ch=async()=>{xe("auth"),Ln(!1),await Et.auth.signOut(),(await window.liveDesk?.auth?.persistSession?.(null))?.runtimeCleared===!1?Pe("Signed out locally. The LiveDesk runtime could not be reached to clear its session."):window.liveDesk?.auth?.persistSession||await rt("/api/auth/session",{method:"DELETE"},qn).catch(()=>{}),xe("")};d.useEffect(()=>{if(!Ki)return;const p=C=>{C.target instanceof Element&&(C.target.closest(".account-popover, .rail-account")||Ln(!1))},S=C=>{C.key==="Escape"&&Ln(!1)};return window.addEventListener("pointerdown",p),window.addEventListener("keydown",S),()=>{window.removeEventListener("pointerdown",p),window.removeEventListener("keydown",S)}},[Ki]);const gm=d.useCallback(async(p={})=>{const S=p.silent===!0,C=p.takeover===!0,R=p.requestLocalAccess===!0;if(!n?.user){S||Pe("Sign in before publishing this host.","error");return}if(!Qo.current){Qo.current=!0,S||(xe("host"),q("Hub · 1/4 · Checking the local runtime…"));try{const U=(R?await Tu():"")||T||qn;if(!(k||await rt("/api/remote/status",void 0,U)).started)throw new Error("Start LiveDesk on this computer before syncing the server.");S||q("Hub · 2/4 · Sending the signed-in session to the Hub…");const oe=await rt("/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}})},U);if(!oe.ok||!oe.authenticated)throw new Error(oe.error||"hub-session-sync-failed");S||q("Hub · 3/4 · Claiming the Hub role and publishing its endpoint…");const ae=await rt("/api/hub/sync",{method:"POST",body:JSON.stringify({takeover:C})},U);if(!ae.ok)throw new Error(ae.error||"host-target-failed");if(!S){q("Hub · 4/4 · Verifying the endpoint and lease renewal…");const J=await rt("/api/hub/status",void 0,U);if(!J.hostTargetActive)throw new Error(J.hostTargetLease?.lastError||"host-target-not-active-after-sync");const Ge=J.hostTargetEndpoint||J.agentEndpoint||"endpoint ready",Le=Number(J.connectedDeviceCount||0),st=Le>0?`${Le} client${Le===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";Pe(`Hub ready · ${Ge} · lease auto-renewal active. ${st}`,"success"),(R||x)&&(b(!0),ld(!0)),D()}u()}catch(j){if(!S){const U=j instanceof Error?j.message:String(j);U.includes("local network access")&&(b(!1),ld(!1)),Pe(`Hub setup failed · ${U}`,"error")}}finally{Qo.current=!1,S||xe("")}}},[T,x,D,u,Tu,n,Pe,q,k]),bl=d.useCallback((p=!0)=>{fe!=="host"&&(dt(!1),p&&window.requestAnimationFrame(()=>Yt.current?.focus()))},[fe]),Sc=d.useCallback(()=>{fe!=="host"&&(Yt.current=document.activeElement instanceof HTMLElement?document.activeElement:null,Ln(!1),dt(!0))},[fe]),Kd=d.useCallback(()=>{dt(!1),gm({takeover:!0,requestLocalAccess:!0})},[gm]);d.useEffect(()=>{if(!ft)return;const p=window.requestAnimationFrame(()=>Dt.current?.focus()),S=R=>{R.target instanceof Element&&R.target.closest(".client-hub-switch-popover, .hub-sync-trigger")||bl(!1)},C=R=>{R.key==="Escape"&&bl()};return window.addEventListener("pointerdown",S),window.addEventListener("keydown",C),()=>{window.cancelAnimationFrame(p),window.removeEventListener("pointerdown",S),window.removeEventListener("keydown",C)}},[bl,ft]);const Ru=d.useCallback(async()=>{if(!(!k?.update?.canApply||fe==="update")){xe("update");try{const p=await rt("/api/update/apply",{method:"POST",body:JSON.stringify({})},T||qn);if(!p.ok)throw new Error(p.error||"LiveDesk update could not be started.");const S=[...new Set((p.targets||[]).map(j=>String(j.deviceId||"").trim()).filter(Boolean))],C=!!(p.managerUpdateAvailable||p.clientPackageUpdateAvailable),R=p.state==="hub-restart-requested"?Date.now():void 0;(S.length>0||C)&&Ra({operationId:String(p.operationId||`wall-update-${Date.now()}`),targetIds:S,stage:p.state==="clients-updated"?"updated":"updating",requiresHubRestart:C,initialHostInstanceId:String(k.hostInstanceId||""),targetManagerVersion:String(p.latestVersion||k.update?.latestVersion||""),targetClientVersion:String(p.latestClientVersion||k.update?.latestClientVersion||""),restartRequestedAt:R,restartDeadlineAt:R?R+yp:void 0}),q(p.state==="hub-restart-requested"?vp:sx),D()}catch(p){Pe(p instanceof Error?p.message:String(p),"error")}finally{xe("")}}},[fe,T,D,Pe,q,k]);d.useEffect(()=>{const p=Wt,S=k?.update;if(!p||p.stage!=="updating"||!S)return;const C=S.restartResult?.operationId===p.operationId?S.restartResult:null;if(C?.outcome==="restored"){const ae=C.error||`The requested Hub ${C.targetVersion||p.targetManagerVersion||"version"} failed verification.`;Ra(J=>J?.operationId===p.operationId?{...J,stage:"restored",error:ae}:J),Pe(`LiveDesk update did not complete. Hub ${C.fallbackVersion||C.appVersion||"the previous version"} was restored. ${ae}`,"error");return}if(C?.outcome==="failed"){const ae=C.error||"No verified LiveDesk Hub replacement could be started.";Ra(J=>J?.operationId===p.operationId?{...J,stage:"failed",error:ae}:J),Pe(`LiveDesk Hub update failed. ${ae}`,"error");return}if(S.operationId===p.operationId&&S.state==="failed"){const ae=S.error||"LiveDesk update failed before the Hub replacement completed.";Ra(J=>J?.operationId===p.operationId?{...J,stage:"failed",error:ae}:J),Pe(ae,"error");return}if(S.operationId===p.operationId){if(S.state==="hub-restart-requested"&&!p.restartDeadlineAt){const ae=Date.now();Ra(J=>J?.operationId===p.operationId?{...J,restartRequestedAt:ae,restartDeadlineAt:ae+yp}:J),q(vp)}!p.requiresHubRestart&&S.state==="clients-updated"&&(Ra(ae=>ae?.operationId===p.operationId?{...ae,stage:"updated"}:ae),Pe("LiveDesk clients updated and reconnected successfully.","success"));return}if(!p.requiresHubRestart)return;const R=k.started===!0&&(!p.initialHostInstanceId||k.hostInstanceId&&k.hostInstanceId!==p.initialHostInstanceId),j=!!S.checkedAt,U=ix(S.currentVersion,p.targetManagerVersion),W=!p.targetClientVersion||ix(S.currentClientVersion,p.targetClientVersion),oe=j&&S.state==="idle"&&S.updateAvailable===!1&&U&&W;R&&oe&&(Ra(ae=>ae?.operationId===p.operationId?{...ae,stage:"updated"}:ae),Pe(`LiveDesk Hub ${S.currentVersion||C?.appVersion||p.targetManagerVersion} restarted and passed version verification.`,"success"))},[Pe,q,k,Wt]),d.useEffect(()=>{const p=Wt;if(!p||p.stage!=="updating"||!p.requiresHubRestart||p.restartDeadlineAt)return;const S=()=>{const R=Date.now();Ra(j=>j?.operationId===p.operationId&&j.stage==="updating"&&!j.restartDeadlineAt?{...j,restartRequestedAt:R,restartDeadlineAt:R+yp}:j),q(vp)};if(k?.update?.state==="hub-restart-requested"){S();return}if(!E)return;const C=window.setTimeout(S,ND);return()=>window.clearTimeout(C)},[E,q,k?.update?.state,Wt]),d.useEffect(()=>{const p=Wt;if(!p||p.stage!=="updating"||!p.requiresHubRestart||!p.restartDeadlineAt)return;const S=Math.max(0,p.restartDeadlineAt-Date.now()),C=p.operationId,R=window.setTimeout(()=>{const j=`LiveDesk Hub did not return and verify ${p.targetManagerVersion||"the requested version"} within ${Math.round(yp/6e4)} minutes. Check the Hub terminal or restart log, then run livedesk@latest manually if the Hub is still offline.`;Ra(U=>U?.operationId===C&&U.stage==="updating"?{...U,stage:"failed",error:j}:U),Pe(j,"error")},S);return()=>window.clearTimeout(R)},[Pe,Wt]),d.useEffect(()=>{if(!Wt||Wt.stage!=="updated")return;const p=Wt.operationId,S=window.setTimeout(()=>{Ra(C=>C?.operationId===p?null:C)},8e3);return()=>window.clearTimeout(S)},[Wt]),d.useEffect(()=>{if(cn!==sx&&cn!==vp)return;const p=k?.update;if(String(p?.state||"")==="failed"){Pe(p?.error||"LiveDesk update failed.","error");return}Wt?.stage==="updated"&&Pe("")},[cn,Pe,k?.update?.error,k?.update?.state,Wt?.stage]);const vm=d.useCallback(async()=>{if(!fe){xe("pin");try{const S=await rt("/api/remote/pairing-pin",{method:"POST"},T||qn);if(!S.ok)throw new Error(S.error||"pin-rotation-failed");await D(),Pe("New PIN published.")}catch(p){Pe(p instanceof Error?p.message:String(p))}finally{xe("")}}},[fe,T,D]),Qd=d.useCallback(p=>{p&&(G(p),se(S=>S.includes(p)?S:[...S,p]))},[]),wl=d.useCallback(p=>{if(!p)return;const S=sr.has(p);G(C=>S?C===p?"":C:p),se(C=>S?C.filter(R=>R!==p):C.includes(p)?C:[...C,p])},[sr]),xl=d.useCallback(()=>{se([]),G("")},[Fa]),ju=d.useCallback(()=>{se(Je.map(p=>p.deviceId)),G("")},[Je]),Yd=d.useCallback((p,S)=>{const C=Je.find(j=>j.deviceId===p);if(!C)return;const R=Uc(C);if(!(R<=1)&&(Qi(j=>{const U=Of(j[p],R),W=(U+S+R)%R;return W===U?j:{...j,[p]:W}}),jn("wall",p),jn("control",p),ai(j=>{if(!j.has(p))return j;const U=new Set(j);return U.delete(p),U}),ds.current.delete(p),xn.current.delete(p),Ct)){const j=wo(p);Ce(!1),j||te("connecting"),Ga(!1),me(p)}},[Je,jn,wo,Ct]);d.useEffect(()=>{const p=S=>{if(Xe&&$s&&Hr)return;const C=S.target,R=C?.tagName?.toLowerCase();C?.isContentEditable||R==="input"||R==="textarea"||R==="select"||((S.ctrlKey||S.metaKey)&&S.key.toLowerCase()==="a"&&(S.preventDefault(),ju()),S.key==="Escape"&&xl())};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[$s,xl,Hr,Xe,ju]);const Xd=(p,S)=>{const C=Je.find(W=>W.deviceId===p),R=C?Uc(C):1,j=Of(en[p],R),U=Of(S,R);if(j!==U&&(Qi(W=>({...W,[p]:U})),ai(W=>{if(!W.has(p))return W;const oe=new Set(W);return oe.delete(p),oe}),ds.current.delete(p),xn.current.delete(p),jn("wall",p),jn("control",p)),Ct){const W=wo(p);j!==U&&(Ce(!1),W||te("connecting")),Ga(!1),me(p)}else Qd(p)},Zd=p=>{const S=$e.current||Ie?.deviceId||"",C=[...new Set([S,p].filter(Boolean))],R=ye||C.some(j=>B.current.has(j));ka(!1),je(!1);for(const j of C)B.current.delete(j);C.length!==0&&(async()=>{for(const j of C)await zr(()=>Cu(j,"remote-audio-control-entry"))})().catch(j=>{R&&Pe("Remote audio was muted locally, but Client capture stop was not confirmed: "+(j instanceof Error?j.message:String(j)),"error")})},Cc=async p=>{const S={requestId:++th.current,deviceId:p,startedAt:performance.now(),startedAtEpochMs:Date.now()};if(si.current=S,!lr.has(p)){si.current?.requestId===S.requestId&&(si.current=null),Ze(!1),Pe(xs);return}const C=Je.find(j=>j.deviceId===p);if(Do(C?.platform)&&(C?.capabilities?.controlPermission===!1||C?.capabilities?.accessibilityPermission===!1)){si.current?.requestId===S.requestId&&(si.current=null),Ze(!1),Pe("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts LiveDesk, then restart the Mac client.","error");return}Zd(p),wo(p),Ga(!1),me(p),Zt("control"),Ze(!0),Pe(`Opening remote control${C?` for ${qr(C)}`:""}.`,"success")},ym=async()=>{if(!Ie){Pe("Select a Client before playing audio.");return}if(!Vt){Pe(xs);return}if(!Yr){Pe("Selected Client does not report remote audio support yet.");return}if(nt)return;const p=!ye,S=p?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:B.current.get(Ie.deviceId),C=ka(p,Ie.deviceId);p&&S?B.current.set(Ie.deviceId,S):p||B.current.delete(Ie.deviceId),ct("audio"),je(p);try{p?(await zr(()=>Cu(Ie.deviceId,"remote-audio-user-enable-reconcile")),await bo(async()=>{if(!S||!es(C,Ie.deviceId,S))return;const R=await rt(`/api/remote/devices/${encodeURIComponent(Ie.deviceId)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:S,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},T);if(R?.ok===!1)throw new Error(R.error||"Remote audio start failed.");es(C,Ie.deviceId,S)||await $r(Ie.deviceId,S,"remote-audio-stale-user-start-compensation")})):await zr(()=>Cu(Ie.deviceId,"remote-audio-user-disabled")),Pe(`${p?"Audio started":"Audio stopped"} for ${qr(Ie)}.`,"success")}catch(R){ka(!1),p&&B.current.delete(Ie.deviceId),je(!1),Pe(R instanceof Error?R.message:String(R),"error")}finally{ct("")}},xo=async(p,S)=>{const C=p.deviceId,R=qr(p),j=String(tt.current[C]||""),U=!!j&&Oe[C]===!0;if(S&&j&&!U)return{ok:!0,skipped:!0,action:"pause",deviceId:C,title:R};if(!S&&!j)return{ok:!0,skipped:!0,action:"resume",deviceId:C,title:R};if(!S&&j.startsWith("pending:"))return{ok:!1,action:"resume",deviceId:C,title:R,error:"Pause is still pending confirmation."};if(S){const Ge=j||`pending:${Date.now()}:${C}`,Le=yt.current?.deviceId===C?yt.current:null,st=!!Le||V===C,zt=st?++Kn.current:0,Cn=()=>tw({deviceId:C,requestTransitionGeneration:zt,currentTransitionGeneration:Kn.current,actualControlOwner:yt.current}),$t=Ne.current.get(C);Ne.current.set(C,{deviceId:C,monitorIndex:Ys(p,en[C]??$t?.monitorIndex),previousControlOwner:Le||$t?.previousControlOwner||null}),Fe(C,!0),he(C,!1),ee(C,Ge),vc(C),st&&(ca.current="",te("paused"));try{const ln=await rt(`/api/remote/devices/${encodeURIComponent(C)}/live/pause`,{method:"POST",body:JSON.stringify({reason:"user-video-pause"})},T);if(!ln?.pauseToken)return Be.current.delete(C),ee(C,""),he(C,!1),Ne.current.delete(C),Cn()&&(ue.current=null,_e(null),Ce(!1),_(`control-pause-rollback-${Date.now()}-${C}`),te("connecting")),{ok:!1,action:"pause",deviceId:C,title:R,error:ln?.error||"video-capture-pause-failed"};const hn=String(tt.current[C]||"");if(hn!==Ge&&hn!==ln.pauseToken)return{ok:!1,action:"pause",deviceId:C,title:R,error:"Pause ownership changed before confirmation."};const fa=Cn(),Ec=fa&&yt.current?.deviceId===C?yt.current:Le,kn=Ne.current.get(C);return kn&&(kn.previousControlOwner=Ec),fa&&yt.current?.deviceId===C&&(yt.current=null),fa&&(ue.current=null,_e(null)),ee(C,ln.pauseToken),fa&&te("paused"),ln.ok===!1||ln.captureStopConfirmed!==!0?(he(C,!0),{ok:!1,unconfirmed:!0,action:"pause",deviceId:C,title:R,error:ln.stopError||ln.error||"Client capture shutdown was not confirmed."}):(he(C,!1),{ok:!0,action:"pause",deviceId:C,title:R})}catch(ln){return he(C,!0),{ok:!1,unconfirmed:!0,action:"pause",deviceId:C,title:R,error:ln instanceof Error?ln.message:String(ln)}}}const W=Ne.current.get(C),oe=W?.previousControlOwner||null,ae=V===C&&(oe!==null||Da.current?.deviceId===C||H==="paused"),J=ae?Kn.current:0;try{Fe(C,!1);const Ge=await rt(`/api/remote/devices/${encodeURIComponent(C)}/live/resume`,{method:"POST",body:JSON.stringify({pauseToken:j})},T);if(Ge?.ok===!1)throw new Error(Ge.error||"video-capture-resume-failed");if(String(tt.current[C]||"")!==j)return{ok:!1,action:"resume",deviceId:C,title:R,error:"Resume ownership changed before confirmation."};const Le=Ne.current.get(C)||W,st=Le?.previousControlOwner||oe,zt=ae&&tw({deviceId:C,requestTransitionGeneration:J,currentTransitionGeneration:Kn.current,actualControlOwner:yt.current});if(ee(C,""),he(C,!1),Ne.current.delete(C),zt){const Cn=++Kn.current;ca.current="";const $t=rp(C,Cn,{sessionId:p.sessionId||st?.sessionId,monitorIndex:Ys(p,en[C]??Le?.monitorIndex)});yt.current=$t,Br($t),Tr.current="",ki.current=null,ue.current=null,_e(null),be(""),ze(""),Ce(!1),jn("control",C);const ln=`control-video-resume-${Cn}-${C}`;_(ln),ne(C),te("connecting")}else jn("wall",C);return{ok:!0,action:"resume",deviceId:C,title:R}}catch(Ge){return Be.current.delete(C),{ok:!1,action:"resume",deviceId:C,title:R,error:Ge instanceof Error?Ge.message:String(Ge)}}},bm=async()=>{if(nl.length===0){Pe("Select one or more Clients before pausing video.");return}if(ra.length===0){Pe(xs);return}if(nt)return;const p=ra.some(C=>{const R=String(tt.current[C.deviceId]||"");return!R||R.startsWith("pending:")||Oe[C.deviceId]===!0}),S=ra.filter(C=>{const R=String(tt.current[C.deviceId]||"");return p?!R||R.startsWith("pending:")||Oe[C.deviceId]===!0:!!R});if(S.length===0){Pe(p?"Selected Clients are already paused.":"Selected Clients are already playing.");return}ct("video");try{const C=await Promise.all(S.map(J=>xo(J,p)));D();const R=C.filter(J=>J.ok&&!J.skipped),j=C.filter(J=>!J.ok&&J.unconfirmed),U=C.filter(J=>!J.ok&&!J.unconfirmed),W=ra.length-S.length+C.filter(J=>J.skipped).length,oe=nl.length-ra.length,ae=p?"pause":"resume";if(U.length>0||j.length>0){const J=U.slice(0,2).map(Ge=>`${Ge.title}: ${Ge.error||"unknown error"}`).join(" · ");Pe([`Video ${ae} completed for ${R.length}/${S.length} Clients.`,j.length>0?`${j.length} Client capture stop${j.length===1?"":"s"} remain unconfirmed.`:"",J,oe>0?`${oe} selected Client${oe===1?"":"s"} were outside the current plan limit.`:""].filter(Boolean).join(" "),"error");return}Pe([`Video ${p?"paused":"resumed"} for ${R.length} Client${R.length===1?"":"s"}.`,W>0?`${W} already ${p?"paused":"playing"}.`:"",oe>0?`${oe} outside the current plan limit.`:""].filter(Boolean).join(" "),"success")}finally{ct("")}},wm=p=>{const S=p instanceof Error?p.message:String(p);return/remote-actions-disabled|remote-access-blocked-by-settings/i.test(S)?"Remote access is blocked. Change Settings > Remote Access > Access mode first.":/power-actions-disabled|allowPowerActions-blocked-by-settings/i.test(S)?"Power actions are off. Turn on Settings > Remote Access > Power actions first.":/agent-tool-capability-unavailable|unsupported-agent-operation/i.test(S)?"This Client needs a newer LiveDesk Client for power actions.":/device-not-connected|404 device-not-found/i.test(S)?"The Client disconnected before the action could be sent.":S},Eu=async p=>{if(!Ie||nt)return;const S=Ie,R={sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[p];if(window.confirm(`${R} ${qr(S)}? Unsaved work on that computer may be lost.`)){ct(p),Pe(`Sending ${R.toLowerCase()} request to ${qr(S)}...`);try{const j=await rt(`/api/remote/devices/${encodeURIComponent(S.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:p})},T);if(!j.ok)throw new Error(j.error||"The remote action could not be sent.");Pe(`${R} request sent to ${qr(S)}.`,"success"),D()}catch(j){Pe(wm(j),"error")}finally{ct("")}}},kc=async(p,S,C="files")=>{const R=p.filter(oe=>oe.file.size>=0);if(R.length===0)return{files:0,bytes:0};if(!Vt)throw new Error(xs);if(S.length===0)throw new Error("Select at least one connected Client.");const j=crypto.randomUUID(),U=R.reduce((oe,ae)=>oe+ae.file.size,0);let W=0;_s({id:j,status:"reading",progress:1,message:`Preparing ${R.length} ${C}`});try{for(let oe=0;oe<R.length;oe+=1){const ae=R[oe],J=ae.file,Ge=Math.max(1,Math.ceil(J.size/kg));for(let Le=0;Le<Ge;Le+=1){const st=Le*kg,zt=Math.min(J.size,st+kg),Cn=J.size===0?new ArrayBuffer(0):await J.slice(st,zt).arrayBuffer(),$t=Le===Ge-1;_s({id:j,status:"sending",progress:Math.max(2,Math.min(98,Math.round(W/Math.max(1,U)*96))),message:`${oe+1}/${R.length} ${ae.relativePath}`});const ln=await rt("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:j,deviceIds:S,remoteDirectory:Wr.trim(),name:J.name,relativePath:ae.relativePath,size:J.size,type:J.type,lastModified:J.lastModified,offset:st,totalBytes:J.size,final:$t,dataBase64:cI(Cn)})},T);if(!ln.ok||ln.queued!==S.length)throw new Error(ln.error||`file-chunk-not-queued-${ln.queued}/${S.length}`);W+=Cn.byteLength,await new Promise(hn=>window.setTimeout(hn,0))}}return _s({id:j,status:"queued",progress:100,message:`Sent ${R.length} file${R.length===1?"":"s"} to ${S.length} Client${S.length===1?"":"s"}`}),window.setTimeout(()=>{_s(oe=>oe?.id===j&&oe.status==="queued"?null:oe)},4500),{files:R.length,bytes:U}}catch(oe){throw _s({id:j,status:"failed",progress:100,message:oe instanceof Error?oe.message:String(oe)}),oe}},Jd=async p=>{const S=Dn.length>0?Dn.map(C=>C.deviceId):Ie?[Ie.deviceId]:[];try{await kc(vx(p),S)}catch(C){Pe(C instanceof Error?C.message:String(C))}},Du=async p=>{try{await kc(vx(p),lo)}catch(S){Pe(S instanceof Error?S.message:String(S))}};d.useEffect(()=>{uu.current=!1},[]);const xm=p=>{p.preventDefault(),p.stopPropagation(),oi(!1),Jd(p.dataTransfer.files)},Iu=async(p="ltd")=>{if(!n){Pe("Sign in with Google before checkout.");return}if(O&&p===Yn){Pe("LiveDesk license is already active.");return}if(O&&Yn==="pro"){Pe("LiveDesk Pro is already active.");return}xe("checkout");try{const{data:S,error:C}=await Et.functions.invoke("dodo-checkout",{body:{plan:p}});if(C)throw C;if(!S?.checkout_url)throw new Error("Checkout function did not return a checkout URL.");window.location.assign(S.checkout_url)}catch(S){Pe(S instanceof Error?S.message:String(S)),xe("")}},Lu=qD(),_u=WD(),Fn=co.filter(p=>po.has(p)).length,sa=gc==="open"&&ua.sampleMs>0?`${ua.framesPerSecond.toFixed(1)} fps`:gc,Ve=Ie?Ct?mo.get(Ie.deviceId):po.get(Ie.deviceId):void 0,Mc=Ie?Ys(Ie,en[Ie.deviceId]):0,ef=Ie?KD(Ie):[],Sm=typeof Ve?.monitorIndex=="number"?Of(Ve.monitorIndex,Math.max(1,Ve.monitorCount||1)):Mc,Pu=(Ve&&Sm===Mc?R0(Ve):null)||(Ie?T0(Ie,Mc):null);Pu&&`${Pu.width}${Pu.height}`;const So=Ie?pa(Ct?"control":"wall",Ie.deviceId):"",da=So?nu[So]:void 0,Ur=So?tu[So]:void 0,gt=Ur?.lastInfo,tf=da&&da.sampleMs>0?`${da.framesPerSecond.toFixed(1)} fps`:"waiting";da&&`${da.totalFrames}${tf}`,Ur&&Ur.sampleMs>0&&`${Ur.framesPerSecond.toFixed(1)}`,Ur&&Ur.sampleMs>0&&`${Ur.changedFramesPerSecond.toFixed(1)}`,gt&&(`${gt.frameSeq}${gt.decoderLabel}${gt.queueSize}${gt.renderQueueSize}${gt.droppedForLatency}${gt.decoderFlushCount}${gt.decoderTimestampFallbacks}${gt.decoderInputCount}${gt.decoderOutputCount}`,gt.visualChanged),gt&&`${Math.round(gt.queuedForMs)}${Math.round(gt.decodedForMs)}${Math.round(gt.scheduledForMs)}${gt.drawMs.toFixed(1)}`,gt?.targetPaintIntervalMs&&`${gt.targetPaintIntervalMs.toFixed(1)}${(1e3/gt.targetPaintIntervalMs).toFixed(1)}`,Ur&&`${Ur.decoderInputFps.toFixed(1)}${Ur.decoderOutputFps.toFixed(1)}`,gt?.canvasPresentation,gt&&`${gt.interactiveBufferWaitCount}${Math.round(gt.interactiveBufferWaitMs)}${gt.interactiveQueueDrainCount}`,da&&(Ve?.frameMode==="mode5-lzo-delta"?`${Bf(da.averageFrameBytes)}${Ve.deltaVisualTileCount||0}${Ve.deltaRefreshTileCount||0}${Ve.deltaTotalTiles||0}`:`${Bf(da.averageFrameBytes)}${Math.round(da.tinyFrameRatio*100)}${Math.round(da.repeatedFrameRatio*100)}`),da&&da.sourceSendSampleCount>0&&`${da.sourceSendAverageMs.toFixed(1)}${da.sourceSendP95Ms.toFixed(1)}`,cx(da),cx(Ur),da&&Ur&&`${ux(da)}${ux(Ur)}`,Ve?Ve.frameMode||Ve.mode||Ve.codec||Ve.mimeType:Ct?Gn.frameMode:St.frameMode,Ct?Gn.frameMode:St.frameMode,Ve?`${Ve.width}${Ve.height}${Bf(Ve.byteLength)}`:Ct?`${_n.maxWidth}${_n.maxHeight}`:`${St.maxWidth}${St.maxHeight}`,Ve&&`${Ve.isKeyFrame?"key":String(Ve.chunkType||"delta")}`,Ve&&Ve.monitorCount&&((Ve.monitorIndex??0)+1,`${Ve.monitorCount}`),Ve&&[`src ${Math.round(Ve.sourceGapMs||0)}ms`,`gap ${Math.round(Ve.agentSendGapMs||0)}ms`,`tx ${Math.round(Ve.agentSendDurationMs||0)}ms`,`pace ${Math.round(Ve.agentPaceMs||0)}ms`,`queue ${Math.round(Ve.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(Ve.agentFrameAgeMs||0)}ms`,Ve.hubPacketTransitAgeMs!==void 0?`sock ${Math.max(0,Math.round(Ve.hubPacketTransitAgeMs))}ms`:"",Ve.droppedByAgent?`drop ${Ve.droppedByAgent}`:"",Ve.hubIngressDropped?`ingress-drop ${Ve.hubIngressDropped}`:"",Ve.hubClientDropped?`ws-drop ${Ve.hubClientDropped}`:"",Ve.captureStageMs?`capture ${Math.round(Ve.captureStageMs)}ms`:"",Ve.requestedFps?`req ${Math.round(Ve.requestedFps)}fps`:"",Ve.effectiveFps?`eff ${Math.round(Ve.effectiveFps)}fps`:"",Ve.captureAverageMs?`avg ${Math.round(Ve.captureAverageMs)}ms`:"",Ve.captureP95Ms?`p95 ${Math.round(Ve.captureP95Ms)}ms`:"",Ve.slowFrameCount?`slow ${Math.round(Ve.slowFrameCount)}`:"",Ve.captureHelperRestarts?`helper ${Math.round(Ve.captureHelperRestarts)}`:"",Ve.convertMs?`rgb565 ${Math.round(Ve.convertMs)}ms`:"",Ve.compressMs?`lzo ${Math.round(Ve.compressMs)}ms`:"",Ve.captureSourceSerial?`cap #${Ve.captureSourceSerial}`:"",Ve.captureSourceSkipped?`cap skip ${Ve.captureSourceSkipped}`:"",Ve.frameMode==="mode5-lzo-delta"?`tiles ${Ve.deltaVisualTileCount||0}+${Ve.deltaRefreshTileCount||0}/${Ve.deltaTotalTiles||0}@${Ve.deltaTileSize||0}`:"",Ve.platformProfile||Ve.hardwareEncoder||"-",Ve.atlasComposeMs?`atlas ${Ve.atlasComposeMs.toFixed(1)}ms`:"",Ve.atlasPoolStarved?`pool ${Ve.atlasPoolStarved}`:"",Ve.atlasTileCount?`tiles ${Ve.atlasReadyTiles||0}/${Ve.atlasTileCount}`:"",Ve.atlasInputRevision?`input #${Ve.atlasInputRevision}`:"",Ve.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(Ve.atlasSourceMaxAgeMs)}ms`:"",gt?.inputFeedbackMs!==void 0&&gt.inputFeedbackAt!==void 0&&performance.now()-gt.inputFeedbackAt<=ex?`feedback ${Math.round(gt.inputFeedbackMs)}ms`:"",Ve.contentHash?`enc ${Ve.contentHash.slice(0,6)}`:"",gt?.visualHash?`pix ${gt.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "),wu==="open"&&[`${ks.sentPerSecond.toFixed(1)} hz`,ks.lastInputSeq>0?`rtt ${Math.round(ks.lastRoundTripMs)}ms`:"",ks.lastInputSeq>0?`apply ${ks.lastAgentApplyMs.toFixed(1)}ms`:"",ks.droppedPerSecond>0?`drop ${ks.droppedPerSecond.toFixed(1)}/s`:"",ks.bufferedAmount>0?`buf ${Bf(ks.bufferedAmount)}`:"",ks.lastInputType||"ready"].filter(Boolean).join(" / "),gt?.inputFeedbackMs!==void 0&&gt.inputFeedbackAt!==void 0&&performance.now()-gt.inputFeedbackAt<=ex&&[gt.inputFeedbackExact?"exact":"estimated",gt.inputFeedbackInputType||"",`total ${Math.round(gt.inputFeedbackMs)}ms`,gt.inputFeedbackAgentApplyMs!==void 0?`apply ${gt.inputFeedbackAgentApplyMs.toFixed(1)}ms`:"",gt.inputFeedbackApplyToCaptureMs!==void 0?`apply→frame ${Math.round(gt.inputFeedbackApplyToCaptureMs)}ms`:"",gt.inputFeedbackInputToFrameMs!==void 0?`input→browser ${Math.round(gt.inputFeedbackInputToFrameMs)}ms`:"",gt.inputFeedbackFrameToPaintMs!==void 0?`browser→paint ${Math.round(gt.inputFeedbackFrameToPaintMs)}ms`:"",gt.inputFeedbackSampleCount?`p50 ${Math.round(gt.inputFeedbackP50Ms||0)}ms`:"",gt.inputFeedbackSampleCount?`p95 ${Math.round(gt.inputFeedbackP95Ms||0)}ms`:"",gt.inputFeedbackSampleCount?`n=${gt.inputFeedbackSampleCount}`:"",`input #${gt.inputFeedbackSeq||0}`].filter(Boolean).join(" / "),Ve&&`${Ve.frameSeq}${Ox(Ve.receivedAt||Ve.capturedAt)}`;const Co=Math.max(0,ua.bytesPerSecond*8/1e6),nf={activeTool:ht,audioError:Au,audioMode:ye,audioState:Mu,audioStats:Sn,lastAudioFrame:xc,selectedAudioCaptureStreamId:ku,controlFrames:mo,controlInputReady:Hr,controlMode:Xe,controlPresentationReady:Cd,controlSessionDeviceId:V,controlSessionFrameReady:le,controlSessionState:H,controlStreamBinding:Ae,devices:N,documentPresentationVisible:Va,focusedDeviceId:Z,frames:po,localFeatureAccess:Vt,quickActionBusy:nt,selectedDeviceId:Ie?.deviceId||"",selectedIds:X,showControlFocus:Ct,videoCaptureStopUnconfirmedByDeviceId:Oe,videoCapturePausedDeviceIds:Rt,wallPresentationReadyDeviceIds:us},af=d.useRef(nf);af.current=nf,d.useEffect(()=>{if(!bd.current)return;const p=window,S=oe=>{if(!oe)return null;const ae=oe.sourceGapMs,J=ae==null||ae===""?null:Number.isFinite(Number(ae))?Number(ae):null,Ge=oe;return{deviceId:oe.deviceId,sessionId:oe.sessionId||"",streamId:oe.streamId||"",commandId:oe.commandId||"",captureGeneration:Number(oe.captureGeneration||0),monitorIndex:Number(oe.monitorIndex||0),streamPurpose:oe.streamPurpose||"",frameSeq:Number(oe.frameSeq||0),frameMode:oe.frameMode||"",mimeType:oe.mimeType||"",currentGenerationVerified:Ge.currentGenerationVerified===!0,receivedAt:Ge.receivedAt||"",capturedAt:Ge.capturedAt||"",sourceGapMs:J,inputFeedbackEventId:String(oe.inputFeedbackEventId||""),inputFeedbackInputSeq:Number(oe.inputFeedbackInputSeq||0),inputFeedbackIssuedAtEpochMs:Number(oe.inputFeedbackIssuedAtEpochMs||0),inputFeedbackAgentApplyMs:Number(oe.inputFeedbackAgentApplyMs||0),inputFeedbackApplyToCaptureMs:Number(oe.inputFeedbackApplyToCaptureMs||0)}},C=oe=>{if(!oe)return null;const ae=window.getComputedStyle(oe),J=oe.getBoundingClientRect(),Ge=Math.max(0,Math.min(J.right,window.innerWidth)-Math.max(J.left,0)),Le=Math.max(0,Math.min(J.bottom,window.innerHeight)-Math.max(J.top,0)),st=Number(ae.opacity),zt=oe.isConnected&&ae.display!=="none"&&ae.visibility!=="hidden"&&ae.visibility!=="collapse"&&Number.isFinite(st)&&st>0&&J.width>0&&J.height>0&&Ge>0&&Le>0;return{connected:oe.isConnected,userVisible:zt,width:Math.max(0,Number(oe.width||0)),height:Math.max(0,Number(oe.height||0)),css:{display:ae.display,visibility:ae.visibility,opacity:Number.isFinite(st)?st:0},rect:{left:J.left,top:J.top,right:J.right,bottom:J.bottom,width:J.width,height:J.height,viewportIntersectionWidth:Ge,viewportIntersectionHeight:Le},codec:tp(oe)}},R=(oe,ae)=>{const J=ri.current.get(pa(oe,ae));return J?{bindingKey:J.bindingKey||"",totalFrames:J.totalFrames,totalChangedFrames:J.totalChangedFrames,lastFrameSeq:Number(J.lastFrameSeq||0),lastPaintAgeMs:J.lastAt===void 0?-1:Math.max(0,performance.now()-J.lastAt),lastInfo:J.lastInfo?{frameSeq:Number(J.lastInfo.frameSeq||0),decoderInputCount:Number(J.lastInfo.decoderInputCount||0),decoderOutputCount:Number(J.lastInfo.decoderOutputCount||0),targetPaintIntervalMs:Number(J.lastInfo.targetPaintIntervalMs||0),droppedForLatency:Number(J.lastInfo.droppedForLatency||0),visualChanged:J.lastInfo.visualChanged===!0,inputFeedbackExact:J.lastInfo.inputFeedbackExact===!0,inputFeedbackMs:Number(J.lastInfo.inputFeedbackMs||0),inputFeedbackSampleCount:Number(J.lastInfo.inputFeedbackSampleCount||0),inputFeedbackP50Ms:Number(J.lastInfo.inputFeedbackP50Ms||0),inputFeedbackP95Ms:Number(J.lastInfo.inputFeedbackP95Ms||0),inputFeedbackTargetMs:nx,inputFeedbackTargetMinSamples:ax,inputFeedbackOnTarget:J.lastInfo.inputFeedbackExact===!0&&Number(J.lastInfo.inputFeedbackSampleCount||0)>=ax&&Number(J.lastInfo.inputFeedbackP95Ms)<nx}:null}:null},j=(oe,ae)=>{if(!oe)return null;if(ae==="wall-visible"){const Ge=ri.current.get(pa("wall",oe));return Ge?{bindingKey:Ge.bindingKey||"",total:Ge.totalFrames,lastFrameSeq:Number(Ge.lastFrameSeq||0),lastPaintAgeMs:Ge.lastAt===void 0?-1:Math.max(0,performance.now()-Ge.lastAt)}:null}if(ae!=="control-visible"&&ae!=="wall-reuse-visible")return null;const J=eu.current.get(`${ae}:${oe}`);return J?{bindingKey:J.bindingKey,total:J.totalPaints,lastFrameSeq:J.lastFrameSeq,lastPaintAgeMs:Math.max(0,performance.now()-J.lastPaintAt)}:null},U=(oe,ae)=>{const J=j(oe,ae);return J?{bindingKey:J.bindingKey,totalPaints:J.total,lastPaintAgeMs:J.lastPaintAgeMs,lastFrameSeq:J.lastFrameSeq}:null},W={readPresentationCounter(oe,ae){return j(String(oe||""),ae)},snapshot(oe){const ae=String(oe||""),J=af.current,Ge=J.devices.find(kn=>kn.deviceId===ae)?.liveCapturePause,Le=String(tt.current[ae]||""),st=Gt.current.get(ae)||null,zt=pn.current.get(ae)||null,Cn=ja.current.get(ae)||null,$t=a1(),ln=r1(),hn={frameStats:au.current===null?0:1,wallRecovery:eo.current===null?0:1,controlWarm:ms.current===null?0:1,controlWallDownshift:Gr.current===null?0:1},fa=si.current?.deviceId===ae?si.current:null,Ec=am.current.get(ae)||null;return{capturedAt:Date.now(),deviceId:ae,activeTool:J.activeTool,documentPresentationVisible:J.documentPresentationVisible,showControlFocus:J.showControlFocus,selectedDeviceId:J.selectedDeviceId,focusedDeviceId:J.focusedDeviceId,selectedDeviceIds:[...J.selectedIds],localFeatureAccess:J.localFeatureAccess,quickActionBusy:J.quickActionBusy,audioMode:J.audioMode,audioState:J.audioState,audioError:J.audioError,audioCaptureStreamId:J.selectedAudioCaptureStreamId,audioFrame:J.lastAudioFrame?{deviceId:J.lastAudioFrame.deviceId,streamId:J.lastAudioFrame.streamId,frameSeq:Number(J.lastAudioFrame.frameSeq||0),mimeType:J.lastAudioFrame.mimeType,sampleRate:Number(J.lastAudioFrame.sampleRate||0),channels:Number(J.lastAudioFrame.channels||0),byteLength:Number(J.lastAudioFrame.byteLength||0)}:null,audioStats:{...J.audioStats},videoCapturePausePhase:Le?Le.startsWith("pending:")?"pending":"confirmed":"none",videoCaptureStopUnconfirmed:J.videoCaptureStopUnconfirmedByDeviceId[ae]===!0,authoritativeLiveCapturePause:Ge?{phase:Ge.phase||"",captureStopConfirmed:Ge.captureStopConfirmed===!0,stopAttemptCount:Math.max(0,Number(Ge.stopAttemptCount||0)),stopError:Ge.stopError||""}:null,controlMode:J.controlMode,controlSessionDeviceId:J.controlSessionDeviceId,controlSessionState:J.controlSessionState,controlSessionFrameReady:J.controlSessionFrameReady,controlPresentationReady:J.controlPresentationReady,controlInputReady:J.controlInputReady,controlConnection:Ec?{...Ec}:null,pendingControlConnection:fa?{...fa,elapsedMs:Math.max(0,performance.now()-fa.startedAt)}:null,videoCapturePaused:J.videoCapturePausedDeviceIds.has(ae),wallPresentationReady:J.wallPresentationReadyDeviceIds.has(ae),controlBinding:J.controlStreamBinding?.deviceId===ae?{...J.controlStreamBinding}:null,actualControlOwner:yt.current?.deviceId===ae?{...yt.current}:null,wallCapturePauseOwner:Da.current?.deviceId===ae?{...Da.current}:null,frameSubscriptions:$t,audioSubscriptions:ln,presentationTimers:{...hn,total:Object.values(hn).reduce((kn,qu)=>kn+qu,0)},wallFrame:S(J.frames.get(ae)),controlFrame:S(ds.current.get(ae)||J.controlFrames.get(ae)),wallPaint:R("wall",ae),controlPaint:R("control",ae),controlVisiblePaint:U(ae,"control-visible"),wallReuseVisiblePaint:U(ae,"wall-reuse-visible"),presentationPaintSequence:xd.current,presentationPaintEvents:wd.current.filter(kn=>kn.deviceId===ae).sort((kn,qu)=>kn.sequence-qu.sequence).map(kn=>({...kn})),wallCanvas:C(st),controlDecodeCanvas:C(zt),controlPresentationCanvas:C(Cn),globalCodec:tp()}}};return p.__liveDeskTransmissionProbe=W,()=>{p.__liveDeskTransmissionProbe===W&&delete p.__liveDeskTransmissionProbe}},[]);const Fi=d.useCallback(()=>{is(!0),un(Date.now()),D(),er.current!==null&&window.clearTimeout(er.current),er.current=window.setTimeout(()=>{er.current=null,un(Date.now()),is(!1)},650)},[D]),Ou=d.useCallback(()=>{if(Ot){Rn(!1);return}Za(!1),Rn(!0),Fi()},[Fi,Ot]),Bu=d.useCallback(()=>{if(Bn){Za(!1);return}Rn(!1),Za(!0),Fi()},[Bn,Fi]),rf=d.useCallback(()=>{if(va){xr(!1);return}xr(!0),Fi()},[va,Fi]),Hu=Ot||Bn,Ac=JSON.stringify(Je.filter(p=>p.connected).map(p=>p.deviceId).sort());d.useEffect(()=>{if(!Hu)return;const p=JSON.parse(Ac);if(p.length===0){is(!1);return}const S=new AbortController,C=[];let R=!1;return er.current!==null&&(window.clearTimeout(er.current),er.current=null),is(!0),un(Date.now()),Promise.allSettled(p.map(j=>rt(`/api/remote/devices/${encodeURIComponent(j)}/status-diagnostic`,{method:"POST",body:JSON.stringify({purpose:"remote-status-current-snapshot"}),signal:S.signal,timeoutMs:1500},T))).then(()=>{R||[500,1800,4500].forEach((j,U,W)=>{const oe=window.setTimeout(()=>{R||(D(),un(Date.now()),U===W.length-1&&is(!1))},j);C.push(oe)})}),()=>{R=!0,S.abort();for(const j of C)window.clearTimeout(j)}},[T,D,Ac,Hu]);const ko=new Map,Nc=new Map;if(Ot||Bn||va)for(const p of Je){const S=p.deviceId,C=Ct&&V===S,j=pa(C?"control":"wall",S),U=C?mo.get(S):po.get(S),W=C?pn.current.get(S)||ja.current.get(S)||null:Gt.current.get(S)||(Mt?Mr.current:null),oe={device:p,frame:U,receiveStat:nu[j],paintStat:tu[j],codec:W?tp(W):{},selectedMonitorIndex:Ys(p,en[S]),control:C,controlInputReady:C&&Hr,controlBinding:C&&Ae?.deviceId===S?Ae:void 0,hubRelay:k?.relay,capturePaused:Rt.has(S),capturePauseConfirmed:p.liveCapturePause?.captureStopConfirmed===!0,capturePauseError:p.liveCapturePause?.stopError||"",clientHeartbeatMs:Number(k?.heartbeatMs||5e3),now:Date.now()},ae=["open","playing","silent"].includes(Mu),J=Sn.nativeCallbackDiagnosticsAvailable&&(Sn.nativeRejectedCallbackCount>0||Sn.nativeCurrentnessDropCount>0),Ge=ae&&!J,Le=S===Ie?.deviceId&&ye?{id:"browser-remote-audio",state:Ge?"ok":"warning",label:Ge?"Remote audio is healthy":"Remote audio needs attention",detail:Sn.lastUpdatedAt>0?[Mu,`context ${Sn.audioContextState}`,`queue ${Math.round(Sn.queuedMs)}ms`,`packet ${Math.round(Sn.lastPacketAgeMs)}ms`,`capture ${Sn.captureHealthy?"healthy":Sn.captureAwaitingCurrentPcm?"awaiting PCM":"down"}`,Sn.backendKind?`backend ${Sn.backendKind}`:"backend unknown",Sn.helperRequired?`helper ${Sn.helperAlive&&Sn.helperPid>0?`pid ${Sn.helperPid}`:"missing"}`:"helper N/A",`drop ${Sn.drops}`,`restart ${Sn.automaticRestarts}`,Sn.nativeCallbackDiagnosticsAvailable?`native reject ${Sn.nativeRejectedCallbackCount}`:"native callback diagnostics unknown",Sn.nativeCallbackDiagnosticsAvailable?`native stale ${Sn.nativeCurrentnessDropCount}`:"",Sn.nativeLastDropReason?`native reason ${Sn.nativeLastDropReason}`:"",xc?`frame #${xc.frameSeq}`:"waiting for frame"].filter(Boolean).join(" · "):"Browser audio diagnostics are collecting while Remote or Debug status is open."}:null;if(Ot||va){const st=KE(oe);Ot&&Le&&st.push(Le),ko.set(S,st)}if(Bn){const st=QE(oe);Le&&st.push(Le),Nc.set(S,st)}}const sf=va?YE({status:k||{},deviceDiagnostics:[...ko.values()],codec:tp(),browser:{hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:Number(navigator.deviceMemory||0)},frameStats:ua}):[],of=fi?.atlasReadyTiles??Fn,Ms=fi?.atlasTileCount??Fn,lf=of===Ms?`${Ms} tiles`:`${of}/${Ms} tiles`,uh=Xn.length>0;Ct?`${sa}${Co.toFixed(Co>=10?0:1)}`:uh?`${lf}${sa}${Co.toFixed(Co>=10?0:1)}`:`${Fn}${sa}${Co.toFixed(Co>=10?0:1)}`;const zu=Dn.length,mi=Ct?Ie?qr(Ie):"No Client":zu===0?"No Client":zu>1?`${zu} selected`:Ie?qr(Ie):"No Client",cf=Ct?[Ie?.deviceId].filter(p=>!!p):Dn.map(p=>p.deviceId),Pa=pd[Ds]||pd.en,Mo=Pa.sync||pd.en.sync,Tc=r||P?"checking":O?Yn==="pro"?"Pro LTD active":`Plus LTD ${Je.length}/${Pf}`:Ld?`Free ${Je.length}/${Ff}`:`Upgrade ${Je.length}/${Ff}`,dh=O?Yn==="pro"?"Pro active":"Upgrade to Pro LTD":n?fe==="checkout"?"Opening checkout":Yn==="ltd"?"Buy Pro LTD":"Buy Plus LTD":fe==="auth"?"Opening Google":"Sign in to buy",fh=Yn==="pro"||fe==="checkout"||fe==="auth"||r||P,uf=n?.user?.user_metadata,Pi=yx(uf,"avatar_url","picture"),ts=yx(uf,"full_name","name")||n?.user?.email||"Google",df=ts.slice(0,1).toUpperCase(),Cm=k?.started?"Local app ready":"Start LiveDesk",Rc=o?.active?"Published":n?"Not published":"Sign in required",Vs=/^\d{6}$/.test(k?.pairingPin||"")?k?.pairingPin:"------",$u=p=>{if(typeof window<"u"&&(p==="support"?window.history.pushState({},"","/support"):ht==="support"&&window.history.pushState({},"","/")),p==="control"){const S=ba||ir;if(S&&(wo(S.deviceId),Ga(!1),me(S.deviceId)),Zt(p),!Vt){Ze(!1),Pe(xs);return}Ze(!0);return}p==="wall"&&Xi(S=>S+1),Zt(p),Ze(!1)},Oi=fe==="update"||Wt?.stage==="updating"||["dispatching","waiting-for-clients","hub-restart-requested"].includes(k?.update?.state||""),km=!!(k?.update?.updateAvailable&&k.update.canApply||Oi||Wt?.error||!k&&Wt),pi=uM(Ds),Uu=d.useCallback(p=>{if(!Wt?.targetIds.includes(p))return;const S=k?.update?.operationId===Wt.operationId?k.update.targets?.find(C=>C.deviceId===p):void 0;switch(S?.state){case"completed":return{state:"updated",label:"Updated"};case"failed":return{state:"failed",label:"Update failed",error:S.error};case"pending-offline":return{state:"offline",label:"Waiting for reconnect"};case"queued":return Wt.stage==="updating"?{state:"queued",label:"Queued"}:void 0;case"waiting":return Wt.stage==="updating"?S.candidateSince?{state:"updating",label:"Verifying restart..."}:{state:"updating",label:"Restarting..."}:void 0;default:return Wt.stage==="updated"?{state:"updated",label:"Updated"}:Wt.stage==="updating"?{state:"updating",label:"Verifying..."}:void 0}},[k?.update,Wt]),jc=(p,S,C)=>{const R=p.device,j=R?i.jsx(wx,{device:R,frame:po.get(R.deviceId),selected:sr.has(R.deviceId),controlEnabled:!C&&$s&&Xe&&Hr&&Ie?.deviceId===R.deviceId,showStatus:St.showScreenStatus,monitorIndex:Ys(R,en[R.deviceId]),monitorCount:Uc(R),onSelect:()=>wl(R.deviceId),onFocusDevice:()=>Qd(R.deviceId),onOpenControl:()=>Cc(R.deviceId),onCycleMonitor:W=>Yd(R.deviceId,W),onCanvasReady:C&&jf({mode4Enabled:Mt,directMode4WallEnabled:_a,isMac:Do(R.platform)})!=="direct"?Od:um,sendInput:yo,remoteModifierState:Wd,updateIndicator:Uu(R.deviceId),presentationReady:St.autoStartLive&&Ir.includes(R.deviceId)?us.has(R.deviceId):void 0,showPresentationSpinner:St.autoStartLive&&Ir.includes(R.deviceId),remoteDiagnostics:Bn?Nc.get(R.deviceId):Ot?ko.get(R.deviceId):void 0,diagnosticsMode:Bn?"debug":"remote"},R.deviceId):p.offline&&p.saved?i.jsx(SI,{entry:p.saved,slotNumber:p.slotNumber}):i.jsx(xI,{index:S}),U=R?.deviceId||p.saved?.deviceId||"";return i.jsx("div",{className:`wall-slot-drop-zone ${Ke?"layout-locked":""} ${na===U&&U?"drag-source":""} ${On===p.slotNumber?"drop-target":""}`,"data-wall-slot-number":p.slotNumber,draggable:Ke&&!!U,onDragStart:W=>U&&Dd(U,W),onDragEnd:ji,onDragOver:W=>{!Ke||!br.current||(W.preventDefault(),W.dataTransfer.dropEffect="move",rn(p.slotNumber))},onDragLeave:W=>{W.currentTarget.contains(W.relatedTarget)||rn(oe=>oe===p.slotNumber?0:oe)},onDrop:W=>{Ke&&(W.preventDefault(),Id(p.slotNumber))},children:j},U||p.saved?.deviceId||`slot-${p.slotNumber}`)};return i.jsxs("main",{className:"app-shell",children:[i.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk tools",children:[i.jsx("div",{className:"rail-brand",title:"LiveDesk",children:i.jsx(Bx,{size:25})}),i.jsx("nav",{className:"rail-tools",children:gI.map(p=>{const S=p.icon,C=Ep(p.tooltip,Ds);return i.jsxs("button",{className:`rail-tool ${p.id==="sync-server"?"sync-server hub-sync-trigger":""} ${ht===p.id?"active":""} accent-${p.accent}`,onClick:()=>p.id==="sync-server"?Sc():$u(p.id),"data-tooltip":p.id==="sync-server"&&ft?void 0:zg(p.label,p.tooltip,Ds),"aria-label":`${p.label}. ${C}`,type:"button",disabled:p.id==="sync-server"&&fe==="host","aria-busy":p.id==="sync-server"&&fe==="host","aria-expanded":p.id==="sync-server"?ft:void 0,"aria-haspopup":p.id==="sync-server"?"dialog":void 0,"aria-controls":p.id==="sync-server"&&ft?"hub-sync-popover":void 0,children:[p.id==="sync-server"&&fe==="host"?i.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):i.jsx(S,{size:19}),i.jsx("span",{children:p.id==="sync-server"&&fe==="host"?"Syncing…":p.label})]},p.id)})}),i.jsxs("div",{className:"rail-footer",children:[vI.map(p=>{const S=p.icon;return i.jsxs("button",{className:`rail-tool compact ${ht===p.id?"active":""} accent-${p.accent}`,onClick:()=>$u(p.id),title:p.label,type:"button",children:[i.jsx(S,{size:18}),i.jsx("span",{children:p.label})]},p.id)}),i.jsxs("button",{className:`rail-tool compact local-settings ${Yo?"active":""}`,onClick:()=>{Zt("settings"),typeof window<"u"&&window.history.pushState({},"","/"),Ln(!1),Ze(!1),Js(!1)},title:"Settings",type:"button",children:[i.jsx(pv,{size:18}),i.jsx("span",{children:"Settings"})]}),i.jsxs("button",{className:`rail-account ${n?"signed-in":""}`,onClick:()=>{Ln(p=>!p)},disabled:r||fe==="auth","aria-expanded":Ki,title:n?`Account: ${n.user?.email||ts}`:"Sign in with Google",type:"button",children:[n?Pi?i.jsx("img",{src:Pi,alt:ts,referrerPolicy:"no-referrer"}):i.jsx("span",{className:"avatar-fallback",children:df}):i.jsx(Gc,{size:18}),i.jsx("span",{children:n?"Account":"Google"})]}),Ki&&i.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[i.jsxs("div",{className:"account-popover-head",children:[i.jsx("div",{className:"account-popover-avatar",children:n&&Pi?i.jsx("img",{src:Pi,alt:ts,referrerPolicy:"no-referrer"}):n?i.jsx("span",{children:df}):i.jsx(Gc,{size:18})}),i.jsxs("div",{children:[i.jsx("strong",{children:n?ts:"Account"}),i.jsx("p",{children:n?.user?.email||"Not signed in"})]})]}),i.jsxs("dl",{className:"account-popover-facts",children:[i.jsx("dt",{children:"User"}),i.jsx("dd",{children:n?.user?.email||"Not signed in"}),i.jsx("dt",{children:"Network"}),i.jsx("dd",{children:Cm}),i.jsx("dt",{children:"Access"}),i.jsx("dd",{children:Rc}),i.jsx("dt",{children:"Plan"}),i.jsx("dd",{children:Tc}),i.jsx("dt",{children:"Ads"}),i.jsx("dd",{children:Yn==="free"?"Standard banner":"Removed"})]}),n?i.jsxs("button",{className:"account-popover-action",onClick:ch,disabled:fe==="auth",type:"button",children:[i.jsx(Cx,{size:16}),"Logout"]}):i.jsxs("button",{className:"account-popover-action primary",onClick:yl,disabled:fe==="auth",type:"button",children:[i.jsx(Gc,{size:16}),"Sign in with Google"]})]})]})]}),ft&&i.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:[i.jsxs("header",{className:"client-hub-switch-head",children:[i.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:i.jsx(Wi,{size:19})}),i.jsx("span",{className:"client-hub-switch-eyebrow",children:pi.eyebrow}),i.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>bl(),"aria-label":pi.closeLabel,children:i.jsx(vr,{size:17})})]}),i.jsx("h2",{id:"hub-sync-title",children:pi.title}),i.jsx("p",{id:"hub-sync-description",children:pi.description}),i.jsxs("p",{id:"hub-sync-notice",className:"client-hub-switch-notice",children:[i.jsx(Aa,{size:16,"aria-hidden":"true"}),i.jsx("span",{children:pi.restartNotice})]}),i.jsxs("div",{className:"client-hub-switch-actions",children:[i.jsx("button",{type:"button",onClick:()=>bl(),children:pi.cancel}),i.jsxs("button",{ref:Dt,className:"primary",type:"button",onClick:Kd,disabled:fe==="host",children:[i.jsx(Wi,{size:16}),pi.confirm]})]})]}),i.jsxs("section",{className:`desk-stage ${Xo&&!os?"dock-open":""} ${Ct?"control-stage":""} ${ic?"agents-stage":""}`,children:[i.jsxs("header",{className:"topbar",children:[i.jsxs("div",{className:"brand",children:[i.jsx("span",{className:"brand-mark",children:i.jsx(Vc,{size:18})}),i.jsxs("div",{className:"brand-copy",children:[i.jsx("h1",{children:"LiveDesk"}),i.jsx("p",{children:"Control wall for local machines"})]}),km?i.jsxs("button",{className:"topbar-update-button",onClick:()=>{Ru()},title:Wt?.error?`LiveDesk Hub update failed: ${Wt.error}`:`Update LiveDesk to ${k?.update?.latestVersion||Wt?.targetManagerVersion||"latest"}`,"aria-label":Wt?.error?`LiveDesk Hub update failed: ${Wt.error}`:Oi?"LiveDesk update in progress":`Update LiveDesk to ${k?.update?.latestVersion||Wt?.targetManagerVersion||"latest"}`,type:"button",disabled:Oi||!k?.update?.canApply,"aria-busy":Oi,children:[Oi?i.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):i.jsx(mv,{size:19,"aria-hidden":"true"}),Oi&&k?.update?.targetCount?i.jsxs("span",{className:"topbar-update-count","aria-hidden":"true",children:[k.update.completedCount||0,"/",k.update.targetCount]}):null]}):null]}),i.jsxs("div",{className:"topbar-tray",children:[vs&&!Ct&&i.jsxs("div",{className:"file-share-top-route","aria-label":"File distribution route",children:[i.jsxs("div",{children:[i.jsx(qc,{size:17}),i.jsxs("span",{children:[i.jsx("small",{children:"Source"}),i.jsx("strong",{children:"LiveDesk Hub"})]})]}),i.jsx(gv,{size:15}),i.jsx(ik,{size:16}),i.jsxs("div",{children:[i.jsx("span",{className:"file-share-top-route-laptops",children:"▣ ▣ ▣"}),i.jsxs("span",{children:[i.jsx("small",{children:"Destination"}),i.jsxs("strong",{children:[Bt," Client",Bt===1?"":"s"]}),i.jsx("em",{children:Wr.trim()||"Desktop/LiveDeskFiles"})]})]})]}),Xo&&!Ct&&i.jsxs("div",{className:"top-actions",children:[i.jsx(Qw,{active:va,refreshing:va&&Ja,onClick:rf}),i.jsx(Vw,{active:Ot,refreshing:Ot&&Ja,onClick:Ou}),i.jsx(Kw,{active:Bn,refreshing:Bn&&Ja,onClick:Bu}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsx(Gw,{controller:ll,onError:Pe}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsxs("button",{className:"text-button wall-layout-button",onClick:()=>{oo()},disabled:!Ke||mt||xt,title:"Release the saved Wall layout and return to Client slot order",type:"button",children:[i.jsx(Lg,{size:15}),"Reset"]}),i.jsxs("button",{className:`text-button wall-layout-button ${Ke?"active":""}`,onClick:()=>{Jo()},disabled:Ke||mt||xt||!n,title:n?"Remember and lock the current Wall layout for this account":"Sign in to save the Wall layout","aria-pressed":Ke,type:"button",children:[xt||mt?i.jsx(yi,{className:"spin",size:15}):i.jsx(Ui,{size:15}),Ke?"Locked":"Lock"]}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsx("div",{className:"segmented-control wall-cadence-control","aria-label":"Wall frame speed",children:pI.map(p=>i.jsx("button",{className:Ua===p.id?"active":"",onClick:()=>{de(p.id),Sr(p.fps),sI(p.id)},title:p.label+" Wall streaming ("+p.fps+" fps)","aria-pressed":Ua===p.id,type:"button",children:p.label},p.id))}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsx("div",{className:"segmented-control","aria-label":"Wall view",children:hI.map(p=>i.jsx("button",{className:bn===p.id?"active":"",onClick:()=>Es(p.id),type:"button",children:p.label},p.id))})]}),Ct&&i.jsxs("div",{className:"top-actions",children:[i.jsx(Qw,{active:va,refreshing:va&&Ja,onClick:rf}),i.jsx(Vw,{active:Ot,refreshing:Ot&&Ja,onClick:Ou}),i.jsx(Kw,{active:Bn,refreshing:Bn&&Ja,onClick:Bu}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsx(Gw,{controller:ll,onError:Pe})]})]})]}),va&&Xo&&i.jsx(OE,{items:sf,collectedAt:Ta,onClose:()=>xr(!1)}),jd?i.jsxs("section",{className:"doc-page",lang:Ds,dir:Ds==="ar"?"rtl":"ltr",children:[i.jsxs("section",{className:"doc-hero",children:[i.jsxs("div",{className:"doc-hero-copy",children:[i.jsxs("span",{className:"pricing-eyebrow",children:[i.jsx(Rp,{size:16}),Pa.eyebrow]}),i.jsx("h2",{children:Pa.title}),i.jsx("p",{children:Pa.intro})]}),i.jsxs("label",{className:"doc-language-picker",children:[i.jsxs("span",{children:[i.jsx(ok,{size:17}),Pa.languageLabel]}),i.jsx("select",{value:Ds,onChange:p=>_o(p.target.value),children:bI.map(p=>i.jsx("option",{value:p.id,children:p.label},p.id))})]})]}),i.jsx("section",{className:"doc-grid",children:Pa.sections.map((p,S)=>{const R=[Wi,Pg,fb,Aa,zp][S]||Rp;return i.jsxs("article",{className:"doc-card",children:[i.jsx("div",{className:"doc-card-icon",children:i.jsx(R,{size:19})}),i.jsxs("div",{children:[i.jsx("h3",{children:p.title}),i.jsx("p",{children:p.body}),i.jsx("ul",{children:p.points.map(j=>i.jsx("li",{children:j},j))})]})]},p.title)})}),Mo&&i.jsxs("section",{className:"doc-sync",children:[i.jsxs("div",{className:"doc-sync-head",children:[i.jsx(fb,{size:20}),i.jsxs("div",{children:[i.jsx("h3",{children:Mo.title}),i.jsx("p",{children:Mo.body})]})]}),i.jsx("ul",{children:Mo.points.map(p=>i.jsx("li",{children:p},p))})]}),i.jsxs("section",{className:"doc-firewall",children:[i.jsxs("div",{className:"doc-firewall-head",children:[i.jsx(Aa,{size:20}),i.jsxs("div",{children:[i.jsx("h3",{children:Pa.firewall.title}),i.jsx("p",{children:Pa.firewall.body})]})]}),i.jsx("ul",{children:Pa.firewall.points.map(p=>i.jsx("li",{children:p},p))})]}),i.jsxs("section",{className:"doc-command-panel",children:[i.jsxs("div",{className:"doc-command-head",children:[i.jsx(Pg,{size:20}),i.jsxs("div",{children:[i.jsx("h3",{children:Pa.commands.title}),i.jsx("p",{children:Pa.commands.body})]})]}),i.jsxs("div",{className:"doc-command-list",children:[Pa.commands.manager&&i.jsxs("div",{className:"doc-command-row",children:[i.jsx("span",{children:Pa.commands.manager}),i.jsx("code",{children:_u}),i.jsx("button",{className:"icon-button",onClick:()=>Sp(_u),title:"Copy command",type:"button",children:i.jsx(Xh,{size:16})})]}),i.jsxs("div",{className:"doc-command-row",children:[i.jsx("span",{children:Pa.commands.primary}),i.jsx("code",{children:Lu}),i.jsx("button",{className:"icon-button",onClick:()=>Sp(Lu),title:"Copy command",type:"button",children:i.jsx(Xh,{size:16})})]}),i.jsxs("div",{className:"doc-command-row",children:[i.jsx("span",{children:Pa.commands.slot}),i.jsx("code",{children:`${Lu} 3`}),i.jsx("button",{className:"icon-button",onClick:()=>Sp(`${Lu} 3`),title:"Copy command",type:"button",children:i.jsx(Xh,{size:16})})]})]})]})]}):ic?i.jsx(Uw,{hubUrl:T,devices:N}):vs?i.jsx(_j,{hubUrl:T,devices:Je,localFeatureAccess:Vt,upgradeNotice:xs,remoteDirectory:Wr,onRemoteDirectoryChange:ei,targetMode:so,selectedTargetIds:Vo,onTargetModeChange:ah,onTargetToggle:p=>Td(S=>S.includes(p)?S.filter(C=>C!==p):[...S,p]),filePickerRef:Ko,folderPickerRef:Rd,onBrowserFileImport:p=>{Du(p)},onBrowserFolderImport:p=>{Du(p)},onNotice:Pe,onTransferChange:p=>{if(!p){_s(null);return}const S=p.state==="failed"||p.state==="partially-failed"||p.state==="cancelled"?"failed":p.state==="completed"?"queued":p.state==="sending"?"sending":"reading";_s({id:p.id,status:S,progress:p.progress,message:p.message}),["completed","partially-failed","failed","cancelled"].includes(p.state)&&window.setTimeout(()=>_s(C=>C?.id===p.id?null:C),4500)}}):sc?i.jsx(_x,{session:n,currentProductKey:"livedesk",appVersion:"",onSignIn:yl}):Yo?i.jsx(J1,{hubUrl:T,runtimeRole:k?.runtimeRole||"hub",runtimeDeviceId:k?.deviceId||"",sessionAccessToken:n?.access_token||"",pin:i.jsxs(eN,{children:[i.jsx("div",{className:"settings-section-grid",children:i.jsxs("section",{className:"settings-section-card settings-pairing-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Pair a Client"}),i.jsx("h3",{children:"Connect another local PC"})]}),i.jsx(Ba,{size:20})]}),i.jsxs("div",{className:"settings-pin-display",children:[i.jsx("span",{children:"Hub PIN"}),i.jsx("strong",{children:Vs}),i.jsxs("button",{className:"text-button ghost compact",onClick:vm,disabled:!k?.started||fe==="pin",type:"button",children:[i.jsx(Ui,{size:15}),fe==="pin"?"Creating":"New PIN"]})]})]})}),i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"File transfer"}),i.jsx("h3",{children:"Client destination folder"})]}),i.jsx(dd,{size:20})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"Remote folder"}),i.jsx("input",{value:Wr,onChange:p=>ei(p.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),i.jsx("p",{className:"settings-help",children:"Blank uses Desktop/LiveDeskFiles on each Client."})]})]}),agent:i.jsx(nN,{hubUrl:T}),captureGallery:i.jsx(PE,{hubUrl:T,onToast:Pe})}):Os?i.jsxs("section",{className:"pricing-page",children:[i.jsxs("header",{className:"pricing-header",children:[i.jsxs("div",{children:[i.jsxs("span",{className:"pricing-eyebrow",children:[i.jsx(_g,{size:15})," LiveDesk plans"]}),i.jsx("h2",{children:"Choose the plan that fits your wall"}),i.jsx("p",{children:"Start free with a local screen wall. Upgrade when you need ad-free monitoring, more Clients, or commercial controls."})]}),i.jsx("button",{className:"pricing-close",onClick:()=>$u("wall"),title:"Close pricing",type:"button",children:i.jsx(vr,{size:18})})]}),i.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[i.jsx("span",{children:"Current plan"}),i.jsx("strong",{children:Hn.name}),i.jsxs("small",{children:[Je.length,"/",LD(uc)," connected devices"]})]}),i.jsxs("div",{className:"pricing-cards","aria-label":"LiveDesk plans",children:[i.jsxs("article",{className:`pricing-plan-card ${Yn==="free"?"current":""}`,children:[i.jsxs("div",{className:"pricing-plan-topline",children:[i.jsx("span",{className:"pricing-plan-badge free",children:"Free"}),i.jsx("strong",{children:"$0"})]}),i.jsx("p",{className:"pricing-plan-audience",children:Oc.free.audience}),i.jsx("h3",{children:"Monitor your local wall"}),i.jsx("p",{children:Oc.free.note}),i.jsxs("ul",{children:[i.jsxs("li",{children:[i.jsx(Oa,{size:16})," Up to ",Ff," devices"]}),i.jsxs("li",{children:[i.jsx(Oa,{size:16})," Live view and local control"]}),i.jsxs("li",{children:[i.jsx(Oa,{size:16})," Standard ad-supported banner"]})]}),i.jsx("span",{className:"pricing-current-label",children:Yn==="free"?"Current plan":"Included for everyone"})]}),i.jsxs("article",{className:`pricing-plan-card featured ${Yn==="ltd"?"current":""}`,children:[i.jsxs("div",{className:"pricing-plan-topline",children:[i.jsxs("span",{className:"pricing-plan-badge plus",children:[i.jsx(lk,{size:14})," Plus"]}),i.jsx("strong",{children:"$5"})]}),i.jsx("p",{className:"pricing-plan-audience",children:Oc.ltd.audience}),i.jsx("h3",{children:"Ad-free monitoring"}),i.jsx("p",{children:"More room for personal computers without the standard banner."}),i.jsxs("ul",{children:[i.jsxs("li",{children:[i.jsx(Oa,{size:16})," Up to ",Pf," devices"]}),i.jsxs("li",{children:[i.jsx(Oa,{size:16})," No standard ad banner"]}),i.jsxs("li",{children:[i.jsx(Oa,{size:16})," ",Oc.ltd.ltd]})]}),i.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>Iu("ltd"):yl,disabled:Yn!=="free"||fe==="checkout"||fe==="auth"||r||P,type:"button",children:[i.jsx(zf,{size:16}),Yn==="free"?n?"Choose Plus":"Sign in for Plus":"Plus active"]})]}),i.jsxs("article",{className:`pricing-plan-card pro ${Yn==="pro"?"current":""}`,children:[i.jsxs("div",{className:"pricing-plan-topline",children:[i.jsxs("span",{className:"pricing-plan-badge pro",children:[i.jsx(Aa,{size:14})," Pro"]}),i.jsx("strong",{children:"$15"})]}),i.jsx("p",{className:"pricing-plan-audience",children:Oc.pro.audience}),i.jsx("h3",{children:"For serious operations"}),i.jsx("p",{children:"Commercial-ready monitoring for larger studios, offices, and teams."}),i.jsxs("ul",{children:[i.jsxs("li",{children:[i.jsx(Oa,{size:16})," 30+ Client walls"]}),i.jsxs("li",{children:[i.jsx(Oa,{size:16})," Commercial use included"]}),i.jsxs("li",{children:[i.jsx(Oa,{size:16})," ",Oc.pro.ltd]})]}),i.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>Iu("pro"):yl,disabled:Yn==="pro"||fe==="checkout"||fe==="auth"||r||P,type:"button",children:[i.jsx(zf,{size:16}),Yn==="pro"?"Pro active":n?"Choose Pro":"Sign in for Pro"]})]})]}),i.jsxs("section",{className:"pricing-includes",children:[i.jsxs("div",{children:[i.jsx(Ba,{size:17}),i.jsx("span",{children:"Screen wall"}),i.jsx("strong",{children:"120+ slots"})]}),i.jsxs("div",{children:[i.jsx(Fg,{size:17}),i.jsx("span",{children:"Focused control"}),i.jsx("strong",{children:"Local-first"})]}),i.jsxs("div",{children:[i.jsx(mb,{size:17}),i.jsx("span",{children:"Remote audio"}),i.jsx("strong",{children:"Available"})]}),i.jsxs("div",{children:[i.jsx(dd,{size:17}),i.jsx("span",{children:"File transfer"}),i.jsx("strong",{children:"Included"})]})]}),i.jsxs("p",{className:"pricing-note",children:[i.jsx(Oa,{size:15})," Commercial use requires Pro. Plus LTD is for personal, creator, and homelab use."]}),i.jsxs("button",{className:"pricing-primary-cta",onClick:n?()=>Iu(Yn==="ltd"?"pro":"ltd"):yl,disabled:fh,type:"button",children:[i.jsx(zf,{size:18}),dh]})]}):i.jsx(i.Fragment,{children:i.jsxs("section",{className:`monitor-layout ${os?"dock-collapsed":""}`,children:[i.jsxs("section",{ref:ac,className:`screen-wall-panel ${im?"drop-active":""}`,onClick:p=>{p.currentTarget===p.target&&xl()},onDragEnter:p=>{p.preventDefault(),oi(!0)},onDragOver:p=>{p.preventDefault(),p.dataTransfer.dropEffect="copy"},onDragLeave:p=>{p.currentTarget===p.target&&oi(!1)},onDrop:xm,children:[Xn.length>0&&i.jsx("canvas",{ref:Xr,className:"atlas-source-canvas",width:Cs?.width||1920,height:Cs?.height||1080,"aria-hidden":"true"}),Ct?i.jsx("section",{className:"control-focus",children:i.jsxs("div",{className:"control-wall",children:[Ie&&ef.length>1&&i.jsx("div",{className:"control-monitor-tabs","aria-label":"Select monitor",children:ef.map(p=>i.jsxs("button",{className:p.index===Mc?"active":"",onClick:()=>Xd(Ie.deviceId,p.index),title:YD(p),type:"button",children:[i.jsx("span",{children:p.name||`Display ${p.index+1}`}),p.width>0&&p.height>0&&i.jsxs("small",{children:[p.width,"x",p.height]})]},p.index))}),Ie&&Hr&&i.jsx("div",{className:"control-modifier-bar","aria-label":"Hold remote modifier keys",children:gD.map(p=>{const S=p.code==="MetaLeft"&&Do(Ie.platform)?"Cmd":p.label,C=Ue.includes(p.code);return i.jsx("button",{className:C?"active":"",type:"button","aria-pressed":C,title:`Hold ${S} on the remote computer`,onClick:()=>Se.current?.(p.code),children:S},p.code)})}),Ie?i.jsx(wx,{device:Ie,frame:Ve,selected:!1,controlEnabled:$s&&Xe&&Hr,showStatus:Gn.showScreenStatus,monitorIndex:Ys(Ie,en[Ie.deviceId]),monitorCount:Uc(Ie),onSelect:()=>{},onFocusDevice:()=>me(Ie.deviceId),onOpenControl:()=>Cc(Ie.deviceId),onCycleMonitor:p=>Yd(Ie.deviceId,p),onCanvasReady:dm,sendInput:yo,remoteModifierState:Wd,presentationReady:Cd,remoteDiagnostics:Bn?Nc.get(Ie.deviceId):Ot?ko.get(Ie.deviceId):void 0,diagnosticsMode:Bn?"debug":"remote"},Ie.deviceId):i.jsxs("div",{className:"control-empty",children:[i.jsx(Ba,{size:30}),i.jsx("strong",{children:"No Client"}),i.jsx("span",{children:"Open a Client from the Wall."})]}),Ie&&el&&i.jsxs("div",{className:"control-connection-overlay",role:"alert",children:[i.jsx(Aa,{size:22,"aria-hidden":"true"}),i.jsx("strong",{children:"Accessibility permission required"}),i.jsx("small",{children:"On the Mac, allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client."})]}),Ie&&!el&&!Cd&&i.jsxs("div",{className:"control-connection-overlay",role:"status","aria-live":"polite",children:[H!=="error"&&i.jsx("span",{className:"control-connection-spinner","aria-hidden":"true"}),i.jsx("strong",{children:H==="error"?"Connection failed":"Connecting"}),i.jsx("small",{children:H==="error"?"See the notification for details. Reopen Control to retry.":fl||He?"Control stream is recovering. See the notification for details.":gc==="open"?"Preparing the first control frame":"Opening the Control stream"})]})]})}):bn==="list"?i.jsxs("div",{className:"wall-device-list",role:"grid","aria-label":"Computer status list",children:[i.jsxs("div",{className:"wall-device-list-head",role:"row",children:[i.jsx("span",{role:"columnheader",children:"Computer"}),i.jsx("span",{role:"columnheader",children:"Status"}),i.jsx("span",{role:"columnheader",children:"CPU"}),i.jsx("span",{role:"columnheader",children:"GPU"}),i.jsx("span",{role:"columnheader",children:"RAM"}),i.jsx("span",{role:"columnheader",children:"VRAM"}),i.jsx("span",{role:"columnheader",children:"Network"}),i.jsx("span",{role:"columnheader",children:"HDD"}),i.jsx("span",{role:"columnheader",children:"Temp"})]}),Ed.length>0?Ed.map(p=>p.device?i.jsx(kI,{device:p.device,slotNumber:p.slotNumber,selected:sr.has(p.device.deviceId),updateIndicator:Uu(p.device.deviceId),remoteDiagnostics:Bn?Nc.get(p.device.deviceId):Ot?ko.get(p.device.deviceId):void 0,diagnosticsMode:Bn?"debug":"remote",onSelect:()=>wl(p.device.deviceId),onOpenControl:()=>Cc(p.device.deviceId)},p.device.deviceId):p.saved?i.jsx(CI,{entry:p.saved,slotNumber:p.slotNumber},`offline-${p.saved.deviceId}`):null):i.jsxs("div",{className:"wall-device-list-empty",children:[i.jsx(Ba,{size:24,"aria-hidden":"true"}),i.jsx("strong",{children:"No connected computers"})]})]}):Mt?i.jsx("div",{className:`screen-wall atlas-slot-wall size-${bn}`,onClick:p=>{p.currentTarget===p.target&&xl()},children:La.map((p,S)=>jc(p,S,!0))}):i.jsx("div",{className:`screen-wall size-${bn}`,onClick:p=>{p.currentTarget===p.target&&xl()},children:La.map((p,S)=>jc(p,S,!1))}),i.jsx(NI,{visible:ih&&!Ct})]}),!Yo&&i.jsxs("aside",{className:`right-dock actions-mode ${os?"collapsed":""}`,"aria-label":"LiveDesk tools",children:[i.jsx("button",{className:"dock-toggle",onClick:()=>Js(p=>!p),"aria-label":os?"Show control panel":"Hide control panel",title:os?"Show control panel":"Hide control panel",type:"button",children:os?i.jsx(Ix,{size:18}):i.jsx(vv,{size:18})}),!os&&i.jsxs(i.Fragment,{children:[i.jsxs("section",{className:"action-dock",children:[i.jsx("input",{ref:Er,className:"hidden-file-input",type:"file",multiple:!0,onChange:p=>{p.currentTarget.files&&Jd(p.currentTarget.files),p.currentTarget.value=""}}),i.jsxs("div",{className:"manual-action-bar",role:"toolbar","aria-label":"Manual Client controls",children:[i.jsx(Pc,{label:"Control",tooltip:Ie?el?"Allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client.":$s?Hr?"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(Ie){if(Ct&&Xe){Ze(!1),Pe("Remote control paused. Screen viewing stays on.");return}Cc(Ie.deviceId)}},disabled:!$s||!!nt,active:Xe,pressed:Ct&&Xe,children:i.jsx(Fg,{size:17})}),i.jsx(Pc,{label:"Audio",tooltip:Ie?Yr?ye?"Stop hearing this Client":"Hear this Client":"Audio is not available on this Client":"Select a Client to use Audio",onClick:()=>{ym()},disabled:!cm||!!nt,active:ye,pressed:ye,children:nt==="audio"?i.jsx(yi,{className:"spin",size:17}):i.jsx(mb,{size:17})}),i.jsx(Pc,{label:al?"Retry pause":rl?"Pause video":"Resume video",tooltip:nl.length===0?"Select one or more Clients to pause video":al?"Retry every selected Client whose capture shutdown is unconfirmed":rl?`Pause video for ${ra.length} selected Client${ra.length===1?"":"s"}`:`Resume video for ${ra.length} selected Client${ra.length===1?"":"s"}`,onClick:()=>{bm()},disabled:ra.length===0||!!nt,active:!rl,pressed:!rl,children:nt==="video"?i.jsx(yi,{className:"spin",size:17}):!rl&&!al?i.jsx(ck,{size:17}):i.jsx(uk,{size:17})}),i.jsx(Pc,{label:"Send files",tooltip:Dn.length===0&&!Ct?"Select one or more Clients to send files":Ie?"Choose files and send them to the selected Client":"Select a Client to send files",onClick:()=>{Pe(`Choose files to send to ${mi}.`),Er.current?.click()},disabled:!!nt||!Vt||(Ct?!Ie:Dn.length===0),children:i.jsx(dd,{size:17})}),i.jsx(Pc,{label:"Restart",tooltip:Ie?tl?"Restart Client":"Restart is not available on this Client":"Select a Client to restart",onClick:()=>{Eu("restart")},disabled:!Ie||!Vt||!!nt||!tl,children:nt==="restart"?i.jsx(yi,{className:"spin",size:17}):i.jsx(Lg,{size:17})}),i.jsx(Pc,{label:"Sleep",tooltip:Ie?tl?"Put Client to sleep":"Sleep is not available on this Client":"Select a Client to put to sleep",onClick:()=>{Eu("sleep")},disabled:!Ie||!Vt||!!nt||!tl,children:nt==="sleep"?i.jsx(yi,{className:"spin",size:17}):i.jsx(dk,{size:17})}),i.jsx(Pc,{label:"Shut down",tooltip:Ie?tl?"Shut down Client":"Shut down is not available on this Client":"Select a Client to shut down",onClick:()=>{Eu("shutdown")},disabled:!Ie||!Vt||!!nt||!tl,danger:!0,children:nt==="shutdown"?i.jsx(yi,{className:"spin",size:17}):i.jsx(Ax,{size:17})})]})]}),i.jsx(Uw,{hubUrl:T,devices:N,variant:"dock",selectedDeviceIds:cf})]})]})]})})]}),Vr&&i.jsxs("aside",{className:`transfer-bar state-${Vr.status}`,"aria-live":"polite",children:[i.jsx("span",{className:"transfer-bar-icon","aria-hidden":"true",children:Vr.status==="queued"?i.jsx(Oa,{size:18}):Vr.status==="failed"?i.jsx(vr,{size:18}):i.jsx(Tx,{size:18})}),i.jsxs("div",{className:"transfer-bar-copy",children:[i.jsx("p",{children:Vr.message}),i.jsx("div",{className:"transfer-bar-track",children:i.jsx("span",{style:{width:`${Math.max(0,Math.min(100,Vr.progress))}%`}})})]}),i.jsxs("strong",{children:[Math.max(0,Math.min(100,Vr.progress)),"%"]})]}),oa&&i.jsxs("aside",{className:`livedesk-toast tone-${oa.tone}`,role:oa.tone==="error"?"alert":"status","aria-live":oa.tone==="error"?"assertive":"polite","aria-busy":oa.tone==="progress",children:[oa.tone==="progress"&&i.jsx("span",{className:"livedesk-toast-spinner","aria-hidden":"true"}),i.jsx("span",{children:oa.message}),i.jsx("button",{className:"livedesk-toast-close",onClick:()=>Pe(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:i.jsx(vr,{size:15})})]})]})}const RI=1e3,jI=5e3;function EI(){return typeof window>"u"?[]:[...new Set([window.location.origin,qn].filter(Boolean))]}function DI(){const[r,o]=d.useState(null),c=d.useRef(null);return d.useEffect(()=>{let u=!1,f=!1,h=null;const g=new AbortController,y=async()=>{for(const x of EI()){if(g.signal.aborted)return;try{const k=(await rt("/api/runtime",{signal:g.signal,timeoutMs:900},x)).role==="hub"?"hub":"client";f=!0,u||o(N=>N?.role===k&&N.baseUrl===x?N:{role:k,baseUrl:x});return}catch{if(g.signal.aborted)return}}},w=()=>{jp(c,y).finally(()=>{!u&&!g.signal.aborted&&(h=window.setTimeout(w,f?jI:RI))}).catch(()=>{})};w();const b=window.setTimeout(()=>{!u&&!f&&o(x=>x?.role==="client"&&x.baseUrl===qn?x:{role:"client",baseUrl:qn})},2500);return()=>{u=!0,g.abort(new Error("LiveDesk runtime role probe stopped.")),h!==null&&window.clearTimeout(h),window.clearTimeout(b)}},[null]),r?r.role==="client"?i.jsx(SM,{runtimeBaseUrl:r.baseUrl}):i.jsx(TI,{runtimeBaseUrl:r.baseUrl}):i.jsxs("main",{className:"runtime-role-boot","aria-busy":"true","aria-label":"Starting LiveDesk",children:[i.jsx("span",{className:"runtime-role-boot-mark","aria-hidden":"true"}),i.jsx("strong",{children:"Starting LiveDesk"}),i.jsx("p",{children:"Loading this computer's assigned role..."})]})}bk.createRoot(document.getElementById("root")).render(i.jsx(d.StrictMode,{children:i.jsx(DI,{})}));