livedesk 0.1.445 → 0.1.447
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.
- package/bin/livedesk.js +974 -304
- package/bootstrap/client-process-identity.js +20 -6
- package/bootstrap/legacy-client-update.js +22 -20
- package/bootstrap/runtime-lock.js +362 -45
- package/bootstrap/runtime-shutdown.js +414 -0
- package/client/bin/livedesk-client-node.js +17 -4
- package/client/bin/livedesk-client.js +365 -104
- package/client/package.json +5 -5
- package/client/src/runtime/agent-process-lifecycle.js +194 -58
- package/client/src/runtime/windows-owned-process-manifest.js +235 -0
- package/electron/main.mjs +55 -38
- package/hub/package.json +1 -1
- package/hub/src/remote-hub.js +284 -88
- package/hub/src/server.js +173 -28
- package/hub/src/transport/relay-hub-control.js +1045 -0
- package/hub/src/transport/udp-rendezvous.js +2 -0
- package/package.json +6 -6
- package/runtime-core/src/role-transition-supervisor.js +20 -18
- package/runtime-core/src/windows-owned-process-tree.js +432 -0
- package/web/dist/assets/index-5opXQY8X.js +25 -0
- package/web/dist/index.html +1 -1
- package/web/dist/assets/index-D3VhnrP6.js +0 -25
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import{r as g0,a as d,M as Pu,S as Kn,R as Mc,B as v0,P as yh,X as Ra,b as Wu,C as Or,F as vy,L as Di,A as px,c as y0,d as yy,E as by,T as b0,D as Np,e as ea,f as x0,g as gx,h as w0,i as S0,j as Hr,k as Ea,l as If,m as $u,n as Tp,o as jo,p as vx,q as Ao,s as yx,t as bx,u as ep,v as C0,w as k0,H as So,W as Vf,x as j0,y as A0,z as Sc,K as xx,G as tp,I as Il,J as wx,N as M0,O as N0,Q as T0,U as Rp,V as Ep,Y as R0,Z as Dp,_ as E0,$ as Lp,a0 as Sx,a1 as D0,a2 as zr,a3 as xy,a4 as _p,a5 as Wf,a6 as Ku,a7 as Mf,a8 as L0,a9 as Cx,aa as _0,ab as kx,ac as I0,ad as z0,ae as np,af as jx,ag as O0,ah as H0,ai as F0,aj as P0,ak as $0,al as B0,am as wy,an as U0,ao as q0,ap as G0,aq as V0,ar as ap,as as sp,at as W0,au as K0,av as Sy,aw as bh,ax as Y0,ay as Cy,az as Ax,aA as Q0,aB as X0,aC as Z0,aD as J0}from"./icons-BIyRF-ou.js";import{r as Mx}from"./react-C7a9r614.js";import{c as eC}from"./supabase-C7qjtLN3.js";(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const c of document.querySelectorAll('link[rel="modulepreload"]'))l(c);new MutationObserver(c=>{for(const u of c)if(u.type==="childList")for(const m of u.addedNodes)m.tagName==="LINK"&&m.rel==="modulepreload"&&l(m)}).observe(document,{childList:!0,subtree:!0});function i(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 l(c){if(c.ep)return;c.ep=!0;const u=i(c);fetch(c.href,u)}})();var xh={exports:{}},Tu={};var ky;function tC(){if(ky)return Tu;ky=1;var t=Symbol.for("react.transitional.element"),a=Symbol.for("react.fragment");function i(l,c,u){var m=null;if(u!==void 0&&(m=""+u),c.key!==void 0&&(m=""+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:l,key:m,ref:c!==void 0?c:null,props:u}}return Tu.Fragment=a,Tu.jsx=i,Tu.jsxs=i,Tu}var jy;function nC(){return jy||(jy=1,xh.exports=tC()),xh.exports}var r=nC(),wh={exports:{}},Ru={},Sh={exports:{}},Ch={};var Ay;function aC(){return Ay||(Ay=1,(function(t){function a(I,se){var W=I.length;I.push(se);e:for(;0<W;){var F=W-1>>>1,oe=I[F];if(0<c(oe,se))I[F]=se,I[W]=oe,W=F;else break e}}function i(I){return I.length===0?null:I[0]}function l(I){if(I.length===0)return null;var se=I[0],W=I.pop();if(W!==se){I[0]=W;e:for(var F=0,oe=I.length,le=oe>>>1;F<le;){var Q=2*(F+1)-1,be=I[Q],he=Q+1,de=I[he];if(0>c(be,W))he<oe&&0>c(de,be)?(I[F]=de,I[he]=W,F=he):(I[F]=be,I[Q]=W,F=Q);else if(he<oe&&0>c(de,W))I[F]=de,I[he]=W,F=he;else break e}}return se}function c(I,se){var W=I.sortIndex-se.sortIndex;return W!==0?W:I.id-se.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 m=Date,h=m.now();t.unstable_now=function(){return m.now()-h}}var g=[],y=[],x=1,b=null,w=3,j=!1,A=!1,k=!1,T=!1,M=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,L=typeof setImmediate<"u"?setImmediate:null;function z(I){for(var se=i(y);se!==null;){if(se.callback===null)l(y);else if(se.startTime<=I)l(y),se.sortIndex=se.expirationTime,a(g,se);else break;se=i(y)}}function H(I){if(k=!1,z(I),!A)if(i(g)!==null)A=!0,G||(G=!0,O());else{var se=i(y);se!==null&&Z(H,se.startTime-I)}}var G=!1,_=-1,Y=5,q=-1;function U(){return T?!0:!(t.unstable_now()-q<Y)}function K(){if(T=!1,G){var I=t.unstable_now();q=I;var se=!0;try{e:{A=!1,k&&(k=!1,N(_),_=-1),j=!0;var W=w;try{t:{for(z(I),b=i(g);b!==null&&!(b.expirationTime>I&&U());){var F=b.callback;if(typeof F=="function"){b.callback=null,w=b.priorityLevel;var oe=F(b.expirationTime<=I);if(I=t.unstable_now(),typeof oe=="function"){b.callback=oe,z(I),se=!0;break t}b===i(g)&&l(g),z(I)}else l(g);b=i(g)}if(b!==null)se=!0;else{var le=i(y);le!==null&&Z(H,le.startTime-I),se=!1}}break e}finally{b=null,w=W,j=!1}se=void 0}}finally{se?O():G=!1}}}var O;if(typeof L=="function")O=function(){L(K)};else if(typeof MessageChannel<"u"){var ve=new MessageChannel,me=ve.port2;ve.port1.onmessage=K,O=function(){me.postMessage(null)}}else O=function(){M(K,0)};function Z(I,se){_=M(function(){I(t.unstable_now())},se)}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(I){I.callback=null},t.unstable_forceFrameRate=function(I){0>I||125<I?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):Y=0<I?Math.floor(1e3/I):5},t.unstable_getCurrentPriorityLevel=function(){return w},t.unstable_next=function(I){switch(w){case 1:case 2:case 3:var se=3;break;default:se=w}var W=w;w=se;try{return I()}finally{w=W}},t.unstable_requestPaint=function(){T=!0},t.unstable_runWithPriority=function(I,se){switch(I){case 1:case 2:case 3:case 4:case 5:break;default:I=3}var W=w;w=I;try{return se()}finally{w=W}},t.unstable_scheduleCallback=function(I,se,W){var F=t.unstable_now();switch(typeof W=="object"&&W!==null?(W=W.delay,W=typeof W=="number"&&0<W?F+W:F):W=F,I){case 1:var oe=-1;break;case 2:oe=250;break;case 5:oe=1073741823;break;case 4:oe=1e4;break;default:oe=5e3}return oe=W+oe,I={id:x++,callback:se,priorityLevel:I,startTime:W,expirationTime:oe,sortIndex:-1},W>F?(I.sortIndex=W,a(y,I),i(g)===null&&I===i(y)&&(k?(N(_),_=-1):k=!0,Z(H,W-F))):(I.sortIndex=oe,a(g,I),A||j||(A=!0,G||(G=!0,O()))),I},t.unstable_shouldYield=U,t.unstable_wrapCallback=function(I){var se=w;return function(){var W=w;w=se;try{return I.apply(this,arguments)}finally{w=W}}}})(Ch)),Ch}var My;function sC(){return My||(My=1,Sh.exports=aC()),Sh.exports}var Ny;function rC(){if(Ny)return Ru;Ny=1;var t=sC(),a=g0(),i=Mx();function l(e){var n="https://react.dev/errors/"+e;if(1<arguments.length){n+="?args[]="+encodeURIComponent(arguments[1]);for(var s=2;s<arguments.length;s++)n+="&args[]="+encodeURIComponent(arguments[s])}return"Minified React error #"+e+"; visit "+n+" 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 n=e,s=e;if(e.alternate)for(;n.return;)n=n.return;else{e=n;do n=e,(n.flags&4098)!==0&&(s=n.return),e=n.return;while(e)}return n.tag===3?s:null}function m(e){if(e.tag===13){var n=e.memoizedState;if(n===null&&(e=e.alternate,e!==null&&(n=e.memoizedState)),n!==null)return n.dehydrated}return null}function h(e){if(e.tag===31){var n=e.memoizedState;if(n===null&&(e=e.alternate,e!==null&&(n=e.memoizedState)),n!==null)return n.dehydrated}return null}function g(e){if(u(e)!==e)throw Error(l(188))}function y(e){var n=e.alternate;if(!n){if(n=u(e),n===null)throw Error(l(188));return n!==e?null:e}for(var s=e,o=n;;){var f=s.return;if(f===null)break;var p=f.alternate;if(p===null){if(o=f.return,o!==null){s=o;continue}break}if(f.child===p.child){for(p=f.child;p;){if(p===s)return g(f),e;if(p===o)return g(f),n;p=p.sibling}throw Error(l(188))}if(s.return!==o.return)s=f,o=p;else{for(var S=!1,R=f.child;R;){if(R===s){S=!0,s=f,o=p;break}if(R===o){S=!0,o=f,s=p;break}R=R.sibling}if(!S){for(R=p.child;R;){if(R===s){S=!0,s=p,o=f;break}if(R===o){S=!0,o=p,s=f;break}R=R.sibling}if(!S)throw Error(l(189))}}if(s.alternate!==o)throw Error(l(190))}if(s.tag!==3)throw Error(l(188));return s.stateNode.current===s?e:n}function x(e){var n=e.tag;if(n===5||n===26||n===27||n===6)return e;for(e=e.child;e!==null;){if(n=x(e),n!==null)return n;e=e.sibling}return null}var b=Object.assign,w=Symbol.for("react.element"),j=Symbol.for("react.transitional.element"),A=Symbol.for("react.portal"),k=Symbol.for("react.fragment"),T=Symbol.for("react.strict_mode"),M=Symbol.for("react.profiler"),N=Symbol.for("react.consumer"),L=Symbol.for("react.context"),z=Symbol.for("react.forward_ref"),H=Symbol.for("react.suspense"),G=Symbol.for("react.suspense_list"),_=Symbol.for("react.memo"),Y=Symbol.for("react.lazy"),q=Symbol.for("react.activity"),U=Symbol.for("react.memo_cache_sentinel"),K=Symbol.iterator;function O(e){return e===null||typeof e!="object"?null:(e=K&&e[K]||e["@@iterator"],typeof e=="function"?e:null)}var ve=Symbol.for("react.client.reference");function me(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===ve?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case k:return"Fragment";case M:return"Profiler";case T:return"StrictMode";case H:return"Suspense";case G:return"SuspenseList";case q:return"Activity"}if(typeof e=="object")switch(e.$$typeof){case A:return"Portal";case L:return e.displayName||"Context";case N:return(e._context.displayName||"Context")+".Consumer";case z:var n=e.render;return e=e.displayName,e||(e=n.displayName||n.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case _:return n=e.displayName||null,n!==null?n:me(e.type)||"Memo";case Y:n=e._payload,e=e._init;try{return me(e(n))}catch{}}return null}var Z=Array.isArray,I=a.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,se=i.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,W={pending:!1,data:null,method:null,action:null},F=[],oe=-1;function le(e){return{current:e}}function Q(e){0>oe||(e.current=F[oe],F[oe]=null,oe--)}function be(e,n){oe++,F[oe]=e.current,e.current=n}var he=le(null),de=le(null),ee=le(null),Ce=le(null);function Re(e,n){switch(be(ee,n),be(de,e),be(he,null),n.nodeType){case 9:case 11:e=(e=n.documentElement)&&(e=e.namespaceURI)?Pv(e):0;break;default:if(e=n.tagName,n=n.namespaceURI)n=Pv(n),e=$v(n,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}Q(he),be(he,e)}function He(){Q(he),Q(de),Q(ee)}function te(e){e.memoizedState!==null&&be(Ce,e);var n=he.current,s=$v(n,e.type);n!==s&&(be(de,e),be(he,s))}function Ue(e){de.current===e&&(Q(he),Q(de)),Ce.current===e&&(Q(Ce),ju._currentValue=W)}var mt,ne;function xe(e){if(mt===void 0)try{throw Error()}catch(s){var n=s.stack.trim().match(/\n( *(at )?)/);mt=n&&n[1]||"",ne=-1<s.stack.indexOf(`
|
|
2
|
+
at`)?" (<anonymous>)":-1<s.stack.indexOf("@")?"@unknown:0:0":""}return`
|
|
3
|
+
`+mt+e+ne}var Oe=!1;function $e(e,n){if(!e||Oe)return"";Oe=!0;var s=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var o={DetermineComponentFrameRoot:function(){try{if(n){var ke=function(){throw Error()};if(Object.defineProperty(ke.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ke,[])}catch(ge){var fe=ge}Reflect.construct(e,[],ke)}else{try{ke.call()}catch(ge){fe=ge}e.call(ke.prototype)}}else{try{throw Error()}catch(ge){fe=ge}(ke=e())&&typeof ke.catch=="function"&&ke.catch(function(){})}}catch(ge){if(ge&&fe&&typeof ge.stack=="string")return[ge.stack,fe.stack]}return[null,null]}};o.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var f=Object.getOwnPropertyDescriptor(o.DetermineComponentFrameRoot,"name");f&&f.configurable&&Object.defineProperty(o.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var p=o.DetermineComponentFrameRoot(),S=p[0],R=p[1];if(S&&R){var V=S.split(`
|
|
4
|
+
`),ue=R.split(`
|
|
5
|
+
`);for(f=o=0;o<V.length&&!V[o].includes("DetermineComponentFrameRoot");)o++;for(;f<ue.length&&!ue[f].includes("DetermineComponentFrameRoot");)f++;if(o===V.length||f===ue.length)for(o=V.length-1,f=ue.length-1;1<=o&&0<=f&&V[o]!==ue[f];)f--;for(;1<=o&&0<=f;o--,f--)if(V[o]!==ue[f]){if(o!==1||f!==1)do if(o--,f--,0>f||V[o]!==ue[f]){var we=`
|
|
6
|
+
`+V[o].replace(" at new "," at ");return e.displayName&&we.includes("<anonymous>")&&(we=we.replace("<anonymous>",e.displayName)),we}while(1<=o&&0<=f);break}}}finally{Oe=!1,Error.prepareStackTrace=s}return(s=e?e.displayName||e.name:"")?xe(s):""}function ze(e,n){switch(e.tag){case 26:case 27:case 5:return xe(e.type);case 16:return xe("Lazy");case 13:return e.child!==n&&n!==null?xe("Suspense Fallback"):xe("Suspense");case 19:return xe("SuspenseList");case 0:case 15:return $e(e.type,!1);case 11:return $e(e.type.render,!1);case 1:return $e(e.type,!0);case 31:return xe("Activity");default:return""}}function Qe(e){try{var n="",s=null;do n+=ze(e,s),s=e,e=e.return;while(e);return n}catch(o){return`
|
|
7
|
+
Error generating stack: `+o.message+`
|
|
8
|
+
`+o.stack}}var qe=Object.prototype.hasOwnProperty,Ye=t.unstable_scheduleCallback,ot=t.unstable_cancelCallback,B=t.unstable_shouldYield,ye=t.unstable_requestPaint,je=t.unstable_now,Pe=t.unstable_getCurrentPriorityLevel,dt=t.unstable_ImmediatePriority,nt=t.unstable_UserBlockingPriority,bt=t.unstable_NormalPriority,it=t.unstable_LowPriority,Ct=t.unstable_IdlePriority,pe=t.log,De=t.unstable_setDisableYieldValue,Fe=null,Ae=null;function ct(e){if(typeof pe=="function"&&De(e),Ae&&typeof Ae.setStrictMode=="function")try{Ae.setStrictMode(Fe,e)}catch{}}var ht=Math.clz32?Math.clz32:yn,Le=Math.log,Dn=Math.LN2;function yn(e){return e>>>=0,e===0?32:31-(Le(e)/Dn|0)|0}var et=256,xt=262144,kn=4194304;function Pn(e){var n=e&42;if(n!==0)return n;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 _e(e,n,s){var o=e.pendingLanes;if(o===0)return 0;var f=0,p=e.suspendedLanes,S=e.pingedLanes;e=e.warmLanes;var R=o&134217727;return R!==0?(o=R&~p,o!==0?f=Pn(o):(S&=R,S!==0?f=Pn(S):s||(s=R&~e,s!==0&&(f=Pn(s))))):(R=o&~p,R!==0?f=Pn(R):S!==0?f=Pn(S):s||(s=o&~e,s!==0&&(f=Pn(s)))),f===0?0:n!==0&&n!==f&&(n&p)===0&&(p=f&-f,s=n&-n,p>=s||p===32&&(s&4194048)!==0)?n:f}function tn(e,n){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&n)===0}function on(e,n){switch(e){case 1:case 2:case 4:case 8:case 64:return n+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 n+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 Da(){var e=kn;return kn<<=1,(kn&62914560)===0&&(kn=4194304),e}function nn(e){for(var n=[],s=0;31>s;s++)n.push(e);return n}function $s(e,n){e.pendingLanes|=n,n!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function Yn(e,n,s,o,f,p){var S=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 R=e.entanglements,V=e.expirationTimes,ue=e.hiddenUpdates;for(s=S&~s;0<s;){var we=31-ht(s),ke=1<<we;R[we]=0,V[we]=-1;var fe=ue[we];if(fe!==null)for(ue[we]=null,we=0;we<fe.length;we++){var ge=fe[we];ge!==null&&(ge.lane&=-536870913)}s&=~ke}o!==0&&Bs(e,o,0),p!==0&&f===0&&e.tag!==0&&(e.suspendedLanes|=p&~(S&~n))}function Bs(e,n,s){e.pendingLanes|=n,e.suspendedLanes&=~n;var o=31-ht(n);e.entangledLanes|=n,e.entanglements[o]=e.entanglements[o]|1073741824|s&261930}function $(e,n){var s=e.entangledLanes|=n;for(e=e.entanglements;s;){var o=31-ht(s),f=1<<o;f&n|e[o]&n&&(e[o]|=n),s&=~f}}function Xe(e,n){var s=n&-n;return s=(s&42)!==0?1:ft(s),(s&(e.suspendedLanes|n))!==0?0:s}function ft(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 mn(e){return e&=-e,2<e?8<e?(e&134217727)!==0?32:268435456:8:2}function Ba(){var e=se.p;return e!==0?e:(e=window.event,e===void 0?32:uy(e.type))}function Ii(e,n){var s=se.p;try{return se.p=e,n()}finally{se.p=s}}var Ss=Math.random().toString(36).slice(2),re="__reactFiber$"+Ss,Ee="__reactProps$"+Ss,Ge="__reactContainer$"+Ss,vt="__reactEvents$"+Ss,Bt="__reactListeners$"+Ss,Vt="__reactHandles$"+Ss,at="__reactResources$"+Ss,Rt="__reactMarker$"+Ss;function ra(e){delete e[re],delete e[Ee],delete e[vt],delete e[Bt],delete e[Vt]}function $n(e){var n=e[re];if(n)return n;for(var s=e.parentNode;s;){if(n=s[Ge]||s[re]){if(s=n.alternate,n.child!==null||s!==null&&s.child!==null)for(e=Kv(e);e!==null;){if(s=e[re])return s;e=Kv(e)}return n}e=s,s=e.parentNode}return null}function bn(e){if(e=e[re]||e[Ge]){var n=e.tag;if(n===5||n===6||n===13||n===31||n===26||n===27||n===3)return e}return null}function en(e){var n=e.tag;if(n===5||n===26||n===27||n===6)return e.stateNode;throw Error(l(33))}function Ke(e){var n=e[at];return n||(n=e[at]={hoistableStyles:new Map,hoistableScripts:new Map}),n}function At(e){e[Rt]=!0}var Us=new Set,Ht={};function jn(e,n){Ln(e,n),Ln(e+"Capture",n)}function Ln(e,n){for(Ht[e]=n,e=0;e<n.length;e++)Us.add(n[e])}var $r=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]*$"),Br={},Dt={};function Cs(e){return qe.call(Dt,e)?!0:qe.call(Br,e)?!1:$r.test(e)?Dt[e]=!0:(Br[e]=!0,!1)}function zi(e,n,s){if(Cs(n))if(s===null)e.removeAttribute(n);else{switch(typeof s){case"undefined":case"function":case"symbol":e.removeAttribute(n);return;case"boolean":var o=n.toLowerCase().slice(0,5);if(o!=="data-"&&o!=="aria-"){e.removeAttribute(n);return}}e.setAttribute(n,""+s)}}function Ur(e,n,s){if(s===null)e.removeAttribute(n);else{switch(typeof s){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(n);return}e.setAttribute(n,""+s)}}function cn(e,n,s,o){if(o===null)e.removeAttribute(s);else{switch(typeof o){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(s);return}e.setAttributeNS(n,s,""+o)}}function ia(e){switch(typeof e){case"bigint":case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Oi(e){var n=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(n==="checkbox"||n==="radio")}function am(e,n,s){var o=Object.getOwnPropertyDescriptor(e.constructor.prototype,n);if(!e.hasOwnProperty(n)&&typeof o<"u"&&typeof o.get=="function"&&typeof o.set=="function"){var f=o.get,p=o.set;return Object.defineProperty(e,n,{configurable:!0,get:function(){return f.call(this)},set:function(S){s=""+S,p.call(this,S)}}),Object.defineProperty(e,n,{enumerable:o.enumerable}),{getValue:function(){return s},setValue:function(S){s=""+S},stopTracking:function(){e._valueTracker=null,delete e[n]}}}}function Dc(e){if(!e._valueTracker){var n=Oi(e)?"checked":"value";e._valueTracker=am(e,n,""+e[n])}}function nd(e){if(!e)return!1;var n=e._valueTracker;if(!n)return!0;var s=n.getValue(),o="";return e&&(o=Oi(e)?e.checked?"true":"false":e.value),e=o,e!==s?(n.setValue(e),!0):!1}function No(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 ad=/[\n"\\]/g;function Ua(e){return e.replace(ad,function(n){return"\\"+n.charCodeAt(0).toString(16)+" "})}function Lc(e,n,s,o,f,p,S,R){e.name="",S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"?e.type=S:e.removeAttribute("type"),n!=null?S==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+ia(n)):e.value!==""+ia(n)&&(e.value=""+ia(n)):S!=="submit"&&S!=="reset"||e.removeAttribute("value"),n!=null?qr(e,S,ia(n)):s!=null?qr(e,S,ia(s)):o!=null&&e.removeAttribute("value"),f==null&&p!=null&&(e.defaultChecked=!!p),f!=null&&(e.checked=f&&typeof f!="function"&&typeof f!="symbol"),R!=null&&typeof R!="function"&&typeof R!="symbol"&&typeof R!="boolean"?e.name=""+ia(R):e.removeAttribute("name")}function _c(e,n,s,o,f,p,S,R){if(p!=null&&typeof p!="function"&&typeof p!="symbol"&&typeof p!="boolean"&&(e.type=p),n!=null||s!=null){if(!(p!=="submit"&&p!=="reset"||n!=null)){Dc(e);return}s=s!=null?""+ia(s):"",n=n!=null?""+ia(n):s,R||n===e.value||(e.value=n),e.defaultValue=n}o=o??f,o=typeof o!="function"&&typeof o!="symbol"&&!!o,e.checked=R?e.checked:!!o,e.defaultChecked=!!o,S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"&&(e.name=S),Dc(e)}function qr(e,n,s){n==="number"&&No(e.ownerDocument)===e||e.defaultValue===""+s||(e.defaultValue=""+s)}function xn(e,n,s,o){if(e=e.options,n){n={};for(var f=0;f<s.length;f++)n["$"+s[f]]=!0;for(s=0;s<e.length;s++)f=n.hasOwnProperty("$"+e[s].value),e[s].selected!==f&&(e[s].selected=f),f&&o&&(e[s].defaultSelected=!0)}else{for(s=""+ia(s),n=null,f=0;f<e.length;f++){if(e[f].value===s){e[f].selected=!0,o&&(e[f].defaultSelected=!0);return}n!==null||e[f].disabled||(n=e[f])}n!==null&&(n.selected=!0)}}function qs(e,n,s){if(n!=null&&(n=""+ia(n),n!==e.value&&(e.value=n),s==null)){e.defaultValue!==n&&(e.defaultValue=n);return}e.defaultValue=s!=null?""+ia(s):""}function Gs(e,n,s,o){if(n==null){if(o!=null){if(s!=null)throw Error(l(92));if(Z(o)){if(1<o.length)throw Error(l(93));o=o[0]}s=o}s==null&&(s=""),n=s}s=ia(n),e.defaultValue=s,o=e.textContent,o===s&&o!==""&&o!==null&&(e.value=o),Dc(e)}function ls(e,n){if(n){var s=e.firstChild;if(s&&s===e.lastChild&&s.nodeType===3){s.nodeValue=n;return}}e.textContent=n}var ya=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 Hi(e,n,s){var o=n.indexOf("--")===0;s==null||typeof s=="boolean"||s===""?o?e.setProperty(n,""):n==="float"?e.cssFloat="":e[n]="":o?e.setProperty(n,s):typeof s!="number"||s===0||ya.has(n)?n==="float"?e.cssFloat=s:e[n]=(""+s).trim():e[n]=s+"px"}function Vs(e,n,s){if(n!=null&&typeof n!="object")throw Error(l(62));if(e=e.style,s!=null){for(var o in s)!s.hasOwnProperty(o)||n!=null&&n.hasOwnProperty(o)||(o.indexOf("--")===0?e.setProperty(o,""):o==="float"?e.cssFloat="":e[o]="");for(var f in n)o=n[f],n.hasOwnProperty(f)&&s[f]!==o&&Hi(e,f,o)}else for(var p in n)n.hasOwnProperty(p)&&Hi(e,p,n[p])}function Fi(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 Fl=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"]]),os=/^[\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 Pl(e){return os.test(""+e)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":e}function qa(){}var Ws=null;function ks(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Ks=null,mr=null;function $l(e){var n=bn(e);if(n&&(e=n.stateNode)){var s=e[Ee]||null;e:switch(e=n.stateNode,n.type){case"input":if(Lc(e,s.value,s.defaultValue,s.defaultValue,s.checked,s.defaultChecked,s.type,s.name),n=s.name,s.type==="radio"&&n!=null){for(s=e;s.parentNode;)s=s.parentNode;for(s=s.querySelectorAll('input[name="'+Ua(""+n)+'"][type="radio"]'),n=0;n<s.length;n++){var o=s[n];if(o!==e&&o.form===e.form){var f=o[Ee]||null;if(!f)throw Error(l(90));Lc(o,f.value,f.defaultValue,f.defaultValue,f.checked,f.defaultChecked,f.type,f.name)}}for(n=0;n<s.length;n++)o=s[n],o.form===e.form&&nd(o)}break e;case"textarea":qs(e,s.value,s.defaultValue);break e;case"select":n=s.value,n!=null&&xn(e,!!s.multiple,n,!1)}}}var Pi=!1;function Ic(e,n,s){if(Pi)return e(n,s);Pi=!0;try{var o=e(n);return o}finally{if(Pi=!1,(Ks!==null||mr!==null)&&(Ld(),Ks&&(n=Ks,e=mr,mr=Ks=null,$l(n),e)))for(n=0;n<e.length;n++)$l(e[n])}}function hr(e,n){var s=e.stateNode;if(s===null)return null;var o=s[Ee]||null;if(o===null)return null;s=o[n];e:switch(n){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(o=!o.disabled)||(e=e.type,o=!(e==="button"||e==="input"||e==="select"||e==="textarea")),e=!o;break e;default:e=!1}if(e)return null;if(s&&typeof s!="function")throw Error(l(231,n,typeof s));return s}var Ga=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),To=!1;if(Ga)try{var $i={};Object.defineProperty($i,"passive",{get:function(){To=!0}}),window.addEventListener("test",$i,$i),window.removeEventListener("test",$i,$i)}catch{To=!1}var wn=null,Bl=null,La=null;function Ul(){if(La)return La;var e,n=Bl,s=n.length,o,f="value"in wn?wn.value:wn.textContent,p=f.length;for(e=0;e<s&&n[e]===f[e];e++);var S=s-e;for(o=1;o<=S&&n[s-o]===f[p-o];o++);return La=f.slice(e,1<o?1-o:void 0)}function ba(e){var n=e.keyCode;return"charCode"in e?(e=e.charCode,e===0&&n===13&&(e=13)):e=n,e===10&&(e=13),32<=e||e===13?e:0}function Bn(){return!0}function zc(){return!1}function la(e){function n(s,o,f,p,S){this._reactName=s,this._targetInst=f,this.type=o,this.nativeEvent=p,this.target=S,this.currentTarget=null;for(var R in e)e.hasOwnProperty(R)&&(s=e[R],this[R]=s?s(p):p[R]);return this.isDefaultPrevented=(p.defaultPrevented!=null?p.defaultPrevented:p.returnValue===!1)?Bn:zc,this.isPropagationStopped=zc,this}return b(n.prototype,{preventDefault:function(){this.defaultPrevented=!0;var s=this.nativeEvent;s&&(s.preventDefault?s.preventDefault():typeof s.returnValue!="unknown"&&(s.returnValue=!1),this.isDefaultPrevented=Bn)},stopPropagation:function(){var s=this.nativeEvent;s&&(s.stopPropagation?s.stopPropagation():typeof s.cancelBubble!="unknown"&&(s.cancelBubble=!0),this.isPropagationStopped=Bn)},persist:function(){},isPersistent:Bn}),n}var wt={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},oa=la(wt),cs=b({},wt,{view:0,detail:0}),Bi=la(cs),Gr,js,us,Vr=b({},cs,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Fc,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!==us&&(us&&e.type==="mousemove"?(Gr=e.screenX-us.screenX,js=e.screenY-us.screenY):js=Gr=0,us=e),Gr)},movementY:function(e){return"movementY"in e?e.movementY:js}}),Wr=la(Vr),Kr=b({},Vr,{dataTransfer:0}),Yr=la(Kr),Ui=b({},cs,{relatedTarget:0}),qi=la(Ui),ql=b({},wt,{animationName:0,elapsedTime:0,pseudoElement:0}),Ro=la(ql),Eo=b({},wt,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),Do=la(Eo),Oc=b({},wt,{data:0}),Hc=la(Oc),Ys={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Va={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"},Qr={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function pr(e){var n=this.nativeEvent;return n.getModifierState?n.getModifierState(e):(e=Qr[e])?!!n[e]:!1}function Fc(){return pr}var Pc=b({},cs,{key:function(e){if(e.key){var n=Ys[e.key]||e.key;if(n!=="Unidentified")return n}return e.type==="keypress"?(e=ba(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?Va[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Fc,charCode:function(e){return e.type==="keypress"?ba(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?ba(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),ng=la(Pc),sm=b({},Vr,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Xr=la(sm),rm=b({},cs,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Fc}),Gi=la(rm),$c=b({},wt,{propertyName:0,elapsedTime:0,pseudoElement:0}),ag=la($c),sg=b({},Vr,{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}),rg=la(sg),im=b({},wt,{newState:0,oldState:0}),sd=la(im),rd=[9,13,27,32],Bc=Ga&&"CompositionEvent"in window,Gl=null;Ga&&"documentMode"in document&&(Gl=document.documentMode);var lm=Ga&&"TextEvent"in window&&!Gl,Lo=Ga&&(!Bc||Gl&&8<Gl&&11>=Gl),_o=" ",Vi=!1;function Qs(e,n){switch(e){case"keyup":return rd.indexOf(n.keyCode)!==-1;case"keydown":return n.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Vl(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Zr=!1;function id(e,n){switch(e){case"compositionend":return Vl(n);case"keypress":return n.which!==32?null:(Vi=!0,_o);case"textInput":return e=n.data,e===_o&&Vi?null:e;default:return null}}function ld(e,n){if(Zr)return e==="compositionend"||!Bc&&Qs(e,n)?(e=Ul(),La=Bl=wn=null,Zr=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(n.ctrlKey||n.altKey||n.metaKey)||n.ctrlKey&&n.altKey){if(n.char&&1<n.char.length)return n.char;if(n.which)return String.fromCharCode(n.which)}return null;case"compositionend":return Lo&&n.locale!=="ko"?null:n.data;default:return null}}var Wl={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 Io(e){var n=e&&e.nodeName&&e.nodeName.toLowerCase();return n==="input"?!!Wl[e.type]:n==="textarea"}function Wi(e,n,s,o){Ks?mr?mr.push(o):mr=[o]:Ks=o,n=Pd(n,"onChange"),0<n.length&&(s=new oa("onChange","change",null,s,o),e.push({event:s,listeners:n}))}var pt=null,Xs=null;function Ki(e){_v(e,0)}function Mt(e){var n=en(e);if(nd(n))return e}function xa(e,n){if(e==="change")return n}var Yi=!1;if(Ga){var Uc;if(Ga){var zo="oninput"in document;if(!zo){var Jr=document.createElement("div");Jr.setAttribute("oninput","return;"),zo=typeof Jr.oninput=="function"}Uc=zo}else Uc=!1;Yi=Uc&&(!document.documentMode||9<document.documentMode)}function rt(){pt&&(pt.detachEvent("onpropertychange",qc),Xs=pt=null)}function qc(e){if(e.propertyName==="value"&&Mt(Xs)){var n=[];Wi(n,Xs,e,ks(e)),Ic(Ki,n)}}function om(e,n,s){e==="focusin"?(rt(),pt=n,Xs=s,pt.attachEvent("onpropertychange",qc)):e==="focusout"&&rt()}function Gc(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return Mt(Xs)}function ei(e,n){if(e==="click")return Mt(n)}function od(e,n){if(e==="input"||e==="change")return Mt(n)}function Vc(e,n){return e===n&&(e!==0||1/e===1/n)||e!==e&&n!==n}var An=typeof Object.is=="function"?Object.is:Vc;function Un(e,n){if(An(e,n))return!0;if(typeof e!="object"||e===null||typeof n!="object"||n===null)return!1;var s=Object.keys(e),o=Object.keys(n);if(s.length!==o.length)return!1;for(o=0;o<s.length;o++){var f=s[o];if(!qe.call(n,f)||!An(e[f],n[f]))return!1}return!0}function ti(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function Qn(e,n){var s=ti(e);e=0;for(var o;s;){if(s.nodeType===3){if(o=e+s.textContent.length,e<=n&&o>=n)return{node:s,offset:n-e};e=o}e:{for(;s;){if(s.nextSibling){s=s.nextSibling;break e}s=s.parentNode}s=void 0}s=ti(s)}}function _a(e,n){return e&&n?e===n?!0:e&&e.nodeType===3?!1:n&&n.nodeType===3?_a(e,n.parentNode):"contains"in e?e.contains(n):e.compareDocumentPosition?!!(e.compareDocumentPosition(n)&16):!1:!1}function Ie(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var n=No(e.document);n instanceof e.HTMLIFrameElement;){try{var s=typeof n.contentWindow.location.href=="string"}catch{s=!1}if(s)e=n.contentWindow;else break;n=No(e.document)}return n}function Oo(e){var n=e&&e.nodeName&&e.nodeName.toLowerCase();return n&&(n==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||n==="textarea"||e.contentEditable==="true")}var cm=Ga&&"documentMode"in document&&11>=document.documentMode,Qi=null,Kl=null,Zs=null,cd=!1;function Wc(e,n,s){var o=s.window===s?s.document:s.nodeType===9?s:s.ownerDocument;cd||Qi==null||Qi!==No(o)||(o=Qi,"selectionStart"in o&&Oo(o)?o={start:o.selectionStart,end:o.selectionEnd}:(o=(o.ownerDocument&&o.ownerDocument.defaultView||window).getSelection(),o={anchorNode:o.anchorNode,anchorOffset:o.anchorOffset,focusNode:o.focusNode,focusOffset:o.focusOffset}),Zs&&Un(Zs,o)||(Zs=o,o=Pd(Kl,"onSelect"),0<o.length&&(n=new oa("onSelect","select",null,n,s),e.push({event:n,listeners:o}),n.target=Qi)))}function Wt(e,n){var s={};return s[e.toLowerCase()]=n.toLowerCase(),s["Webkit"+e]="webkit"+n,s["Moz"+e]="moz"+n,s}var ni={animationend:Wt("Animation","AnimationEnd"),animationiteration:Wt("Animation","AnimationIteration"),animationstart:Wt("Animation","AnimationStart"),transitionrun:Wt("Transition","TransitionRun"),transitionstart:Wt("Transition","TransitionStart"),transitioncancel:Wt("Transition","TransitionCancel"),transitionend:Wt("Transition","TransitionEnd")},Xi={},ai={};Ga&&(ai=document.createElement("div").style,"AnimationEvent"in window||(delete ni.animationend.animation,delete ni.animationiteration.animation,delete ni.animationstart.animation),"TransitionEvent"in window||delete ni.transitionend.transition);function si(e){if(Xi[e])return Xi[e];if(!ni[e])return e;var n=ni[e],s;for(s in n)if(n.hasOwnProperty(s)&&s in ai)return Xi[e]=n[s];return e}var ud=si("animationend"),Xt=si("animationiteration"),ri=si("animationstart"),um=si("transitionrun"),Js=si("transitionstart"),dd=si("transitioncancel"),Zi=si("transitionend"),Ho=new Map,Ji="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(" ");Ji.push("scrollEnd");function wa(e,n){Ho.set(e,n),jn(n,[e])}var Sa=typeof reportError=="function"?reportError:function(e){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var n=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(n))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",e);return}console.error(e)},Mn=[],er=0,Wa=0;function qn(){for(var e=er,n=Wa=er=0;n<e;){var s=Mn[n];Mn[n++]=null;var o=Mn[n];Mn[n++]=null;var f=Mn[n];Mn[n++]=null;var p=Mn[n];if(Mn[n++]=null,o!==null&&f!==null){var S=o.pending;S===null?f.next=f:(f.next=S.next,S.next=f),o.pending=f}p!==0&&ii(s,f,p)}}function Xn(e,n,s,o){Mn[er++]=e,Mn[er++]=n,Mn[er++]=s,Mn[er++]=o,Wa|=o,e.lanes|=o,e=e.alternate,e!==null&&(e.lanes|=o)}function Kc(e,n,s,o){return Xn(e,n,s,o),Fo(e)}function gr(e,n){return Xn(e,null,null,n),Fo(e)}function ii(e,n,s){e.lanes|=s;var o=e.alternate;o!==null&&(o.lanes|=s);for(var f=!1,p=e.return;p!==null;)p.childLanes|=s,o=p.alternate,o!==null&&(o.childLanes|=s),p.tag===22&&(e=p.stateNode,e===null||e._visibility&1||(f=!0)),e=p,p=p.return;return e.tag===3?(p=e.stateNode,f&&n!==null&&(f=31-ht(s),e=p.hiddenUpdates,o=e[f],o===null?e[f]=[n]:o.push(n),n.lane=s|536870912),p):null}function Fo(e){if(50<yu)throw yu=0,Bm=null,Error(l(185));for(var n=e.return;n!==null;)e=n,n=e.return;return e.tag===3?e.stateNode:null}var Zn={};function li(e,n,s,o){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=n,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=o,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function ca(e,n,s,o){return new li(e,n,s,o)}function Gn(e){return e=e.prototype,!(!e||!e.isReactComponent)}function _n(e,n){var s=e.alternate;return s===null?(s=ca(e.tag,n,e.key,e.mode),s.elementType=e.elementType,s.type=e.type,s.stateNode=e.stateNode,s.alternate=e,e.alternate=s):(s.pendingProps=n,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,n=e.dependencies,s.dependencies=n===null?null:{lanes:n.lanes,firstContext:n.firstContext},s.sibling=e.sibling,s.index=e.index,s.ref=e.ref,s.refCleanup=e.refCleanup,s}function Yl(e,n){e.flags&=65011714;var s=e.alternate;return s===null?(e.childLanes=0,e.lanes=n,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,n=s.dependencies,e.dependencies=n===null?null:{lanes:n.lanes,firstContext:n.firstContext}),e}function tr(e,n,s,o,f,p){var S=0;if(o=e,typeof e=="function")Gn(e)&&(S=1);else if(typeof e=="string")S=s0(e,s,he.current)?26:e==="html"||e==="head"||e==="body"?27:5;else e:switch(e){case q:return e=ca(31,s,n,f),e.elementType=q,e.lanes=p,e;case k:return Ca(s.children,f,p,n);case T:S=8,f|=24;break;case M:return e=ca(12,s,n,f|2),e.elementType=M,e.lanes=p,e;case H:return e=ca(13,s,n,f),e.elementType=H,e.lanes=p,e;case G:return e=ca(19,s,n,f),e.elementType=G,e.lanes=p,e;default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case L:S=10;break e;case N:S=9;break e;case z:S=11;break e;case _:S=14;break e;case Y:S=16,o=null;break e}S=29,s=Error(l(130,e===null?"null":typeof e,"")),o=null}return n=ca(S,s,n,f),n.elementType=e,n.type=o,n.lanes=p,n}function Ca(e,n,s,o){return e=ca(7,e,o,n),e.lanes=s,e}function vr(e,n,s){return e=ca(6,e,null,n),e.lanes=s,e}function Ql(e){var n=ca(18,null,null,0);return n.stateNode=e,n}function ds(e,n,s){return n=ca(4,e.children!==null?e.children:[],e.key,n),n.lanes=s,n.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},n}var Yc=new WeakMap;function Ka(e,n){if(typeof e=="object"&&e!==null){var s=Yc.get(e);return s!==void 0?s:(n={value:e,source:n,stack:Qe(n)},Yc.set(e,n),n)}return{value:e,source:n,stack:Qe(n)}}var nr=[],ar=0,Xl=null,As=0,Ia=[],za=0,yr=null,ua=1,Ms="";function Ns(e,n){nr[ar++]=As,nr[ar++]=Xl,Xl=e,As=n}function fd(e,n,s){Ia[za++]=ua,Ia[za++]=Ms,Ia[za++]=yr,yr=e;var o=ua;e=Ms;var f=32-ht(o)-1;o&=~(1<<f),s+=1;var p=32-ht(n)+f;if(30<p){var S=f-f%5;p=(o&(1<<S)-1).toString(32),o>>=S,f-=S,ua=1<<32-ht(n)+f|s<<f|o,Ms=p+e}else ua=1<<p|s<<f|o,Ms=e}function Qc(e){e.return!==null&&(Ns(e,1),fd(e,1,0))}function Po(e){for(;e===Xl;)Xl=nr[--ar],nr[ar]=null,As=nr[--ar],nr[ar]=null;for(;e===yr;)yr=Ia[--za],Ia[za]=null,Ms=Ia[--za],Ia[za]=null,ua=Ia[--za],Ia[za]=null}function Zl(e,n){Ia[za++]=ua,Ia[za++]=Ms,Ia[za++]=yr,ua=n.id,Ms=n.overflow,yr=e}var Vn=null,Kt=null,kt=!1,sr=null,Nn=!1,el=Error(l(519));function Oa(e){var n=Error(l(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw oi(Ka(n,e)),el}function br(e){var n=e.stateNode,s=e.type,o=e.memoizedProps;switch(n[re]=e,n[Ee]=o,s){case"dialog":It("cancel",n),It("close",n);break;case"iframe":case"object":case"embed":It("load",n);break;case"video":case"audio":for(s=0;s<xu.length;s++)It(xu[s],n);break;case"source":It("error",n);break;case"img":case"image":case"link":It("error",n),It("load",n);break;case"details":It("toggle",n);break;case"input":It("invalid",n),_c(n,o.value,o.defaultValue,o.checked,o.defaultChecked,o.type,o.name,!0);break;case"select":It("invalid",n);break;case"textarea":It("invalid",n),Gs(n,o.value,o.defaultValue,o.children)}s=o.children,typeof s!="string"&&typeof s!="number"&&typeof s!="bigint"||n.textContent===""+s||o.suppressHydrationWarning===!0||Hv(n.textContent,s)?(o.popover!=null&&(It("beforetoggle",n),It("toggle",n)),o.onScroll!=null&&It("scroll",n),o.onScrollEnd!=null&&It("scrollend",n),o.onClick!=null&&(n.onclick=qa),n=!0):n=!1,n||Oa(e,!0)}function $o(e){for(Vn=e.return;Vn;)switch(Vn.tag){case 5:case 31:case 13:Nn=!1;return;case 27:case 3:Nn=!0;return;default:Vn=Vn.return}}function tl(e){if(e!==Vn)return!1;if(!kt)return $o(e),kt=!0,!1;var n=e.tag,s;if((s=n!==3&&n!==27)&&((s=n===5)&&(s=e.type,s=!(s!=="form"&&s!=="button")||ah(e.type,e.memoizedProps)),s=!s),s&&Kt&&Oa(e),$o(e),n===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(l(317));Kt=Wv(e)}else if(n===31){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(l(317));Kt=Wv(e)}else n===27?(n=Kt,Cl(e.type)?(e=oh,oh=null,Kt=e):Kt=n):Kt=Vn?zs(e.stateNode.nextSibling):null;return!0}function xr(){Kt=Vn=null,kt=!1}function nl(){var e=sr;return e!==null&&(ns===null?ns=e:ns.push.apply(ns,e),sr=null),e}function oi(e){sr===null?sr=[e]:sr.push(e)}var ci=le(null),ui=null,Ya=null;function rr(e,n,s){be(ci,n._currentValue),n._currentValue=s}function Ha(e){e._currentValue=ci.current,Q(ci)}function Jl(e,n,s){for(;e!==null;){var o=e.alternate;if((e.childLanes&n)!==n?(e.childLanes|=n,o!==null&&(o.childLanes|=n)):o!==null&&(o.childLanes&n)!==n&&(o.childLanes|=n),e===s)break;e=e.return}}function al(e,n,s,o){var f=e.child;for(f!==null&&(f.return=e);f!==null;){var p=f.dependencies;if(p!==null){var S=f.child;p=p.firstContext;e:for(;p!==null;){var R=p;p=f;for(var V=0;V<n.length;V++)if(R.context===n[V]){p.lanes|=s,R=p.alternate,R!==null&&(R.lanes|=s),Jl(p.return,s,e),o||(S=null);break e}p=R.next}}else if(f.tag===18){if(S=f.return,S===null)throw Error(l(341));S.lanes|=s,p=S.alternate,p!==null&&(p.lanes|=s),Jl(S,s,e),S=null}else S=f.child;if(S!==null)S.return=f;else for(S=f;S!==null;){if(S===e){S=null;break}if(f=S.sibling,f!==null){f.return=S.return,S=f;break}S=S.return}f=S}}function ir(e,n,s,o){e=null;for(var f=n,p=!1;f!==null;){if(!p){if((f.flags&524288)!==0)p=!0;else if((f.flags&262144)!==0)break}if(f.tag===10){var S=f.alternate;if(S===null)throw Error(l(387));if(S=S.memoizedProps,S!==null){var R=f.type;An(f.pendingProps.value,S.value)||(e!==null?e.push(R):e=[R])}}else if(f===Ce.current){if(S=f.alternate,S===null)throw Error(l(387));S.memoizedState.memoizedState!==f.memoizedState.memoizedState&&(e!==null?e.push(ju):e=[ju])}f=f.return}e!==null&&al(n,e,s,o),n.flags|=262144}function di(e){for(e=e.firstContext;e!==null;){if(!An(e.context._currentValue,e.memoizedValue))return!0;e=e.next}return!1}function Fa(e){ui=e,Ya=null,e=e.dependencies,e!==null&&(e.firstContext=null)}function In(e){return fi(ui,e)}function eo(e,n){return ui===null&&Fa(e),fi(e,n)}function fi(e,n){var s=n._currentValue;if(n={context:n,memoizedValue:s,next:null},Ya===null){if(e===null)throw Error(l(308));Ya=n,e.dependencies={lanes:0,firstContext:n},e.flags|=524288}else Ya=Ya.next=n;return s}var sl=typeof AbortController<"u"?AbortController:function(){var e=[],n=this.signal={aborted:!1,addEventListener:function(s,o){e.push(o)}};this.abort=function(){n.aborted=!0,e.forEach(function(s){return s()})}},wr=t.unstable_scheduleCallback,Ts=t.unstable_NormalPriority,Zt={$$typeof:L,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function Bo(){return{controller:new sl,data:new Map,refCount:0}}function Sr(e){e.refCount--,e.refCount===0&&wr(Ts,function(){e.controller.abort()})}var Qa=null,md=0,mi=0,Rs=null;function Uo(e,n){if(Qa===null){var s=Qa=[];md=0,mi=Km(),Rs={status:"pending",value:void 0,then:function(o){s.push(o)}}}return md++,n.then(qo,qo),n}function qo(){if(--md===0&&Qa!==null){Rs!==null&&(Rs.status="fulfilled");var e=Qa;Qa=null,mi=0,Rs=null;for(var n=0;n<e.length;n++)(0,e[n])()}}function hd(e,n){var s=[],o={status:"pending",value:null,reason:null,then:function(f){s.push(f)}};return e.then(function(){o.status="fulfilled",o.value=n;for(var f=0;f<s.length;f++)(0,s[f])(n)},function(f){for(o.status="rejected",o.reason=f,f=0;f<s.length;f++)(0,s[f])(void 0)}),o}var fs=I.S;I.S=function(e,n){ov=je(),typeof n=="object"&&n!==null&&typeof n.then=="function"&&Uo(e,n),fs!==null&&fs(e,n)};var Cr=le(null);function to(){var e=Cr.current;return e!==null?e:Jt.pooledCache}function rl(e,n){n===null?be(Cr,Cr.current):be(Cr,n.pool)}function Go(){var e=to();return e===null?null:{parent:Zt._currentValue,pool:e}}var kr=Error(l(460)),Vo=Error(l(474)),jr=Error(l(542)),Xa={then:function(){}};function Wo(e){return e=e.status,e==="fulfilled"||e==="rejected"}function pd(e,n,s){switch(s=e[s],s===void 0?e.push(n):s!==n&&(n.then(qa,qa),n=s),n.status){case"fulfilled":return n.value;case"rejected":throw e=n.reason,no(e),e;default:if(typeof n.status=="string")n.then(qa,qa);else{if(e=Jt,e!==null&&100<e.shellSuspendCounter)throw Error(l(482));e=n,e.status="pending",e.then(function(o){if(n.status==="pending"){var f=n;f.status="fulfilled",f.value=o}},function(o){if(n.status==="pending"){var f=n;f.status="rejected",f.reason=o}})}switch(n.status){case"fulfilled":return n.value;case"rejected":throw e=n.reason,no(e),e}throw hn=n,kr}}function Ar(e){try{var n=e._init;return n(e._payload)}catch(s){throw s!==null&&typeof s=="object"&&typeof s.then=="function"?(hn=s,kr):s}}var hn=null;function Xc(){if(hn===null)throw Error(l(459));var e=hn;return hn=null,e}function no(e){if(e===kr||e===jr)throw Error(l(483))}var lr=null,il=0;function Mr(e){var n=il;return il+=1,lr===null&&(lr=[]),pd(lr,e,n)}function hi(e,n){n=n.props.ref,e.ref=n!==void 0?n:null}function Nr(e,n){throw n.$$typeof===w?Error(l(525)):(e=Object.prototype.toString.call(n),Error(l(31,e==="[object Object]"?"object with keys {"+Object.keys(n).join(", ")+"}":e)))}function gd(e){function n(ae,X){if(e){var ce=ae.deletions;ce===null?(ae.deletions=[X],ae.flags|=16):ce.push(X)}}function s(ae,X){if(!e)return null;for(;X!==null;)n(ae,X),X=X.sibling;return null}function o(ae){for(var X=new Map;ae!==null;)ae.key!==null?X.set(ae.key,ae):X.set(ae.index,ae),ae=ae.sibling;return X}function f(ae,X){return ae=_n(ae,X),ae.index=0,ae.sibling=null,ae}function p(ae,X,ce){return ae.index=ce,e?(ce=ae.alternate,ce!==null?(ce=ce.index,ce<X?(ae.flags|=67108866,X):ce):(ae.flags|=67108866,X)):(ae.flags|=1048576,X)}function S(ae){return e&&ae.alternate===null&&(ae.flags|=67108866),ae}function R(ae,X,ce,Se){return X===null||X.tag!==6?(X=vr(ce,ae.mode,Se),X.return=ae,X):(X=f(X,ce),X.return=ae,X)}function V(ae,X,ce,Se){var st=ce.type;return st===k?we(ae,X,ce.props.children,Se,ce.key):X!==null&&(X.elementType===st||typeof st=="object"&&st!==null&&st.$$typeof===Y&&Ar(st)===X.type)?(X=f(X,ce.props),hi(X,ce),X.return=ae,X):(X=tr(ce.type,ce.key,ce.props,null,ae.mode,Se),hi(X,ce),X.return=ae,X)}function ue(ae,X,ce,Se){return X===null||X.tag!==4||X.stateNode.containerInfo!==ce.containerInfo||X.stateNode.implementation!==ce.implementation?(X=ds(ce,ae.mode,Se),X.return=ae,X):(X=f(X,ce.children||[]),X.return=ae,X)}function we(ae,X,ce,Se,st){return X===null||X.tag!==7?(X=Ca(ce,ae.mode,Se,st),X.return=ae,X):(X=f(X,ce),X.return=ae,X)}function ke(ae,X,ce){if(typeof X=="string"&&X!==""||typeof X=="number"||typeof X=="bigint")return X=vr(""+X,ae.mode,ce),X.return=ae,X;if(typeof X=="object"&&X!==null){switch(X.$$typeof){case j:return ce=tr(X.type,X.key,X.props,null,ae.mode,ce),hi(ce,X),ce.return=ae,ce;case A:return X=ds(X,ae.mode,ce),X.return=ae,X;case Y:return X=Ar(X),ke(ae,X,ce)}if(Z(X)||O(X))return X=Ca(X,ae.mode,ce,null),X.return=ae,X;if(typeof X.then=="function")return ke(ae,Mr(X),ce);if(X.$$typeof===L)return ke(ae,eo(ae,X),ce);Nr(ae,X)}return null}function fe(ae,X,ce,Se){var st=X!==null?X.key:null;if(typeof ce=="string"&&ce!==""||typeof ce=="number"||typeof ce=="bigint")return st!==null?null:R(ae,X,""+ce,Se);if(typeof ce=="object"&&ce!==null){switch(ce.$$typeof){case j:return ce.key===st?V(ae,X,ce,Se):null;case A:return ce.key===st?ue(ae,X,ce,Se):null;case Y:return ce=Ar(ce),fe(ae,X,ce,Se)}if(Z(ce)||O(ce))return st!==null?null:we(ae,X,ce,Se,null);if(typeof ce.then=="function")return fe(ae,X,Mr(ce),Se);if(ce.$$typeof===L)return fe(ae,X,eo(ae,ce),Se);Nr(ae,ce)}return null}function ge(ae,X,ce,Se,st){if(typeof Se=="string"&&Se!==""||typeof Se=="number"||typeof Se=="bigint")return ae=ae.get(ce)||null,R(X,ae,""+Se,st);if(typeof Se=="object"&&Se!==null){switch(Se.$$typeof){case j:return ae=ae.get(Se.key===null?ce:Se.key)||null,V(X,ae,Se,st);case A:return ae=ae.get(Se.key===null?ce:Se.key)||null,ue(X,ae,Se,st);case Y:return Se=Ar(Se),ge(ae,X,ce,Se,st)}if(Z(Se)||O(Se))return ae=ae.get(ce)||null,we(X,ae,Se,st,null);if(typeof Se.then=="function")return ge(ae,X,ce,Mr(Se),st);if(Se.$$typeof===L)return ge(ae,X,ce,eo(X,Se),st);Nr(X,Se)}return null}function Je(ae,X,ce,Se){for(var st=null,Ft=null,tt=X,jt=X=0,Ot=null;tt!==null&&jt<ce.length;jt++){tt.index>jt?(Ot=tt,tt=null):Ot=tt.sibling;var Pt=fe(ae,tt,ce[jt],Se);if(Pt===null){tt===null&&(tt=Ot);break}e&&tt&&Pt.alternate===null&&n(ae,tt),X=p(Pt,X,jt),Ft===null?st=Pt:Ft.sibling=Pt,Ft=Pt,tt=Ot}if(jt===ce.length)return s(ae,tt),kt&&Ns(ae,jt),st;if(tt===null){for(;jt<ce.length;jt++)tt=ke(ae,ce[jt],Se),tt!==null&&(X=p(tt,X,jt),Ft===null?st=tt:Ft.sibling=tt,Ft=tt);return kt&&Ns(ae,jt),st}for(tt=o(tt);jt<ce.length;jt++)Ot=ge(tt,ae,jt,ce[jt],Se),Ot!==null&&(e&&Ot.alternate!==null&&tt.delete(Ot.key===null?jt:Ot.key),X=p(Ot,X,jt),Ft===null?st=Ot:Ft.sibling=Ot,Ft=Ot);return e&&tt.forEach(function(Nl){return n(ae,Nl)}),kt&&Ns(ae,jt),st}function lt(ae,X,ce,Se){if(ce==null)throw Error(l(151));for(var st=null,Ft=null,tt=X,jt=X=0,Ot=null,Pt=ce.next();tt!==null&&!Pt.done;jt++,Pt=ce.next()){tt.index>jt?(Ot=tt,tt=null):Ot=tt.sibling;var Nl=fe(ae,tt,Pt.value,Se);if(Nl===null){tt===null&&(tt=Ot);break}e&&tt&&Nl.alternate===null&&n(ae,tt),X=p(Nl,X,jt),Ft===null?st=Nl:Ft.sibling=Nl,Ft=Nl,tt=Ot}if(Pt.done)return s(ae,tt),kt&&Ns(ae,jt),st;if(tt===null){for(;!Pt.done;jt++,Pt=ce.next())Pt=ke(ae,Pt.value,Se),Pt!==null&&(X=p(Pt,X,jt),Ft===null?st=Pt:Ft.sibling=Pt,Ft=Pt);return kt&&Ns(ae,jt),st}for(tt=o(tt);!Pt.done;jt++,Pt=ce.next())Pt=ge(tt,ae,jt,Pt.value,Se),Pt!==null&&(e&&Pt.alternate!==null&&tt.delete(Pt.key===null?jt:Pt.key),X=p(Pt,X,jt),Ft===null?st=Pt:Ft.sibling=Pt,Ft=Pt);return e&&tt.forEach(function(p0){return n(ae,p0)}),kt&&Ns(ae,jt),st}function Qt(ae,X,ce,Se){if(typeof ce=="object"&&ce!==null&&ce.type===k&&ce.key===null&&(ce=ce.props.children),typeof ce=="object"&&ce!==null){switch(ce.$$typeof){case j:e:{for(var st=ce.key;X!==null;){if(X.key===st){if(st=ce.type,st===k){if(X.tag===7){s(ae,X.sibling),Se=f(X,ce.props.children),Se.return=ae,ae=Se;break e}}else if(X.elementType===st||typeof st=="object"&&st!==null&&st.$$typeof===Y&&Ar(st)===X.type){s(ae,X.sibling),Se=f(X,ce.props),hi(Se,ce),Se.return=ae,ae=Se;break e}s(ae,X);break}else n(ae,X);X=X.sibling}ce.type===k?(Se=Ca(ce.props.children,ae.mode,Se,ce.key),Se.return=ae,ae=Se):(Se=tr(ce.type,ce.key,ce.props,null,ae.mode,Se),hi(Se,ce),Se.return=ae,ae=Se)}return S(ae);case A:e:{for(st=ce.key;X!==null;){if(X.key===st)if(X.tag===4&&X.stateNode.containerInfo===ce.containerInfo&&X.stateNode.implementation===ce.implementation){s(ae,X.sibling),Se=f(X,ce.children||[]),Se.return=ae,ae=Se;break e}else{s(ae,X);break}else n(ae,X);X=X.sibling}Se=ds(ce,ae.mode,Se),Se.return=ae,ae=Se}return S(ae);case Y:return ce=Ar(ce),Qt(ae,X,ce,Se)}if(Z(ce))return Je(ae,X,ce,Se);if(O(ce)){if(st=O(ce),typeof st!="function")throw Error(l(150));return ce=st.call(ce),lt(ae,X,ce,Se)}if(typeof ce.then=="function")return Qt(ae,X,Mr(ce),Se);if(ce.$$typeof===L)return Qt(ae,X,eo(ae,ce),Se);Nr(ae,ce)}return typeof ce=="string"&&ce!==""||typeof ce=="number"||typeof ce=="bigint"?(ce=""+ce,X!==null&&X.tag===6?(s(ae,X.sibling),Se=f(X,ce),Se.return=ae,ae=Se):(s(ae,X),Se=vr(ce,ae.mode,Se),Se.return=ae,ae=Se),S(ae)):s(ae,X)}return function(ae,X,ce,Se){try{il=0;var st=Qt(ae,X,ce,Se);return lr=null,st}catch(tt){if(tt===kr||tt===jr)throw tt;var Ft=ca(29,tt,null,ae.mode);return Ft.lanes=Se,Ft.return=ae,Ft}}}var Tr=gd(!0),ll=gd(!1),Rr=!1;function Zc(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Jc(e,n){e=e.updateQueue,n.updateQueue===e&&(n.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function Er(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Es(e,n,s){var o=e.updateQueue;if(o===null)return null;if(o=o.shared,($t&2)!==0){var f=o.pending;return f===null?n.next=n:(n.next=f.next,f.next=n),o.pending=n,n=Fo(e),ii(e,null,s),n}return Xn(e,o,n,s),Fo(e)}function pi(e,n,s){if(n=n.updateQueue,n!==null&&(n=n.shared,(s&4194048)!==0)){var o=n.lanes;o&=e.pendingLanes,s|=o,n.lanes=s,$(e,s)}}function gi(e,n){var s=e.updateQueue,o=e.alternate;if(o!==null&&(o=o.updateQueue,s===o)){var f=null,p=null;if(s=s.firstBaseUpdate,s!==null){do{var S={lane:s.lane,tag:s.tag,payload:s.payload,callback:null,next:null};p===null?f=p=S:p=p.next=S,s=s.next}while(s!==null);p===null?f=p=n:p=p.next=n}else f=p=n;s={baseState:o.baseState,firstBaseUpdate:f,lastBaseUpdate:p,shared:o.shared,callbacks:o.callbacks},e.updateQueue=s;return}e=s.lastBaseUpdate,e===null?s.firstBaseUpdate=n:e.next=n,s.lastBaseUpdate=n}var Ko=!1;function vi(){if(Ko){var e=Rs;if(e!==null)throw e}}function ao(e,n,s,o){Ko=!1;var f=e.updateQueue;Rr=!1;var p=f.firstBaseUpdate,S=f.lastBaseUpdate,R=f.shared.pending;if(R!==null){f.shared.pending=null;var V=R,ue=V.next;V.next=null,S===null?p=ue:S.next=ue,S=V;var we=e.alternate;we!==null&&(we=we.updateQueue,R=we.lastBaseUpdate,R!==S&&(R===null?we.firstBaseUpdate=ue:R.next=ue,we.lastBaseUpdate=V))}if(p!==null){var ke=f.baseState;S=0,we=ue=V=null,R=p;do{var fe=R.lane&-536870913,ge=fe!==R.lane;if(ge?(zt&fe)===fe:(o&fe)===fe){fe!==0&&fe===mi&&(Ko=!0),we!==null&&(we=we.next={lane:0,tag:R.tag,payload:R.payload,callback:null,next:null});e:{var Je=e,lt=R;fe=n;var Qt=s;switch(lt.tag){case 1:if(Je=lt.payload,typeof Je=="function"){ke=Je.call(Qt,ke,fe);break e}ke=Je;break e;case 3:Je.flags=Je.flags&-65537|128;case 0:if(Je=lt.payload,fe=typeof Je=="function"?Je.call(Qt,ke,fe):Je,fe==null)break e;ke=b({},ke,fe);break e;case 2:Rr=!0}}fe=R.callback,fe!==null&&(e.flags|=64,ge&&(e.flags|=8192),ge=f.callbacks,ge===null?f.callbacks=[fe]:ge.push(fe))}else ge={lane:fe,tag:R.tag,payload:R.payload,callback:R.callback,next:null},we===null?(ue=we=ge,V=ke):we=we.next=ge,S|=fe;if(R=R.next,R===null){if(R=f.shared.pending,R===null)break;ge=R,R=ge.next,ge.next=null,f.lastBaseUpdate=ge,f.shared.pending=null}}while(!0);we===null&&(V=ke),f.baseState=V,f.firstBaseUpdate=ue,f.lastBaseUpdate=we,p===null&&(f.shared.lanes=0),yl|=S,e.lanes=S,e.memoizedState=ke}}function ol(e,n){if(typeof e!="function")throw Error(l(191,e));e.call(n)}function vd(e,n){var s=e.callbacks;if(s!==null)for(e.callbacks=null,e=0;e<s.length;e++)ol(s[e],n)}var cl=le(null),Yo=le(0);function Qo(e,n){e=Mi,be(Yo,e),be(cl,n),Mi=e|n.baseLanes}function Xo(){be(Yo,Mi),be(cl,cl.current)}function Zo(){Mi=Yo.current,Q(cl),Q(Yo)}var ka=le(null),Za=null;function Ds(e){var n=e.alternate;be(Me,Me.current&1),be(ka,e),Za===null&&(n===null||cl.current!==null||n.memoizedState!==null)&&(Za=e)}function ul(e){be(Me,Me.current),be(ka,e),Za===null&&(Za=e)}function eu(e){e.tag===22?(be(Me,Me.current),be(ka,e),Za===null&&(Za=e)):Ls()}function Ls(){be(Me,Me.current),be(ka,ka.current)}function da(e){Q(ka),Za===e&&(Za=null),Q(Me)}var Me=le(0);function yi(e){for(var n=e;n!==null;){if(n.tag===13){var s=n.memoizedState;if(s!==null&&(s=s.dehydrated,s===null||ih(s)||lh(s)))return n}else if(n.tag===19&&(n.memoizedProps.revealOrder==="forwards"||n.memoizedProps.revealOrder==="backwards"||n.memoizedProps.revealOrder==="unstable_legacy-backwards"||n.memoizedProps.revealOrder==="together")){if((n.flags&128)!==0)return n}else if(n.child!==null){n.child.return=n,n=n.child;continue}if(n===e)break;for(;n.sibling===null;){if(n.return===null||n.return===e)return null;n=n.return}n.sibling.return=n.return,n=n.sibling}return null}var _s=0,yt=null,Ut=null,un=null,bi=!1,dn=!1,Tn=!1,Nt=0,so=0,ms=null,dl=0;function an(){throw Error(l(321))}function Jo(e,n){if(n===null)return!1;for(var s=0;s<n.length&&s<e.length;s++)if(!An(e[s],n[s]))return!1;return!0}function ec(e,n,s,o,f,p){return _s=p,yt=n,n.memoizedState=null,n.updateQueue=null,n.lanes=0,I.H=e===null||e.memoizedState===null?bg:vm,Tn=!1,p=s(o,f),Tn=!1,dn&&(p=ro(n,s,o,f)),fl(e),p}function fl(e){I.H=cu;var n=Ut!==null&&Ut.next!==null;if(_s=0,un=Ut=yt=null,bi=!1,so=0,ms=null,n)throw Error(l(300));e===null||On||(e=e.dependencies,e!==null&&di(e)&&(On=!0))}function ro(e,n,s,o){yt=e;var f=0;do{if(dn&&(ms=null),so=0,dn=!1,25<=f)throw Error(l(301));if(f+=1,un=Ut=null,e.updateQueue!=null){var p=e.updateQueue;p.lastEffect=null,p.events=null,p.stores=null,p.memoCache!=null&&(p.memoCache.index=0)}I.H=xg,p=n(s,o)}while(dn);return p}function dm(){var e=I.H,n=e.useState()[0];return n=typeof n.then=="function"?lo(n):n,e=e.useState()[0],(Ut!==null?Ut.memoizedState:null)!==e&&(yt.flags|=1024),n}function tc(){var e=Nt!==0;return Nt=0,e}function io(e,n,s){n.updateQueue=e.updateQueue,n.flags&=-2053,e.lanes&=~s}function tu(e){if(bi){for(e=e.memoizedState;e!==null;){var n=e.queue;n!==null&&(n.pending=null),e=e.next}bi=!1}_s=0,un=Ut=yt=null,dn=!1,so=Nt=0,ms=null}function fa(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return un===null?yt.memoizedState=un=e:un=un.next=e,un}function sn(){if(Ut===null){var e=yt.alternate;e=e!==null?e.memoizedState:null}else e=Ut.next;var n=un===null?yt.memoizedState:un.next;if(n!==null)un=n,Ut=e;else{if(e===null)throw yt.alternate===null?Error(l(467)):Error(l(310));Ut=e,e={memoizedState:Ut.memoizedState,baseState:Ut.baseState,baseQueue:Ut.baseQueue,queue:Ut.queue,next:null},un===null?yt.memoizedState=un=e:un=un.next=e}return un}function nc(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function lo(e){var n=so;return so+=1,ms===null&&(ms=[]),e=pd(ms,e,n),n=yt,(un===null?n.memoizedState:un.next)===null&&(n=n.alternate,I.H=n===null||n.memoizedState===null?bg:vm),e}function zn(e){if(e!==null&&typeof e=="object"){if(typeof e.then=="function")return lo(e);if(e.$$typeof===L)return In(e)}throw Error(l(438,String(e)))}function ml(e){var n=null,s=yt.updateQueue;if(s!==null&&(n=s.memoCache),n==null){var o=yt.alternate;o!==null&&(o=o.updateQueue,o!==null&&(o=o.memoCache,o!=null&&(n={data:o.data.map(function(f){return f.slice()}),index:0})))}if(n==null&&(n={data:[],index:0}),s===null&&(s=nc(),yt.updateQueue=s),s.memoCache=n,s=n.data[n.index],s===void 0)for(s=n.data[n.index]=Array(e),o=0;o<e;o++)s[o]=U;return n.index++,s}function or(e,n){return typeof n=="function"?n(e):n}function nu(e){var n=sn();return au(n,Ut,e)}function au(e,n,s){var o=e.queue;if(o===null)throw Error(l(311));o.lastRenderedReducer=s;var f=e.baseQueue,p=o.pending;if(p!==null){if(f!==null){var S=f.next;f.next=p.next,p.next=S}n.baseQueue=f=p,o.pending=null}if(p=e.baseState,f===null)e.memoizedState=p;else{n=f.next;var R=S=null,V=null,ue=n,we=!1;do{var ke=ue.lane&-536870913;if(ke!==ue.lane?(zt&ke)===ke:(_s&ke)===ke){var fe=ue.revertLane;if(fe===0)V!==null&&(V=V.next={lane:0,revertLane:0,gesture:null,action:ue.action,hasEagerState:ue.hasEagerState,eagerState:ue.eagerState,next:null}),ke===mi&&(we=!0);else if((_s&fe)===fe){ue=ue.next,fe===mi&&(we=!0);continue}else ke={lane:0,revertLane:ue.revertLane,gesture:null,action:ue.action,hasEagerState:ue.hasEagerState,eagerState:ue.eagerState,next:null},V===null?(R=V=ke,S=p):V=V.next=ke,yt.lanes|=fe,yl|=fe;ke=ue.action,Tn&&s(p,ke),p=ue.hasEagerState?ue.eagerState:s(p,ke)}else fe={lane:ke,revertLane:ue.revertLane,gesture:ue.gesture,action:ue.action,hasEagerState:ue.hasEagerState,eagerState:ue.eagerState,next:null},V===null?(R=V=fe,S=p):V=V.next=fe,yt.lanes|=ke,yl|=ke;ue=ue.next}while(ue!==null&&ue!==n);if(V===null?S=p:V.next=R,!An(p,e.memoizedState)&&(On=!0,we&&(s=Rs,s!==null)))throw s;e.memoizedState=p,e.baseState=S,e.baseQueue=V,o.lastRenderedState=p}return f===null&&(o.lanes=0),[e.memoizedState,o.dispatch]}function su(e){var n=sn(),s=n.queue;if(s===null)throw Error(l(311));s.lastRenderedReducer=e;var o=s.dispatch,f=s.pending,p=n.memoizedState;if(f!==null){s.pending=null;var S=f=f.next;do p=e(p,S.action),S=S.next;while(S!==f);An(p,n.memoizedState)||(On=!0),n.memoizedState=p,n.baseQueue===null&&(n.baseState=p),s.lastRenderedState=p}return[p,o]}function ru(e,n,s){var o=yt,f=sn(),p=kt;if(p){if(s===void 0)throw Error(l(407));s=s()}else s=n();var S=!An((Ut||f).memoizedState,s);if(S&&(f.memoizedState=s,On=!0),f=f.queue,ma(iu.bind(null,o,f,e),[e]),f.getSnapshot!==n||S||un!==null&&un.memoizedState.tag&1){if(o.flags|=2048,Te(9,{destroy:void 0},hl.bind(null,o,f,s,n),null),Jt===null)throw Error(l(349));p||(_s&127)!==0||oo(o,n,s)}return s}function oo(e,n,s){e.flags|=16384,e={getSnapshot:n,value:s},n=yt.updateQueue,n===null?(n=nc(),yt.updateQueue=n,n.stores=[e]):(s=n.stores,s===null?n.stores=[e]:s.push(e))}function hl(e,n,s,o){n.value=s,n.getSnapshot=o,yd(n)&&bd(e)}function iu(e,n,s){return s(function(){yd(n)&&bd(e)})}function yd(e){var n=e.getSnapshot;e=e.value;try{var s=n();return!An(e,s)}catch{return!0}}function bd(e){var n=gr(e,2);n!==null&&as(n,e,2)}function lu(e){var n=fa();if(typeof e=="function"){var s=e;if(e=s(),Tn){ct(!0);try{s()}finally{ct(!1)}}}return n.memoizedState=n.baseState=e,n.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:or,lastRenderedState:e},n}function ac(e,n,s,o){return e.baseState=s,au(e,Ut,typeof o=="function"?o:or)}function pl(e,n,s,o,f){if(wd(e))throw Error(l(485));if(e=n.action,e!==null){var p={payload:f,action:e,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(S){p.listeners.push(S)}};I.T!==null?s(!0):p.isTransition=!1,o(p),s=n.pending,s===null?(p.next=n.pending=p,xd(n,p)):(p.next=s.next,n.pending=s.next=p)}}function xd(e,n){var s=n.action,o=n.payload,f=e.state;if(n.isTransition){var p=I.T,S={};I.T=S;try{var R=s(f,o),V=I.S;V!==null&&V(S,R),Dr(e,n,R)}catch(ue){v(e,n,ue)}finally{p!==null&&S.types!==null&&(p.types=S.types),I.T=p}}else try{p=s(f,o),Dr(e,n,p)}catch(ue){v(e,n,ue)}}function Dr(e,n,s){s!==null&&typeof s=="object"&&typeof s.then=="function"?s.then(function(o){sc(e,n,o)},function(o){return v(e,n,o)}):sc(e,n,s)}function sc(e,n,s){n.status="fulfilled",n.value=s,C(n),e.state=s,n=e.pending,n!==null&&(s=n.next,s===n?e.pending=null:(s=s.next,n.next=s,xd(e,s)))}function v(e,n,s){var o=e.pending;if(e.pending=null,o!==null){o=o.next;do n.status="rejected",n.reason=s,C(n),n=n.next;while(n!==o)}e.action=null}function C(e){e=e.listeners;for(var n=0;n<e.length;n++)(0,e[n])()}function E(e,n){return n}function P(e,n){if(kt){var s=Jt.formState;if(s!==null){e:{var o=yt;if(kt){if(Kt){t:{for(var f=Kt,p=Nn;f.nodeType!==8;){if(!p){f=null;break t}if(f=zs(f.nextSibling),f===null){f=null;break t}}p=f.data,f=p==="F!"||p==="F"?f:null}if(f){Kt=zs(f.nextSibling),o=f.data==="F!";break e}}Oa(o)}o=!1}o&&(n=s[0])}}return s=fa(),s.memoizedState=s.baseState=n,o={pending:null,lanes:0,dispatch:null,lastRenderedReducer:E,lastRenderedState:n},s.queue=o,s=gg.bind(null,yt,o),o.dispatch=s,o=lu(!1),p=gm.bind(null,yt,!1,o.queue),o=fa(),f={state:n,dispatch:null,action:e,pending:null},o.queue=f,s=pl.bind(null,yt,f,p,s),f.dispatch=s,o.memoizedState=e,[n,s,!1]}function D(e){var n=sn();return J(n,Ut,e)}function J(e,n,s){if(n=au(e,n,E)[0],e=nu(or)[0],typeof n=="object"&&n!==null&&typeof n.then=="function")try{var o=lo(n)}catch(S){throw S===kr?jr:S}else o=n;n=sn();var f=n.queue,p=f.dispatch;return s!==n.memoizedState&&(yt.flags|=2048,Te(9,{destroy:void 0},ie.bind(null,f,s),null)),[o,p,e]}function ie(e,n){e.action=n}function Ne(e){var n=sn(),s=Ut;if(s!==null)return J(n,s,e);sn(),n=n.memoizedState,s=sn();var o=s.queue.dispatch;return s.memoizedState=e,[n,o,!1]}function Te(e,n,s,o){return e={tag:e,create:s,deps:o,inst:n,next:null},n=yt.updateQueue,n===null&&(n=nc(),yt.updateQueue=n),s=n.lastEffect,s===null?n.lastEffect=e.next=e:(o=s.next,s.next=e,e.next=o,n.lastEffect=e),e}function Be(){return sn().memoizedState}function Lt(e,n,s,o){var f=fa();yt.flags|=e,f.memoizedState=Te(1|n,{destroy:void 0},s,o===void 0?null:o)}function ut(e,n,s,o){var f=sn();o=o===void 0?null:o;var p=f.memoizedState.inst;Ut!==null&&o!==null&&Jo(o,Ut.memoizedState.deps)?f.memoizedState=Te(n,p,s,o):(yt.flags|=e,f.memoizedState=Te(1|n,p,s,o))}function pn(e,n){Lt(8390656,8,e,n)}function ma(e,n){ut(2048,8,e,n)}function Pa(e){yt.flags|=4;var n=yt.updateQueue;if(n===null)n=nc(),yt.updateQueue=n,n.events=[e];else{var s=n.events;s===null?n.events=[e]:s.push(e)}}function Is(e){var n=sn().memoizedState;return Pa({ref:n,nextImpl:e}),function(){if(($t&2)!==0)throw Error(l(440));return n.impl.apply(void 0,arguments)}}function xi(e,n){return ut(4,2,e,n)}function co(e,n){return ut(4,4,e,n)}function ig(e,n){if(typeof n=="function"){e=e();var s=n(e);return function(){typeof s=="function"?s():n(null)}}if(n!=null)return e=e(),n.current=e,function(){n.current=null}}function lg(e,n,s){s=s!=null?s.concat([e]):null,ut(4,4,ig.bind(null,n,e),s)}function fm(){}function og(e,n){var s=sn();n=n===void 0?null:n;var o=s.memoizedState;return n!==null&&Jo(n,o[1])?o[0]:(s.memoizedState=[e,n],e)}function cg(e,n){var s=sn();n=n===void 0?null:n;var o=s.memoizedState;if(n!==null&&Jo(n,o[1]))return o[0];if(o=e(),Tn){ct(!0);try{e()}finally{ct(!1)}}return s.memoizedState=[o,n],o}function mm(e,n,s){return s===void 0||(_s&1073741824)!==0&&(zt&261930)===0?e.memoizedState=n:(e.memoizedState=s,e=uv(),yt.lanes|=e,yl|=e,s)}function ug(e,n,s,o){return An(s,n)?s:cl.current!==null?(e=mm(e,s,o),An(e,n)||(On=!0),e):(_s&42)===0||(_s&1073741824)!==0&&(zt&261930)===0?(On=!0,e.memoizedState=s):(e=uv(),yt.lanes|=e,yl|=e,n)}function dg(e,n,s,o,f){var p=se.p;se.p=p!==0&&8>p?p:8;var S=I.T,R={};I.T=R,gm(e,!1,n,s);try{var V=f(),ue=I.S;if(ue!==null&&ue(R,V),V!==null&&typeof V=="object"&&typeof V.then=="function"){var we=hd(V,o);ou(e,n,we,gs(e))}else ou(e,n,o,gs(e))}catch(ke){ou(e,n,{then:function(){},status:"rejected",reason:ke},gs())}finally{se.p=p,S!==null&&R.types!==null&&(S.types=R.types),I.T=S}}function uS(){}function hm(e,n,s,o){if(e.tag!==5)throw Error(l(476));var f=fg(e).queue;dg(e,f,n,W,s===null?uS:function(){return mg(e),s(o)})}function fg(e){var n=e.memoizedState;if(n!==null)return n;n={memoizedState:W,baseState:W,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:or,lastRenderedState:W},next:null};var s={};return n.next={memoizedState:s,baseState:s,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:or,lastRenderedState:s},next:null},e.memoizedState=n,e=e.alternate,e!==null&&(e.memoizedState=n),n}function mg(e){var n=fg(e);n.next===null&&(n=e.alternate.memoizedState),ou(e,n.next.queue,{},gs())}function pm(){return In(ju)}function hg(){return sn().memoizedState}function pg(){return sn().memoizedState}function dS(e){for(var n=e.return;n!==null;){switch(n.tag){case 24:case 3:var s=gs();e=Er(s);var o=Es(n,e,s);o!==null&&(as(o,n,s),pi(o,n,s)),n={cache:Bo()},e.payload=n;return}n=n.return}}function fS(e,n,s){var o=gs();s={lane:o,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null},wd(e)?vg(n,s):(s=Kc(e,n,s,o),s!==null&&(as(s,e,o),yg(s,n,o)))}function gg(e,n,s){var o=gs();ou(e,n,s,o)}function ou(e,n,s,o){var f={lane:o,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null};if(wd(e))vg(n,f);else{var p=e.alternate;if(e.lanes===0&&(p===null||p.lanes===0)&&(p=n.lastRenderedReducer,p!==null))try{var S=n.lastRenderedState,R=p(S,s);if(f.hasEagerState=!0,f.eagerState=R,An(R,S))return Xn(e,n,f,0),Jt===null&&qn(),!1}catch{}if(s=Kc(e,n,f,o),s!==null)return as(s,e,o),yg(s,n,o),!0}return!1}function gm(e,n,s,o){if(o={lane:2,revertLane:Km(),gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null},wd(e)){if(n)throw Error(l(479))}else n=Kc(e,s,o,2),n!==null&&as(n,e,2)}function wd(e){var n=e.alternate;return e===yt||n!==null&&n===yt}function vg(e,n){dn=bi=!0;var s=e.pending;s===null?n.next=n:(n.next=s.next,s.next=n),e.pending=n}function yg(e,n,s){if((s&4194048)!==0){var o=n.lanes;o&=e.pendingLanes,s|=o,n.lanes=s,$(e,s)}}var cu={readContext:In,use:zn,useCallback:an,useContext:an,useEffect:an,useImperativeHandle:an,useLayoutEffect:an,useInsertionEffect:an,useMemo:an,useReducer:an,useRef:an,useState:an,useDebugValue:an,useDeferredValue:an,useTransition:an,useSyncExternalStore:an,useId:an,useHostTransitionStatus:an,useFormState:an,useActionState:an,useOptimistic:an,useMemoCache:an,useCacheRefresh:an};cu.useEffectEvent=an;var bg={readContext:In,use:zn,useCallback:function(e,n){return fa().memoizedState=[e,n===void 0?null:n],e},useContext:In,useEffect:pn,useImperativeHandle:function(e,n,s){s=s!=null?s.concat([e]):null,Lt(4194308,4,ig.bind(null,n,e),s)},useLayoutEffect:function(e,n){return Lt(4194308,4,e,n)},useInsertionEffect:function(e,n){Lt(4,2,e,n)},useMemo:function(e,n){var s=fa();n=n===void 0?null:n;var o=e();if(Tn){ct(!0);try{e()}finally{ct(!1)}}return s.memoizedState=[o,n],o},useReducer:function(e,n,s){var o=fa();if(s!==void 0){var f=s(n);if(Tn){ct(!0);try{s(n)}finally{ct(!1)}}}else f=n;return o.memoizedState=o.baseState=f,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:f},o.queue=e,e=e.dispatch=fS.bind(null,yt,e),[o.memoizedState,e]},useRef:function(e){var n=fa();return e={current:e},n.memoizedState=e},useState:function(e){e=lu(e);var n=e.queue,s=gg.bind(null,yt,n);return n.dispatch=s,[e.memoizedState,s]},useDebugValue:fm,useDeferredValue:function(e,n){var s=fa();return mm(s,e,n)},useTransition:function(){var e=lu(!1);return e=dg.bind(null,yt,e.queue,!0,!1),fa().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,n,s){var o=yt,f=fa();if(kt){if(s===void 0)throw Error(l(407));s=s()}else{if(s=n(),Jt===null)throw Error(l(349));(zt&127)!==0||oo(o,n,s)}f.memoizedState=s;var p={value:s,getSnapshot:n};return f.queue=p,pn(iu.bind(null,o,p,e),[e]),o.flags|=2048,Te(9,{destroy:void 0},hl.bind(null,o,p,s,n),null),s},useId:function(){var e=fa(),n=Jt.identifierPrefix;if(kt){var s=Ms,o=ua;s=(o&~(1<<32-ht(o)-1)).toString(32)+s,n="_"+n+"R_"+s,s=Nt++,0<s&&(n+="H"+s.toString(32)),n+="_"}else s=dl++,n="_"+n+"r_"+s.toString(32)+"_";return e.memoizedState=n},useHostTransitionStatus:pm,useFormState:P,useActionState:P,useOptimistic:function(e){var n=fa();n.memoizedState=n.baseState=e;var s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return n.queue=s,n=gm.bind(null,yt,!0,s),s.dispatch=n,[e,n]},useMemoCache:ml,useCacheRefresh:function(){return fa().memoizedState=dS.bind(null,yt)},useEffectEvent:function(e){var n=fa(),s={impl:e};return n.memoizedState=s,function(){if(($t&2)!==0)throw Error(l(440));return s.impl.apply(void 0,arguments)}}},vm={readContext:In,use:zn,useCallback:og,useContext:In,useEffect:ma,useImperativeHandle:lg,useInsertionEffect:xi,useLayoutEffect:co,useMemo:cg,useReducer:nu,useRef:Be,useState:function(){return nu(or)},useDebugValue:fm,useDeferredValue:function(e,n){var s=sn();return ug(s,Ut.memoizedState,e,n)},useTransition:function(){var e=nu(or)[0],n=sn().memoizedState;return[typeof e=="boolean"?e:lo(e),n]},useSyncExternalStore:ru,useId:hg,useHostTransitionStatus:pm,useFormState:D,useActionState:D,useOptimistic:function(e,n){var s=sn();return ac(s,Ut,e,n)},useMemoCache:ml,useCacheRefresh:pg};vm.useEffectEvent=Is;var xg={readContext:In,use:zn,useCallback:og,useContext:In,useEffect:ma,useImperativeHandle:lg,useInsertionEffect:xi,useLayoutEffect:co,useMemo:cg,useReducer:su,useRef:Be,useState:function(){return su(or)},useDebugValue:fm,useDeferredValue:function(e,n){var s=sn();return Ut===null?mm(s,e,n):ug(s,Ut.memoizedState,e,n)},useTransition:function(){var e=su(or)[0],n=sn().memoizedState;return[typeof e=="boolean"?e:lo(e),n]},useSyncExternalStore:ru,useId:hg,useHostTransitionStatus:pm,useFormState:Ne,useActionState:Ne,useOptimistic:function(e,n){var s=sn();return Ut!==null?ac(s,Ut,e,n):(s.baseState=e,[e,s.queue.dispatch])},useMemoCache:ml,useCacheRefresh:pg};xg.useEffectEvent=Is;function ym(e,n,s,o){n=e.memoizedState,s=s(o,n),s=s==null?n:b({},n,s),e.memoizedState=s,e.lanes===0&&(e.updateQueue.baseState=s)}var bm={enqueueSetState:function(e,n,s){e=e._reactInternals;var o=gs(),f=Er(o);f.payload=n,s!=null&&(f.callback=s),n=Es(e,f,o),n!==null&&(as(n,e,o),pi(n,e,o))},enqueueReplaceState:function(e,n,s){e=e._reactInternals;var o=gs(),f=Er(o);f.tag=1,f.payload=n,s!=null&&(f.callback=s),n=Es(e,f,o),n!==null&&(as(n,e,o),pi(n,e,o))},enqueueForceUpdate:function(e,n){e=e._reactInternals;var s=gs(),o=Er(s);o.tag=2,n!=null&&(o.callback=n),n=Es(e,o,s),n!==null&&(as(n,e,s),pi(n,e,s))}};function wg(e,n,s,o,f,p,S){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(o,p,S):n.prototype&&n.prototype.isPureReactComponent?!Un(s,o)||!Un(f,p):!0}function Sg(e,n,s,o){e=n.state,typeof n.componentWillReceiveProps=="function"&&n.componentWillReceiveProps(s,o),typeof n.UNSAFE_componentWillReceiveProps=="function"&&n.UNSAFE_componentWillReceiveProps(s,o),n.state!==e&&bm.enqueueReplaceState(n,n.state,null)}function uo(e,n){var s=n;if("ref"in n){s={};for(var o in n)o!=="ref"&&(s[o]=n[o])}if(e=e.defaultProps){s===n&&(s=b({},s));for(var f in e)s[f]===void 0&&(s[f]=e[f])}return s}function Cg(e){Sa(e)}function kg(e){console.error(e)}function jg(e){Sa(e)}function Sd(e,n){try{var s=e.onUncaughtError;s(n.value,{componentStack:n.stack})}catch(o){setTimeout(function(){throw o})}}function Ag(e,n,s){try{var o=e.onCaughtError;o(s.value,{componentStack:s.stack,errorBoundary:n.tag===1?n.stateNode:null})}catch(f){setTimeout(function(){throw f})}}function xm(e,n,s){return s=Er(s),s.tag=3,s.payload={element:null},s.callback=function(){Sd(e,n)},s}function Mg(e){return e=Er(e),e.tag=3,e}function Ng(e,n,s,o){var f=s.type.getDerivedStateFromError;if(typeof f=="function"){var p=o.value;e.payload=function(){return f(p)},e.callback=function(){Ag(n,s,o)}}var S=s.stateNode;S!==null&&typeof S.componentDidCatch=="function"&&(e.callback=function(){Ag(n,s,o),typeof f!="function"&&(bl===null?bl=new Set([this]):bl.add(this));var R=o.stack;this.componentDidCatch(o.value,{componentStack:R!==null?R:""})})}function mS(e,n,s,o,f){if(s.flags|=32768,o!==null&&typeof o=="object"&&typeof o.then=="function"){if(n=s.alternate,n!==null&&ir(n,s,f,!0),s=ka.current,s!==null){switch(s.tag){case 31:case 13:return Za===null?_d():s.alternate===null&&Sn===0&&(Sn=3),s.flags&=-257,s.flags|=65536,s.lanes=f,o===Xa?s.flags|=16384:(n=s.updateQueue,n===null?s.updateQueue=new Set([o]):n.add(o),Gm(e,o,f)),!1;case 22:return s.flags|=65536,o===Xa?s.flags|=16384:(n=s.updateQueue,n===null?(n={transitions:null,markerInstances:null,retryQueue:new Set([o])},s.updateQueue=n):(s=n.retryQueue,s===null?n.retryQueue=new Set([o]):s.add(o)),Gm(e,o,f)),!1}throw Error(l(435,s.tag))}return Gm(e,o,f),_d(),!1}if(kt)return n=ka.current,n!==null?((n.flags&65536)===0&&(n.flags|=256),n.flags|=65536,n.lanes=f,o!==el&&(e=Error(l(422),{cause:o}),oi(Ka(e,s)))):(o!==el&&(n=Error(l(423),{cause:o}),oi(Ka(n,s))),e=e.current.alternate,e.flags|=65536,f&=-f,e.lanes|=f,o=Ka(o,s),f=xm(e.stateNode,o,f),gi(e,f),Sn!==4&&(Sn=2)),!1;var p=Error(l(520),{cause:o});if(p=Ka(p,s),vu===null?vu=[p]:vu.push(p),Sn!==4&&(Sn=2),n===null)return!0;o=Ka(o,s),s=n;do{switch(s.tag){case 3:return s.flags|=65536,e=f&-f,s.lanes|=e,e=xm(s.stateNode,o,e),gi(s,e),!1;case 1:if(n=s.type,p=s.stateNode,(s.flags&128)===0&&(typeof n.getDerivedStateFromError=="function"||p!==null&&typeof p.componentDidCatch=="function"&&(bl===null||!bl.has(p))))return s.flags|=65536,f&=-f,s.lanes|=f,f=Mg(f),Ng(f,e,s,o),gi(s,f),!1}s=s.return}while(s!==null);return!1}var wm=Error(l(461)),On=!1;function ha(e,n,s,o){n.child=e===null?ll(n,null,s,o):Tr(n,e.child,s,o)}function Tg(e,n,s,o,f){s=s.render;var p=n.ref;if("ref"in o){var S={};for(var R in o)R!=="ref"&&(S[R]=o[R])}else S=o;return Fa(n),o=ec(e,n,s,S,p,f),R=tc(),e!==null&&!On?(io(e,n,f),wi(e,n,f)):(kt&&R&&Qc(n),n.flags|=1,ha(e,n,o,f),n.child)}function Rg(e,n,s,o,f){if(e===null){var p=s.type;return typeof p=="function"&&!Gn(p)&&p.defaultProps===void 0&&s.compare===null?(n.tag=15,n.type=p,Eg(e,n,p,o,f)):(e=tr(s.type,null,o,n,n.mode,f),e.ref=n.ref,e.return=n,n.child=e)}if(p=e.child,!Tm(e,f)){var S=p.memoizedProps;if(s=s.compare,s=s!==null?s:Un,s(S,o)&&e.ref===n.ref)return wi(e,n,f)}return n.flags|=1,e=_n(p,o),e.ref=n.ref,e.return=n,n.child=e}function Eg(e,n,s,o,f){if(e!==null){var p=e.memoizedProps;if(Un(p,o)&&e.ref===n.ref)if(On=!1,n.pendingProps=o=p,Tm(e,f))(e.flags&131072)!==0&&(On=!0);else return n.lanes=e.lanes,wi(e,n,f)}return Sm(e,n,s,o,f)}function Dg(e,n,s,o){var f=o.children,p=e!==null?e.memoizedState:null;if(e===null&&n.stateNode===null&&(n.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),o.mode==="hidden"){if((n.flags&128)!==0){if(p=p!==null?p.baseLanes|s:s,e!==null){for(o=n.child=e.child,f=0;o!==null;)f=f|o.lanes|o.childLanes,o=o.sibling;o=f&~p}else o=0,n.child=null;return Lg(e,n,p,s,o)}if((s&536870912)!==0)n.memoizedState={baseLanes:0,cachePool:null},e!==null&&rl(n,p!==null?p.cachePool:null),p!==null?Qo(n,p):Xo(),eu(n);else return o=n.lanes=536870912,Lg(e,n,p!==null?p.baseLanes|s:s,s,o)}else p!==null?(rl(n,p.cachePool),Qo(n,p),Ls(),n.memoizedState=null):(e!==null&&rl(n,null),Xo(),Ls());return ha(e,n,f,s),n.child}function uu(e,n){return e!==null&&e.tag===22||n.stateNode!==null||(n.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),n.sibling}function Lg(e,n,s,o,f){var p=to();return p=p===null?null:{parent:Zt._currentValue,pool:p},n.memoizedState={baseLanes:s,cachePool:p},e!==null&&rl(n,null),Xo(),eu(n),e!==null&&ir(e,n,o,!0),n.childLanes=f,null}function Cd(e,n){return n=jd({mode:n.mode,children:n.children},e.mode),n.ref=e.ref,e.child=n,n.return=e,n}function _g(e,n,s){return Tr(n,e.child,null,s),e=Cd(n,n.pendingProps),e.flags|=2,da(n),n.memoizedState=null,e}function hS(e,n,s){var o=n.pendingProps,f=(n.flags&128)!==0;if(n.flags&=-129,e===null){if(kt){if(o.mode==="hidden")return e=Cd(n,o),n.lanes=536870912,uu(null,e);if(ul(n),(e=Kt)?(e=Vv(e,Nn),e=e!==null&&e.data==="&"?e:null,e!==null&&(n.memoizedState={dehydrated:e,treeContext:yr!==null?{id:ua,overflow:Ms}:null,retryLane:536870912,hydrationErrors:null},s=Ql(e),s.return=n,n.child=s,Vn=n,Kt=null)):e=null,e===null)throw Oa(n);return n.lanes=536870912,null}return Cd(n,o)}var p=e.memoizedState;if(p!==null){var S=p.dehydrated;if(ul(n),f)if(n.flags&256)n.flags&=-257,n=_g(e,n,s);else if(n.memoizedState!==null)n.child=e.child,n.flags|=128,n=null;else throw Error(l(558));else if(On||ir(e,n,s,!1),f=(s&e.childLanes)!==0,On||f){if(o=Jt,o!==null&&(S=Xe(o,s),S!==0&&S!==p.retryLane))throw p.retryLane=S,gr(e,S),as(o,e,S),wm;_d(),n=_g(e,n,s)}else e=p.treeContext,Kt=zs(S.nextSibling),Vn=n,kt=!0,sr=null,Nn=!1,e!==null&&Zl(n,e),n=Cd(n,o),n.flags|=4096;return n}return e=_n(e.child,{mode:o.mode,children:o.children}),e.ref=n.ref,n.child=e,e.return=n,e}function kd(e,n){var s=n.ref;if(s===null)e!==null&&e.ref!==null&&(n.flags|=4194816);else{if(typeof s!="function"&&typeof s!="object")throw Error(l(284));(e===null||e.ref!==s)&&(n.flags|=4194816)}}function Sm(e,n,s,o,f){return Fa(n),s=ec(e,n,s,o,void 0,f),o=tc(),e!==null&&!On?(io(e,n,f),wi(e,n,f)):(kt&&o&&Qc(n),n.flags|=1,ha(e,n,s,f),n.child)}function Ig(e,n,s,o,f,p){return Fa(n),n.updateQueue=null,s=ro(n,o,s,f),fl(e),o=tc(),e!==null&&!On?(io(e,n,p),wi(e,n,p)):(kt&&o&&Qc(n),n.flags|=1,ha(e,n,s,p),n.child)}function zg(e,n,s,o,f){if(Fa(n),n.stateNode===null){var p=Zn,S=s.contextType;typeof S=="object"&&S!==null&&(p=In(S)),p=new s(o,p),n.memoizedState=p.state!==null&&p.state!==void 0?p.state:null,p.updater=bm,n.stateNode=p,p._reactInternals=n,p=n.stateNode,p.props=o,p.state=n.memoizedState,p.refs={},Zc(n),S=s.contextType,p.context=typeof S=="object"&&S!==null?In(S):Zn,p.state=n.memoizedState,S=s.getDerivedStateFromProps,typeof S=="function"&&(ym(n,s,S,o),p.state=n.memoizedState),typeof s.getDerivedStateFromProps=="function"||typeof p.getSnapshotBeforeUpdate=="function"||typeof p.UNSAFE_componentWillMount!="function"&&typeof p.componentWillMount!="function"||(S=p.state,typeof p.componentWillMount=="function"&&p.componentWillMount(),typeof p.UNSAFE_componentWillMount=="function"&&p.UNSAFE_componentWillMount(),S!==p.state&&bm.enqueueReplaceState(p,p.state,null),ao(n,o,p,f),vi(),p.state=n.memoizedState),typeof p.componentDidMount=="function"&&(n.flags|=4194308),o=!0}else if(e===null){p=n.stateNode;var R=n.memoizedProps,V=uo(s,R);p.props=V;var ue=p.context,we=s.contextType;S=Zn,typeof we=="object"&&we!==null&&(S=In(we));var ke=s.getDerivedStateFromProps;we=typeof ke=="function"||typeof p.getSnapshotBeforeUpdate=="function",R=n.pendingProps!==R,we||typeof p.UNSAFE_componentWillReceiveProps!="function"&&typeof p.componentWillReceiveProps!="function"||(R||ue!==S)&&Sg(n,p,o,S),Rr=!1;var fe=n.memoizedState;p.state=fe,ao(n,o,p,f),vi(),ue=n.memoizedState,R||fe!==ue||Rr?(typeof ke=="function"&&(ym(n,s,ke,o),ue=n.memoizedState),(V=Rr||wg(n,s,V,o,fe,ue,S))?(we||typeof p.UNSAFE_componentWillMount!="function"&&typeof p.componentWillMount!="function"||(typeof p.componentWillMount=="function"&&p.componentWillMount(),typeof p.UNSAFE_componentWillMount=="function"&&p.UNSAFE_componentWillMount()),typeof p.componentDidMount=="function"&&(n.flags|=4194308)):(typeof p.componentDidMount=="function"&&(n.flags|=4194308),n.memoizedProps=o,n.memoizedState=ue),p.props=o,p.state=ue,p.context=S,o=V):(typeof p.componentDidMount=="function"&&(n.flags|=4194308),o=!1)}else{p=n.stateNode,Jc(e,n),S=n.memoizedProps,we=uo(s,S),p.props=we,ke=n.pendingProps,fe=p.context,ue=s.contextType,V=Zn,typeof ue=="object"&&ue!==null&&(V=In(ue)),R=s.getDerivedStateFromProps,(ue=typeof R=="function"||typeof p.getSnapshotBeforeUpdate=="function")||typeof p.UNSAFE_componentWillReceiveProps!="function"&&typeof p.componentWillReceiveProps!="function"||(S!==ke||fe!==V)&&Sg(n,p,o,V),Rr=!1,fe=n.memoizedState,p.state=fe,ao(n,o,p,f),vi();var ge=n.memoizedState;S!==ke||fe!==ge||Rr||e!==null&&e.dependencies!==null&&di(e.dependencies)?(typeof R=="function"&&(ym(n,s,R,o),ge=n.memoizedState),(we=Rr||wg(n,s,we,o,fe,ge,V)||e!==null&&e.dependencies!==null&&di(e.dependencies))?(ue||typeof p.UNSAFE_componentWillUpdate!="function"&&typeof p.componentWillUpdate!="function"||(typeof p.componentWillUpdate=="function"&&p.componentWillUpdate(o,ge,V),typeof p.UNSAFE_componentWillUpdate=="function"&&p.UNSAFE_componentWillUpdate(o,ge,V)),typeof p.componentDidUpdate=="function"&&(n.flags|=4),typeof p.getSnapshotBeforeUpdate=="function"&&(n.flags|=1024)):(typeof p.componentDidUpdate!="function"||S===e.memoizedProps&&fe===e.memoizedState||(n.flags|=4),typeof p.getSnapshotBeforeUpdate!="function"||S===e.memoizedProps&&fe===e.memoizedState||(n.flags|=1024),n.memoizedProps=o,n.memoizedState=ge),p.props=o,p.state=ge,p.context=V,o=we):(typeof p.componentDidUpdate!="function"||S===e.memoizedProps&&fe===e.memoizedState||(n.flags|=4),typeof p.getSnapshotBeforeUpdate!="function"||S===e.memoizedProps&&fe===e.memoizedState||(n.flags|=1024),o=!1)}return p=o,kd(e,n),o=(n.flags&128)!==0,p||o?(p=n.stateNode,s=o&&typeof s.getDerivedStateFromError!="function"?null:p.render(),n.flags|=1,e!==null&&o?(n.child=Tr(n,e.child,null,f),n.child=Tr(n,null,s,f)):ha(e,n,s,f),n.memoizedState=p.state,e=n.child):e=wi(e,n,f),e}function Og(e,n,s,o){return xr(),n.flags|=256,ha(e,n,s,o),n.child}var Cm={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function km(e){return{baseLanes:e,cachePool:Go()}}function jm(e,n,s){return e=e!==null?e.childLanes&~s:0,n&&(e|=ps),e}function Hg(e,n,s){var o=n.pendingProps,f=!1,p=(n.flags&128)!==0,S;if((S=p)||(S=e!==null&&e.memoizedState===null?!1:(Me.current&2)!==0),S&&(f=!0,n.flags&=-129),S=(n.flags&32)!==0,n.flags&=-33,e===null){if(kt){if(f?Ds(n):Ls(),(e=Kt)?(e=Vv(e,Nn),e=e!==null&&e.data!=="&"?e:null,e!==null&&(n.memoizedState={dehydrated:e,treeContext:yr!==null?{id:ua,overflow:Ms}:null,retryLane:536870912,hydrationErrors:null},s=Ql(e),s.return=n,n.child=s,Vn=n,Kt=null)):e=null,e===null)throw Oa(n);return lh(e)?n.lanes=32:n.lanes=536870912,null}var R=o.children;return o=o.fallback,f?(Ls(),f=n.mode,R=jd({mode:"hidden",children:R},f),o=Ca(o,f,s,null),R.return=n,o.return=n,R.sibling=o,n.child=R,o=n.child,o.memoizedState=km(s),o.childLanes=jm(e,S,s),n.memoizedState=Cm,uu(null,o)):(Ds(n),Am(n,R))}var V=e.memoizedState;if(V!==null&&(R=V.dehydrated,R!==null)){if(p)n.flags&256?(Ds(n),n.flags&=-257,n=Mm(e,n,s)):n.memoizedState!==null?(Ls(),n.child=e.child,n.flags|=128,n=null):(Ls(),R=o.fallback,f=n.mode,o=jd({mode:"visible",children:o.children},f),R=Ca(R,f,s,null),R.flags|=2,o.return=n,R.return=n,o.sibling=R,n.child=o,Tr(n,e.child,null,s),o=n.child,o.memoizedState=km(s),o.childLanes=jm(e,S,s),n.memoizedState=Cm,n=uu(null,o));else if(Ds(n),lh(R)){if(S=R.nextSibling&&R.nextSibling.dataset,S)var ue=S.dgst;S=ue,o=Error(l(419)),o.stack="",o.digest=S,oi({value:o,source:null,stack:null}),n=Mm(e,n,s)}else if(On||ir(e,n,s,!1),S=(s&e.childLanes)!==0,On||S){if(S=Jt,S!==null&&(o=Xe(S,s),o!==0&&o!==V.retryLane))throw V.retryLane=o,gr(e,o),as(S,e,o),wm;ih(R)||_d(),n=Mm(e,n,s)}else ih(R)?(n.flags|=192,n.child=e.child,n=null):(e=V.treeContext,Kt=zs(R.nextSibling),Vn=n,kt=!0,sr=null,Nn=!1,e!==null&&Zl(n,e),n=Am(n,o.children),n.flags|=4096);return n}return f?(Ls(),R=o.fallback,f=n.mode,V=e.child,ue=V.sibling,o=_n(V,{mode:"hidden",children:o.children}),o.subtreeFlags=V.subtreeFlags&65011712,ue!==null?R=_n(ue,R):(R=Ca(R,f,s,null),R.flags|=2),R.return=n,o.return=n,o.sibling=R,n.child=o,uu(null,o),o=n.child,R=e.child.memoizedState,R===null?R=km(s):(f=R.cachePool,f!==null?(V=Zt._currentValue,f=f.parent!==V?{parent:V,pool:V}:f):f=Go(),R={baseLanes:R.baseLanes|s,cachePool:f}),o.memoizedState=R,o.childLanes=jm(e,S,s),n.memoizedState=Cm,uu(e.child,o)):(Ds(n),s=e.child,e=s.sibling,s=_n(s,{mode:"visible",children:o.children}),s.return=n,s.sibling=null,e!==null&&(S=n.deletions,S===null?(n.deletions=[e],n.flags|=16):S.push(e)),n.child=s,n.memoizedState=null,s)}function Am(e,n){return n=jd({mode:"visible",children:n},e.mode),n.return=e,e.child=n}function jd(e,n){return e=ca(22,e,null,n),e.lanes=0,e}function Mm(e,n,s){return Tr(n,e.child,null,s),e=Am(n,n.pendingProps.children),e.flags|=2,n.memoizedState=null,e}function Fg(e,n,s){e.lanes|=n;var o=e.alternate;o!==null&&(o.lanes|=n),Jl(e.return,n,s)}function Nm(e,n,s,o,f,p){var S=e.memoizedState;S===null?e.memoizedState={isBackwards:n,rendering:null,renderingStartTime:0,last:o,tail:s,tailMode:f,treeForkCount:p}:(S.isBackwards=n,S.rendering=null,S.renderingStartTime=0,S.last=o,S.tail=s,S.tailMode=f,S.treeForkCount=p)}function Pg(e,n,s){var o=n.pendingProps,f=o.revealOrder,p=o.tail;o=o.children;var S=Me.current,R=(S&2)!==0;if(R?(S=S&1|2,n.flags|=128):S&=1,be(Me,S),ha(e,n,o,s),o=kt?As:0,!R&&e!==null&&(e.flags&128)!==0)e:for(e=n.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&Fg(e,s,n);else if(e.tag===19)Fg(e,s,n);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===n)break e;for(;e.sibling===null;){if(e.return===null||e.return===n)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}switch(f){case"forwards":for(s=n.child,f=null;s!==null;)e=s.alternate,e!==null&&yi(e)===null&&(f=s),s=s.sibling;s=f,s===null?(f=n.child,n.child=null):(f=s.sibling,s.sibling=null),Nm(n,!1,f,s,p,o);break;case"backwards":case"unstable_legacy-backwards":for(s=null,f=n.child,n.child=null;f!==null;){if(e=f.alternate,e!==null&&yi(e)===null){n.child=f;break}e=f.sibling,f.sibling=s,s=f,f=e}Nm(n,!0,s,null,p,o);break;case"together":Nm(n,!1,null,null,void 0,o);break;default:n.memoizedState=null}return n.child}function wi(e,n,s){if(e!==null&&(n.dependencies=e.dependencies),yl|=n.lanes,(s&n.childLanes)===0)if(e!==null){if(ir(e,n,s,!1),(s&n.childLanes)===0)return null}else return null;if(e!==null&&n.child!==e.child)throw Error(l(153));if(n.child!==null){for(e=n.child,s=_n(e,e.pendingProps),n.child=s,s.return=n;e.sibling!==null;)e=e.sibling,s=s.sibling=_n(e,e.pendingProps),s.return=n;s.sibling=null}return n.child}function Tm(e,n){return(e.lanes&n)!==0?!0:(e=e.dependencies,!!(e!==null&&di(e)))}function pS(e,n,s){switch(n.tag){case 3:Re(n,n.stateNode.containerInfo),rr(n,Zt,e.memoizedState.cache),xr();break;case 27:case 5:te(n);break;case 4:Re(n,n.stateNode.containerInfo);break;case 10:rr(n,n.type,n.memoizedProps.value);break;case 31:if(n.memoizedState!==null)return n.flags|=128,ul(n),null;break;case 13:var o=n.memoizedState;if(o!==null)return o.dehydrated!==null?(Ds(n),n.flags|=128,null):(s&n.child.childLanes)!==0?Hg(e,n,s):(Ds(n),e=wi(e,n,s),e!==null?e.sibling:null);Ds(n);break;case 19:var f=(e.flags&128)!==0;if(o=(s&n.childLanes)!==0,o||(ir(e,n,s,!1),o=(s&n.childLanes)!==0),f){if(o)return Pg(e,n,s);n.flags|=128}if(f=n.memoizedState,f!==null&&(f.rendering=null,f.tail=null,f.lastEffect=null),be(Me,Me.current),o)break;return null;case 22:return n.lanes=0,Dg(e,n,s,n.pendingProps);case 24:rr(n,Zt,e.memoizedState.cache)}return wi(e,n,s)}function $g(e,n,s){if(e!==null)if(e.memoizedProps!==n.pendingProps)On=!0;else{if(!Tm(e,s)&&(n.flags&128)===0)return On=!1,pS(e,n,s);On=(e.flags&131072)!==0}else On=!1,kt&&(n.flags&1048576)!==0&&fd(n,As,n.index);switch(n.lanes=0,n.tag){case 16:e:{var o=n.pendingProps;if(e=Ar(n.elementType),n.type=e,typeof e=="function")Gn(e)?(o=uo(e,o),n.tag=1,n=zg(null,n,e,o,s)):(n.tag=0,n=Sm(null,n,e,o,s));else{if(e!=null){var f=e.$$typeof;if(f===z){n.tag=11,n=Tg(null,n,e,o,s);break e}else if(f===_){n.tag=14,n=Rg(null,n,e,o,s);break e}}throw n=me(e)||e,Error(l(306,n,""))}}return n;case 0:return Sm(e,n,n.type,n.pendingProps,s);case 1:return o=n.type,f=uo(o,n.pendingProps),zg(e,n,o,f,s);case 3:e:{if(Re(n,n.stateNode.containerInfo),e===null)throw Error(l(387));o=n.pendingProps;var p=n.memoizedState;f=p.element,Jc(e,n),ao(n,o,null,s);var S=n.memoizedState;if(o=S.cache,rr(n,Zt,o),o!==p.cache&&al(n,[Zt],s,!0),vi(),o=S.element,p.isDehydrated)if(p={element:o,isDehydrated:!1,cache:S.cache},n.updateQueue.baseState=p,n.memoizedState=p,n.flags&256){n=Og(e,n,o,s);break e}else if(o!==f){f=Ka(Error(l(424)),n),oi(f),n=Og(e,n,o,s);break e}else for(e=n.stateNode.containerInfo,e.nodeType===9?e=e.body:e=e.nodeName==="HTML"?e.ownerDocument.body:e,Kt=zs(e.firstChild),Vn=n,kt=!0,sr=null,Nn=!0,s=ll(n,null,o,s),n.child=s;s;)s.flags=s.flags&-3|4096,s=s.sibling;else{if(xr(),o===f){n=wi(e,n,s);break e}ha(e,n,o,s)}n=n.child}return n;case 26:return kd(e,n),e===null?(s=Zv(n.type,null,n.pendingProps,null))?n.memoizedState=s:kt||(s=n.type,e=n.pendingProps,o=$d(ee.current).createElement(s),o[re]=n,o[Ee]=e,pa(o,s,e),At(o),n.stateNode=o):n.memoizedState=Zv(n.type,e.memoizedProps,n.pendingProps,e.memoizedState),null;case 27:return te(n),e===null&&kt&&(o=n.stateNode=Yv(n.type,n.pendingProps,ee.current),Vn=n,Nn=!0,f=Kt,Cl(n.type)?(oh=f,Kt=zs(o.firstChild)):Kt=f),ha(e,n,n.pendingProps.children,s),kd(e,n),e===null&&(n.flags|=4194304),n.child;case 5:return e===null&&kt&&((f=o=Kt)&&(o=GS(o,n.type,n.pendingProps,Nn),o!==null?(n.stateNode=o,Vn=n,Kt=zs(o.firstChild),Nn=!1,f=!0):f=!1),f||Oa(n)),te(n),f=n.type,p=n.pendingProps,S=e!==null?e.memoizedProps:null,o=p.children,ah(f,p)?o=null:S!==null&&ah(f,S)&&(n.flags|=32),n.memoizedState!==null&&(f=ec(e,n,dm,null,null,s),ju._currentValue=f),kd(e,n),ha(e,n,o,s),n.child;case 6:return e===null&&kt&&((e=s=Kt)&&(s=VS(s,n.pendingProps,Nn),s!==null?(n.stateNode=s,Vn=n,Kt=null,e=!0):e=!1),e||Oa(n)),null;case 13:return Hg(e,n,s);case 4:return Re(n,n.stateNode.containerInfo),o=n.pendingProps,e===null?n.child=Tr(n,null,o,s):ha(e,n,o,s),n.child;case 11:return Tg(e,n,n.type,n.pendingProps,s);case 7:return ha(e,n,n.pendingProps,s),n.child;case 8:return ha(e,n,n.pendingProps.children,s),n.child;case 12:return ha(e,n,n.pendingProps.children,s),n.child;case 10:return o=n.pendingProps,rr(n,n.type,o.value),ha(e,n,o.children,s),n.child;case 9:return f=n.type._context,o=n.pendingProps.children,Fa(n),f=In(f),o=o(f),n.flags|=1,ha(e,n,o,s),n.child;case 14:return Rg(e,n,n.type,n.pendingProps,s);case 15:return Eg(e,n,n.type,n.pendingProps,s);case 19:return Pg(e,n,s);case 31:return hS(e,n,s);case 22:return Dg(e,n,s,n.pendingProps);case 24:return Fa(n),o=In(Zt),e===null?(f=to(),f===null&&(f=Jt,p=Bo(),f.pooledCache=p,p.refCount++,p!==null&&(f.pooledCacheLanes|=s),f=p),n.memoizedState={parent:o,cache:f},Zc(n),rr(n,Zt,f)):((e.lanes&s)!==0&&(Jc(e,n),ao(n,null,null,s),vi()),f=e.memoizedState,p=n.memoizedState,f.parent!==o?(f={parent:o,cache:o},n.memoizedState=f,n.lanes===0&&(n.memoizedState=n.updateQueue.baseState=f),rr(n,Zt,o)):(o=p.cache,rr(n,Zt,o),o!==f.cache&&al(n,[Zt],s,!0))),ha(e,n,n.pendingProps.children,s),n.child;case 29:throw n.pendingProps}throw Error(l(156,n.tag))}function Si(e){e.flags|=4}function Rm(e,n,s,o,f){if((n=(e.mode&32)!==0)&&(n=!1),n){if(e.flags|=16777216,(f&335544128)===f)if(e.stateNode.complete)e.flags|=8192;else if(hv())e.flags|=8192;else throw hn=Xa,Vo}else e.flags&=-16777217}function Bg(e,n){if(n.type!=="stylesheet"||(n.state.loading&4)!==0)e.flags&=-16777217;else if(e.flags|=16777216,!ay(n))if(hv())e.flags|=8192;else throw hn=Xa,Vo}function Ad(e,n){n!==null&&(e.flags|=4),e.flags&16384&&(n=e.tag!==22?Da():536870912,e.lanes|=n,oc|=n)}function du(e,n){if(!kt)switch(e.tailMode){case"hidden":n=e.tail;for(var s=null;n!==null;)n.alternate!==null&&(s=n),n=n.sibling;s===null?e.tail=null:s.sibling=null;break;case"collapsed":s=e.tail;for(var o=null;s!==null;)s.alternate!==null&&(o=s),s=s.sibling;o===null?n||e.tail===null?e.tail=null:e.tail.sibling=null:o.sibling=null}}function rn(e){var n=e.alternate!==null&&e.alternate.child===e.child,s=0,o=0;if(n)for(var f=e.child;f!==null;)s|=f.lanes|f.childLanes,o|=f.subtreeFlags&65011712,o|=f.flags&65011712,f.return=e,f=f.sibling;else for(f=e.child;f!==null;)s|=f.lanes|f.childLanes,o|=f.subtreeFlags,o|=f.flags,f.return=e,f=f.sibling;return e.subtreeFlags|=o,e.childLanes=s,n}function gS(e,n,s){var o=n.pendingProps;switch(Po(n),n.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return rn(n),null;case 1:return rn(n),null;case 3:return s=n.stateNode,o=null,e!==null&&(o=e.memoizedState.cache),n.memoizedState.cache!==o&&(n.flags|=2048),Ha(Zt),He(),s.pendingContext&&(s.context=s.pendingContext,s.pendingContext=null),(e===null||e.child===null)&&(tl(n)?Si(n):e===null||e.memoizedState.isDehydrated&&(n.flags&256)===0||(n.flags|=1024,nl())),rn(n),null;case 26:var f=n.type,p=n.memoizedState;return e===null?(Si(n),p!==null?(rn(n),Bg(n,p)):(rn(n),Rm(n,f,null,o,s))):p?p!==e.memoizedState?(Si(n),rn(n),Bg(n,p)):(rn(n),n.flags&=-16777217):(e=e.memoizedProps,e!==o&&Si(n),rn(n),Rm(n,f,e,o,s)),null;case 27:if(Ue(n),s=ee.current,f=n.type,e!==null&&n.stateNode!=null)e.memoizedProps!==o&&Si(n);else{if(!o){if(n.stateNode===null)throw Error(l(166));return rn(n),null}e=he.current,tl(n)?br(n):(e=Yv(f,o,s),n.stateNode=e,Si(n))}return rn(n),null;case 5:if(Ue(n),f=n.type,e!==null&&n.stateNode!=null)e.memoizedProps!==o&&Si(n);else{if(!o){if(n.stateNode===null)throw Error(l(166));return rn(n),null}if(p=he.current,tl(n))br(n);else{var S=$d(ee.current);switch(p){case 1:p=S.createElementNS("http://www.w3.org/2000/svg",f);break;case 2:p=S.createElementNS("http://www.w3.org/1998/Math/MathML",f);break;default:switch(f){case"svg":p=S.createElementNS("http://www.w3.org/2000/svg",f);break;case"math":p=S.createElementNS("http://www.w3.org/1998/Math/MathML",f);break;case"script":p=S.createElement("div"),p.innerHTML="<script><\/script>",p=p.removeChild(p.firstChild);break;case"select":p=typeof o.is=="string"?S.createElement("select",{is:o.is}):S.createElement("select"),o.multiple?p.multiple=!0:o.size&&(p.size=o.size);break;default:p=typeof o.is=="string"?S.createElement(f,{is:o.is}):S.createElement(f)}}p[re]=n,p[Ee]=o;e:for(S=n.child;S!==null;){if(S.tag===5||S.tag===6)p.appendChild(S.stateNode);else if(S.tag!==4&&S.tag!==27&&S.child!==null){S.child.return=S,S=S.child;continue}if(S===n)break e;for(;S.sibling===null;){if(S.return===null||S.return===n)break e;S=S.return}S.sibling.return=S.return,S=S.sibling}n.stateNode=p;e:switch(pa(p,f,o),f){case"button":case"input":case"select":case"textarea":o=!!o.autoFocus;break e;case"img":o=!0;break e;default:o=!1}o&&Si(n)}}return rn(n),Rm(n,n.type,e===null?null:e.memoizedProps,n.pendingProps,s),null;case 6:if(e&&n.stateNode!=null)e.memoizedProps!==o&&Si(n);else{if(typeof o!="string"&&n.stateNode===null)throw Error(l(166));if(e=ee.current,tl(n)){if(e=n.stateNode,s=n.memoizedProps,o=null,f=Vn,f!==null)switch(f.tag){case 27:case 5:o=f.memoizedProps}e[re]=n,e=!!(e.nodeValue===s||o!==null&&o.suppressHydrationWarning===!0||Hv(e.nodeValue,s)),e||Oa(n,!0)}else e=$d(e).createTextNode(o),e[re]=n,n.stateNode=e}return rn(n),null;case 31:if(s=n.memoizedState,e===null||e.memoizedState!==null){if(o=tl(n),s!==null){if(e===null){if(!o)throw Error(l(318));if(e=n.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(l(557));e[re]=n}else xr(),(n.flags&128)===0&&(n.memoizedState=null),n.flags|=4;rn(n),e=!1}else s=nl(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=s),e=!0;if(!e)return n.flags&256?(da(n),n):(da(n),null);if((n.flags&128)!==0)throw Error(l(558))}return rn(n),null;case 13:if(o=n.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(f=tl(n),o!==null&&o.dehydrated!==null){if(e===null){if(!f)throw Error(l(318));if(f=n.memoizedState,f=f!==null?f.dehydrated:null,!f)throw Error(l(317));f[re]=n}else xr(),(n.flags&128)===0&&(n.memoizedState=null),n.flags|=4;rn(n),f=!1}else f=nl(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=f),f=!0;if(!f)return n.flags&256?(da(n),n):(da(n),null)}return da(n),(n.flags&128)!==0?(n.lanes=s,n):(s=o!==null,e=e!==null&&e.memoizedState!==null,s&&(o=n.child,f=null,o.alternate!==null&&o.alternate.memoizedState!==null&&o.alternate.memoizedState.cachePool!==null&&(f=o.alternate.memoizedState.cachePool.pool),p=null,o.memoizedState!==null&&o.memoizedState.cachePool!==null&&(p=o.memoizedState.cachePool.pool),p!==f&&(o.flags|=2048)),s!==e&&s&&(n.child.flags|=8192),Ad(n,n.updateQueue),rn(n),null);case 4:return He(),e===null&&Zm(n.stateNode.containerInfo),rn(n),null;case 10:return Ha(n.type),rn(n),null;case 19:if(Q(Me),o=n.memoizedState,o===null)return rn(n),null;if(f=(n.flags&128)!==0,p=o.rendering,p===null)if(f)du(o,!1);else{if(Sn!==0||e!==null&&(e.flags&128)!==0)for(e=n.child;e!==null;){if(p=yi(e),p!==null){for(n.flags|=128,du(o,!1),e=p.updateQueue,n.updateQueue=e,Ad(n,e),n.subtreeFlags=0,e=s,s=n.child;s!==null;)Yl(s,e),s=s.sibling;return be(Me,Me.current&1|2),kt&&Ns(n,o.treeForkCount),n.child}e=e.sibling}o.tail!==null&&je()>Ed&&(n.flags|=128,f=!0,du(o,!1),n.lanes=4194304)}else{if(!f)if(e=yi(p),e!==null){if(n.flags|=128,f=!0,e=e.updateQueue,n.updateQueue=e,Ad(n,e),du(o,!0),o.tail===null&&o.tailMode==="hidden"&&!p.alternate&&!kt)return rn(n),null}else 2*je()-o.renderingStartTime>Ed&&s!==536870912&&(n.flags|=128,f=!0,du(o,!1),n.lanes=4194304);o.isBackwards?(p.sibling=n.child,n.child=p):(e=o.last,e!==null?e.sibling=p:n.child=p,o.last=p)}return o.tail!==null?(e=o.tail,o.rendering=e,o.tail=e.sibling,o.renderingStartTime=je(),e.sibling=null,s=Me.current,be(Me,f?s&1|2:s&1),kt&&Ns(n,o.treeForkCount),e):(rn(n),null);case 22:case 23:return da(n),Zo(),o=n.memoizedState!==null,e!==null?e.memoizedState!==null!==o&&(n.flags|=8192):o&&(n.flags|=8192),o?(s&536870912)!==0&&(n.flags&128)===0&&(rn(n),n.subtreeFlags&6&&(n.flags|=8192)):rn(n),s=n.updateQueue,s!==null&&Ad(n,s.retryQueue),s=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(s=e.memoizedState.cachePool.pool),o=null,n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(o=n.memoizedState.cachePool.pool),o!==s&&(n.flags|=2048),e!==null&&Q(Cr),null;case 24:return s=null,e!==null&&(s=e.memoizedState.cache),n.memoizedState.cache!==s&&(n.flags|=2048),Ha(Zt),rn(n),null;case 25:return null;case 30:return null}throw Error(l(156,n.tag))}function vS(e,n){switch(Po(n),n.tag){case 1:return e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 3:return Ha(Zt),He(),e=n.flags,(e&65536)!==0&&(e&128)===0?(n.flags=e&-65537|128,n):null;case 26:case 27:case 5:return Ue(n),null;case 31:if(n.memoizedState!==null){if(da(n),n.alternate===null)throw Error(l(340));xr()}return e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 13:if(da(n),e=n.memoizedState,e!==null&&e.dehydrated!==null){if(n.alternate===null)throw Error(l(340));xr()}return e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 19:return Q(Me),null;case 4:return He(),null;case 10:return Ha(n.type),null;case 22:case 23:return da(n),Zo(),e!==null&&Q(Cr),e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 24:return Ha(Zt),null;case 25:return null;default:return null}}function Ug(e,n){switch(Po(n),n.tag){case 3:Ha(Zt),He();break;case 26:case 27:case 5:Ue(n);break;case 4:He();break;case 31:n.memoizedState!==null&&da(n);break;case 13:da(n);break;case 19:Q(Me);break;case 10:Ha(n.type);break;case 22:case 23:da(n),Zo(),e!==null&&Q(Cr);break;case 24:Ha(Zt)}}function fu(e,n){try{var s=n.updateQueue,o=s!==null?s.lastEffect:null;if(o!==null){var f=o.next;s=f;do{if((s.tag&e)===e){o=void 0;var p=s.create,S=s.inst;o=p(),S.destroy=o}s=s.next}while(s!==f)}}catch(R){Gt(n,n.return,R)}}function gl(e,n,s){try{var o=n.updateQueue,f=o!==null?o.lastEffect:null;if(f!==null){var p=f.next;o=p;do{if((o.tag&e)===e){var S=o.inst,R=S.destroy;if(R!==void 0){S.destroy=void 0,f=n;var V=s,ue=R;try{ue()}catch(we){Gt(f,V,we)}}}o=o.next}while(o!==p)}}catch(we){Gt(n,n.return,we)}}function qg(e){var n=e.updateQueue;if(n!==null){var s=e.stateNode;try{vd(n,s)}catch(o){Gt(e,e.return,o)}}}function Gg(e,n,s){s.props=uo(e.type,e.memoizedProps),s.state=e.memoizedState;try{s.componentWillUnmount()}catch(o){Gt(e,n,o)}}function mu(e,n){try{var s=e.ref;if(s!==null){switch(e.tag){case 26:case 27:case 5:var o=e.stateNode;break;case 30:o=e.stateNode;break;default:o=e.stateNode}typeof s=="function"?e.refCleanup=s(o):s.current=o}}catch(f){Gt(e,n,f)}}function Lr(e,n){var s=e.ref,o=e.refCleanup;if(s!==null)if(typeof o=="function")try{o()}catch(f){Gt(e,n,f)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof s=="function")try{s(null)}catch(f){Gt(e,n,f)}else s.current=null}function Vg(e){var n=e.type,s=e.memoizedProps,o=e.stateNode;try{e:switch(n){case"button":case"input":case"select":case"textarea":s.autoFocus&&o.focus();break e;case"img":s.src?o.src=s.src:s.srcSet&&(o.srcset=s.srcSet)}}catch(f){Gt(e,e.return,f)}}function Em(e,n,s){try{var o=e.stateNode;FS(o,e.type,s,n),o[Ee]=n}catch(f){Gt(e,e.return,f)}}function Wg(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&Cl(e.type)||e.tag===4}function Dm(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Wg(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&&Cl(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 Lm(e,n,s){var o=e.tag;if(o===5||o===6)e=e.stateNode,n?(s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s).insertBefore(e,n):(n=s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s,n.appendChild(e),s=s._reactRootContainer,s!=null||n.onclick!==null||(n.onclick=qa));else if(o!==4&&(o===27&&Cl(e.type)&&(s=e.stateNode,n=null),e=e.child,e!==null))for(Lm(e,n,s),e=e.sibling;e!==null;)Lm(e,n,s),e=e.sibling}function Md(e,n,s){var o=e.tag;if(o===5||o===6)e=e.stateNode,n?s.insertBefore(e,n):s.appendChild(e);else if(o!==4&&(o===27&&Cl(e.type)&&(s=e.stateNode),e=e.child,e!==null))for(Md(e,n,s),e=e.sibling;e!==null;)Md(e,n,s),e=e.sibling}function Kg(e){var n=e.stateNode,s=e.memoizedProps;try{for(var o=e.type,f=n.attributes;f.length;)n.removeAttributeNode(f[0]);pa(n,o,s),n[re]=e,n[Ee]=s}catch(p){Gt(e,e.return,p)}}var Ci=!1,Hn=!1,_m=!1,Yg=typeof WeakSet=="function"?WeakSet:Set,Jn=null;function yS(e,n){if(e=e.containerInfo,th=Kd,e=Ie(e),Oo(e)){if("selectionStart"in e)var s={start:e.selectionStart,end:e.selectionEnd};else e:{s=(s=e.ownerDocument)&&s.defaultView||window;var o=s.getSelection&&s.getSelection();if(o&&o.rangeCount!==0){s=o.anchorNode;var f=o.anchorOffset,p=o.focusNode;o=o.focusOffset;try{s.nodeType,p.nodeType}catch{s=null;break e}var S=0,R=-1,V=-1,ue=0,we=0,ke=e,fe=null;t:for(;;){for(var ge;ke!==s||f!==0&&ke.nodeType!==3||(R=S+f),ke!==p||o!==0&&ke.nodeType!==3||(V=S+o),ke.nodeType===3&&(S+=ke.nodeValue.length),(ge=ke.firstChild)!==null;)fe=ke,ke=ge;for(;;){if(ke===e)break t;if(fe===s&&++ue===f&&(R=S),fe===p&&++we===o&&(V=S),(ge=ke.nextSibling)!==null)break;ke=fe,fe=ke.parentNode}ke=ge}s=R===-1||V===-1?null:{start:R,end:V}}else s=null}s=s||{start:0,end:0}}else s=null;for(nh={focusedElem:e,selectionRange:s},Kd=!1,Jn=n;Jn!==null;)if(n=Jn,e=n.child,(n.subtreeFlags&1028)!==0&&e!==null)e.return=n,Jn=e;else for(;Jn!==null;){switch(n=Jn,p=n.alternate,e=n.flags,n.tag){case 0:if((e&4)!==0&&(e=n.updateQueue,e=e!==null?e.events:null,e!==null))for(s=0;s<e.length;s++)f=e[s],f.ref.impl=f.nextImpl;break;case 11:case 15:break;case 1:if((e&1024)!==0&&p!==null){e=void 0,s=n,f=p.memoizedProps,p=p.memoizedState,o=s.stateNode;try{var Je=uo(s.type,f);e=o.getSnapshotBeforeUpdate(Je,p),o.__reactInternalSnapshotBeforeUpdate=e}catch(lt){Gt(s,s.return,lt)}}break;case 3:if((e&1024)!==0){if(e=n.stateNode.containerInfo,s=e.nodeType,s===9)rh(e);else if(s===1)switch(e.nodeName){case"HEAD":case"HTML":case"BODY":rh(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(l(163))}if(e=n.sibling,e!==null){e.return=n.return,Jn=e;break}Jn=n.return}}function Qg(e,n,s){var o=s.flags;switch(s.tag){case 0:case 11:case 15:ji(e,s),o&4&&fu(5,s);break;case 1:if(ji(e,s),o&4)if(e=s.stateNode,n===null)try{e.componentDidMount()}catch(S){Gt(s,s.return,S)}else{var f=uo(s.type,n.memoizedProps);n=n.memoizedState;try{e.componentDidUpdate(f,n,e.__reactInternalSnapshotBeforeUpdate)}catch(S){Gt(s,s.return,S)}}o&64&&qg(s),o&512&&mu(s,s.return);break;case 3:if(ji(e,s),o&64&&(e=s.updateQueue,e!==null)){if(n=null,s.child!==null)switch(s.child.tag){case 27:case 5:n=s.child.stateNode;break;case 1:n=s.child.stateNode}try{vd(e,n)}catch(S){Gt(s,s.return,S)}}break;case 27:n===null&&o&4&&Kg(s);case 26:case 5:ji(e,s),n===null&&o&4&&Vg(s),o&512&&mu(s,s.return);break;case 12:ji(e,s);break;case 31:ji(e,s),o&4&&Jg(e,s);break;case 13:ji(e,s),o&4&&ev(e,s),o&64&&(e=s.memoizedState,e!==null&&(e=e.dehydrated,e!==null&&(s=MS.bind(null,s),WS(e,s))));break;case 22:if(o=s.memoizedState!==null||Ci,!o){n=n!==null&&n.memoizedState!==null||Hn,f=Ci;var p=Hn;Ci=o,(Hn=n)&&!p?Ai(e,s,(s.subtreeFlags&8772)!==0):ji(e,s),Ci=f,Hn=p}break;case 30:break;default:ji(e,s)}}function Xg(e){var n=e.alternate;n!==null&&(e.alternate=null,Xg(n)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(n=e.stateNode,n!==null&&ra(n)),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 fn=null,Ja=!1;function ki(e,n,s){for(s=s.child;s!==null;)Zg(e,n,s),s=s.sibling}function Zg(e,n,s){if(Ae&&typeof Ae.onCommitFiberUnmount=="function")try{Ae.onCommitFiberUnmount(Fe,s)}catch{}switch(s.tag){case 26:Hn||Lr(s,n),ki(e,n,s),s.memoizedState?s.memoizedState.count--:s.stateNode&&(s=s.stateNode,s.parentNode.removeChild(s));break;case 27:Hn||Lr(s,n);var o=fn,f=Ja;Cl(s.type)&&(fn=s.stateNode,Ja=!1),ki(e,n,s),Su(s.stateNode),fn=o,Ja=f;break;case 5:Hn||Lr(s,n);case 6:if(o=fn,f=Ja,fn=null,ki(e,n,s),fn=o,Ja=f,fn!==null)if(Ja)try{(fn.nodeType===9?fn.body:fn.nodeName==="HTML"?fn.ownerDocument.body:fn).removeChild(s.stateNode)}catch(p){Gt(s,n,p)}else try{fn.removeChild(s.stateNode)}catch(p){Gt(s,n,p)}break;case 18:fn!==null&&(Ja?(e=fn,qv(e.nodeType===9?e.body:e.nodeName==="HTML"?e.ownerDocument.body:e,s.stateNode),gc(e)):qv(fn,s.stateNode));break;case 4:o=fn,f=Ja,fn=s.stateNode.containerInfo,Ja=!0,ki(e,n,s),fn=o,Ja=f;break;case 0:case 11:case 14:case 15:gl(2,s,n),Hn||gl(4,s,n),ki(e,n,s);break;case 1:Hn||(Lr(s,n),o=s.stateNode,typeof o.componentWillUnmount=="function"&&Gg(s,n,o)),ki(e,n,s);break;case 21:ki(e,n,s);break;case 22:Hn=(o=Hn)||s.memoizedState!==null,ki(e,n,s),Hn=o;break;default:ki(e,n,s)}}function Jg(e,n){if(n.memoizedState===null&&(e=n.alternate,e!==null&&(e=e.memoizedState,e!==null))){e=e.dehydrated;try{gc(e)}catch(s){Gt(n,n.return,s)}}}function ev(e,n){if(n.memoizedState===null&&(e=n.alternate,e!==null&&(e=e.memoizedState,e!==null&&(e=e.dehydrated,e!==null))))try{gc(e)}catch(s){Gt(n,n.return,s)}}function bS(e){switch(e.tag){case 31:case 13:case 19:var n=e.stateNode;return n===null&&(n=e.stateNode=new Yg),n;case 22:return e=e.stateNode,n=e._retryCache,n===null&&(n=e._retryCache=new Yg),n;default:throw Error(l(435,e.tag))}}function Nd(e,n){var s=bS(e);n.forEach(function(o){if(!s.has(o)){s.add(o);var f=NS.bind(null,e,o);o.then(f,f)}})}function es(e,n){var s=n.deletions;if(s!==null)for(var o=0;o<s.length;o++){var f=s[o],p=e,S=n,R=S;e:for(;R!==null;){switch(R.tag){case 27:if(Cl(R.type)){fn=R.stateNode,Ja=!1;break e}break;case 5:fn=R.stateNode,Ja=!1;break e;case 3:case 4:fn=R.stateNode.containerInfo,Ja=!0;break e}R=R.return}if(fn===null)throw Error(l(160));Zg(p,S,f),fn=null,Ja=!1,p=f.alternate,p!==null&&(p.return=null),f.return=null}if(n.subtreeFlags&13886)for(n=n.child;n!==null;)tv(n,e),n=n.sibling}var cr=null;function tv(e,n){var s=e.alternate,o=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:es(n,e),ts(e),o&4&&(gl(3,e,e.return),fu(3,e),gl(5,e,e.return));break;case 1:es(n,e),ts(e),o&512&&(Hn||s===null||Lr(s,s.return)),o&64&&Ci&&(e=e.updateQueue,e!==null&&(o=e.callbacks,o!==null&&(s=e.shared.hiddenCallbacks,e.shared.hiddenCallbacks=s===null?o:s.concat(o))));break;case 26:var f=cr;if(es(n,e),ts(e),o&512&&(Hn||s===null||Lr(s,s.return)),o&4){var p=s!==null?s.memoizedState:null;if(o=e.memoizedState,s===null)if(o===null)if(e.stateNode===null){e:{o=e.type,s=e.memoizedProps,f=f.ownerDocument||f;t:switch(o){case"title":p=f.getElementsByTagName("title")[0],(!p||p[Rt]||p[re]||p.namespaceURI==="http://www.w3.org/2000/svg"||p.hasAttribute("itemprop"))&&(p=f.createElement(o),f.head.insertBefore(p,f.querySelector("head > title"))),pa(p,o,s),p[re]=e,At(p),o=p;break e;case"link":var S=ty("link","href",f).get(o+(s.href||""));if(S){for(var R=0;R<S.length;R++)if(p=S[R],p.getAttribute("href")===(s.href==null||s.href===""?null:s.href)&&p.getAttribute("rel")===(s.rel==null?null:s.rel)&&p.getAttribute("title")===(s.title==null?null:s.title)&&p.getAttribute("crossorigin")===(s.crossOrigin==null?null:s.crossOrigin)){S.splice(R,1);break t}}p=f.createElement(o),pa(p,o,s),f.head.appendChild(p);break;case"meta":if(S=ty("meta","content",f).get(o+(s.content||""))){for(R=0;R<S.length;R++)if(p=S[R],p.getAttribute("content")===(s.content==null?null:""+s.content)&&p.getAttribute("name")===(s.name==null?null:s.name)&&p.getAttribute("property")===(s.property==null?null:s.property)&&p.getAttribute("http-equiv")===(s.httpEquiv==null?null:s.httpEquiv)&&p.getAttribute("charset")===(s.charSet==null?null:s.charSet)){S.splice(R,1);break t}}p=f.createElement(o),pa(p,o,s),f.head.appendChild(p);break;default:throw Error(l(468,o))}p[re]=e,At(p),o=p}e.stateNode=o}else ny(f,e.type,e.stateNode);else e.stateNode=ey(f,o,e.memoizedProps);else p!==o?(p===null?s.stateNode!==null&&(s=s.stateNode,s.parentNode.removeChild(s)):p.count--,o===null?ny(f,e.type,e.stateNode):ey(f,o,e.memoizedProps)):o===null&&e.stateNode!==null&&Em(e,e.memoizedProps,s.memoizedProps)}break;case 27:es(n,e),ts(e),o&512&&(Hn||s===null||Lr(s,s.return)),s!==null&&o&4&&Em(e,e.memoizedProps,s.memoizedProps);break;case 5:if(es(n,e),ts(e),o&512&&(Hn||s===null||Lr(s,s.return)),e.flags&32){f=e.stateNode;try{ls(f,"")}catch(Je){Gt(e,e.return,Je)}}o&4&&e.stateNode!=null&&(f=e.memoizedProps,Em(e,f,s!==null?s.memoizedProps:f)),o&1024&&(_m=!0);break;case 6:if(es(n,e),ts(e),o&4){if(e.stateNode===null)throw Error(l(162));o=e.memoizedProps,s=e.stateNode;try{s.nodeValue=o}catch(Je){Gt(e,e.return,Je)}}break;case 3:if(qd=null,f=cr,cr=Bd(n.containerInfo),es(n,e),cr=f,ts(e),o&4&&s!==null&&s.memoizedState.isDehydrated)try{gc(n.containerInfo)}catch(Je){Gt(e,e.return,Je)}_m&&(_m=!1,nv(e));break;case 4:o=cr,cr=Bd(e.stateNode.containerInfo),es(n,e),ts(e),cr=o;break;case 12:es(n,e),ts(e);break;case 31:es(n,e),ts(e),o&4&&(o=e.updateQueue,o!==null&&(e.updateQueue=null,Nd(e,o)));break;case 13:es(n,e),ts(e),e.child.flags&8192&&e.memoizedState!==null!=(s!==null&&s.memoizedState!==null)&&(Rd=je()),o&4&&(o=e.updateQueue,o!==null&&(e.updateQueue=null,Nd(e,o)));break;case 22:f=e.memoizedState!==null;var V=s!==null&&s.memoizedState!==null,ue=Ci,we=Hn;if(Ci=ue||f,Hn=we||V,es(n,e),Hn=we,Ci=ue,ts(e),o&8192)e:for(n=e.stateNode,n._visibility=f?n._visibility&-2:n._visibility|1,f&&(s===null||V||Ci||Hn||fo(e)),s=null,n=e;;){if(n.tag===5||n.tag===26){if(s===null){V=s=n;try{if(p=V.stateNode,f)S=p.style,typeof S.setProperty=="function"?S.setProperty("display","none","important"):S.display="none";else{R=V.stateNode;var ke=V.memoizedProps.style,fe=ke!=null&&ke.hasOwnProperty("display")?ke.display:null;R.style.display=fe==null||typeof fe=="boolean"?"":(""+fe).trim()}}catch(Je){Gt(V,V.return,Je)}}}else if(n.tag===6){if(s===null){V=n;try{V.stateNode.nodeValue=f?"":V.memoizedProps}catch(Je){Gt(V,V.return,Je)}}}else if(n.tag===18){if(s===null){V=n;try{var ge=V.stateNode;f?Gv(ge,!0):Gv(V.stateNode,!1)}catch(Je){Gt(V,V.return,Je)}}}else if((n.tag!==22&&n.tag!==23||n.memoizedState===null||n===e)&&n.child!==null){n.child.return=n,n=n.child;continue}if(n===e)break e;for(;n.sibling===null;){if(n.return===null||n.return===e)break e;s===n&&(s=null),n=n.return}s===n&&(s=null),n.sibling.return=n.return,n=n.sibling}o&4&&(o=e.updateQueue,o!==null&&(s=o.retryQueue,s!==null&&(o.retryQueue=null,Nd(e,s))));break;case 19:es(n,e),ts(e),o&4&&(o=e.updateQueue,o!==null&&(e.updateQueue=null,Nd(e,o)));break;case 30:break;case 21:break;default:es(n,e),ts(e)}}function ts(e){var n=e.flags;if(n&2){try{for(var s,o=e.return;o!==null;){if(Wg(o)){s=o;break}o=o.return}if(s==null)throw Error(l(160));switch(s.tag){case 27:var f=s.stateNode,p=Dm(e);Md(e,p,f);break;case 5:var S=s.stateNode;s.flags&32&&(ls(S,""),s.flags&=-33);var R=Dm(e);Md(e,R,S);break;case 3:case 4:var V=s.stateNode.containerInfo,ue=Dm(e);Lm(e,ue,V);break;default:throw Error(l(161))}}catch(we){Gt(e,e.return,we)}e.flags&=-3}n&4096&&(e.flags&=-4097)}function nv(e){if(e.subtreeFlags&1024)for(e=e.child;e!==null;){var n=e;nv(n),n.tag===5&&n.flags&1024&&n.stateNode.reset(),e=e.sibling}}function ji(e,n){if(n.subtreeFlags&8772)for(n=n.child;n!==null;)Qg(e,n.alternate,n),n=n.sibling}function fo(e){for(e=e.child;e!==null;){var n=e;switch(n.tag){case 0:case 11:case 14:case 15:gl(4,n,n.return),fo(n);break;case 1:Lr(n,n.return);var s=n.stateNode;typeof s.componentWillUnmount=="function"&&Gg(n,n.return,s),fo(n);break;case 27:Su(n.stateNode);case 26:case 5:Lr(n,n.return),fo(n);break;case 22:n.memoizedState===null&&fo(n);break;case 30:fo(n);break;default:fo(n)}e=e.sibling}}function Ai(e,n,s){for(s=s&&(n.subtreeFlags&8772)!==0,n=n.child;n!==null;){var o=n.alternate,f=e,p=n,S=p.flags;switch(p.tag){case 0:case 11:case 15:Ai(f,p,s),fu(4,p);break;case 1:if(Ai(f,p,s),o=p,f=o.stateNode,typeof f.componentDidMount=="function")try{f.componentDidMount()}catch(ue){Gt(o,o.return,ue)}if(o=p,f=o.updateQueue,f!==null){var R=o.stateNode;try{var V=f.shared.hiddenCallbacks;if(V!==null)for(f.shared.hiddenCallbacks=null,f=0;f<V.length;f++)ol(V[f],R)}catch(ue){Gt(o,o.return,ue)}}s&&S&64&&qg(p),mu(p,p.return);break;case 27:Kg(p);case 26:case 5:Ai(f,p,s),s&&o===null&&S&4&&Vg(p),mu(p,p.return);break;case 12:Ai(f,p,s);break;case 31:Ai(f,p,s),s&&S&4&&Jg(f,p);break;case 13:Ai(f,p,s),s&&S&4&&ev(f,p);break;case 22:p.memoizedState===null&&Ai(f,p,s),mu(p,p.return);break;case 30:break;default:Ai(f,p,s)}n=n.sibling}}function Im(e,n){var s=null;e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(s=e.memoizedState.cachePool.pool),e=null,n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(e=n.memoizedState.cachePool.pool),e!==s&&(e!=null&&e.refCount++,s!=null&&Sr(s))}function zm(e,n){e=null,n.alternate!==null&&(e=n.alternate.memoizedState.cache),n=n.memoizedState.cache,n!==e&&(n.refCount++,e!=null&&Sr(e))}function ur(e,n,s,o){if(n.subtreeFlags&10256)for(n=n.child;n!==null;)av(e,n,s,o),n=n.sibling}function av(e,n,s,o){var f=n.flags;switch(n.tag){case 0:case 11:case 15:ur(e,n,s,o),f&2048&&fu(9,n);break;case 1:ur(e,n,s,o);break;case 3:ur(e,n,s,o),f&2048&&(e=null,n.alternate!==null&&(e=n.alternate.memoizedState.cache),n=n.memoizedState.cache,n!==e&&(n.refCount++,e!=null&&Sr(e)));break;case 12:if(f&2048){ur(e,n,s,o),e=n.stateNode;try{var p=n.memoizedProps,S=p.id,R=p.onPostCommit;typeof R=="function"&&R(S,n.alternate===null?"mount":"update",e.passiveEffectDuration,-0)}catch(V){Gt(n,n.return,V)}}else ur(e,n,s,o);break;case 31:ur(e,n,s,o);break;case 13:ur(e,n,s,o);break;case 23:break;case 22:p=n.stateNode,S=n.alternate,n.memoizedState!==null?p._visibility&2?ur(e,n,s,o):hu(e,n):p._visibility&2?ur(e,n,s,o):(p._visibility|=2,rc(e,n,s,o,(n.subtreeFlags&10256)!==0||!1)),f&2048&&Im(S,n);break;case 24:ur(e,n,s,o),f&2048&&zm(n.alternate,n);break;default:ur(e,n,s,o)}}function rc(e,n,s,o,f){for(f=f&&((n.subtreeFlags&10256)!==0||!1),n=n.child;n!==null;){var p=e,S=n,R=s,V=o,ue=S.flags;switch(S.tag){case 0:case 11:case 15:rc(p,S,R,V,f),fu(8,S);break;case 23:break;case 22:var we=S.stateNode;S.memoizedState!==null?we._visibility&2?rc(p,S,R,V,f):hu(p,S):(we._visibility|=2,rc(p,S,R,V,f)),f&&ue&2048&&Im(S.alternate,S);break;case 24:rc(p,S,R,V,f),f&&ue&2048&&zm(S.alternate,S);break;default:rc(p,S,R,V,f)}n=n.sibling}}function hu(e,n){if(n.subtreeFlags&10256)for(n=n.child;n!==null;){var s=e,o=n,f=o.flags;switch(o.tag){case 22:hu(s,o),f&2048&&Im(o.alternate,o);break;case 24:hu(s,o),f&2048&&zm(o.alternate,o);break;default:hu(s,o)}n=n.sibling}}var pu=8192;function ic(e,n,s){if(e.subtreeFlags&pu)for(e=e.child;e!==null;)sv(e,n,s),e=e.sibling}function sv(e,n,s){switch(e.tag){case 26:ic(e,n,s),e.flags&pu&&e.memoizedState!==null&&r0(s,cr,e.memoizedState,e.memoizedProps);break;case 5:ic(e,n,s);break;case 3:case 4:var o=cr;cr=Bd(e.stateNode.containerInfo),ic(e,n,s),cr=o;break;case 22:e.memoizedState===null&&(o=e.alternate,o!==null&&o.memoizedState!==null?(o=pu,pu=16777216,ic(e,n,s),pu=o):ic(e,n,s));break;default:ic(e,n,s)}}function rv(e){var n=e.alternate;if(n!==null&&(e=n.child,e!==null)){n.child=null;do n=e.sibling,e.sibling=null,e=n;while(e!==null)}}function gu(e){var n=e.deletions;if((e.flags&16)!==0){if(n!==null)for(var s=0;s<n.length;s++){var o=n[s];Jn=o,lv(o,e)}rv(e)}if(e.subtreeFlags&10256)for(e=e.child;e!==null;)iv(e),e=e.sibling}function iv(e){switch(e.tag){case 0:case 11:case 15:gu(e),e.flags&2048&&gl(9,e,e.return);break;case 3:gu(e);break;case 12:gu(e);break;case 22:var n=e.stateNode;e.memoizedState!==null&&n._visibility&2&&(e.return===null||e.return.tag!==13)?(n._visibility&=-3,Td(e)):gu(e);break;default:gu(e)}}function Td(e){var n=e.deletions;if((e.flags&16)!==0){if(n!==null)for(var s=0;s<n.length;s++){var o=n[s];Jn=o,lv(o,e)}rv(e)}for(e=e.child;e!==null;){switch(n=e,n.tag){case 0:case 11:case 15:gl(8,n,n.return),Td(n);break;case 22:s=n.stateNode,s._visibility&2&&(s._visibility&=-3,Td(n));break;default:Td(n)}e=e.sibling}}function lv(e,n){for(;Jn!==null;){var s=Jn;switch(s.tag){case 0:case 11:case 15:gl(8,s,n);break;case 23:case 22:if(s.memoizedState!==null&&s.memoizedState.cachePool!==null){var o=s.memoizedState.cachePool.pool;o!=null&&o.refCount++}break;case 24:Sr(s.memoizedState.cache)}if(o=s.child,o!==null)o.return=s,Jn=o;else e:for(s=e;Jn!==null;){o=Jn;var f=o.sibling,p=o.return;if(Xg(o),o===s){Jn=null;break e}if(f!==null){f.return=p,Jn=f;break e}Jn=p}}}var xS={getCacheForType:function(e){var n=In(Zt),s=n.data.get(e);return s===void 0&&(s=e(),n.data.set(e,s)),s},cacheSignal:function(){return In(Zt).controller.signal}},wS=typeof WeakMap=="function"?WeakMap:Map,$t=0,Jt=null,_t=null,zt=0,qt=0,hs=null,vl=!1,lc=!1,Om=!1,Mi=0,Sn=0,yl=0,mo=0,Hm=0,ps=0,oc=0,vu=null,ns=null,Fm=!1,Rd=0,ov=0,Ed=1/0,Dd=null,bl=null,Wn=0,xl=null,cc=null,Ni=0,Pm=0,$m=null,cv=null,yu=0,Bm=null;function gs(){return($t&2)!==0&&zt!==0?zt&-zt:I.T!==null?Km():Ba()}function uv(){if(ps===0)if((zt&536870912)===0||kt){var e=xt;xt<<=1,(xt&3932160)===0&&(xt=262144),ps=e}else ps=536870912;return e=ka.current,e!==null&&(e.flags|=32),ps}function as(e,n,s){(e===Jt&&(qt===2||qt===9)||e.cancelPendingCommit!==null)&&(uc(e,0),wl(e,zt,ps,!1)),$s(e,s),(($t&2)===0||e!==Jt)&&(e===Jt&&(($t&2)===0&&(mo|=s),Sn===4&&wl(e,zt,ps,!1)),_r(e))}function dv(e,n,s){if(($t&6)!==0)throw Error(l(327));var o=!s&&(n&127)===0&&(n&e.expiredLanes)===0||tn(e,n),f=o?kS(e,n):qm(e,n,!0),p=o;do{if(f===0){lc&&!o&&wl(e,n,0,!1);break}else{if(s=e.current.alternate,p&&!SS(s)){f=qm(e,n,!1),p=!1;continue}if(f===2){if(p=n,e.errorRecoveryDisabledLanes&p)var S=0;else S=e.pendingLanes&-536870913,S=S!==0?S:S&536870912?536870912:0;if(S!==0){n=S;e:{var R=e;f=vu;var V=R.current.memoizedState.isDehydrated;if(V&&(uc(R,S).flags|=256),S=qm(R,S,!1),S!==2){if(Om&&!V){R.errorRecoveryDisabledLanes|=p,mo|=p,f=4;break e}p=ns,ns=f,p!==null&&(ns===null?ns=p:ns.push.apply(ns,p))}f=S}if(p=!1,f!==2)continue}}if(f===1){uc(e,0),wl(e,n,0,!0);break}e:{switch(o=e,p=f,p){case 0:case 1:throw Error(l(345));case 4:if((n&4194048)!==n)break;case 6:wl(o,n,ps,!vl);break e;case 2:ns=null;break;case 3:case 5:break;default:throw Error(l(329))}if((n&62914560)===n&&(f=Rd+300-je(),10<f)){if(wl(o,n,ps,!vl),_e(o,0,!0)!==0)break e;Ni=n,o.timeoutHandle=Bv(fv.bind(null,o,s,ns,Dd,Fm,n,ps,mo,oc,vl,p,"Throttled",-0,0),f);break e}fv(o,s,ns,Dd,Fm,n,ps,mo,oc,vl,p,null,-0,0)}}break}while(!0);_r(e)}function fv(e,n,s,o,f,p,S,R,V,ue,we,ke,fe,ge){if(e.timeoutHandle=-1,ke=n.subtreeFlags,ke&8192||(ke&16785408)===16785408){ke={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:qa},sv(n,p,ke);var Je=(p&62914560)===p?Rd-je():(p&4194048)===p?ov-je():0;if(Je=i0(ke,Je),Je!==null){Ni=p,e.cancelPendingCommit=Je(xv.bind(null,e,n,p,s,o,f,S,R,V,we,ke,null,fe,ge)),wl(e,p,S,!ue);return}}xv(e,n,p,s,o,f,S,R,V)}function SS(e){for(var n=e;;){var s=n.tag;if((s===0||s===11||s===15)&&n.flags&16384&&(s=n.updateQueue,s!==null&&(s=s.stores,s!==null)))for(var o=0;o<s.length;o++){var f=s[o],p=f.getSnapshot;f=f.value;try{if(!An(p(),f))return!1}catch{return!1}}if(s=n.child,n.subtreeFlags&16384&&s!==null)s.return=n,n=s;else{if(n===e)break;for(;n.sibling===null;){if(n.return===null||n.return===e)return!0;n=n.return}n.sibling.return=n.return,n=n.sibling}}return!0}function wl(e,n,s,o){n&=~Hm,n&=~mo,e.suspendedLanes|=n,e.pingedLanes&=~n,o&&(e.warmLanes|=n),o=e.expirationTimes;for(var f=n;0<f;){var p=31-ht(f),S=1<<p;o[p]=-1,f&=~S}s!==0&&Bs(e,s,n)}function Ld(){return($t&6)===0?(bu(0),!1):!0}function Um(){if(_t!==null){if(qt===0)var e=_t.return;else e=_t,Ya=ui=null,tu(e),lr=null,il=0,e=_t;for(;e!==null;)Ug(e.alternate,e),e=e.return;_t=null}}function uc(e,n){var s=e.timeoutHandle;s!==-1&&(e.timeoutHandle=-1,BS(s)),s=e.cancelPendingCommit,s!==null&&(e.cancelPendingCommit=null,s()),Ni=0,Um(),Jt=e,_t=s=_n(e.current,null),zt=n,qt=0,hs=null,vl=!1,lc=tn(e,n),Om=!1,oc=ps=Hm=mo=yl=Sn=0,ns=vu=null,Fm=!1,(n&8)!==0&&(n|=n&32);var o=e.entangledLanes;if(o!==0)for(e=e.entanglements,o&=n;0<o;){var f=31-ht(o),p=1<<f;n|=e[f],o&=~p}return Mi=n,qn(),s}function mv(e,n){yt=null,I.H=cu,n===kr||n===jr?(n=Xc(),qt=3):n===Vo?(n=Xc(),qt=4):qt=n===wm?8:n!==null&&typeof n=="object"&&typeof n.then=="function"?6:1,hs=n,_t===null&&(Sn=1,Sd(e,Ka(n,e.current)))}function hv(){var e=ka.current;return e===null?!0:(zt&4194048)===zt?Za===null:(zt&62914560)===zt||(zt&536870912)!==0?e===Za:!1}function pv(){var e=I.H;return I.H=cu,e===null?cu:e}function gv(){var e=I.A;return I.A=xS,e}function _d(){Sn=4,vl||(zt&4194048)!==zt&&ka.current!==null||(lc=!0),(yl&134217727)===0&&(mo&134217727)===0||Jt===null||wl(Jt,zt,ps,!1)}function qm(e,n,s){var o=$t;$t|=2;var f=pv(),p=gv();(Jt!==e||zt!==n)&&(Dd=null,uc(e,n)),n=!1;var S=Sn;e:do try{if(qt!==0&&_t!==null){var R=_t,V=hs;switch(qt){case 8:Um(),S=6;break e;case 3:case 2:case 9:case 6:ka.current===null&&(n=!0);var ue=qt;if(qt=0,hs=null,dc(e,R,V,ue),s&&lc){S=0;break e}break;default:ue=qt,qt=0,hs=null,dc(e,R,V,ue)}}CS(),S=Sn;break}catch(we){mv(e,we)}while(!0);return n&&e.shellSuspendCounter++,Ya=ui=null,$t=o,I.H=f,I.A=p,_t===null&&(Jt=null,zt=0,qn()),S}function CS(){for(;_t!==null;)vv(_t)}function kS(e,n){var s=$t;$t|=2;var o=pv(),f=gv();Jt!==e||zt!==n?(Dd=null,Ed=je()+500,uc(e,n)):lc=tn(e,n);e:do try{if(qt!==0&&_t!==null){n=_t;var p=hs;t:switch(qt){case 1:qt=0,hs=null,dc(e,n,p,1);break;case 2:case 9:if(Wo(p)){qt=0,hs=null,yv(n);break}n=function(){qt!==2&&qt!==9||Jt!==e||(qt=7),_r(e)},p.then(n,n);break e;case 3:qt=7;break e;case 4:qt=5;break e;case 7:Wo(p)?(qt=0,hs=null,yv(n)):(qt=0,hs=null,dc(e,n,p,7));break;case 5:var S=null;switch(_t.tag){case 26:S=_t.memoizedState;case 5:case 27:var R=_t;if(S?ay(S):R.stateNode.complete){qt=0,hs=null;var V=R.sibling;if(V!==null)_t=V;else{var ue=R.return;ue!==null?(_t=ue,Id(ue)):_t=null}break t}}qt=0,hs=null,dc(e,n,p,5);break;case 6:qt=0,hs=null,dc(e,n,p,6);break;case 8:Um(),Sn=6;break e;default:throw Error(l(462))}}jS();break}catch(we){mv(e,we)}while(!0);return Ya=ui=null,I.H=o,I.A=f,$t=s,_t!==null?0:(Jt=null,zt=0,qn(),Sn)}function jS(){for(;_t!==null&&!B();)vv(_t)}function vv(e){var n=$g(e.alternate,e,Mi);e.memoizedProps=e.pendingProps,n===null?Id(e):_t=n}function yv(e){var n=e,s=n.alternate;switch(n.tag){case 15:case 0:n=Ig(s,n,n.pendingProps,n.type,void 0,zt);break;case 11:n=Ig(s,n,n.pendingProps,n.type.render,n.ref,zt);break;case 5:tu(n);default:Ug(s,n),n=_t=Yl(n,Mi),n=$g(s,n,Mi)}e.memoizedProps=e.pendingProps,n===null?Id(e):_t=n}function dc(e,n,s,o){Ya=ui=null,tu(n),lr=null,il=0;var f=n.return;try{if(mS(e,f,n,s,zt)){Sn=1,Sd(e,Ka(s,e.current)),_t=null;return}}catch(p){if(f!==null)throw _t=f,p;Sn=1,Sd(e,Ka(s,e.current)),_t=null;return}n.flags&32768?(kt||o===1?e=!0:lc||(zt&536870912)!==0?e=!1:(vl=e=!0,(o===2||o===9||o===3||o===6)&&(o=ka.current,o!==null&&o.tag===13&&(o.flags|=16384))),bv(n,e)):Id(n)}function Id(e){var n=e;do{if((n.flags&32768)!==0){bv(n,vl);return}e=n.return;var s=gS(n.alternate,n,Mi);if(s!==null){_t=s;return}if(n=n.sibling,n!==null){_t=n;return}_t=n=e}while(n!==null);Sn===0&&(Sn=5)}function bv(e,n){do{var s=vS(e.alternate,e);if(s!==null){s.flags&=32767,_t=s;return}if(s=e.return,s!==null&&(s.flags|=32768,s.subtreeFlags=0,s.deletions=null),!n&&(e=e.sibling,e!==null)){_t=e;return}_t=e=s}while(e!==null);Sn=6,_t=null}function xv(e,n,s,o,f,p,S,R,V){e.cancelPendingCommit=null;do zd();while(Wn!==0);if(($t&6)!==0)throw Error(l(327));if(n!==null){if(n===e.current)throw Error(l(177));if(p=n.lanes|n.childLanes,p|=Wa,Yn(e,s,p,S,R,V),e===Jt&&(_t=Jt=null,zt=0),cc=n,xl=e,Ni=s,Pm=p,$m=f,cv=o,(n.subtreeFlags&10256)!==0||(n.flags&10256)!==0?(e.callbackNode=null,e.callbackPriority=0,TS(bt,function(){return jv(),null})):(e.callbackNode=null,e.callbackPriority=0),o=(n.flags&13878)!==0,(n.subtreeFlags&13878)!==0||o){o=I.T,I.T=null,f=se.p,se.p=2,S=$t,$t|=4;try{yS(e,n,s)}finally{$t=S,se.p=f,I.T=o}}Wn=1,wv(),Sv(),Cv()}}function wv(){if(Wn===1){Wn=0;var e=xl,n=cc,s=(n.flags&13878)!==0;if((n.subtreeFlags&13878)!==0||s){s=I.T,I.T=null;var o=se.p;se.p=2;var f=$t;$t|=4;try{tv(n,e);var p=nh,S=Ie(e.containerInfo),R=p.focusedElem,V=p.selectionRange;if(S!==R&&R&&R.ownerDocument&&_a(R.ownerDocument.documentElement,R)){if(V!==null&&Oo(R)){var ue=V.start,we=V.end;if(we===void 0&&(we=ue),"selectionStart"in R)R.selectionStart=ue,R.selectionEnd=Math.min(we,R.value.length);else{var ke=R.ownerDocument||document,fe=ke&&ke.defaultView||window;if(fe.getSelection){var ge=fe.getSelection(),Je=R.textContent.length,lt=Math.min(V.start,Je),Qt=V.end===void 0?lt:Math.min(V.end,Je);!ge.extend&<>Qt&&(S=Qt,Qt=lt,lt=S);var ae=Qn(R,lt),X=Qn(R,Qt);if(ae&&X&&(ge.rangeCount!==1||ge.anchorNode!==ae.node||ge.anchorOffset!==ae.offset||ge.focusNode!==X.node||ge.focusOffset!==X.offset)){var ce=ke.createRange();ce.setStart(ae.node,ae.offset),ge.removeAllRanges(),lt>Qt?(ge.addRange(ce),ge.extend(X.node,X.offset)):(ce.setEnd(X.node,X.offset),ge.addRange(ce))}}}}for(ke=[],ge=R;ge=ge.parentNode;)ge.nodeType===1&&ke.push({element:ge,left:ge.scrollLeft,top:ge.scrollTop});for(typeof R.focus=="function"&&R.focus(),R=0;R<ke.length;R++){var Se=ke[R];Se.element.scrollLeft=Se.left,Se.element.scrollTop=Se.top}}Kd=!!th,nh=th=null}finally{$t=f,se.p=o,I.T=s}}e.current=n,Wn=2}}function Sv(){if(Wn===2){Wn=0;var e=xl,n=cc,s=(n.flags&8772)!==0;if((n.subtreeFlags&8772)!==0||s){s=I.T,I.T=null;var o=se.p;se.p=2;var f=$t;$t|=4;try{Qg(e,n.alternate,n)}finally{$t=f,se.p=o,I.T=s}}Wn=3}}function Cv(){if(Wn===4||Wn===3){Wn=0,ye();var e=xl,n=cc,s=Ni,o=cv;(n.subtreeFlags&10256)!==0||(n.flags&10256)!==0?Wn=5:(Wn=0,cc=xl=null,kv(e,e.pendingLanes));var f=e.pendingLanes;if(f===0&&(bl=null),mn(s),n=n.stateNode,Ae&&typeof Ae.onCommitFiberRoot=="function")try{Ae.onCommitFiberRoot(Fe,n,void 0,(n.current.flags&128)===128)}catch{}if(o!==null){n=I.T,f=se.p,se.p=2,I.T=null;try{for(var p=e.onRecoverableError,S=0;S<o.length;S++){var R=o[S];p(R.value,{componentStack:R.stack})}}finally{I.T=n,se.p=f}}(Ni&3)!==0&&zd(),_r(e),f=e.pendingLanes,(s&261930)!==0&&(f&42)!==0?e===Bm?yu++:(yu=0,Bm=e):yu=0,bu(0)}}function kv(e,n){(e.pooledCacheLanes&=n)===0&&(n=e.pooledCache,n!=null&&(e.pooledCache=null,Sr(n)))}function zd(){return wv(),Sv(),Cv(),jv()}function jv(){if(Wn!==5)return!1;var e=xl,n=Pm;Pm=0;var s=mn(Ni),o=I.T,f=se.p;try{se.p=32>s?32:s,I.T=null,s=$m,$m=null;var p=xl,S=Ni;if(Wn=0,cc=xl=null,Ni=0,($t&6)!==0)throw Error(l(331));var R=$t;if($t|=4,iv(p.current),av(p,p.current,S,s),$t=R,bu(0,!1),Ae&&typeof Ae.onPostCommitFiberRoot=="function")try{Ae.onPostCommitFiberRoot(Fe,p)}catch{}return!0}finally{se.p=f,I.T=o,kv(e,n)}}function Av(e,n,s){n=Ka(s,n),n=xm(e.stateNode,n,2),e=Es(e,n,2),e!==null&&($s(e,2),_r(e))}function Gt(e,n,s){if(e.tag===3)Av(e,e,s);else for(;n!==null;){if(n.tag===3){Av(n,e,s);break}else if(n.tag===1){var o=n.stateNode;if(typeof n.type.getDerivedStateFromError=="function"||typeof o.componentDidCatch=="function"&&(bl===null||!bl.has(o))){e=Ka(s,e),s=Mg(2),o=Es(n,s,2),o!==null&&(Ng(s,o,n,e),$s(o,2),_r(o));break}}n=n.return}}function Gm(e,n,s){var o=e.pingCache;if(o===null){o=e.pingCache=new wS;var f=new Set;o.set(n,f)}else f=o.get(n),f===void 0&&(f=new Set,o.set(n,f));f.has(s)||(Om=!0,f.add(s),e=AS.bind(null,e,n,s),n.then(e,e))}function AS(e,n,s){var o=e.pingCache;o!==null&&o.delete(n),e.pingedLanes|=e.suspendedLanes&s,e.warmLanes&=~s,Jt===e&&(zt&s)===s&&(Sn===4||Sn===3&&(zt&62914560)===zt&&300>je()-Rd?($t&2)===0&&uc(e,0):Hm|=s,oc===zt&&(oc=0)),_r(e)}function Mv(e,n){n===0&&(n=Da()),e=gr(e,n),e!==null&&($s(e,n),_r(e))}function MS(e){var n=e.memoizedState,s=0;n!==null&&(s=n.retryLane),Mv(e,s)}function NS(e,n){var s=0;switch(e.tag){case 31:case 13:var o=e.stateNode,f=e.memoizedState;f!==null&&(s=f.retryLane);break;case 19:o=e.stateNode;break;case 22:o=e.stateNode._retryCache;break;default:throw Error(l(314))}o!==null&&o.delete(n),Mv(e,s)}function TS(e,n){return Ye(e,n)}var Od=null,fc=null,Vm=!1,Hd=!1,Wm=!1,Sl=0;function _r(e){e!==fc&&e.next===null&&(fc===null?Od=fc=e:fc=fc.next=e),Hd=!0,Vm||(Vm=!0,ES())}function bu(e,n){if(!Wm&&Hd){Wm=!0;do for(var s=!1,o=Od;o!==null;){if(e!==0){var f=o.pendingLanes;if(f===0)var p=0;else{var S=o.suspendedLanes,R=o.pingedLanes;p=(1<<31-ht(42|e)+1)-1,p&=f&~(S&~R),p=p&201326741?p&201326741|1:p?p|2:0}p!==0&&(s=!0,Ev(o,p))}else p=zt,p=_e(o,o===Jt?p:0,o.cancelPendingCommit!==null||o.timeoutHandle!==-1),(p&3)===0||tn(o,p)||(s=!0,Ev(o,p));o=o.next}while(s);Wm=!1}}function RS(){Nv()}function Nv(){Hd=Vm=!1;var e=0;Sl!==0&&$S()&&(e=Sl);for(var n=je(),s=null,o=Od;o!==null;){var f=o.next,p=Tv(o,n);p===0?(o.next=null,s===null?Od=f:s.next=f,f===null&&(fc=s)):(s=o,(e!==0||(p&3)!==0)&&(Hd=!0)),o=f}Wn!==0&&Wn!==5||bu(e),Sl!==0&&(Sl=0)}function Tv(e,n){for(var s=e.suspendedLanes,o=e.pingedLanes,f=e.expirationTimes,p=e.pendingLanes&-62914561;0<p;){var S=31-ht(p),R=1<<S,V=f[S];V===-1?((R&s)===0||(R&o)!==0)&&(f[S]=on(R,n)):V<=n&&(e.expiredLanes|=R),p&=~R}if(n=Jt,s=zt,s=_e(e,e===n?s:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),o=e.callbackNode,s===0||e===n&&(qt===2||qt===9)||e.cancelPendingCommit!==null)return o!==null&&o!==null&&ot(o),e.callbackNode=null,e.callbackPriority=0;if((s&3)===0||tn(e,s)){if(n=s&-s,n===e.callbackPriority)return n;switch(o!==null&&ot(o),mn(s)){case 2:case 8:s=nt;break;case 32:s=bt;break;case 268435456:s=Ct;break;default:s=bt}return o=Rv.bind(null,e),s=Ye(s,o),e.callbackPriority=n,e.callbackNode=s,n}return o!==null&&o!==null&&ot(o),e.callbackPriority=2,e.callbackNode=null,2}function Rv(e,n){if(Wn!==0&&Wn!==5)return e.callbackNode=null,e.callbackPriority=0,null;var s=e.callbackNode;if(zd()&&e.callbackNode!==s)return null;var o=zt;return o=_e(e,e===Jt?o:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),o===0?null:(dv(e,o,n),Tv(e,je()),e.callbackNode!=null&&e.callbackNode===s?Rv.bind(null,e):null)}function Ev(e,n){if(zd())return null;dv(e,n,!0)}function ES(){US(function(){($t&6)!==0?Ye(dt,RS):Nv()})}function Km(){if(Sl===0){var e=mi;e===0&&(e=et,et<<=1,(et&261888)===0&&(et=256)),Sl=e}return Sl}function Dv(e){return e==null||typeof e=="symbol"||typeof e=="boolean"?null:typeof e=="function"?e:Pl(""+e)}function Lv(e,n){var s=n.ownerDocument.createElement("input");return s.name=n.name,s.value=n.value,e.id&&s.setAttribute("form",e.id),n.parentNode.insertBefore(s,n),e=new FormData(e),s.parentNode.removeChild(s),e}function DS(e,n,s,o,f){if(n==="submit"&&s&&s.stateNode===f){var p=Dv((f[Ee]||null).action),S=o.submitter;S&&(n=(n=S[Ee]||null)?Dv(n.formAction):S.getAttribute("formAction"),n!==null&&(p=n,S=null));var R=new oa("action","action",null,o,f);e.push({event:R,listeners:[{instance:null,listener:function(){if(o.defaultPrevented){if(Sl!==0){var V=S?Lv(f,S):new FormData(f);hm(s,{pending:!0,data:V,method:f.method,action:p},null,V)}}else typeof p=="function"&&(R.preventDefault(),V=S?Lv(f,S):new FormData(f),hm(s,{pending:!0,data:V,method:f.method,action:p},p,V))},currentTarget:f}]})}}for(var Ym=0;Ym<Ji.length;Ym++){var Qm=Ji[Ym],LS=Qm.toLowerCase(),_S=Qm[0].toUpperCase()+Qm.slice(1);wa(LS,"on"+_S)}wa(ud,"onAnimationEnd"),wa(Xt,"onAnimationIteration"),wa(ri,"onAnimationStart"),wa("dblclick","onDoubleClick"),wa("focusin","onFocus"),wa("focusout","onBlur"),wa(um,"onTransitionRun"),wa(Js,"onTransitionStart"),wa(dd,"onTransitionCancel"),wa(Zi,"onTransitionEnd"),Ln("onMouseEnter",["mouseout","mouseover"]),Ln("onMouseLeave",["mouseout","mouseover"]),Ln("onPointerEnter",["pointerout","pointerover"]),Ln("onPointerLeave",["pointerout","pointerover"]),jn("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),jn("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),jn("onBeforeInput",["compositionend","keypress","textInput","paste"]),jn("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),jn("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),jn("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var xu="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(" "),IS=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(xu));function _v(e,n){n=(n&4)!==0;for(var s=0;s<e.length;s++){var o=e[s],f=o.event;o=o.listeners;e:{var p=void 0;if(n)for(var S=o.length-1;0<=S;S--){var R=o[S],V=R.instance,ue=R.currentTarget;if(R=R.listener,V!==p&&f.isPropagationStopped())break e;p=R,f.currentTarget=ue;try{p(f)}catch(we){Sa(we)}f.currentTarget=null,p=V}else for(S=0;S<o.length;S++){if(R=o[S],V=R.instance,ue=R.currentTarget,R=R.listener,V!==p&&f.isPropagationStopped())break e;p=R,f.currentTarget=ue;try{p(f)}catch(we){Sa(we)}f.currentTarget=null,p=V}}}}function It(e,n){var s=n[vt];s===void 0&&(s=n[vt]=new Set);var o=e+"__bubble";s.has(o)||(Iv(n,e,2,!1),s.add(o))}function Xm(e,n,s){var o=0;n&&(o|=4),Iv(s,e,o,n)}var Fd="_reactListening"+Math.random().toString(36).slice(2);function Zm(e){if(!e[Fd]){e[Fd]=!0,Us.forEach(function(s){s!=="selectionchange"&&(IS.has(s)||Xm(s,!1,e),Xm(s,!0,e))});var n=e.nodeType===9?e:e.ownerDocument;n===null||n[Fd]||(n[Fd]=!0,Xm("selectionchange",!1,n))}}function Iv(e,n,s,o){switch(uy(n)){case 2:var f=c0;break;case 8:f=u0;break;default:f=mh}s=f.bind(null,n,s,e),f=void 0,!To||n!=="touchstart"&&n!=="touchmove"&&n!=="wheel"||(f=!0),o?f!==void 0?e.addEventListener(n,s,{capture:!0,passive:f}):e.addEventListener(n,s,!0):f!==void 0?e.addEventListener(n,s,{passive:f}):e.addEventListener(n,s,!1)}function Jm(e,n,s,o,f){var p=o;if((n&1)===0&&(n&2)===0&&o!==null)e:for(;;){if(o===null)return;var S=o.tag;if(S===3||S===4){var R=o.stateNode.containerInfo;if(R===f)break;if(S===4)for(S=o.return;S!==null;){var V=S.tag;if((V===3||V===4)&&S.stateNode.containerInfo===f)return;S=S.return}for(;R!==null;){if(S=$n(R),S===null)return;if(V=S.tag,V===5||V===6||V===26||V===27){o=p=S;continue e}R=R.parentNode}}o=o.return}Ic(function(){var ue=p,we=ks(s),ke=[];e:{var fe=Ho.get(e);if(fe!==void 0){var ge=oa,Je=e;switch(e){case"keypress":if(ba(s)===0)break e;case"keydown":case"keyup":ge=ng;break;case"focusin":Je="focus",ge=qi;break;case"focusout":Je="blur",ge=qi;break;case"beforeblur":case"afterblur":ge=qi;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":ge=Wr;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":ge=Yr;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":ge=Gi;break;case ud:case Xt:case ri:ge=Ro;break;case Zi:ge=ag;break;case"scroll":case"scrollend":ge=Bi;break;case"wheel":ge=rg;break;case"copy":case"cut":case"paste":ge=Do;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":ge=Xr;break;case"toggle":case"beforetoggle":ge=sd}var lt=(n&4)!==0,Qt=!lt&&(e==="scroll"||e==="scrollend"),ae=lt?fe!==null?fe+"Capture":null:fe;lt=[];for(var X=ue,ce;X!==null;){var Se=X;if(ce=Se.stateNode,Se=Se.tag,Se!==5&&Se!==26&&Se!==27||ce===null||ae===null||(Se=hr(X,ae),Se!=null&<.push(wu(X,Se,ce))),Qt)break;X=X.return}0<lt.length&&(fe=new ge(fe,Je,null,s,we),ke.push({event:fe,listeners:lt}))}}if((n&7)===0){e:{if(fe=e==="mouseover"||e==="pointerover",ge=e==="mouseout"||e==="pointerout",fe&&s!==Ws&&(Je=s.relatedTarget||s.fromElement)&&($n(Je)||Je[Ge]))break e;if((ge||fe)&&(fe=we.window===we?we:(fe=we.ownerDocument)?fe.defaultView||fe.parentWindow:window,ge?(Je=s.relatedTarget||s.toElement,ge=ue,Je=Je?$n(Je):null,Je!==null&&(Qt=u(Je),lt=Je.tag,Je!==Qt||lt!==5&<!==27&<!==6)&&(Je=null)):(ge=null,Je=ue),ge!==Je)){if(lt=Wr,Se="onMouseLeave",ae="onMouseEnter",X="mouse",(e==="pointerout"||e==="pointerover")&&(lt=Xr,Se="onPointerLeave",ae="onPointerEnter",X="pointer"),Qt=ge==null?fe:en(ge),ce=Je==null?fe:en(Je),fe=new lt(Se,X+"leave",ge,s,we),fe.target=Qt,fe.relatedTarget=ce,Se=null,$n(we)===ue&&(lt=new lt(ae,X+"enter",Je,s,we),lt.target=ce,lt.relatedTarget=Qt,Se=lt),Qt=Se,ge&&Je)t:{for(lt=zS,ae=ge,X=Je,ce=0,Se=ae;Se;Se=lt(Se))ce++;Se=0;for(var st=X;st;st=lt(st))Se++;for(;0<ce-Se;)ae=lt(ae),ce--;for(;0<Se-ce;)X=lt(X),Se--;for(;ce--;){if(ae===X||X!==null&&ae===X.alternate){lt=ae;break t}ae=lt(ae),X=lt(X)}lt=null}else lt=null;ge!==null&&zv(ke,fe,ge,lt,!1),Je!==null&&Qt!==null&&zv(ke,Qt,Je,lt,!0)}}e:{if(fe=ue?en(ue):window,ge=fe.nodeName&&fe.nodeName.toLowerCase(),ge==="select"||ge==="input"&&fe.type==="file")var Ft=xa;else if(Io(fe))if(Yi)Ft=od;else{Ft=Gc;var tt=om}else ge=fe.nodeName,!ge||ge.toLowerCase()!=="input"||fe.type!=="checkbox"&&fe.type!=="radio"?ue&&Fi(ue.elementType)&&(Ft=xa):Ft=ei;if(Ft&&(Ft=Ft(e,ue))){Wi(ke,Ft,s,we);break e}tt&&tt(e,fe,ue),e==="focusout"&&ue&&fe.type==="number"&&ue.memoizedProps.value!=null&&qr(fe,"number",fe.value)}switch(tt=ue?en(ue):window,e){case"focusin":(Io(tt)||tt.contentEditable==="true")&&(Qi=tt,Kl=ue,Zs=null);break;case"focusout":Zs=Kl=Qi=null;break;case"mousedown":cd=!0;break;case"contextmenu":case"mouseup":case"dragend":cd=!1,Wc(ke,s,we);break;case"selectionchange":if(cm)break;case"keydown":case"keyup":Wc(ke,s,we)}var jt;if(Bc)e:{switch(e){case"compositionstart":var Ot="onCompositionStart";break e;case"compositionend":Ot="onCompositionEnd";break e;case"compositionupdate":Ot="onCompositionUpdate";break e}Ot=void 0}else Zr?Qs(e,s)&&(Ot="onCompositionEnd"):e==="keydown"&&s.keyCode===229&&(Ot="onCompositionStart");Ot&&(Lo&&s.locale!=="ko"&&(Zr||Ot!=="onCompositionStart"?Ot==="onCompositionEnd"&&Zr&&(jt=Ul()):(wn=we,Bl="value"in wn?wn.value:wn.textContent,Zr=!0)),tt=Pd(ue,Ot),0<tt.length&&(Ot=new Hc(Ot,e,null,s,we),ke.push({event:Ot,listeners:tt}),jt?Ot.data=jt:(jt=Vl(s),jt!==null&&(Ot.data=jt)))),(jt=lm?id(e,s):ld(e,s))&&(Ot=Pd(ue,"onBeforeInput"),0<Ot.length&&(tt=new Hc("onBeforeInput","beforeinput",null,s,we),ke.push({event:tt,listeners:Ot}),tt.data=jt)),DS(ke,e,ue,s,we)}_v(ke,n)})}function wu(e,n,s){return{instance:e,listener:n,currentTarget:s}}function Pd(e,n){for(var s=n+"Capture",o=[];e!==null;){var f=e,p=f.stateNode;if(f=f.tag,f!==5&&f!==26&&f!==27||p===null||(f=hr(e,s),f!=null&&o.unshift(wu(e,f,p)),f=hr(e,n),f!=null&&o.push(wu(e,f,p))),e.tag===3)return o;e=e.return}return[]}function zS(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5&&e.tag!==27);return e||null}function zv(e,n,s,o,f){for(var p=n._reactName,S=[];s!==null&&s!==o;){var R=s,V=R.alternate,ue=R.stateNode;if(R=R.tag,V!==null&&V===o)break;R!==5&&R!==26&&R!==27||ue===null||(V=ue,f?(ue=hr(s,p),ue!=null&&S.unshift(wu(s,ue,V))):f||(ue=hr(s,p),ue!=null&&S.push(wu(s,ue,V)))),s=s.return}S.length!==0&&e.push({event:n,listeners:S})}var OS=/\r\n?/g,HS=/\u0000|\uFFFD/g;function Ov(e){return(typeof e=="string"?e:""+e).replace(OS,`
|
|
9
|
+
`).replace(HS,"")}function Hv(e,n){return n=Ov(n),Ov(e)===n}function Yt(e,n,s,o,f,p){switch(s){case"children":typeof o=="string"?n==="body"||n==="textarea"&&o===""||ls(e,o):(typeof o=="number"||typeof o=="bigint")&&n!=="body"&&ls(e,""+o);break;case"className":Ur(e,"class",o);break;case"tabIndex":Ur(e,"tabindex",o);break;case"dir":case"role":case"viewBox":case"width":case"height":Ur(e,s,o);break;case"style":Vs(e,o,p);break;case"data":if(n!=="object"){Ur(e,"data",o);break}case"src":case"href":if(o===""&&(n!=="a"||s!=="href")){e.removeAttribute(s);break}if(o==null||typeof o=="function"||typeof o=="symbol"||typeof o=="boolean"){e.removeAttribute(s);break}o=Pl(""+o),e.setAttribute(s,o);break;case"action":case"formAction":if(typeof o=="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 p=="function"&&(s==="formAction"?(n!=="input"&&Yt(e,n,"name",f.name,f,null),Yt(e,n,"formEncType",f.formEncType,f,null),Yt(e,n,"formMethod",f.formMethod,f,null),Yt(e,n,"formTarget",f.formTarget,f,null)):(Yt(e,n,"encType",f.encType,f,null),Yt(e,n,"method",f.method,f,null),Yt(e,n,"target",f.target,f,null)));if(o==null||typeof o=="symbol"||typeof o=="boolean"){e.removeAttribute(s);break}o=Pl(""+o),e.setAttribute(s,o);break;case"onClick":o!=null&&(e.onclick=qa);break;case"onScroll":o!=null&&It("scroll",e);break;case"onScrollEnd":o!=null&&It("scrollend",e);break;case"dangerouslySetInnerHTML":if(o!=null){if(typeof o!="object"||!("__html"in o))throw Error(l(61));if(s=o.__html,s!=null){if(f.children!=null)throw Error(l(60));e.innerHTML=s}}break;case"multiple":e.multiple=o&&typeof o!="function"&&typeof o!="symbol";break;case"muted":e.muted=o&&typeof o!="function"&&typeof o!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(o==null||typeof o=="function"||typeof o=="boolean"||typeof o=="symbol"){e.removeAttribute("xlink:href");break}s=Pl(""+o),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":o!=null&&typeof o!="function"&&typeof o!="symbol"?e.setAttribute(s,""+o):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":o&&typeof o!="function"&&typeof o!="symbol"?e.setAttribute(s,""):e.removeAttribute(s);break;case"capture":case"download":o===!0?e.setAttribute(s,""):o!==!1&&o!=null&&typeof o!="function"&&typeof o!="symbol"?e.setAttribute(s,o):e.removeAttribute(s);break;case"cols":case"rows":case"size":case"span":o!=null&&typeof o!="function"&&typeof o!="symbol"&&!isNaN(o)&&1<=o?e.setAttribute(s,o):e.removeAttribute(s);break;case"rowSpan":case"start":o==null||typeof o=="function"||typeof o=="symbol"||isNaN(o)?e.removeAttribute(s):e.setAttribute(s,o);break;case"popover":It("beforetoggle",e),It("toggle",e),zi(e,"popover",o);break;case"xlinkActuate":cn(e,"http://www.w3.org/1999/xlink","xlink:actuate",o);break;case"xlinkArcrole":cn(e,"http://www.w3.org/1999/xlink","xlink:arcrole",o);break;case"xlinkRole":cn(e,"http://www.w3.org/1999/xlink","xlink:role",o);break;case"xlinkShow":cn(e,"http://www.w3.org/1999/xlink","xlink:show",o);break;case"xlinkTitle":cn(e,"http://www.w3.org/1999/xlink","xlink:title",o);break;case"xlinkType":cn(e,"http://www.w3.org/1999/xlink","xlink:type",o);break;case"xmlBase":cn(e,"http://www.w3.org/XML/1998/namespace","xml:base",o);break;case"xmlLang":cn(e,"http://www.w3.org/XML/1998/namespace","xml:lang",o);break;case"xmlSpace":cn(e,"http://www.w3.org/XML/1998/namespace","xml:space",o);break;case"is":zi(e,"is",o);break;case"innerText":case"textContent":break;default:(!(2<s.length)||s[0]!=="o"&&s[0]!=="O"||s[1]!=="n"&&s[1]!=="N")&&(s=Fl.get(s)||s,zi(e,s,o))}}function eh(e,n,s,o,f,p){switch(s){case"style":Vs(e,o,p);break;case"dangerouslySetInnerHTML":if(o!=null){if(typeof o!="object"||!("__html"in o))throw Error(l(61));if(s=o.__html,s!=null){if(f.children!=null)throw Error(l(60));e.innerHTML=s}}break;case"children":typeof o=="string"?ls(e,o):(typeof o=="number"||typeof o=="bigint")&&ls(e,""+o);break;case"onScroll":o!=null&&It("scroll",e);break;case"onScrollEnd":o!=null&&It("scrollend",e);break;case"onClick":o!=null&&(e.onclick=qa);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!Ht.hasOwnProperty(s))e:{if(s[0]==="o"&&s[1]==="n"&&(f=s.endsWith("Capture"),n=s.slice(2,f?s.length-7:void 0),p=e[Ee]||null,p=p!=null?p[s]:null,typeof p=="function"&&e.removeEventListener(n,p,f),typeof o=="function")){typeof p!="function"&&p!==null&&(s in e?e[s]=null:e.hasAttribute(s)&&e.removeAttribute(s)),e.addEventListener(n,o,f);break e}s in e?e[s]=o:o===!0?e.setAttribute(s,""):zi(e,s,o)}}}function pa(e,n,s){switch(n){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":It("error",e),It("load",e);var o=!1,f=!1,p;for(p in s)if(s.hasOwnProperty(p)){var S=s[p];if(S!=null)switch(p){case"src":o=!0;break;case"srcSet":f=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(l(137,n));default:Yt(e,n,p,S,s,null)}}f&&Yt(e,n,"srcSet",s.srcSet,s,null),o&&Yt(e,n,"src",s.src,s,null);return;case"input":It("invalid",e);var R=p=S=f=null,V=null,ue=null;for(o in s)if(s.hasOwnProperty(o)){var we=s[o];if(we!=null)switch(o){case"name":f=we;break;case"type":S=we;break;case"checked":V=we;break;case"defaultChecked":ue=we;break;case"value":p=we;break;case"defaultValue":R=we;break;case"children":case"dangerouslySetInnerHTML":if(we!=null)throw Error(l(137,n));break;default:Yt(e,n,o,we,s,null)}}_c(e,p,R,V,ue,S,f,!1);return;case"select":It("invalid",e),o=S=p=null;for(f in s)if(s.hasOwnProperty(f)&&(R=s[f],R!=null))switch(f){case"value":p=R;break;case"defaultValue":S=R;break;case"multiple":o=R;default:Yt(e,n,f,R,s,null)}n=p,s=S,e.multiple=!!o,n!=null?xn(e,!!o,n,!1):s!=null&&xn(e,!!o,s,!0);return;case"textarea":It("invalid",e),p=f=o=null;for(S in s)if(s.hasOwnProperty(S)&&(R=s[S],R!=null))switch(S){case"value":o=R;break;case"defaultValue":f=R;break;case"children":p=R;break;case"dangerouslySetInnerHTML":if(R!=null)throw Error(l(91));break;default:Yt(e,n,S,R,s,null)}Gs(e,o,f,p);return;case"option":for(V in s)s.hasOwnProperty(V)&&(o=s[V],o!=null)&&(V==="selected"?e.selected=o&&typeof o!="function"&&typeof o!="symbol":Yt(e,n,V,o,s,null));return;case"dialog":It("beforetoggle",e),It("toggle",e),It("cancel",e),It("close",e);break;case"iframe":case"object":It("load",e);break;case"video":case"audio":for(o=0;o<xu.length;o++)It(xu[o],e);break;case"image":It("error",e),It("load",e);break;case"details":It("toggle",e);break;case"embed":case"source":case"link":It("error",e),It("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(ue in s)if(s.hasOwnProperty(ue)&&(o=s[ue],o!=null))switch(ue){case"children":case"dangerouslySetInnerHTML":throw Error(l(137,n));default:Yt(e,n,ue,o,s,null)}return;default:if(Fi(n)){for(we in s)s.hasOwnProperty(we)&&(o=s[we],o!==void 0&&eh(e,n,we,o,s,void 0));return}}for(R in s)s.hasOwnProperty(R)&&(o=s[R],o!=null&&Yt(e,n,R,o,s,null))}function FS(e,n,s,o){switch(n){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var f=null,p=null,S=null,R=null,V=null,ue=null,we=null;for(ge in s){var ke=s[ge];if(s.hasOwnProperty(ge)&&ke!=null)switch(ge){case"checked":break;case"value":break;case"defaultValue":V=ke;default:o.hasOwnProperty(ge)||Yt(e,n,ge,null,o,ke)}}for(var fe in o){var ge=o[fe];if(ke=s[fe],o.hasOwnProperty(fe)&&(ge!=null||ke!=null))switch(fe){case"type":p=ge;break;case"name":f=ge;break;case"checked":ue=ge;break;case"defaultChecked":we=ge;break;case"value":S=ge;break;case"defaultValue":R=ge;break;case"children":case"dangerouslySetInnerHTML":if(ge!=null)throw Error(l(137,n));break;default:ge!==ke&&Yt(e,n,fe,ge,o,ke)}}Lc(e,S,R,V,ue,we,p,f);return;case"select":ge=S=R=fe=null;for(p in s)if(V=s[p],s.hasOwnProperty(p)&&V!=null)switch(p){case"value":break;case"multiple":ge=V;default:o.hasOwnProperty(p)||Yt(e,n,p,null,o,V)}for(f in o)if(p=o[f],V=s[f],o.hasOwnProperty(f)&&(p!=null||V!=null))switch(f){case"value":fe=p;break;case"defaultValue":R=p;break;case"multiple":S=p;default:p!==V&&Yt(e,n,f,p,o,V)}n=R,s=S,o=ge,fe!=null?xn(e,!!s,fe,!1):!!o!=!!s&&(n!=null?xn(e,!!s,n,!0):xn(e,!!s,s?[]:"",!1));return;case"textarea":ge=fe=null;for(R in s)if(f=s[R],s.hasOwnProperty(R)&&f!=null&&!o.hasOwnProperty(R))switch(R){case"value":break;case"children":break;default:Yt(e,n,R,null,o,f)}for(S in o)if(f=o[S],p=s[S],o.hasOwnProperty(S)&&(f!=null||p!=null))switch(S){case"value":fe=f;break;case"defaultValue":ge=f;break;case"children":break;case"dangerouslySetInnerHTML":if(f!=null)throw Error(l(91));break;default:f!==p&&Yt(e,n,S,f,o,p)}qs(e,fe,ge);return;case"option":for(var Je in s)fe=s[Je],s.hasOwnProperty(Je)&&fe!=null&&!o.hasOwnProperty(Je)&&(Je==="selected"?e.selected=!1:Yt(e,n,Je,null,o,fe));for(V in o)fe=o[V],ge=s[V],o.hasOwnProperty(V)&&fe!==ge&&(fe!=null||ge!=null)&&(V==="selected"?e.selected=fe&&typeof fe!="function"&&typeof fe!="symbol":Yt(e,n,V,fe,o,ge));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 lt in s)fe=s[lt],s.hasOwnProperty(lt)&&fe!=null&&!o.hasOwnProperty(lt)&&Yt(e,n,lt,null,o,fe);for(ue in o)if(fe=o[ue],ge=s[ue],o.hasOwnProperty(ue)&&fe!==ge&&(fe!=null||ge!=null))switch(ue){case"children":case"dangerouslySetInnerHTML":if(fe!=null)throw Error(l(137,n));break;default:Yt(e,n,ue,fe,o,ge)}return;default:if(Fi(n)){for(var Qt in s)fe=s[Qt],s.hasOwnProperty(Qt)&&fe!==void 0&&!o.hasOwnProperty(Qt)&&eh(e,n,Qt,void 0,o,fe);for(we in o)fe=o[we],ge=s[we],!o.hasOwnProperty(we)||fe===ge||fe===void 0&&ge===void 0||eh(e,n,we,fe,o,ge);return}}for(var ae in s)fe=s[ae],s.hasOwnProperty(ae)&&fe!=null&&!o.hasOwnProperty(ae)&&Yt(e,n,ae,null,o,fe);for(ke in o)fe=o[ke],ge=s[ke],!o.hasOwnProperty(ke)||fe===ge||fe==null&&ge==null||Yt(e,n,ke,fe,o,ge)}function Fv(e){switch(e){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function PS(){if(typeof performance.getEntriesByType=="function"){for(var e=0,n=0,s=performance.getEntriesByType("resource"),o=0;o<s.length;o++){var f=s[o],p=f.transferSize,S=f.initiatorType,R=f.duration;if(p&&R&&Fv(S)){for(S=0,R=f.responseEnd,o+=1;o<s.length;o++){var V=s[o],ue=V.startTime;if(ue>R)break;var we=V.transferSize,ke=V.initiatorType;we&&Fv(ke)&&(V=V.responseEnd,S+=we*(V<R?1:(R-ue)/(V-ue)))}if(--o,n+=8*(p+S)/(f.duration/1e3),e++,10<e)break}}if(0<e)return n/e/1e6}return navigator.connection&&(e=navigator.connection.downlink,typeof e=="number")?e:5}var th=null,nh=null;function $d(e){return e.nodeType===9?e:e.ownerDocument}function Pv(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 $v(e,n){if(e===0)switch(n){case"svg":return 1;case"math":return 2;default:return 0}return e===1&&n==="foreignObject"?0:e}function ah(e,n){return e==="textarea"||e==="noscript"||typeof n.children=="string"||typeof n.children=="number"||typeof n.children=="bigint"||typeof n.dangerouslySetInnerHTML=="object"&&n.dangerouslySetInnerHTML!==null&&n.dangerouslySetInnerHTML.__html!=null}var sh=null;function $S(){var e=window.event;return e&&e.type==="popstate"?e===sh?!1:(sh=e,!0):(sh=null,!1)}var Bv=typeof setTimeout=="function"?setTimeout:void 0,BS=typeof clearTimeout=="function"?clearTimeout:void 0,Uv=typeof Promise=="function"?Promise:void 0,US=typeof queueMicrotask=="function"?queueMicrotask:typeof Uv<"u"?function(e){return Uv.resolve(null).then(e).catch(qS)}:Bv;function qS(e){setTimeout(function(){throw e})}function Cl(e){return e==="head"}function qv(e,n){var s=n,o=0;do{var f=s.nextSibling;if(e.removeChild(s),f&&f.nodeType===8)if(s=f.data,s==="/$"||s==="/&"){if(o===0){e.removeChild(f),gc(n);return}o--}else if(s==="$"||s==="$?"||s==="$~"||s==="$!"||s==="&")o++;else if(s==="html")Su(e.ownerDocument.documentElement);else if(s==="head"){s=e.ownerDocument.head,Su(s);for(var p=s.firstChild;p;){var S=p.nextSibling,R=p.nodeName;p[Rt]||R==="SCRIPT"||R==="STYLE"||R==="LINK"&&p.rel.toLowerCase()==="stylesheet"||s.removeChild(p),p=S}}else s==="body"&&Su(e.ownerDocument.body);s=f}while(s);gc(n)}function Gv(e,n){var s=e;e=0;do{var o=s.nextSibling;if(s.nodeType===1?n?(s._stashedDisplay=s.style.display,s.style.display="none"):(s.style.display=s._stashedDisplay||"",s.getAttribute("style")===""&&s.removeAttribute("style")):s.nodeType===3&&(n?(s._stashedText=s.nodeValue,s.nodeValue=""):s.nodeValue=s._stashedText||""),o&&o.nodeType===8)if(s=o.data,s==="/$"){if(e===0)break;e--}else s!=="$"&&s!=="$?"&&s!=="$~"&&s!=="$!"||e++;s=o}while(s)}function rh(e){var n=e.firstChild;for(n&&n.nodeType===10&&(n=n.nextSibling);n;){var s=n;switch(n=n.nextSibling,s.nodeName){case"HTML":case"HEAD":case"BODY":rh(s),ra(s);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(s.rel.toLowerCase()==="stylesheet")continue}e.removeChild(s)}}function GS(e,n,s,o){for(;e.nodeType===1;){var f=s;if(e.nodeName.toLowerCase()!==n.toLowerCase()){if(!o&&(e.nodeName!=="INPUT"||e.type!=="hidden"))break}else if(o){if(!e[Rt])switch(n){case"meta":if(!e.hasAttribute("itemprop"))break;return e;case"link":if(p=e.getAttribute("rel"),p==="stylesheet"&&e.hasAttribute("data-precedence"))break;if(p!==f.rel||e.getAttribute("href")!==(f.href==null||f.href===""?null:f.href)||e.getAttribute("crossorigin")!==(f.crossOrigin==null?null:f.crossOrigin)||e.getAttribute("title")!==(f.title==null?null:f.title))break;return e;case"style":if(e.hasAttribute("data-precedence"))break;return e;case"script":if(p=e.getAttribute("src"),(p!==(f.src==null?null:f.src)||e.getAttribute("type")!==(f.type==null?null:f.type)||e.getAttribute("crossorigin")!==(f.crossOrigin==null?null:f.crossOrigin))&&p&&e.hasAttribute("async")&&!e.hasAttribute("itemprop"))break;return e;default:return e}}else if(n==="input"&&e.type==="hidden"){var p=f.name==null?null:""+f.name;if(f.type==="hidden"&&e.getAttribute("name")===p)return e}else return e;if(e=zs(e.nextSibling),e===null)break}return null}function VS(e,n,s){if(n==="")return null;for(;e.nodeType!==3;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!s||(e=zs(e.nextSibling),e===null))return null;return e}function Vv(e,n){for(;e.nodeType!==8;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!n||(e=zs(e.nextSibling),e===null))return null;return e}function ih(e){return e.data==="$?"||e.data==="$~"}function lh(e){return e.data==="$!"||e.data==="$?"&&e.ownerDocument.readyState!=="loading"}function WS(e,n){var s=e.ownerDocument;if(e.data==="$~")e._reactRetry=n;else if(e.data!=="$?"||s.readyState!=="loading")n();else{var o=function(){n(),s.removeEventListener("DOMContentLoaded",o)};s.addEventListener("DOMContentLoaded",o),e._reactRetry=o}}function zs(e){for(;e!=null;e=e.nextSibling){var n=e.nodeType;if(n===1||n===3)break;if(n===8){if(n=e.data,n==="$"||n==="$!"||n==="$?"||n==="$~"||n==="&"||n==="F!"||n==="F")break;if(n==="/$"||n==="/&")return null}}return e}var oh=null;function Wv(e){e=e.nextSibling;for(var n=0;e;){if(e.nodeType===8){var s=e.data;if(s==="/$"||s==="/&"){if(n===0)return zs(e.nextSibling);n--}else s!=="$"&&s!=="$!"&&s!=="$?"&&s!=="$~"&&s!=="&"||n++}e=e.nextSibling}return null}function Kv(e){e=e.previousSibling;for(var n=0;e;){if(e.nodeType===8){var s=e.data;if(s==="$"||s==="$!"||s==="$?"||s==="$~"||s==="&"){if(n===0)return e;n--}else s!=="/$"&&s!=="/&"||n++}e=e.previousSibling}return null}function Yv(e,n,s){switch(n=$d(s),e){case"html":if(e=n.documentElement,!e)throw Error(l(452));return e;case"head":if(e=n.head,!e)throw Error(l(453));return e;case"body":if(e=n.body,!e)throw Error(l(454));return e;default:throw Error(l(451))}}function Su(e){for(var n=e.attributes;n.length;)e.removeAttributeNode(n[0]);ra(e)}var Os=new Map,Qv=new Set;function Bd(e){return typeof e.getRootNode=="function"?e.getRootNode():e.nodeType===9?e:e.ownerDocument}var Ti=se.d;se.d={f:KS,r:YS,D:QS,C:XS,L:ZS,m:JS,X:t0,S:e0,M:n0};function KS(){var e=Ti.f(),n=Ld();return e||n}function YS(e){var n=bn(e);n!==null&&n.tag===5&&n.type==="form"?mg(n):Ti.r(e)}var mc=typeof document>"u"?null:document;function Xv(e,n,s){var o=mc;if(o&&typeof n=="string"&&n){var f=Ua(n);f='link[rel="'+e+'"][href="'+f+'"]',typeof s=="string"&&(f+='[crossorigin="'+s+'"]'),Qv.has(f)||(Qv.add(f),e={rel:e,crossOrigin:s,href:n},o.querySelector(f)===null&&(n=o.createElement("link"),pa(n,"link",e),At(n),o.head.appendChild(n)))}}function QS(e){Ti.D(e),Xv("dns-prefetch",e,null)}function XS(e,n){Ti.C(e,n),Xv("preconnect",e,n)}function ZS(e,n,s){Ti.L(e,n,s);var o=mc;if(o&&e&&n){var f='link[rel="preload"][as="'+Ua(n)+'"]';n==="image"&&s&&s.imageSrcSet?(f+='[imagesrcset="'+Ua(s.imageSrcSet)+'"]',typeof s.imageSizes=="string"&&(f+='[imagesizes="'+Ua(s.imageSizes)+'"]')):f+='[href="'+Ua(e)+'"]';var p=f;switch(n){case"style":p=hc(e);break;case"script":p=pc(e)}Os.has(p)||(e=b({rel:"preload",href:n==="image"&&s&&s.imageSrcSet?void 0:e,as:n},s),Os.set(p,e),o.querySelector(f)!==null||n==="style"&&o.querySelector(Cu(p))||n==="script"&&o.querySelector(ku(p))||(n=o.createElement("link"),pa(n,"link",e),At(n),o.head.appendChild(n)))}}function JS(e,n){Ti.m(e,n);var s=mc;if(s&&e){var o=n&&typeof n.as=="string"?n.as:"script",f='link[rel="modulepreload"][as="'+Ua(o)+'"][href="'+Ua(e)+'"]',p=f;switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":p=pc(e)}if(!Os.has(p)&&(e=b({rel:"modulepreload",href:e},n),Os.set(p,e),s.querySelector(f)===null)){switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(s.querySelector(ku(p)))return}o=s.createElement("link"),pa(o,"link",e),At(o),s.head.appendChild(o)}}}function e0(e,n,s){Ti.S(e,n,s);var o=mc;if(o&&e){var f=Ke(o).hoistableStyles,p=hc(e);n=n||"default";var S=f.get(p);if(!S){var R={loading:0,preload:null};if(S=o.querySelector(Cu(p)))R.loading=5;else{e=b({rel:"stylesheet",href:e,"data-precedence":n},s),(s=Os.get(p))&&ch(e,s);var V=S=o.createElement("link");At(V),pa(V,"link",e),V._p=new Promise(function(ue,we){V.onload=ue,V.onerror=we}),V.addEventListener("load",function(){R.loading|=1}),V.addEventListener("error",function(){R.loading|=2}),R.loading|=4,Ud(S,n,o)}S={type:"stylesheet",instance:S,count:1,state:R},f.set(p,S)}}}function t0(e,n){Ti.X(e,n);var s=mc;if(s&&e){var o=Ke(s).hoistableScripts,f=pc(e),p=o.get(f);p||(p=s.querySelector(ku(f)),p||(e=b({src:e,async:!0},n),(n=Os.get(f))&&uh(e,n),p=s.createElement("script"),At(p),pa(p,"link",e),s.head.appendChild(p)),p={type:"script",instance:p,count:1,state:null},o.set(f,p))}}function n0(e,n){Ti.M(e,n);var s=mc;if(s&&e){var o=Ke(s).hoistableScripts,f=pc(e),p=o.get(f);p||(p=s.querySelector(ku(f)),p||(e=b({src:e,async:!0,type:"module"},n),(n=Os.get(f))&&uh(e,n),p=s.createElement("script"),At(p),pa(p,"link",e),s.head.appendChild(p)),p={type:"script",instance:p,count:1,state:null},o.set(f,p))}}function Zv(e,n,s,o){var f=(f=ee.current)?Bd(f):null;if(!f)throw Error(l(446));switch(e){case"meta":case"title":return null;case"style":return typeof s.precedence=="string"&&typeof s.href=="string"?(n=hc(s.href),s=Ke(f).hoistableStyles,o=s.get(n),o||(o={type:"style",instance:null,count:0,state:null},s.set(n,o)),o):{type:"void",instance:null,count:0,state:null};case"link":if(s.rel==="stylesheet"&&typeof s.href=="string"&&typeof s.precedence=="string"){e=hc(s.href);var p=Ke(f).hoistableStyles,S=p.get(e);if(S||(f=f.ownerDocument||f,S={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},p.set(e,S),(p=f.querySelector(Cu(e)))&&!p._p&&(S.instance=p,S.state.loading=5),Os.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},Os.set(e,s),p||a0(f,e,s,S.state))),n&&o===null)throw Error(l(528,""));return S}if(n&&o!==null)throw Error(l(529,""));return null;case"script":return n=s.async,s=s.src,typeof s=="string"&&n&&typeof n!="function"&&typeof n!="symbol"?(n=pc(s),s=Ke(f).hoistableScripts,o=s.get(n),o||(o={type:"script",instance:null,count:0,state:null},s.set(n,o)),o):{type:"void",instance:null,count:0,state:null};default:throw Error(l(444,e))}}function hc(e){return'href="'+Ua(e)+'"'}function Cu(e){return'link[rel="stylesheet"]['+e+"]"}function Jv(e){return b({},e,{"data-precedence":e.precedence,precedence:null})}function a0(e,n,s,o){e.querySelector('link[rel="preload"][as="style"]['+n+"]")?o.loading=1:(n=e.createElement("link"),o.preload=n,n.addEventListener("load",function(){return o.loading|=1}),n.addEventListener("error",function(){return o.loading|=2}),pa(n,"link",s),At(n),e.head.appendChild(n))}function pc(e){return'[src="'+Ua(e)+'"]'}function ku(e){return"script[async]"+e}function ey(e,n,s){if(n.count++,n.instance===null)switch(n.type){case"style":var o=e.querySelector('style[data-href~="'+Ua(s.href)+'"]');if(o)return n.instance=o,At(o),o;var f=b({},s,{"data-href":s.href,"data-precedence":s.precedence,href:null,precedence:null});return o=(e.ownerDocument||e).createElement("style"),At(o),pa(o,"style",f),Ud(o,s.precedence,e),n.instance=o;case"stylesheet":f=hc(s.href);var p=e.querySelector(Cu(f));if(p)return n.state.loading|=4,n.instance=p,At(p),p;o=Jv(s),(f=Os.get(f))&&ch(o,f),p=(e.ownerDocument||e).createElement("link"),At(p);var S=p;return S._p=new Promise(function(R,V){S.onload=R,S.onerror=V}),pa(p,"link",o),n.state.loading|=4,Ud(p,s.precedence,e),n.instance=p;case"script":return p=pc(s.src),(f=e.querySelector(ku(p)))?(n.instance=f,At(f),f):(o=s,(f=Os.get(p))&&(o=b({},s),uh(o,f)),e=e.ownerDocument||e,f=e.createElement("script"),At(f),pa(f,"link",o),e.head.appendChild(f),n.instance=f);case"void":return null;default:throw Error(l(443,n.type))}else n.type==="stylesheet"&&(n.state.loading&4)===0&&(o=n.instance,n.state.loading|=4,Ud(o,s.precedence,e));return n.instance}function Ud(e,n,s){for(var o=s.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),f=o.length?o[o.length-1]:null,p=f,S=0;S<o.length;S++){var R=o[S];if(R.dataset.precedence===n)p=R;else if(p!==f)break}p?p.parentNode.insertBefore(e,p.nextSibling):(n=s.nodeType===9?s.head:s,n.insertBefore(e,n.firstChild))}function ch(e,n){e.crossOrigin==null&&(e.crossOrigin=n.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=n.referrerPolicy),e.title==null&&(e.title=n.title)}function uh(e,n){e.crossOrigin==null&&(e.crossOrigin=n.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=n.referrerPolicy),e.integrity==null&&(e.integrity=n.integrity)}var qd=null;function ty(e,n,s){if(qd===null){var o=new Map,f=qd=new Map;f.set(s,o)}else f=qd,o=f.get(s),o||(o=new Map,f.set(s,o));if(o.has(e))return o;for(o.set(e,null),s=s.getElementsByTagName(e),f=0;f<s.length;f++){var p=s[f];if(!(p[Rt]||p[re]||e==="link"&&p.getAttribute("rel")==="stylesheet")&&p.namespaceURI!=="http://www.w3.org/2000/svg"){var S=p.getAttribute(n)||"";S=e+S;var R=o.get(S);R?R.push(p):o.set(S,[p])}}return o}function ny(e,n,s){e=e.ownerDocument||e,e.head.insertBefore(s,n==="title"?e.querySelector("head > title"):null)}function s0(e,n,s){if(s===1||n.itemProp!=null)return!1;switch(e){case"meta":case"title":return!0;case"style":if(typeof n.precedence!="string"||typeof n.href!="string"||n.href==="")break;return!0;case"link":if(typeof n.rel!="string"||typeof n.href!="string"||n.href===""||n.onLoad||n.onError)break;return n.rel==="stylesheet"?(e=n.disabled,typeof n.precedence=="string"&&e==null):!0;case"script":if(n.async&&typeof n.async!="function"&&typeof n.async!="symbol"&&!n.onLoad&&!n.onError&&n.src&&typeof n.src=="string")return!0}return!1}function ay(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function r0(e,n,s,o){if(s.type==="stylesheet"&&(typeof o.media!="string"||matchMedia(o.media).matches!==!1)&&(s.state.loading&4)===0){if(s.instance===null){var f=hc(o.href),p=n.querySelector(Cu(f));if(p){n=p._p,n!==null&&typeof n=="object"&&typeof n.then=="function"&&(e.count++,e=Gd.bind(e),n.then(e,e)),s.state.loading|=4,s.instance=p,At(p);return}p=n.ownerDocument||n,o=Jv(o),(f=Os.get(f))&&ch(o,f),p=p.createElement("link"),At(p);var S=p;S._p=new Promise(function(R,V){S.onload=R,S.onerror=V}),pa(p,"link",o),s.instance=p}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(s,n),(n=s.state.preload)&&(s.state.loading&3)===0&&(e.count++,s=Gd.bind(e),n.addEventListener("load",s),n.addEventListener("error",s))}}var dh=0;function i0(e,n){return e.stylesheets&&e.count===0&&Wd(e,e.stylesheets),0<e.count||0<e.imgCount?function(s){var o=setTimeout(function(){if(e.stylesheets&&Wd(e,e.stylesheets),e.unsuspend){var p=e.unsuspend;e.unsuspend=null,p()}},6e4+n);0<e.imgBytes&&dh===0&&(dh=62500*PS());var f=setTimeout(function(){if(e.waitingForImages=!1,e.count===0&&(e.stylesheets&&Wd(e,e.stylesheets),e.unsuspend)){var p=e.unsuspend;e.unsuspend=null,p()}},(e.imgBytes>dh?50:800)+n);return e.unsuspend=s,function(){e.unsuspend=null,clearTimeout(o),clearTimeout(f)}}:null}function Gd(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Wd(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Vd=null;function Wd(e,n){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Vd=new Map,n.forEach(l0,e),Vd=null,Gd.call(e))}function l0(e,n){if(!(n.state.loading&4)){var s=Vd.get(e);if(s)var o=s.get(null);else{s=new Map,Vd.set(e,s);for(var f=e.querySelectorAll("link[data-precedence],style[data-precedence]"),p=0;p<f.length;p++){var S=f[p];(S.nodeName==="LINK"||S.getAttribute("media")!=="not all")&&(s.set(S.dataset.precedence,S),o=S)}o&&s.set(null,o)}f=n.instance,S=f.getAttribute("data-precedence"),p=s.get(S)||o,p===o&&s.set(null,f),s.set(S,f),this.count++,o=Gd.bind(this),f.addEventListener("load",o),f.addEventListener("error",o),p?p.parentNode.insertBefore(f,p.nextSibling):(e=e.nodeType===9?e.head:e,e.insertBefore(f,e.firstChild)),n.state.loading|=4}}var ju={$$typeof:L,Provider:null,Consumer:null,_currentValue:W,_currentValue2:W,_threadCount:0};function o0(e,n,s,o,f,p,S,R,V){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=nn(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=nn(0),this.hiddenUpdates=nn(null),this.identifierPrefix=o,this.onUncaughtError=f,this.onCaughtError=p,this.onRecoverableError=S,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=V,this.incompleteTransitions=new Map}function sy(e,n,s,o,f,p,S,R,V,ue,we,ke){return e=new o0(e,n,s,S,V,ue,we,ke,R),n=1,p===!0&&(n|=24),p=ca(3,null,null,n),e.current=p,p.stateNode=e,n=Bo(),n.refCount++,e.pooledCache=n,n.refCount++,p.memoizedState={element:o,isDehydrated:s,cache:n},Zc(p),e}function ry(e){return e?(e=Zn,e):Zn}function iy(e,n,s,o,f,p){f=ry(f),o.context===null?o.context=f:o.pendingContext=f,o=Er(n),o.payload={element:s},p=p===void 0?null:p,p!==null&&(o.callback=p),s=Es(e,o,n),s!==null&&(as(s,e,n),pi(s,e,n))}function ly(e,n){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var s=e.retryLane;e.retryLane=s!==0&&s<n?s:n}}function fh(e,n){ly(e,n),(e=e.alternate)&&ly(e,n)}function oy(e){if(e.tag===13||e.tag===31){var n=gr(e,67108864);n!==null&&as(n,e,67108864),fh(e,67108864)}}function cy(e){if(e.tag===13||e.tag===31){var n=gs();n=ft(n);var s=gr(e,n);s!==null&&as(s,e,n),fh(e,n)}}var Kd=!0;function c0(e,n,s,o){var f=I.T;I.T=null;var p=se.p;try{se.p=2,mh(e,n,s,o)}finally{se.p=p,I.T=f}}function u0(e,n,s,o){var f=I.T;I.T=null;var p=se.p;try{se.p=8,mh(e,n,s,o)}finally{se.p=p,I.T=f}}function mh(e,n,s,o){if(Kd){var f=hh(o);if(f===null)Jm(e,n,o,Yd,s),dy(e,o);else if(f0(f,e,n,s,o))o.stopPropagation();else if(dy(e,o),n&4&&-1<d0.indexOf(e)){for(;f!==null;){var p=bn(f);if(p!==null)switch(p.tag){case 3:if(p=p.stateNode,p.current.memoizedState.isDehydrated){var S=Pn(p.pendingLanes);if(S!==0){var R=p;for(R.pendingLanes|=2,R.entangledLanes|=2;S;){var V=1<<31-ht(S);R.entanglements[1]|=V,S&=~V}_r(p),($t&6)===0&&(Ed=je()+500,bu(0))}}break;case 31:case 13:R=gr(p,2),R!==null&&as(R,p,2),Ld(),fh(p,2)}if(p=hh(o),p===null&&Jm(e,n,o,Yd,s),p===f)break;f=p}f!==null&&o.stopPropagation()}else Jm(e,n,o,null,s)}}function hh(e){return e=ks(e),ph(e)}var Yd=null;function ph(e){if(Yd=null,e=$n(e),e!==null){var n=u(e);if(n===null)e=null;else{var s=n.tag;if(s===13){if(e=m(n),e!==null)return e;e=null}else if(s===31){if(e=h(n),e!==null)return e;e=null}else if(s===3){if(n.stateNode.current.memoizedState.isDehydrated)return n.tag===3?n.stateNode.containerInfo:null;e=null}else n!==e&&(e=null)}}return Yd=e,null}function uy(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(Pe()){case dt:return 2;case nt:return 8;case bt:case it:return 32;case Ct:return 268435456;default:return 32}default:return 32}}var gh=!1,kl=null,jl=null,Al=null,Au=new Map,Mu=new Map,Ml=[],d0="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 dy(e,n){switch(e){case"focusin":case"focusout":kl=null;break;case"dragenter":case"dragleave":jl=null;break;case"mouseover":case"mouseout":Al=null;break;case"pointerover":case"pointerout":Au.delete(n.pointerId);break;case"gotpointercapture":case"lostpointercapture":Mu.delete(n.pointerId)}}function Nu(e,n,s,o,f,p){return e===null||e.nativeEvent!==p?(e={blockedOn:n,domEventName:s,eventSystemFlags:o,nativeEvent:p,targetContainers:[f]},n!==null&&(n=bn(n),n!==null&&oy(n)),e):(e.eventSystemFlags|=o,n=e.targetContainers,f!==null&&n.indexOf(f)===-1&&n.push(f),e)}function f0(e,n,s,o,f){switch(n){case"focusin":return kl=Nu(kl,e,n,s,o,f),!0;case"dragenter":return jl=Nu(jl,e,n,s,o,f),!0;case"mouseover":return Al=Nu(Al,e,n,s,o,f),!0;case"pointerover":var p=f.pointerId;return Au.set(p,Nu(Au.get(p)||null,e,n,s,o,f)),!0;case"gotpointercapture":return p=f.pointerId,Mu.set(p,Nu(Mu.get(p)||null,e,n,s,o,f)),!0}return!1}function fy(e){var n=$n(e.target);if(n!==null){var s=u(n);if(s!==null){if(n=s.tag,n===13){if(n=m(s),n!==null){e.blockedOn=n,Ii(e.priority,function(){cy(s)});return}}else if(n===31){if(n=h(s),n!==null){e.blockedOn=n,Ii(e.priority,function(){cy(s)});return}}else if(n===3&&s.stateNode.current.memoizedState.isDehydrated){e.blockedOn=s.tag===3?s.stateNode.containerInfo:null;return}}}e.blockedOn=null}function Qd(e){if(e.blockedOn!==null)return!1;for(var n=e.targetContainers;0<n.length;){var s=hh(e.nativeEvent);if(s===null){s=e.nativeEvent;var o=new s.constructor(s.type,s);Ws=o,s.target.dispatchEvent(o),Ws=null}else return n=bn(s),n!==null&&oy(n),e.blockedOn=s,!1;n.shift()}return!0}function my(e,n,s){Qd(e)&&s.delete(n)}function m0(){gh=!1,kl!==null&&Qd(kl)&&(kl=null),jl!==null&&Qd(jl)&&(jl=null),Al!==null&&Qd(Al)&&(Al=null),Au.forEach(my),Mu.forEach(my)}function Xd(e,n){e.blockedOn===n&&(e.blockedOn=null,gh||(gh=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,m0)))}var Zd=null;function hy(e){Zd!==e&&(Zd=e,t.unstable_scheduleCallback(t.unstable_NormalPriority,function(){Zd===e&&(Zd=null);for(var n=0;n<e.length;n+=3){var s=e[n],o=e[n+1],f=e[n+2];if(typeof o!="function"){if(ph(o||s)===null)continue;break}var p=bn(s);p!==null&&(e.splice(n,3),n-=3,hm(p,{pending:!0,data:f,method:s.method,action:o},o,f))}}))}function gc(e){function n(V){return Xd(V,e)}kl!==null&&Xd(kl,e),jl!==null&&Xd(jl,e),Al!==null&&Xd(Al,e),Au.forEach(n),Mu.forEach(n);for(var s=0;s<Ml.length;s++){var o=Ml[s];o.blockedOn===e&&(o.blockedOn=null)}for(;0<Ml.length&&(s=Ml[0],s.blockedOn===null);)fy(s),s.blockedOn===null&&Ml.shift();if(s=(e.ownerDocument||e).$$reactFormReplay,s!=null)for(o=0;o<s.length;o+=3){var f=s[o],p=s[o+1],S=f[Ee]||null;if(typeof p=="function")S||hy(s);else if(S){var R=null;if(p&&p.hasAttribute("formAction")){if(f=p,S=p[Ee]||null)R=S.formAction;else if(ph(f)!==null)continue}else R=S.action;typeof R=="function"?s[o+1]=R:(s.splice(o,3),o-=3),hy(s)}}}function py(){function e(p){p.canIntercept&&p.info==="react-transition"&&p.intercept({handler:function(){return new Promise(function(S){return f=S})},focusReset:"manual",scroll:"manual"})}function n(){f!==null&&(f(),f=null),o||setTimeout(s,20)}function s(){if(!o&&!navigation.transition){var p=navigation.currentEntry;p&&p.url!=null&&navigation.navigate(p.url,{state:p.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var o=!1,f=null;return navigation.addEventListener("navigate",e),navigation.addEventListener("navigatesuccess",n),navigation.addEventListener("navigateerror",n),setTimeout(s,100),function(){o=!0,navigation.removeEventListener("navigate",e),navigation.removeEventListener("navigatesuccess",n),navigation.removeEventListener("navigateerror",n),f!==null&&(f(),f=null)}}}function vh(e){this._internalRoot=e}Jd.prototype.render=vh.prototype.render=function(e){var n=this._internalRoot;if(n===null)throw Error(l(409));var s=n.current,o=gs();iy(s,o,e,n,null,null)},Jd.prototype.unmount=vh.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var n=e.containerInfo;iy(e.current,2,null,e,null,null),Ld(),n[Ge]=null}};function Jd(e){this._internalRoot=e}Jd.prototype.unstable_scheduleHydration=function(e){if(e){var n=Ba();e={blockedOn:null,target:e,priority:n};for(var s=0;s<Ml.length&&n!==0&&n<Ml[s].priority;s++);Ml.splice(s,0,e),s===0&&fy(e)}};var gy=a.version;if(gy!=="19.2.7")throw Error(l(527,gy,"19.2.7"));se.findDOMNode=function(e){var n=e._reactInternals;if(n===void 0)throw typeof e.render=="function"?Error(l(188)):(e=Object.keys(e).join(","),Error(l(268,e)));return e=y(n),e=e!==null?x(e):null,e=e===null?null:e.stateNode,e};var h0={bundleType:0,version:"19.2.7",rendererPackageName:"react-dom",currentDispatcherRef:I,reconcilerVersion:"19.2.7"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var ef=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!ef.isDisabled&&ef.supportsFiber)try{Fe=ef.inject(h0),Ae=ef}catch{}}return Ru.createRoot=function(e,n){if(!c(e))throw Error(l(299));var s=!1,o="",f=Cg,p=kg,S=jg;return n!=null&&(n.unstable_strictMode===!0&&(s=!0),n.identifierPrefix!==void 0&&(o=n.identifierPrefix),n.onUncaughtError!==void 0&&(f=n.onUncaughtError),n.onCaughtError!==void 0&&(p=n.onCaughtError),n.onRecoverableError!==void 0&&(S=n.onRecoverableError)),n=sy(e,1,!1,null,null,s,o,null,f,p,S,py),e[Ge]=n.current,Zm(e),new vh(n)},Ru.hydrateRoot=function(e,n,s){if(!c(e))throw Error(l(299));var o=!1,f="",p=Cg,S=kg,R=jg,V=null;return s!=null&&(s.unstable_strictMode===!0&&(o=!0),s.identifierPrefix!==void 0&&(f=s.identifierPrefix),s.onUncaughtError!==void 0&&(p=s.onUncaughtError),s.onCaughtError!==void 0&&(S=s.onCaughtError),s.onRecoverableError!==void 0&&(R=s.onRecoverableError),s.formState!==void 0&&(V=s.formState)),n=sy(e,1,!0,n,s??null,o,f,V,p,S,R,py),n.context=ry(null),s=n.current,o=gs(),o=ft(o),f=Er(o),f.callback=null,Es(s,f,o),s=o,n.current.lanes=s,$s(n,s),_r(n),e[Ge]=n.current,Zm(e),new Jd(n)},Ru.version="19.2.7",Ru}var Ty;function iC(){if(Ty)return wh.exports;Ty=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(a){console.error(a)}}return t(),wh.exports=rC(),wh.exports}var lC=iC();const oC="https://otbyfkjxrkngvjziawki.supabase.co",cC="sb_publishable_NpUs0RDJH2YnllsqTKO6TQ_1jTdSsNQ",uC={getItem:()=>null,setItem:()=>{},removeItem:()=>{}},Ry=typeof window<"u"&&!!window.liveDesk,St=eC(oC,cC,{auth:{autoRefreshToken:!0,persistSession:!Ry,storage:Ry?uC:void 0,detectSessionInUrl:!0,flowType:"pkce",storageKey:"livedesk.mindexec.supabase.auth"}}),dC=new Set(["browserLanguage","platform","online","viewport","timezone","screen"]),fC={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(([a,i])=>dC.has(a)&&i!==void 0))}};function mC(t,a="Support request failed."){if(t&&typeof t=="object"&&"message"in t){const i=String(t.message||"").trim();if(i)return i.replace(/^.*Support request failed:\s*/i,"")}return t instanceof Error?t.message:a}function hC(t=fC){return t.collect()}async function pC(t,a="livedesk"){const{data:i,error:l}=await St.from("app_admins").select("role").eq("user_id",t).limit(1);if(l)throw l;const c=i?.[0]?.role||"user";if(c!=="owner"){const{error:j}=await St.rpc("register_product_access",{p_product_key:a,p_access_type:"free"});if(j)throw j}const[u,m,h]=await Promise.all([St.from("products").select("id, product_key, name, description, sort_order").order("sort_order"),St.from("product_admins").select("product_id, role").eq("user_id",t),St.from("user_products").select("product_id").eq("user_id",t).eq("is_active",!0)]);if(u.error)throw u.error;if(m.error)throw m.error;if(h.error)throw h.error;const g=u.data||[],y=(m.data||[]).map(j=>String(j.product_id)),x=(h.data||[]).map(j=>String(j.product_id)),b=c==="owner",w=b?g.map(j=>j.id):[...new Set([...y,...x])];return{products:g,access:{userId:t,globalRole:c,accessibleProductIds:w,managedProductIds:b?g.map(j=>j.id):y,canViewAllProducts:b,canViewAllPrivatePosts:b,canManageAllProducts:b,canCreateAnnouncements:b||y.length>0}}}async function gC(t=""){const{data:a,error:i}=await St.rpc("search_support_posts",{p_query:t.trim()||null,p_limit:250});if(i)throw i;return a||[]}async function vC(t){const{data:a,error:i}=await St.from("support_attachments").select("*").eq("post_id",t).order("created_at");if(i)throw i;const l=a||[];return Promise.all(l.map(async c=>{const u=await St.storage.from("support-attachments").createSignedUrl(c.storage_path,3600);return{...c,signed_url:u.data?.signedUrl||void 0}}))}async function yC(){const{data:t,error:a}=await St.from("support_notifications").select("*").order("created_at",{ascending:!1}).limit(30);if(a)throw a;return t||[]}async function bC(t){const{error:a}=await St.rpc("mark_support_notification_read",{p_notification_id:t});if(a)throw a}async function Ey(t){const{data:a,error:i}=await St.from("support_comments").select("*").eq("post_id",t).order("created_at");if(i)throw i;return a||[]}async function xC(t){const{data:a,error:i}=await St.from("support_votes").select("post_id").eq("user_id",t);if(i)throw i;return new Set((a||[]).map(l=>String(l.post_id)))}async function wC(t){const{data:a,error:i}=await St.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?hC():{}});if(i)throw i;const l=Array.isArray(a)?a[0]?.post_id:a?.post_id;if(!l)throw new Error("Support post was not created.");return String(l)}const SC=new Set(["image/png","image/jpeg","image/webp","text/plain","text/markdown","application/json","application/pdf"]);async function CC(t,a){if(!SC.has(a.type))throw new Error("This file type is not allowed.");if(a.size<=0||a.size>10*1024*1024)throw new Error("Attachments must be smaller than 10 MB.");const i=a.name.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"attachment",l=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`,c=`${t}/${l}-${i}`,u=await St.storage.from("support-attachments").upload(c,a,{contentType:a.type,upsert:!1});if(u.error)throw u.error;const{data:m,error:h}=await St.rpc("add_support_attachment",{p_post_id:t,p_storage_path:c,p_file_name:i,p_mime_type:a.type,p_size_bytes:a.size});if(h)throw await St.storage.from("support-attachments").remove([c]),h;const g=Array.isArray(m)?m[0]?.attachment_id:m?.attachment_id;if(!g)throw new Error("Attachment metadata was not created.");return String(g)}async function kC(t,a,i,l){const{error:c}=await St.rpc("update_support_post",{p_post_id:t,p_title:a,p_body:i,p_visibility:l});if(c)throw c}async function jC(t,a){const{error:i}=await St.rpc("add_support_comment",{p_post_id:t,p_body:a});if(i)throw i}async function AC(t){const{data:a,error:i}=await St.rpc("toggle_support_vote",{p_post_id:t});if(i)throw i;const l=Array.isArray(a)?a[0]:a;return{voted:!!l?.voted,totalVotes:Number(l?.total_votes||0)}}async function MC(t,a){const{error:i}=await St.rpc("change_support_post_status",{p_post_id:t,p_target_status:a});if(i)throw i}async function NC(t){const{error:a}=await St.rpc("set_support_post_hidden",{p_post_id:t,p_hidden:!0});if(a)throw a}async function TC(t,a){const{error:i}=await St.rpc("set_support_post_locked",{p_post_id:t,p_locked:a});if(i)throw i}async function RC(t,a){const{error:i}=await St.rpc("set_support_post_pinned",{p_post_id:t,p_pinned:a});if(i)throw i}async function EC(t,a){const{error:i}=await St.rpc("mark_support_duplicate",{p_post_id:t,p_duplicate_of_post_id:a});if(i)throw i}async function DC(t,a){const{error:i}=await St.rpc("accept_support_answer",{p_post_id:t,p_comment_id:a});if(i)throw i}async function LC(t,a=!0){const{error:i}=await St.rpc("hide_support_comment",{p_comment_id:t,p_hidden:a});if(i)throw i}const rp=[{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"}],_C=[{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"}],IC={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"]},zC={type:"all",product:"",status:"all",visibility:"all",sort:"recent",query:""};function kh(){if(typeof window>"u")return zC;const t=new URLSearchParams(window.location.search),a=window.location.pathname.match(/^\/support\/(questions|issues|features|announcements)$/)?.[1],i=t.get("type")||a||"",l=i==="questions"||i==="question"?"question":i==="issues"||i==="issue"?"issue":i==="features"||i==="feature"?"feature":i==="announcements"||i==="announcement"?"announcement":"all",c=t.get("visibility"),u=t.get("sort");return{type:l,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 OC(t){return t==="all"?"":t==="question"?"questions":t==="issue"?"issues":t==="feature"?"features":"announcements"}function HC(t,a){const i={...t,...a},l=new URLSearchParams;i.product&&l.set("product",i.product),i.status!=="all"&&l.set("status",i.status),i.visibility!=="all"&&l.set("visibility",i.visibility),i.sort!=="recent"&&l.set("sort",i.sort),i.query&&l.set("q",i.query);const c=OC(i.type),u=l.toString();return`/support${c?`/${c}`:""}${u?`?${u}`:""}`}function tf(t){const a=new Date(t);return Number.isFinite(a.getTime())?a.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"}):t}function jh(t){return t.replaceAll("-"," ").replace(/\b\w/g,a=>a.toUpperCase())}function Dy(t){return t==="question"?x0:t==="issue"?gx:t==="feature"?w0:S0}function Ly(t){return rp.find(a=>a.id===t)?.shortLabel||t}function Ah(t,a){return t.find(i=>i.id===a)?.name||"Product"}function ss(t){const a=mC(t);return/relation .* does not exist|function .* does not exist|schema cache/i.test(a)?"Support Board database is not installed yet. Apply the latest Supabase migration first.":/not-authenticated|jwt/i.test(a)?"Sign in again to use Support.":/product-access-denied|product-not-found/i.test(a)?"You do not have access to this product.":a}function Nx({session:t,currentProductKey:a="livedesk",appVersion:i="",onSignIn:l}){const[c,u]=d.useState(()=>kh()),[m,h]=d.useState(null),[g,y]=d.useState([]),[x,b]=d.useState([]),[w,j]=d.useState(""),[A,k]=d.useState([]),[T,M]=d.useState([]),[N,L]=d.useState([]),[z,H]=d.useState(()=>new Set),[G,_]=d.useState(!0),[Y,q]=d.useState(""),[U,K]=d.useState(""),[O,ve]=d.useState(!1),[me,Z]=d.useState(!1),[I,se]=d.useState(""),[W,F]=d.useState(()=>kh().query),[oe,le]=d.useState(!1),[Q,be]=d.useState(!1),[he,de]=d.useState(""),[ee,Ce]=d.useState(""),[Re,He]=d.useState("free"),[te,Ue]=d.useState(""),[mt,ne]=d.useState(""),[xe,Oe]=d.useState("admin"),[$e,ze]=d.useState(""),[Qe,qe]=d.useState(""),[Ye,ot]=d.useState(""),[B,ye]=d.useState(""),[je,Pe]=d.useState(""),[dt,nt]=d.useState([]),[bt,it]=d.useState({productId:"",postType:"question",title:"",body:"",visibility:"public",includeEnvironment:!0,files:[]}),Ct=d.useCallback($=>{const Xe={...c,...$};u(Xe),typeof window<"u"&&window.history.pushState({},"",HC(c,$))},[c]);d.useEffect(()=>{const $=()=>u(kh());return window.addEventListener("popstate",$),()=>window.removeEventListener("popstate",$)},[]);const pe=d.useCallback(async()=>{const $=await gC(c.query);return b($),t?.user.id&&H(await xC(t.user.id)),$},[c.query,t?.user.id]),De=d.useCallback(async()=>{if(!t?.user.id){h(null),y([]),b([]),j(""),L([]),_(!1);return}_(!0),K("");try{const $=await pC(t.user.id,a);h($.access),y($.products),await pe(),L(await yC())}catch($){K(ss($))}finally{_(!1)}},[a,pe,t?.user.id]);d.useEffect(()=>{De()},[De]);const Fe=d.useMemo(()=>m?m.canViewAllProducts?g:g.filter($=>m.accessibleProductIds.includes($.id)):[],[m,g]),Ae=d.useMemo(()=>{const $=Fe.find(Xe=>Xe.product_key===c.product);return m?.canViewAllProducts&&!c.product||c.product==="all"&&m?.canViewAllProducts?"all":$?$.product_key:Fe.some(Xe=>Xe.product_key===a)?a:Fe[0]?.product_key||""},[m?.canViewAllProducts,Fe,a,c.product]),ct=Ae==="all"?"":Fe.find($=>$.product_key===Ae)?.id||"",ht=d.useMemo(()=>{const $=new Map(g.map(ft=>[ft.id,ft.product_key]));return[...x.filter(ft=>c.type!=="all"&&ft.post_type!==c.type||Ae!=="all"&&ct&&ft.product_id!==ct||c.status==="needs-response"&&!["open","needs-info"].includes(ft.status)||c.status!=="all"&&c.status!=="needs-response"&&ft.status!==c.status||c.visibility!=="all"&&ft.visibility!==c.visibility?!1:$.has(ft.product_id))].sort((ft,mn)=>c.sort==="votes"?mn.vote_count-ft.vote_count||mn.updated_at.localeCompare(ft.updated_at):c.sort==="newest"?mn.created_at.localeCompare(ft.created_at):Number(mn.is_pinned)-Number(ft.is_pinned)||mn.updated_at.localeCompare(ft.updated_at))},[x,g,c.sort,c.status,c.type,c.visibility,ct,Ae]),Le=ht.find($=>$.id===w)||ht[0]||null,Dn=!!(Le&&m&&(m.canViewAllProducts||m.managedProductIds.includes(Le.product_id))),yn=!!(Le&&t?.user.id===Le.author_id)||Dn;d.useEffect(()=>{if(!Le){j(""),k([]),Z(!1);return}Le.id!==w&&j(Le.id)},[Le,w]),d.useEffect(()=>{let $=!0;return w?(Ey(w).then(Xe=>{$&&k(Xe)}).catch(Xe=>{$&&K(ss(Xe))}),vC(w).then(Xe=>{$&&M(Xe)}).catch(Xe=>{$&&K(ss(Xe))}),()=>{$=!1}):(k([]),M([]),()=>{$=!1})},[w]),d.useEffect(()=>{!bt.productId&&Fe[0]&&it($=>({...$,productId:ct||Fe[0].id}))},[Fe,bt.productId,ct]),d.useEffect(()=>{F(c.query)},[c.query]),d.useEffect(()=>{!ee&&Fe[0]&&Ce(Fe[0].id),!mt&&Fe[0]&&ne(Fe[0].id)},[Fe,ee,mt]);const et=$=>{Le&&b(Xe=>Xe.map(ft=>ft.id===Le.id?{...ft,...$}:ft))},xt=async $=>{if($.preventDefault(),!(!t||!bt.productId)){q("create"),K("");try{const Xe=await wC({productId:bt.productId,postType:bt.postType,title:bt.title,body:bt.body,visibility:bt.postType==="announcement"?"public":bt.visibility,appVersion:i,includeEnvironment:bt.postType==="issue"&&bt.includeEnvironment});for(const mn of dt)await CC(Xe,mn);const ft=await pe();ve(!1),nt([]),it(mn=>({...mn,title:"",body:"",files:[]})),j(Xe),ft.some(mn=>mn.id===Xe)||await De()}catch(Xe){K(ss(Xe))}finally{q("")}}},kn=async $=>{if($.preventDefault(),!!Le){q("edit"),K("");try{await kC(Le.id,Le.title,Le.body,Le.visibility),Z(!1),await pe()}catch(Xe){K(ss(Xe))}finally{q("")}}},Pn=async $=>{if($.preventDefault(),!(!Le||!I.trim())){q("comment"),K("");try{await jC(Le.id,I),se(""),k(await Ey(Le.id)),await pe()}catch(Xe){K(ss(Xe))}finally{q("")}}},_e=async()=>{if(!(!Le||Le.post_type!=="feature")){q("vote"),K("");try{const $=await AC(Le.id);H(Xe=>{const ft=new Set(Xe);return $.voted?ft.add(Le.id):ft.delete(Le.id),ft}),et({vote_count:$.totalVotes})}catch($){K(ss($))}finally{q("")}}},tn=async $=>{if(Le){q("status"),K("");try{await MC(Le.id,$),et({status:$}),await pe()}catch(Xe){K(ss(Xe))}finally{q("")}}},on=async()=>{if(!(!Le||!window.confirm("Hide this Support post from the board?"))){q("hide"),K("");try{await NC(Le.id),j(""),await pe()}catch($){K(ss($))}finally{q("")}}},Da=async()=>{if(Le){q("lock"),K("");try{await TC(Le.id,!Le.is_locked),et({is_locked:!Le.is_locked}),await pe()}catch($){K(ss($))}finally{q("")}}},nn=async()=>{if(Le){q("pin"),K("");try{await RC(Le.id,!Le.is_pinned),et({is_pinned:!Le.is_pinned}),await pe()}catch($){K(ss($))}finally{q("")}}},$s=async $=>{if(Le){q(`accept-${$}`),K("");try{await DC(Le.id,$),et({accepted_comment_id:$,status:Le.post_type==="question"?"answered":Le.status}),await pe()}catch(Xe){K(ss(Xe))}finally{q("")}}},Yn=async()=>{if(!(!Le||!B||B===Le.id)){q("duplicate"),K("");try{await EC(Le.id,B),j(""),ye(""),await pe()}catch($){K(ss($))}finally{q("")}}},Bs=async $=>{if(!$.read_at)try{await bC($.id),L(Xe=>Xe.map(ft=>ft.id===$.id?{...ft,read_at:new Date().toISOString()}:ft))}catch(Xe){K(ss(Xe))}$.post_id&&j($.post_id),le(!1)};return t?G&&!m?r.jsxs("section",{className:"support-page support-loading",children:[r.jsx(Mc,{className:"support-spin",size:23})," Loading Support Board..."]}):r.jsxs("section",{className:"support-page",children:[r.jsx("header",{className:"support-page-header support-page-actions-only",children:r.jsxs("div",{className:"support-header-actions",children:[r.jsxs("div",{className:"support-notification-wrap",children:[r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>le($=>!$),title:"Notifications",children:[r.jsx(v0,{size:16})," ",N.filter($=>!$.read_at).length>0&&r.jsx("b",{children:N.filter($=>!$.read_at).length})]}),oe&&r.jsxs("div",{className:"support-notification-popover",children:[r.jsx("strong",{children:"Notifications"}),N.length===0?r.jsx("span",{className:"support-muted",children:"No notifications yet."}):N.map($=>r.jsxs("button",{type:"button",className:$.read_at?"":"unread",onClick:()=>{Bs($)},children:[r.jsx("b",{children:$.title}),r.jsx("span",{children:$.body}),r.jsx("small",{children:tf($.created_at)})]},$.id))]})]}),m?.canViewAllProducts&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>be($=>!$),children:[r.jsx(Kn,{size:16})," Admin"]}),r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{De()},disabled:G,children:[r.jsx(Mc,{size:16,className:G?"support-spin":""})," Refresh"]}),r.jsxs("button",{className:"support-primary-button",type:"button",onClick:()=>ve(!0),disabled:Fe.length===0,children:[r.jsx(yh,{size:17})," New request"]})]})}),U&&r.jsxs("div",{className:"support-error",role:"alert",children:[r.jsx(Ra,{size:17})," ",r.jsx("span",{children:U}),r.jsx("button",{type:"button",onClick:()=>K(""),"aria-label":"Dismiss error",children:r.jsx(Ra,{size:15})})]}),O&&r.jsxs("form",{className:"support-composer",onSubmit:$=>{xt($)},children:[r.jsxs("div",{className:"support-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"New Support request"}),r.jsx("strong",{children:"Describe one actionable problem or idea."})]}),r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>ve(!1),"aria-label":"Close composer",children:r.jsx(Ra,{size:18})})]}),r.jsxs("div",{className:"support-form-grid",children:[r.jsxs("label",{children:[r.jsx("span",{children:"Product"}),r.jsx("select",{value:bt.productId,onChange:$=>it(Xe=>({...Xe,productId:$.target.value})),children:Fe.map($=>r.jsx("option",{value:$.id,children:$.name},$.id))})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Type"}),r.jsx("select",{value:bt.postType,onChange:$=>it(Xe=>({...Xe,postType:$.target.value})),children:rp.filter($=>$.id!=="announcement"||m?.canCreateAnnouncements).map($=>r.jsx("option",{value:$.id,children:$.label},$.id))})]}),r.jsxs("label",{className:"support-form-wide",children:[r.jsx("span",{children:"Title"}),r.jsx("input",{required:!0,minLength:3,maxLength:180,value:bt.title,onChange:$=>it(Xe=>({...Xe,title:$.target.value})),placeholder:"A short, searchable summary"})]}),r.jsxs("label",{className:"support-form-wide",children:[r.jsx("span",{children:bt.postType==="issue"?"What happened?":bt.postType==="feature"?"Describe the desired behavior":bt.postType==="announcement"?"Announcement":"Question"}),r.jsx("textarea",{required:!0,value:bt.body,onChange:$=>it(Xe=>({...Xe,body:$.target.value})),placeholder:"Include the context another person needs to respond.",rows:6})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Visibility"}),r.jsxs("select",{value:bt.visibility,disabled:bt.postType==="announcement",onChange:$=>it(Xe=>({...Xe,visibility:$.target.value})),children:[r.jsx("option",{value:"public",children:"Public"}),r.jsx("option",{value:"private",children:"Private"})]})]}),bt.postType==="issue"&&r.jsxs("label",{className:"support-checkbox",children:[r.jsx("input",{type:"checkbox",checked:bt.includeEnvironment,onChange:$=>it(Xe=>({...Xe,includeEnvironment:$.target.checked}))}),r.jsx("span",{children:"Attach safe browser/runtime details"})]}),r.jsxs("label",{className:"support-form-wide",children:[r.jsx("span",{children:"Attachments"}),r.jsx("input",{type:"file",multiple:!0,accept:"image/png,image/jpeg,image/webp,text/plain,text/markdown,application/json,application/pdf",onChange:$=>nt(Array.from($.target.files||[]).slice(0,5))}),r.jsx("small",{className:"support-muted",children:"Up to 5 files, 10 MB each. Images, text, JSON, Markdown, and PDF."})]})]}),r.jsxs("div",{className:"support-composer-footer",children:[r.jsx("span",{children:dt.length>0?`${dt.length} attachment${dt.length===1?"":"s"} selected.`:"Private posts are visible only to you and the product support staff."}),r.jsxs("button",{className:"support-primary-button",type:"submit",disabled:Y==="create",children:[r.jsx(Wu,{size:16})," ",Y==="create"?"Submitting...":"Submit request"]})]})]}),r.jsxs("div",{className:"support-tabs",role:"tablist","aria-label":"Support post type",children:[r.jsx("button",{className:c.type==="all"?"active":"",type:"button",onClick:()=>Ct({type:"all"}),children:"All"}),rp.map($=>{const Xe=Dy($.id);return r.jsxs("button",{className:c.type===$.id?"active":"",type:"button",onClick:()=>Ct({type:$.id}),children:[r.jsx(Xe,{size:15})," ",$.label]},$.id)})]}),Q&&m?.canViewAllProducts&&r.jsxs("section",{className:"support-admin-panel",children:[r.jsxs("div",{className:"support-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Owner controls"}),r.jsx("strong",{children:"Products and access are managed by immutable user IDs behind these email lookup forms."})]}),r.jsx(Kn,{size:19})]}),r.jsxs("div",{className:"support-admin-grid",children:[r.jsxs("form",{onSubmit:$=>{},children:[r.jsx("strong",{children:"Grant product access"}),r.jsx("input",{type:"email",required:!0,placeholder:"User email",value:he,onChange:$=>de($.target.value)}),r.jsx("select",{value:ee,onChange:$=>Ce($.target.value),children:Fe.map($=>r.jsx("option",{value:$.id,children:$.name},$.id))}),r.jsxs("select",{value:Re,onChange:$=>He($.target.value),children:[r.jsx("option",{value:"free",children:"Free"}),r.jsx("option",{value:"user",children:"User"}),r.jsx("option",{value:"paid",children:"Paid"}),r.jsx("option",{value:"beta",children:"Beta"}),r.jsx("option",{value:"staff",children:"Staff"})]}),r.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:je==="access",children:[r.jsx(Or,{size:15})," Grant access"]})]}),r.jsxs("form",{onSubmit:$=>{},children:[r.jsx("strong",{children:"Assign product admin"}),r.jsx("input",{type:"email",required:!0,placeholder:"Admin email",value:te,onChange:$=>Ue($.target.value)}),r.jsx("select",{value:mt,onChange:$=>ne($.target.value),children:Fe.map($=>r.jsx("option",{value:$.id,children:$.name},$.id))}),r.jsxs("select",{value:xe,onChange:$=>Oe($.target.value),children:[r.jsx("option",{value:"admin",children:"Admin"}),r.jsx("option",{value:"support",children:"Support"}),r.jsx("option",{value:"moderator",children:"Moderator"})]}),r.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:je==="product-admin",children:[r.jsx(Kn,{size:15})," Assign admin"]})]}),r.jsxs("form",{onSubmit:$=>{},children:[r.jsx("strong",{children:"Add a product"}),r.jsx("input",{required:!0,pattern:"[a-z0-9][a-z0-9_-]{1,48}",placeholder:"product-key",value:$e,onChange:$=>ze($.target.value)}),r.jsx("input",{required:!0,placeholder:"Product name",value:Qe,onChange:$=>qe($.target.value)}),r.jsx("input",{placeholder:"Description",value:Ye,onChange:$=>ot($.target.value)}),r.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:je==="product",children:[r.jsx(yh,{size:15})," Add product"]})]})]})]}),r.jsxs("form",{className:"support-search-bar",onSubmit:$=>{$.preventDefault(),Ct({query:W.trim()})},children:[r.jsxs("label",{children:[r.jsx("span",{children:"Search Support"}),r.jsx("input",{value:W,onChange:$=>F($.target.value),placeholder:"Search titles and request details"})]}),r.jsxs("button",{className:"support-secondary-button",type:"submit",children:[r.jsx(vy,{size:15})," Search"]}),c.query&&r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{F(""),Ct({query:""})},"aria-label":"Clear search",children:r.jsx(Ra,{size:16})})]}),r.jsxs("div",{className:"support-filter-bar",children:[r.jsxs("div",{className:"support-filter-title",children:[r.jsx(vy,{size:16}),r.jsx("span",{children:"Filter"})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Product"}),r.jsxs("select",{value:Ae,onChange:$=>Ct({product:$.target.value}),disabled:!m?.canViewAllProducts&&Fe.length<=1,children:[r.jsx("option",{value:"all",children:"All products"}),Fe.map($=>r.jsx("option",{value:$.product_key,children:$.name},$.id))]})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Status"}),r.jsx("select",{value:c.status,onChange:$=>Ct({status:$.target.value}),children:_C.map($=>r.jsx("option",{value:$.id,children:$.label},$.id))})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Visibility"}),r.jsxs("select",{value:c.visibility,onChange:$=>Ct({visibility:$.target.value}),children:[r.jsx("option",{value:"all",children:"All visibility"}),r.jsx("option",{value:"public",children:"Public"}),r.jsx("option",{value:"private",children:"Private"})]})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Sort"}),r.jsxs("select",{value:c.sort,onChange:$=>Ct({sort:$.target.value}),children:[r.jsx("option",{value:"recent",children:"Recently updated"}),r.jsx("option",{value:"newest",children:"Newest"}),r.jsx("option",{value:"votes",children:"Most votes"})]})]})]}),m?.canViewAllProducts&&r.jsxs("div",{className:"support-admin-shortcuts",children:[r.jsxs("span",{children:[r.jsx(Kn,{size:15})," Owner view"]}),r.jsx("button",{type:"button",onClick:()=>Ct({status:"needs-response"}),children:"Needs response"}),r.jsx("button",{type:"button",onClick:()=>Ct({visibility:"private"}),children:"Private requests"}),r.jsx("button",{type:"button",onClick:()=>Ct({type:"feature",status:"all",sort:"votes"}),children:"High-vote features"})]}),r.jsxs("div",{className:"support-board-layout",children:[r.jsxs("section",{className:"support-post-list","aria-label":"Support posts",children:[r.jsxs("div",{className:"support-list-heading",children:[r.jsxs("span",{children:[ht.length," request",ht.length===1?"":"s"]}),r.jsx("small",{children:Ae==="all"?"All products":Ah(Fe,ct)})]}),ht.length===0?r.jsxs("div",{className:"support-list-empty",children:[r.jsx(Pu,{size:25}),r.jsx("strong",{children:"No posts match these filters."}),r.jsx("span",{children:"Start with a focused question, issue report, or feature request."}),Fe.length>0&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>ve(!0),children:[r.jsx(yh,{size:16})," Create the first request"]})]}):ht.map($=>{const Xe=Dy($.post_type);return r.jsxs("button",{type:"button",className:`support-post-row ${$.id===Le?.id?"active":""}`,onClick:()=>{j($.id),Z(!1)},children:[r.jsx("span",{className:"support-post-row-icon",children:r.jsx(Xe,{size:17})}),r.jsxs("span",{className:"support-post-row-copy",children:[r.jsxs("span",{className:"support-post-row-meta",children:[r.jsx("b",{children:Ah(g,$.product_id)}),r.jsx("em",{children:Ly($.post_type)}),$.visibility==="private"&&r.jsx(Di,{size:13})]}),r.jsx("strong",{children:$.title}),r.jsxs("small",{children:[jh($.status)," · ",tf($.updated_at)," · ",$.comment_count," comments"]})]}),$.post_type==="feature"&&r.jsxs("span",{className:"support-vote-count",children:[r.jsx(px,{size:14})," ",$.vote_count]})]},$.id)})]}),r.jsx("section",{className:"support-post-detail","aria-label":"Support post detail",children:Le?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"support-detail-head",children:[r.jsxs("div",{className:"support-detail-badges",children:[r.jsx("span",{className:"support-product-badge",children:Ah(g,Le.product_id)}),r.jsx("span",{className:"support-type-badge",children:Ly(Le.post_type)}),r.jsx("span",{className:`support-status-badge status-${Le.status}`,children:jh(Le.status)}),Le.visibility==="private"&&r.jsxs("span",{className:"support-private-badge",children:[r.jsx(Di,{size:13})," Private"]})]}),r.jsxs("div",{className:"support-detail-actions",children:[yn&&r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>Z($=>!$),title:"Edit post",children:r.jsx(y0,{size:16})}),Dn&&r.jsxs(r.Fragment,{children:[r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{nn()},disabled:Y==="pin",title:Le.is_pinned?"Unpin post":"Pin post",children:r.jsx(yy,{size:16})}),r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{Da()},disabled:Y==="lock",title:Le.is_locked?"Unlock post":"Lock post",children:r.jsx(Di,{size:16})}),r.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{on()},disabled:Y==="hide",title:"Hide post",children:r.jsx(by,{size:16})})]})]})]}),me?r.jsxs("form",{className:"support-edit-form",onSubmit:$=>{kn($)},children:[r.jsx("input",{value:Le.title,onChange:$=>et({title:$.target.value}),minLength:3,maxLength:180,required:!0}),r.jsx("textarea",{value:Le.body,onChange:$=>et({body:$.target.value}),rows:9,required:!0}),r.jsxs("div",{className:"support-edit-actions",children:[r.jsxs("select",{value:Le.visibility,onChange:$=>et({visibility:$.target.value}),children:[r.jsx("option",{value:"public",children:"Public"}),r.jsx("option",{value:"private",children:"Private"})]}),r.jsxs("button",{className:"support-primary-button",type:"submit",disabled:Y==="edit",children:[r.jsx(Or,{size:16})," Save changes"]})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("h3",{children:Le.title}),r.jsx("div",{className:"support-detail-body",children:Le.body.split(`
|
|
10
|
+
`).map(($,Xe)=>r.jsx("p",{children:$||" "},`${Le.id}-body-${Xe}`))})]}),r.jsxs("div",{className:"support-detail-meta",children:[r.jsxs("span",{children:["Opened ",tf(Le.created_at)]}),Le.app_version&&r.jsxs("span",{children:["Version ",Le.app_version]}),Le.platform&&r.jsx("span",{children:Le.platform}),Le.is_locked&&r.jsxs("span",{children:[r.jsx(Di,{size:13})," Locked"]}),Le.is_pinned&&r.jsxs("span",{children:[r.jsx(yy,{size:13})," Pinned"]})]}),r.jsxs("div",{className:"support-detail-controls",children:[Le.post_type==="feature"&&r.jsxs("button",{className:`support-vote-button ${z.has(Le.id)?"voted":""}`,type:"button",onClick:()=>{_e()},disabled:Y==="vote",children:[r.jsx(b0,{size:16})," ",z.has(Le.id)?"Voted":"Vote"," ",r.jsx("b",{children:Le.vote_count})]}),Dn&&r.jsxs("label",{className:"support-status-control",children:[r.jsx("span",{children:"Change status"}),r.jsx("select",{value:Le.status,onChange:$=>{tn($.target.value)},disabled:Y==="status",children:(IC[Le.post_type]||[]).map($=>r.jsx("option",{value:$,children:jh($)},$))})]}),Dn&&r.jsxs(r.Fragment,{children:[r.jsxs("select",{className:"support-status-control",value:B,onChange:$=>ye($.target.value),children:[r.jsx("option",{value:"",children:"Duplicate of..."}),ht.filter($=>$.id!==Le.id&&$.product_id===Le.product_id).map($=>r.jsx("option",{value:$.id,children:$.title.slice(0,55)},$.id))]}),r.jsx("button",{className:"support-secondary-button",type:"button",onClick:()=>{Yn()},disabled:!B||Y==="duplicate",children:"Merge duplicate"})]})]}),T.length>0&&r.jsxs("div",{className:"support-attachments",children:[r.jsx("div",{className:"support-section-heading",children:r.jsxs("div",{children:[r.jsx("span",{children:"Attachments"}),r.jsxs("strong",{children:[T.length," file",T.length===1?"":"s"]})]})}),T.map($=>r.jsxs("a",{href:$.signed_url,target:"_blank",rel:"noreferrer",children:[r.jsx(Np,{size:14})," ",$.file_name,r.jsxs("small",{children:[Math.ceil($.size_bytes/1024)," KB"]})]},$.id))]}),r.jsxs("div",{className:"support-comments",children:[r.jsxs("div",{className:"support-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Discussion"}),r.jsxs("strong",{children:[A.length," comment",A.length===1?"":"s"]})]}),Le.is_locked&&r.jsxs("span",{className:"support-locked-label",children:[r.jsx(Di,{size:14})," Locked"]})]}),A.length===0?r.jsx("p",{className:"support-muted",children:"No response yet. Keep the conversation focused on this request."}):r.jsx("div",{className:"support-comment-list",children:A.map($=>r.jsxs("article",{className:`support-comment ${$.is_staff_answer?"staff":""} ${Le.accepted_comment_id===$.id?"accepted":""}`,children:[r.jsxs("div",{className:"support-comment-head",children:[r.jsx("strong",{children:$.is_staff_answer?"LiveDesk Support":$.author_id===t.user.id?"You":"Support user"}),$.is_staff_answer&&r.jsxs("span",{children:[r.jsx(Kn,{size:13})," Staff answer"]}),Le.accepted_comment_id===$.id&&r.jsxs("span",{children:[r.jsx(ea,{size:13})," Accepted"]}),r.jsx("time",{children:tf($.created_at)})]}),r.jsx("p",{children:$.body}),r.jsxs("div",{className:"support-comment-actions",children:[(t.user.id===Le.author_id||Dn)&&Le.post_type==="question"&&Le.accepted_comment_id!==$.id&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{$s($.id)},disabled:Y===`accept-${$.id}`,children:[r.jsx(Or,{size:14})," Accept answer"]}),Dn&&r.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{LC($.id)},title:"Hide comment",children:r.jsx(by,{size:14})})]})]},$.id))}),!Le.is_locked&&r.jsxs("form",{className:"support-comment-form",onSubmit:$=>{Pn($)},children:[r.jsx("textarea",{value:I,onChange:$=>se($.target.value),placeholder:"Add a focused reply...",rows:3}),r.jsxs("button",{className:"support-primary-button",type:"submit",disabled:Y==="comment"||!I.trim(),children:[r.jsx(Wu,{size:15})," Reply"]})]})]})]}):r.jsxs("div",{className:"support-detail-empty",children:[r.jsx(Pu,{size:28}),r.jsx("strong",{children:"Select a Support request"}),r.jsx("span",{children:"Its discussion and staff actions will appear here."})]})})]})]}):r.jsx("section",{className:"support-page support-auth-page",children:r.jsxs("div",{className:"support-empty-hero",children:[r.jsx("span",{className:"support-hero-icon",children:r.jsx(Pu,{size:28})}),r.jsx("p",{className:"support-eyebrow",children:"LiveDesk Support"}),r.jsx("h2",{children:"Get help, report issues, and shape the product."}),r.jsx("p",{children:"Sign in to see the products attached to your account and submit a private or public request."}),r.jsxs("button",{className:"support-primary-button",type:"button",onClick:l,children:[r.jsx(Kn,{size:17})," Sign in with Google"]})]})})}function nf(t){return!!t&&typeof t=="object"}function Tx(t){let a=t;return nf(a)&&"data"in a&&(a=a.data),nf(a)&&"session"in a&&(a=a.session),!nf(a)||typeof a.access_token!="string"||!a.access_token||!nf(a.user)||typeof a.user.id!="string"||!a.user.id?null:a}function _y(t){return t?.access_token?t.refresh_token?"":"refresh-token-required":"access-token-required"}const Bu=5179,En=Hl(`http://127.0.0.1:${Bu}`);function FC(t){const a=t.split(".").map(i=>Number(i));return a.length===4&&a.every(i=>Number.isInteger(i)&&i>=0&&i<=255)?a:[]}function PC(t){const a=t.trim().toLowerCase();return a==="localhost"||a==="127.0.0.1"||a==="::1"||a==="[::1]"}function $C(t){const a=t.trim().toLowerCase();return!a||a==="0.0.0.0"||a==="::"||a==="[::]"}function BC(t){const a=FC(t);return a.length===0?!1:a[0]===10||a[0]===172&&a[1]>=16&&a[1]<=31||a[0]===192&&a[1]===168}function UC(t){return t.includes(":")&&!t.startsWith("[")?`[${t}]`:t}function qC(t){const a=String(t||"").trim();if(!a)return null;const i=/^[a-z][a-z\d+.-]*:\/\//i.test(a)?a:`tcp://${a}`;try{const l=new URL(i),c=l.hostname.replace(/^\[|\]$/g,""),u=Number(l.port);return!c||!Number.isInteger(u)||u<1||u>65535||$C(c)?null:{host:c,port:u}}catch{return null}}function Hl(t){const a=String(t||"").trim()||`http://127.0.0.1:${Bu}`,i=/^[a-z][a-z\d+.-]*:\/\//i.test(a)?a:`http://${a}`;try{const l=new URL(i);return l.port||(l.port=String(Bu)),l.hash="",l.search="",l.toString().replace(/\/+$/,"")}catch{return`http://127.0.0.1:${Bu}`}}function GC(t){const a=qC(t);return a?Hl(`http://${UC(a.host)}:${Bu}`):""}function Iy(t){const i=[t?.endpoint,...Array.isArray(t?.endpoint_candidates)?t.endpoint_candidates:[]].map(l=>GC(String(l||""))).filter(Boolean);return[...new Set(i)]}function Uu(t=En){if(!(typeof window>"u"||window.location.protocol!=="https:"))try{const a=new URL(t);if(a.protocol!=="http:")return;if(PC(a.hostname))return"loopback";if(BC(a.hostname))return"local"}catch{return}}function Kf(t,a=En){const i=new URL(t,Hl(a));return i.protocol=i.protocol==="https:"?"wss:":"ws:",i.toString()}async function We(t,a,i=En){const l=Hl(i),c={...a,headers:{"Content-Type":"application/json",...a?.headers||{}},cache:"no-store"},u=Uu(l);u&&(c.targetAddressSpace=u);let m;try{m=await fetch(`${l}${t}`,c)}catch(g){throw u?new Error("LiveDesk Hub is not reachable at this local network address. If Chrome shows a local network prompt, allow it; otherwise restart the Hub so port 5179 is open on the network."):g}let h=null;try{h=await m.json()}catch{h=null}if(!m.ok){const g=h&&typeof h=="object"&&"error"in h?String(h.error||""):"";throw new Error(`${m.status} ${g||m.statusText}`)}return h}async function Rx({baseUrl:t=En,targetRole:a,previousRuntimePid:i=0,allowedStates:l=["running","waiting-auth"],timeoutMs:c=3e4}){const u=Date.now()+c;let m=null;for(;Date.now()<u;){try{const g=await We("/api/runtime/status",void 0,t),y=String(g.role||"").toLowerCase(),x=String(g.state||"").toLowerCase(),b=Number(g.runtimePid||0),w=i>1?b>1&&b!==i:b>1;if(y===a&&l.map(j=>j.toLowerCase()).includes(x)&&w)return g}catch(g){m=g}await new Promise(g=>setTimeout(g,300))}const h=m instanceof Error?` ${m.message}`:"";throw new Error(`LiveDesk runtime did not become ${a} with a new process.${h}`)}function VC(t,a=120){if(typeof window>"u")return;const i=new URL(window.location.href);i.port=String(t),i.pathname="/",i.search="",i.hash="";const l=i.toString();let c=0;const u=()=>{fetch(l,{cache:"no-store",mode:"no-cors"}).then(()=>window.location.replace(l)).catch(()=>{if(c+=1,c>=a){window.location.replace(l);return}window.setTimeout(u,250)})};u()}function Ex(t){if(!t)return"-";const a=Date.now()-Date.parse(t);return Number.isFinite(a)?a<1e3?"now":a<6e4?`${Math.round(a/1e3)}s`:a<36e5?`${Math.round(a/6e4)}m`:`${Math.round(a/36e5)}h`:"-"}async function Nf(t){await navigator.clipboard.writeText(t)}function Dx({size:t=22}){return r.jsxs("svg",{width:t,height:t,viewBox:"0 0 28 28",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[r.jsx("rect",{x:"2.5",y:"4",width:"14",height:"9",rx:"1.5",stroke:"currentColor",strokeWidth:"1.7",opacity:"0.42"}),r.jsx("path",{d:"M7 16v1.5h5",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",opacity:"0.42"}),r.jsx("rect",{x:"10.5",y:"2.5",width:"14",height:"9",rx:"1.5",stroke:"currentColor",strokeWidth:"1.7",opacity:"0.62"}),r.jsx("path",{d:"M15 14.5V16h5",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",opacity:"0.62"}),r.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"}),r.jsx("path",{d:"M12 21v1.5H9.5M16 21v1.5h2.5M9.5 22.5h9",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round"})]})}const Lx={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 Hub-hosted Codex tasks on connected Clients within the selected permissions, timeouts, and audit controls."},ip={en:Lx,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에 전달합니다. 선택한 권한, 제한 시간과 감사 기록 범위 안에서만 실행됩니다."},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 タスクを接続中の 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:"在已连接 Client 上运行由 Hub 托管的 Codex 任务,并遵守所选权限、超时和审计控制。"},"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:"在已連線 Client 上執行由 Hub 託管的 Codex 工作,並遵守所選權限、逾時與稽核控制。"},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:"Ejecuta tareas Codex alojadas en el Hub sobre Clients conectados, respetando permisos, límites de tiempo y auditoría."},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:"Exécute des tâches Codex hébergées par le Hub sur les Clients connectés, selon les permissions, délais et règles d’audit."},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:"Führt Hub-gehostete Codex-Aufgaben auf verbundenen Clients innerhalb der gewählten Berechtigungen, Zeitlimits und Auditregeln 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:"Executa tarefas Codex hospedadas no Hub em Clients conectados, respeitando permissões, limites de tempo e auditoria."},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:"Esegue attività Codex ospitate dall’Hub sui Client connessi rispettando permessi, timeout e controlli di audit."},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:"Jalankan tugas Codex yang di-host Hub pada Client terhubung sesuai izin, batas waktu, dan kontrol audit."},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:"Chạy tác vụ Codex do Hub lưu trữ trên các Client đã kết nối trong phạm vi quyền, thời gian chờ và kiểm toán đã chọn."},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 ที่โฮสต์บน Hub กับ Client ที่เชื่อมต่อ ภายใต้สิทธิ์ timeout และการตรวจสอบที่เลือก"},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:"चुनी हुई permissions, timeout और audit controls के भीतर जुड़े Clients पर Hub-hosted Codex tasks चलाता है।"},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 المستضافة على Hub في Clients المتصلين ضمن الصلاحيات والمهل وضوابط التدقيق المحددة."},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 üzerinde barındırılan Codex görevlerini seçili izinler, zaman aşımları ve denetim kontrolleri içinde bağlı Client’larda çalıştırır."}};function Yf(t){const a=t?[t]:typeof navigator>"u"?["en"]:navigator.languages?.length?navigator.languages:[navigator.language];for(const i of a){const l=String(i||"").trim(),c=l.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(ip[l])return l;if(ip[u])return u}return"en"}function zf(t,a){const i=Yf(a);return ip[i]?.[t]||Lx[t]}function lp(t,a,i){return`${t}
|
|
11
|
+
${zf(a,i)}`}const _x={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"},WC={en:_x,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"}},Ix={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"},KC={en:Ix,ko:{eyebrow:"컴퓨터 역할",title:"이 컴퓨터를 Hub로 사용할까요?",description:"Hub는 Client 컴퓨터를 연결하고 관리합니다.",restartNotice:"다른 컴퓨터가 Hub라면 이 컴퓨터가 새 Hub가 됩니다.",cancel:"취소",confirm:"Hub로 설정",closeLabel:"Hub 설정 확인 닫기"}};function YC(t){const a=Yf(t);return WC[a]||_x}function QC(t){const a=Yf(t);return KC[a]||Ix}const XC=[{id:"docs",label:"Doc",icon:If},{id:"support",label:"Support",icon:Pu},{id:"pricing",label:"Pricing",icon:$u},{id:"settings",label:"Settings",icon:Tp}],zy=[0,1e3,2e3,5e3,1e4,2e4,3e4];function ZC(){return typeof window>"u"?"":window.location.port==="5179"?window.location.origin:"http://127.0.0.1:5179"}async function ho(t,a=!1){const i=a?"":sessionStorage.getItem("livedesk.client.csrf");if(i)return i;const l=await fetch(`${t}/api/runtime/status`,{cache:"no-store"}),c=await l.json().catch(()=>({}));if(!l.ok)throw new Error(c.error||`Client runtime returned HTTP ${l.status}.`);const u=String(c.csrfToken||"");return u&&sessionStorage.setItem("livedesk.client.csrf",u),u}function op(t){return`${Math.max(0,Math.min(100,Number(t||0))).toFixed(0)}%`}function Mh(t){return Number.isFinite(t)?`${Math.max(0,Math.min(100,Number(t))).toFixed(0)}%`:"—"}function zx(t){return Number.isFinite(t)?op(Number(t)):"0%"}function Co(t){const a=Number(t);return!Number.isFinite(a)||a<0?"—":a>=1024**4?`${(a/1024**4).toFixed(a>=10*1024**4?0:1)} TB`:a>=1024**3?`${(a/1024**3).toFixed(a>=10*1024**3?0:1)} GB`:`${(a/1024**2).toFixed(0)} MB`}function Oy(t){const a=Math.max(0,Number(t||0));return a>=1024**3?`${(a/1024**3).toFixed(1)} GB/s`:a>=1024**2?`${(a/1024**2).toFixed(1)} MB/s`:a>=1024?`${(a/1024).toFixed(1)} KB/s`:`${a.toFixed(0)} B/s`}function JC(t,a){const i=Number(t||0)/1073741824,l=Number(a||0)/1024**3;return l>0?`${i.toFixed(1)} / ${l.toFixed(1)} GB`:"Checking..."}function e1(t,a){return!Number.isFinite(a)||Number(a)<=0?"Dedicated memory unavailable":Number.isFinite(t)?`${Co(t)} / ${Co(a)}`:`${Co(a)} available`}function t1(t){const a=Math.max(0,Math.floor(Number(t||0)/60)),i=Math.floor(a/1440),l=Math.floor(a%1440/60),c=a%60;return i>0?`${i}d ${l}h`:l>0?`${l}h ${c}m`:`${c}m`}function af({icon:t,label:a,value:i,detail:l,percent:c}){return r.jsxs("article",{className:"client-resource-metric",children:[r.jsxs("div",{className:"client-resource-metric-head",children:[r.jsx(t,{size:17}),r.jsx("span",{children:a}),r.jsx("strong",{children:i})]}),r.jsx("small",{title:l,children:l}),r.jsx("i",{"aria-hidden":"true",children:r.jsx("b",{style:{width:zx(c)}})})]})}function n1(t,a){const i=t?.user.user_metadata||{},l=i.full_name||i.name||i.preferred_username||t?.user.email||t?.user.id||a?.userName||a?.auth?.name||a?.userEmail||a?.userId||"Account";return String(l).trim()||"Account"}function a1(t,a){const i=t?.user.user_metadata||{},l=i.avatar_url||i.picture||a?.userAvatarUrl||a?.auth?.avatarUrl;return typeof l=="string"?l.trim():""}function s1({page:t,status:a}){const l={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 r.jsxs("section",{className:"client-service-page",children:[r.jsx("span",{className:"client-unified-section-label",children:l.label}),r.jsx("h2",{children:l.title}),r.jsx("p",{children:l.body}),r.jsxs("div",{className:"client-service-page-card",children:[t==="docs"&&r.jsxs(r.Fragment,{children:[r.jsx("strong",{children:"Automatic connection"}),r.jsx("span",{children:"Start LiveDesk. This computer signs in, finds the Hub, and becomes available without another action."})]}),t==="pricing"&&r.jsxs(r.Fragment,{children:[r.jsx("strong",{children:"One plan, managed at the Hub"}),r.jsx("span",{children:"Computer access follows the account and plan used by the Hub."})]}),t==="settings"&&r.jsxs(r.Fragment,{children:[r.jsx("strong",{children:"Saved sign-in"}),r.jsx("span",{children:a?.auth?.persisted?"Enabled on this computer":"Sign in once to enable automatic reconnection"})]})]})]})}function r1({session:t,status:a,pin:i,error:l,roleChangeMessage:c,videoAccelerationBusy:u,slotInput:m,slotBusy:h,onSignIn:g,onPinChange:y,onSubmitPin:x,onSlotInputChange:b,onSaveSlot:w,onEnableVideoAcceleration:j}){const A=a?.connectionState==="connected",k=a?.videoAcceleration,T=u||k?.busy||k?.state==="installing",M=k?.ready?`${k.encoder||"H.264"} · ${k.driver||"VAAPI"}`:T?"Setting up…":k?.message||"Setup available",N=a?.system?.memoryTotalBytes?Number(a.system.memoryUsedBytes||0)/a.system.memoryTotalBytes*100:0,L=a?.system?.gpus||[],z=L.find(O=>Number.isFinite(O.usagePercent)||Number.isFinite(O.memoryTotalBytes))||L[0],H=Number.isFinite(z?.usagePercent)?Number(z?.usagePercent):null,G=Number.isFinite(z?.memoryTotalBytes)&&Number(z?.memoryTotalBytes)>0&&Number.isFinite(z?.memoryUsedBytes)?Number(z?.memoryUsedBytes)/Number(z?.memoryTotalBytes)*100:null,_=a?.system?.disks||[],Y=a?.system?.network,q=Y?.interfaces||[],U=[...new Set(q.map(O=>O.name).filter(Boolean))],K=q.map(O=>O.address).filter(Boolean);return r.jsxs("section",{className:"client-home-page",children:[r.jsxs("header",{className:"client-home-heading",children:[r.jsxs("div",{children:[r.jsx("p",{className:"client-unified-eyebrow",children:"THIS COMPUTER"}),r.jsx("h2",{children:a?.deviceName||"This Computer"})]}),r.jsxs("span",{className:`client-unified-role-chip ${A?"connected":""}`,children:[r.jsx(Ea,{size:15})," ",A?"Online":"Connecting"]})]}),r.jsxs("div",{className:"client-home-layout",children:[r.jsxs("section",{className:"client-main-surface","aria-label":"Client computer",children:[r.jsxs("div",{className:"client-main-surface-head",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"SYSTEM STATUS"}),r.jsx("strong",{children:"Hardware at a glance"})]}),r.jsxs("small",{children:[r.jsx(bx,{size:14})," Uptime ",t1(a?.system?.uptimeSeconds)]})]}),r.jsxs("div",{className:"client-system-dashboard",children:[r.jsxs("section",{className:"client-performance-panel","aria-label":"Performance",children:[r.jsxs("div",{className:"client-system-subhead",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"PERFORMANCE"}),r.jsx("strong",{children:"Live resources"})]}),r.jsx("small",{children:"Live updates"})]}),r.jsxs("div",{className:"client-live-metrics",children:[r.jsx(af,{icon:ep,label:"CPU",value:op(a?.system?.cpuUsagePercent),detail:a?.system?.cpuLogicalCores?`${a.system.cpuLogicalCores} logical cores · Current processor usage`:"Current processor usage",percent:a?.system?.cpuUsagePercent}),r.jsx(af,{icon:C0,label:"Memory",value:op(N),detail:JC(a?.system?.memoryUsedBytes,a?.system?.memoryTotalBytes),percent:N}),r.jsx(af,{icon:k0,label:"GPU",value:Mh(H),detail:z?.name||(a?.system?.hardwareCollecting?"Detecting graphics hardware…":"Graphics usage unavailable"),percent:H}),r.jsx(af,{icon:Hr,label:"VRAM",value:Mh(G),detail:e1(z?.memoryUsedBytes,z?.memoryTotalBytes),percent:G})]})]}),r.jsxs("section",{className:"client-storage-panel","aria-label":"Local storage",children:[r.jsxs("div",{className:"client-system-subhead",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"STORAGE"}),r.jsx("strong",{children:"Local drives"})]}),r.jsx("small",{children:_.length>0?`${_.length} ${_.length===1?"drive":"drives"}`:a?.system?.hardwareCollecting?"Detecting…":"Unavailable"})]}),r.jsxs("div",{className:"client-disk-list",children:[_.map(O=>r.jsxs("article",{className:"client-disk-row",children:[r.jsxs("div",{className:"client-disk-row-head",children:[r.jsxs("span",{children:[r.jsx(So,{size:16}),r.jsx("strong",{children:O.mount||"Disk"}),r.jsx("small",{children:O.name||"Local disk"})]}),r.jsx("strong",{children:Mh(O.usedPercent)})]}),r.jsxs("small",{children:[Co(O.freeBytes)," free · ",Co(O.totalBytes)," total"]}),r.jsx("i",{"aria-hidden":"true",children:r.jsx("b",{style:{width:zx(O.usedPercent)}})})]},`${O.mount}-${O.name||""}`)),_.length===0&&r.jsxs("div",{className:"client-disk-empty",children:[r.jsx(So,{size:18}),r.jsx("span",{children:a?.system?.hardwareCollecting?"Detecting local drives…":"Storage information is not available."})]})]})]}),r.jsxs("section",{className:"client-network-panel","aria-label":"Network activity",children:[r.jsxs("div",{className:"client-system-subhead",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"NETWORK"}),r.jsx("strong",{children:"Live traffic"})]}),r.jsx("small",{children:U.length>0?U.join(", "):"Detecting adapter"})]}),r.jsxs("div",{className:"client-network-live",children:[r.jsxs("div",{className:"client-network-adapter",children:[r.jsx(Vf,{size:18}),r.jsxs("span",{children:[r.jsx("strong",{children:U.join(", ")||"Network"}),r.jsx("small",{children:K.join(" / ")||"Checking active connection"})]})]}),r.jsxs("div",{className:"client-network-rate download",children:[r.jsx(j0,{size:17}),r.jsxs("span",{children:[r.jsx("small",{children:"Receive"}),r.jsx("strong",{children:Oy(Y?.receiveBytesPerSecond)})]})]}),r.jsxs("div",{className:"client-network-rate upload",children:[r.jsx(A0,{size:17}),r.jsxs("span",{children:[r.jsx("small",{children:"Send"}),r.jsx("strong",{children:Oy(Y?.sendBytesPerSecond)})]})]}),r.jsxs("small",{className:"client-network-total",children:["Total ",Co(Y?.receivedBytes)," received / ",Co(Y?.sentBytes)," sent"]})]})]})]})]}),r.jsxs("aside",{className:"client-connection-panel",children:[r.jsx("span",{className:"client-unified-section-label",children:"LIVEDESK SERVICES"}),r.jsx("h3",{children:A?"Connected to the Hub":a?.authenticated?"Finding the Hub":"Connect this computer"}),A?r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"client-unified-copy",children:"This computer is available from the LiveDesk Hub."}),r.jsxs("div",{className:"client-service-status-list",children:[r.jsxs("div",{children:[r.jsx(Ea,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Screen sharing"}),r.jsx("small",{children:a?.permissions?.screenCapture?"Active":"Waiting"})]})]}),r.jsxs("div",{children:[r.jsx(Kn,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Remote control"}),r.jsx("small",{children:a?.permissions?.remoteInput?"Available":"Unavailable"})]})]}),r.jsxs("div",{children:[r.jsx(Sc,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"File delivery"}),r.jsx("small",{children:a?.permissions?.files?"Ready to receive":"Unavailable"})]})]}),r.jsxs("div",{children:[r.jsx(Ao,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Computer audio"}),r.jsx("small",{children:a?.permissions?.audio?"Available":"Unavailable"})]})]})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"client-unified-copy",children:a?.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&&!a?.authenticated?r.jsxs("button",{className:"client-unified-primary",type:"button",onClick:g,children:[r.jsx(jo,{size:16})," Sign in with Google"]}):r.jsxs("p",{className:"client-unified-success",children:[r.jsx(ea,{size:16})," Signed in as ",t?.user.email||t?.user.id||a?.userEmail||a?.userId||"saved account"]}),r.jsxs("div",{className:"client-unified-pin-row",children:[r.jsx(xx,{size:16}),r.jsx("input",{value:i,onChange:O=>y(O.target.value),placeholder:"6-digit Hub PIN",inputMode:"numeric","aria-label":"6-digit Hub PIN"}),r.jsx("button",{className:"client-unified-secondary",type:"button",onClick:x,disabled:i.length!==6,children:"Connect"})]})]}),k?.supported&&r.jsxs("div",{className:`client-video-acceleration state-${k.ready?"ready":k.state||"setup-required"}`,children:[r.jsx(ep,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Hardware video"}),r.jsx("small",{children:M})]}),!k.ready&&k.canInstall&&r.jsx("button",{type:"button",onClick:j,disabled:T,title:"Install and verify Linux FFmpeg hardware video support",children:T?"Setting up":"Enable"})]}),(l||a?.lastError)&&r.jsxs("p",{className:"client-unified-error",role:"alert",children:[r.jsx(yx,{size:15})," ",l||a?.lastError]}),c&&r.jsx("p",{className:"client-unified-success",children:c}),r.jsxs("div",{className:"client-slot-setting",children:[r.jsxs("label",{htmlFor:"client-slot-number",children:[r.jsx("span",{children:"Slot"}),r.jsx("input",{id:"client-slot-number",value:m,onChange:O=>b(O.target.value),inputMode:"numeric",pattern:"[0-9]*",placeholder:"1-999","aria-label":"Wall slot number",disabled:!A||h})]}),r.jsxs("button",{type:"button",onClick:w,disabled:!A||h||!m,"aria-label":"Save slot number",title:"Save slot number",children:[r.jsx(Tp,{size:17}),r.jsx("span",{children:h?"Saving":"Set"})]})]})]})]})]})}function i1(){const[t,a]=d.useState(null),[i,l]=d.useState(null),[c,u]=d.useState(!1),[m,h]=d.useState(""),[g,y]=d.useState(""),[x,b]=d.useState(""),[w,j]=d.useState(!1),[A,k]=d.useState(!1),[T,M]=d.useState(""),[N,L]=d.useState(!1),[z,H]=d.useState(null),[G,_]=d.useState(!1),[Y,q]=d.useState("computer"),[U,K]=d.useState(!1),O=d.useRef(null),ve=d.useRef(null),me=d.useRef(!1),Z=d.useRef(!1),I=d.useRef(!1),se=d.useRef(0),W=d.useRef(!1),F=d.useMemo(ZC,[]),oe=d.useMemo(()=>n1(i,t),[i,t]),le=d.useMemo(()=>a1(i,t),[i,t]),[Q,be]=d.useState(!1),he=oe.slice(0,1).toUpperCase()||"L";d.useEffect(()=>{be(!1)},[le]);const de=d.useCallback(async()=>{if(y(""),window.liveDesk?.auth?.signInWithGoogle){const B=await window.liveDesk.auth.signInWithGoogle();return B?.ok===!1?(y(B.error||"LiveDesk could not open the system browser for Google sign-in."),!1):!0}return window.location.assign(`${F}/auth/google`),!0},[F]),ee=d.useCallback(async()=>{I.current||(I.current=!0,y("Your saved Google sign-in is incomplete. LiveDesk is reopening sign-in once to repair it."),await St.auth.signOut({scope:"local"}).catch(()=>{}),l(null),await de()||(I.current=!1))},[de]),Ce=d.useCallback(async B=>{const ye=_y(B);if(ye)throw new Error(ye);if(me.current)return!1;me.current=!0;try{const je=await window.liveDesk?.auth?.persistSession?.(B);if(je?.ok===!1)throw new Error(je.error||"LiveDesk could not validate the desktop session.");for(let Pe=0;Pe<2;Pe+=1){const dt=await ho(F,Pe>0),nt=await fetch(`${F}/api/auth/session`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":dt},signal:AbortSignal.timeout(1e4),body:JSON.stringify({accessToken:B.access_token,refreshToken:B.refresh_token,expiresAt:B.expires_at,user:{id:B.user.id,email:B.user.email}})}),bt=await nt.json().catch(()=>({}));if(nt.status===403&&Pe===0){sessionStorage.removeItem("livedesk.client.csrf");continue}if(!nt.ok)throw new Error(bt.error||`Client runtime returned HTTP ${nt.status}.`);return y(""),!0}throw new Error("Client runtime rejected the session transfer.")}finally{me.current=!1}},[F]),Re=d.useCallback(async()=>{try{const B=await fetch(`${F}/api/client/status`,{cache:"no-store"}),ye=await B.json().catch(()=>({}));if(!B.ok)throw new Error(ye.error||`Client runtime returned HTTP ${B.status}.`);if(ye.csrfToken&&sessionStorage.setItem("livedesk.client.csrf",ye.csrfToken),String(ye.role||"").toLowerCase()==="hub")throw new Error("This computer is assigned to the Hub role.");a(ye)}catch(B){y(B instanceof Error?B.message:String(B))}},[F]);d.useEffect(()=>{Re();const B=window.setInterval(()=>{Re()},2e3);return()=>window.clearInterval(B)},[Re]),d.useEffect(()=>{if(W.current)return;const B=Number(t?.slotNumber||0);M(B>0?String(B):"")},[t?.slotNumber]),d.useEffect(()=>{if(!z)return;const B=window.setTimeout(()=>H(null),5e3);return()=>window.clearTimeout(B)},[z]);const He=d.useCallback(async()=>{const B=Date.now();if(!(!t?.authenticated||t.connectionState==="connected"||!["waiting","reconnecting"].includes(String(t.agent?.state||""))||B-se.current<4e3)){se.current=B;try{const ye=await fetch(`${F}/api/client/reconnect`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await ho(F)},body:JSON.stringify({onlyIfWaiting:!0,reason:"app-active"})});if(!ye.ok)throw new Error(`Client reconnect returned HTTP ${ye.status}.`);await Re()}catch(ye){y(ye instanceof Error?ye.message:String(ye))}}},[F,Re,t]);d.useEffect(()=>{const B=()=>{He()},ye=()=>{He()},je=()=>{document.visibilityState==="visible"&&He()};return window.addEventListener("online",B),window.addEventListener("focus",ye),document.addEventListener("visibilitychange",je),()=>{window.removeEventListener("online",B),window.removeEventListener("focus",ye),document.removeEventListener("visibilitychange",je)}},[He]),d.useEffect(()=>{if(!c||!t||!i?.access_token||t.authenticated)return;if(_y(i)==="refresh-token-required"){ee().catch(dt=>{I.current=!1,y(dt instanceof Error?dt.message:String(dt))});return}let B=!1,ye,je=0;const Pe=async()=>{if(B)return;try{const nt=await Ce(i);if(await Re(),nt)return}catch(nt){y(nt instanceof Error?nt.message:String(nt))}if(B)return;const dt=zy[Math.min(je,zy.length-1)];je+=1,ye=window.setTimeout(()=>{Pe()},dt)};return Pe(),()=>{B=!0,ye!==void 0&&window.clearTimeout(ye)}},[c,Re,ee,i,t,Ce]),d.useEffect(()=>{const B=new URLSearchParams(window.location.search),ye=B.get("auth_error");if(!ye)return;y(ye),B.delete("auth_error");const je=B.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${je?`?${je}`:""}${window.location.hash}`)},[]),d.useEffect(()=>{let B=!0;if(!window.liveDesk?.auth)return l(null),u(!0),Re(),()=>{B=!1};const ye=window.liveDesk?.auth?.onComplete?.(Pe=>{Pe.ok&&Pe.session?St.auth.setSession(Pe.session).catch(dt=>y(dt instanceof Error?dt.message:String(dt))):Pe.error&&y(Pe.error)});(async()=>{try{const Pe=window.liveDesk?.auth?.getSession?await window.liveDesk.auth.getSession():await St.auth.getSession();if(!B)return;const dt=Tx(Pe);l(dt),Re()}catch(Pe){B&&y(Pe instanceof Error?Pe.message:String(Pe))}finally{B&&u(!0)}})();const{data:je}=St.auth.onAuthStateChange((Pe,dt)=>{B&&(l(dt),u(!0),Re())});return()=>{B=!1,ye?.(),je.subscription.unsubscribe()}},[Re]),d.useEffect(()=>{if(!c||!t||Z.current||I.current||i||t.authenticated)return;const B=new URLSearchParams(window.location.search);if(!B.has("livedesk_launch"))return;Z.current=!0,B.delete("livedesk_launch");const ye=B.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${ye?`?${ye}`:""}${window.location.hash}`),de().catch(je=>y(je instanceof Error?je.message:String(je)))},[c,i,de,t]);const te=async()=>{K(!1),window.liveDesk?.auth?.persistSession?(await St.auth.signOut(),(await window.liveDesk.auth.persistSession(null))?.runtimeCleared===!1&&y("Signed out locally. The LiveDesk runtime could not be reached to clear its session.")):await fetch(`${F}/api/auth/session`,{method:"DELETE",headers:{"X-LiveDesk-CSRF":await ho(F)}}).catch(()=>{}),l(null),await Re()};d.useEffect(()=>{if(!U)return;const B=je=>{je.target instanceof Element&&je.target.closest(".account-popover, .rail-account")||K(!1)},ye=je=>{je.key==="Escape"&&K(!1)};return window.addEventListener("pointerdown",B),window.addEventListener("keydown",ye),()=>{window.removeEventListener("pointerdown",B),window.removeEventListener("keydown",ye)}},[U]);const Ue=d.useCallback((B=!0)=>{w||(_(!1),B&&window.requestAnimationFrame(()=>ve.current?.focus()))},[w]),mt=d.useCallback(()=>{w||!t?.authenticated||(ve.current=document.activeElement instanceof HTMLElement?document.activeElement:null,b(""),_(!0))},[w,t?.authenticated]);d.useEffect(()=>{if(!G)return;const B=window.requestAnimationFrame(()=>O.current?.focus()),ye=Pe=>{Pe.target instanceof Element&&Pe.target.closest(".client-hub-switch-popover, .client-hub-switch-trigger")||Ue(!1)},je=Pe=>{Pe.key==="Escape"&&Ue()};return window.addEventListener("pointerdown",ye),window.addEventListener("keydown",je),()=>{window.cancelAnimationFrame(B),window.removeEventListener("pointerdown",ye),window.removeEventListener("keydown",je)}},[Ue,G]);const ne=async()=>{y("");try{const B=await fetch(`${F}/api/client/pin`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await ho(F)},body:JSON.stringify({pin:m})}),ye=await B.json().catch(()=>({}));if(!B.ok||ye?.ok===!1)throw new Error(ye?.error||"PIN could not be accepted.");h(""),await Re()}catch(B){y(B instanceof Error?B.message:String(B))}},xe=async()=>{_(!1),j(!0),b(""),y("");try{const B=await fetch(`${F}/api/runtime/switch-role`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await ho(F)},body:JSON.stringify({role:"hub"})}),ye=await B.json().catch(()=>({}));if(!B.ok||ye?.ok===!1)throw new Error(ye?.error||`Role change failed with HTTP ${B.status}.`);b("Hub role accepted. LiveDesk is restarting this computer with the Hub Wall.");const je=Number(t?.runtimePid||0);await Rx({baseUrl:F,targetRole:"hub",previousRuntimePid:je,allowedStates:["running"]}),window.location.reload()}catch(B){y(B instanceof Error?B.message:String(B)),j(!1)}},Oe=async()=>{if(N)return;const B=Number(T);if(!Number.isInteger(B)||B<1||B>999){H({kind:"error",message:"Enter a slot number from 1 to 999."});return}L(!0),H(null);try{const ye=await fetch(`${F}/api/client/slot`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await ho(F)},body:JSON.stringify({slotNumber:B})}),je=await ye.json().catch(()=>({}));if(!ye.ok||je.ok===!1){if(je.error==="slot-taken"){const Pe=je.conflict?.deviceName||je.conflict?.hostname||je.conflict?.deviceId||"another computer";throw new Error(`Slot ${String(B).padStart(3,"0")} is already used by ${Pe}.`)}throw new Error(je.error||`Slot update failed with HTTP ${ye.status}.`)}W.current=!1,M(String(B)),a(je),H({kind:"success",message:`Slot ${String(B).padStart(3,"0")} saved. LiveDesk is reconnecting this Client.`})}catch(ye){H({kind:"error",message:ye instanceof Error?ye.message:String(ye)})}finally{L(!1),await Re()}},$e=async()=>{if(!A){k(!0),y("");try{const B=await fetch(`${F}/api/client/video-acceleration/install`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await ho(F)},body:JSON.stringify({confirm:!0})}),ye=await B.json().catch(()=>({}));if(a(ye),!B.ok||ye.videoAcceleration?.ready!==!0)throw new Error(ye.videoAcceleration?.error||ye.error||"Linux hardware video setup did not complete.")}catch(B){y(B instanceof Error?B.message:String(B))}finally{k(!1),await Re()}}},ze=!!(t?.authenticated||i),Qe=d.useMemo(()=>Yf(),[]),qe=zf("switch-to-hub",Qe),Ye=zf("client",Qe),ot=YC(Qe);return r.jsxs("main",{className:"app-shell client-unified-shell",children:[r.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk Client tools",children:[r.jsx("div",{className:"rail-brand",title:"LiveDesk",children:r.jsx(Dx,{size:25})}),r.jsx("nav",{className:"rail-tools","aria-label":"Client navigation",children:r.jsxs("div",{className:"client-main-tool-slot",children:[r.jsxs("button",{className:"rail-tool client-main-tool client-hub-tool client-hub-switch-trigger accent-blue",type:"button",onClick:mt,disabled:w||!t?.authenticated,"aria-busy":w,"aria-expanded":G,"aria-haspopup":"dialog","aria-controls":G?"client-hub-switch-popover":void 0,"aria-label":`Hub. ${qe}`,"data-tooltip":G?void 0:lp("Hub","switch-to-hub",Qe),children:[r.jsx(Hr,{size:19}),r.jsx("span",{children:w?"Switching…":"Hub"})]}),r.jsxs("button",{className:`rail-tool client-main-tool accent-blue ${Y==="computer"?"active":""}`,type:"button",onClick:()=>q("computer"),"aria-current":Y==="computer"?"page":void 0,"aria-label":`Client. ${Ye}`,"data-tooltip":lp("Client","client",Qe),children:[r.jsx(Ea,{size:19}),r.jsx("span",{children:"Client"})]})]})}),r.jsxs("div",{className:"rail-footer",children:[XC.map(B=>{const ye=B.icon;return r.jsxs("button",{className:`rail-tool compact ${Y===B.id?"active":""}`,type:"button",onClick:()=>q(B.id),title:B.label,children:[r.jsx(ye,{size:18}),r.jsx("span",{children:B.label})]},B.id)}),r.jsxs("button",{className:`rail-account ${ze?"signed-in":""}`,type:"button",onClick:()=>K(B=>!B),"aria-expanded":U,"aria-haspopup":"dialog",title:ze?"Account":"Sign in",children:[ze&&le&&!Q?r.jsx("img",{src:le,alt:oe,referrerPolicy:"no-referrer",onError:()=>be(!0)},le):ze?r.jsx("span",{className:"avatar-fallback",children:he}):r.jsx(jo,{size:18}),r.jsx("span",{children:ze?"Account":"Sign in"})]})]})]}),G&&r.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:[r.jsxs("header",{className:"client-hub-switch-head",children:[r.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:r.jsx(Hr,{size:19})}),r.jsx("span",{className:"client-hub-switch-eyebrow",children:ot.eyebrow}),r.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>Ue(),"aria-label":ot.closeLabel,children:r.jsx(Ra,{size:17})})]}),r.jsx("h2",{id:"client-hub-switch-title",children:ot.title}),r.jsx("p",{id:"client-hub-switch-description",children:ot.description}),r.jsxs("p",{id:"client-hub-switch-restart",className:"client-hub-switch-notice",children:[r.jsx(Kn,{size:16,"aria-hidden":"true"}),r.jsx("span",{children:ot.restartNotice})]}),r.jsxs("div",{className:"client-hub-switch-actions",children:[r.jsx("button",{type:"button",onClick:()=>Ue(),children:ot.cancel}),r.jsxs("button",{ref:O,className:"primary",type:"button",onClick:()=>{xe()},disabled:w||!t?.authenticated,children:[r.jsx(Hr,{size:16}),ot.confirm]})]})]}),U&&r.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[r.jsxs("div",{className:"account-popover-head",children:[r.jsx("div",{className:"account-popover-avatar",children:ze&&le&&!Q?r.jsx("img",{src:le,alt:oe,referrerPolicy:"no-referrer",onError:()=>be(!0)},le):ze?r.jsx("span",{children:he}):r.jsx(jo,{size:18})}),r.jsxs("div",{children:[r.jsx("strong",{children:ze?oe:"Account"}),r.jsx("p",{children:i?.user.email||t?.userEmail||t?.userId||"Not signed in"})]})]}),r.jsxs("dl",{className:"account-popover-facts",children:[r.jsx("dt",{children:"User"}),r.jsx("dd",{children:i?.user.email||t?.userEmail||t?.userId||"Not signed in"}),r.jsx("dt",{children:"Runtime"}),r.jsx("dd",{children:t?"Local app ready":"Checking local app"}),r.jsx("dt",{children:"Session"}),r.jsx("dd",{children:t?.auth?.persisted?"Saved on this computer":ze?"Active for this run":"Not saved"}),r.jsx("dt",{children:"Role"}),r.jsx("dd",{children:"Client"})]}),ze?r.jsxs("button",{className:"account-popover-action",onClick:()=>{te()},type:"button",children:[r.jsx(vx,{size:16}),"Logout"]}):r.jsxs("button",{className:"account-popover-action primary",onClick:()=>{K(!1),de()},type:"button",children:[r.jsx(jo,{size:16}),"Sign in with Google"]})]}),r.jsxs("section",{className:"desk-stage client-unified-stage",children:[r.jsx("header",{className:"topbar",children:r.jsxs("div",{className:"brand",children:[r.jsx("span",{className:"brand-mark",children:r.jsx(Ao,{size:18})}),r.jsxs("div",{children:[r.jsx("h1",{children:"LiveDesk"}),r.jsx("p",{children:"Client workspace"})]})]})}),Y==="support"?r.jsx("section",{className:"client-unified-page",children:r.jsx(Nx,{session:i,currentProductKey:"livedesk",appVersion:t?.appVersion||"",onSignIn:()=>{de()}})}):Y!=="computer"?r.jsx("section",{className:"client-unified-page",children:r.jsx(s1,{page:Y,status:t})}):r.jsx(r1,{session:i,status:t,pin:m,error:g,roleChangeMessage:x,videoAccelerationBusy:A,slotInput:T,slotBusy:N,onSignIn:()=>{de()},onPinChange:B=>h(B.replace(/\D/g,"").slice(0,6)),onSubmitPin:()=>{ne()},onSlotInputChange:B=>{W.current=!0,M(B.replace(/\D/g,"").slice(0,3))},onSaveSlot:()=>{Oe()},onEnableVideoAcceleration:()=>{$e()}})]}),z&&r.jsxs("div",{className:`client-side-toast ${z.kind}`,role:z.kind==="error"?"alert":"status",children:[z.kind==="error"?r.jsx(yx,{size:18}):r.jsx(ea,{size:18}),r.jsx("span",{children:z.message}),r.jsx("button",{type:"button",onClick:()=>H(null),"aria-label":"Dismiss notification",children:r.jsx(Ra,{size:16})})]})]})}function Rl(t,a,i){if(i<0||a<0||a+i>t.length)throw new Error("Invalid LZO1X block: input overrun.")}function Nh(t,a,i){let l=0;for(;Rl(t,a.inputIndex,1),t[a.inputIndex]===0;)l+=1,a.inputIndex+=1;const c=l*255+i+t[a.inputIndex];return a.inputIndex+=1,c}function sf(t,a,i,l){if(Rl(t,a.inputIndex,l),a.outputIndex+l>i.length)throw new Error("Invalid LZO1X block: output overrun.");i.set(t.subarray(a.inputIndex,a.inputIndex+l),a.outputIndex),a.inputIndex+=l,a.outputIndex+=l}function l1(t,a,i,l){const c=a-i;if(c<=0||l<=0)throw new Error("Invalid LZO1X block: invalid match distance.");let u=Math.min(c,l);for(t.set(t.subarray(i,i+u),a);u<l;){const m=Math.min(u,l-u);t.copyWithin(a+u,a,a+m),u+=m}return a+l}function Ox(t,a){if(!(t instanceof Uint8Array)||t.length<3||a<0)throw new Error("Invalid LZO1X block.");const i=new Uint8Array(a),l={inputIndex:0,outputIndex:0};let c=0,u=0;if(t[l.inputIndex]>=22){const m=t[l.inputIndex]-17;l.inputIndex+=1,sf(t,l,i,m),c=4}else t[l.inputIndex]>=18&&(c=t[l.inputIndex]-17,l.inputIndex+=1,sf(t,l,i,c));for(;;){Rl(t,l.inputIndex,1);const m=t[l.inputIndex];l.inputIndex+=1;let h,g;if((m&192)!==0)Rl(t,l.inputIndex,1),g=l.outputIndex-((t[l.inputIndex]<<3)+(m>>2&7)+1),l.inputIndex+=1,u=(m>>5)+1,h=m&3;else if((m&32)!==0){u=(m&31)+2,u===2&&(u+=Nh(t,l,31)),Rl(t,l.inputIndex,2);const y=t[l.inputIndex]|t[l.inputIndex+1]<<8;l.inputIndex+=2,g=l.outputIndex-((y>>2)+1),h=y&3}else if((m&16)!==0){u=(m&7)+2,u===2&&(u+=Nh(t,l,7)),Rl(t,l.inputIndex,2);const y=t[l.inputIndex]|t[l.inputIndex+1]<<8;if(l.inputIndex+=2,g=l.outputIndex-(((m&8)<<11)+(y>>2)),h=y&3,g===l.outputIndex)break;g-=16384}else if(c===0){let y=m+3;y===3&&(y+=Nh(t,l,15)),sf(t,l,i,y),c=4;continue}else c!==4?(Rl(t,l.inputIndex,1),h=m&3,g=l.outputIndex-((m>>2)+(t[l.inputIndex]<<2)+1),l.inputIndex+=1,u=2):(Rl(t,l.inputIndex,1),h=m&3,g=l.outputIndex-((m>>2)+(t[l.inputIndex]<<2)+2049),l.inputIndex+=1,u=3);if(g<0||l.outputIndex+u+h>i.length)throw new Error("Invalid LZO1X block: lookbehind overrun.");l.outputIndex=l1(i,l.outputIndex,g,u),c=h,sf(t,l,i,h)}if(u!==3||l.inputIndex!==t.length||l.outputIndex!==i.length)throw new Error("Invalid LZO1X block: incomplete output.");return i}const Hy=16,Fy=8,o1=24*1024*1024,Hx=new Uint8Array(new Uint32Array([16909060]).buffer)[0]===4,cp=new Uint32Array(65536);for(let t=0;t<cp.length;t+=1){const a=Math.round((t>>11&31)*255/31),i=Math.round((t>>5&63)*255/63),l=Math.round((t&31)*255/31);cp[t]=Hx?(a|i<<8|l<<16|4278190080)>>>0:(a<<24|i<<16|l<<8|255)>>>0}function Tl(t,a){return t[a]|t[a+1]<<8}function c1(t,a){const i=Number(a);if(!Number.isSafeInteger(i)||i<Hy||i>o1)throw new Error(`Invalid Mode 5 packet length: ${a}.`);const l=t instanceof Uint8Array?t:new Uint8Array(t),c=Ox(l,i);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,m=Tl(c,6),h=Tl(c,8),g=Tl(c,10),y=Tl(c,12);if(m<=0||h<=0||m>3840||h>2160)throw new Error(`Invalid Mode 5 frame size: ${m}x${h}.`);if(g<=0||g>256||y>8192)throw new Error(`Invalid Mode 5 tile header: ${g}/${y}.`);const x=[];let b=Hy;for(let w=0;w<y;w+=1){if(b+Fy>c.length)throw new Error("Mode 5 tile header is truncated.");const j=Tl(c,b),A=Tl(c,b+2),k=Tl(c,b+4),T=Tl(c,b+6);b+=Fy;const M=k*T*2;if(k<=0||T<=0||k>g||T>g||j+k>m||A+T>h||b+M>c.length)throw new Error(`Invalid Mode 5 tile ${w}.`);x.push({x:j,y:A,width:k,height:T,pixels:c.subarray(b,b+M)}),b+=M}if(b!==c.length)throw new Error(`Mode 5 packet has ${c.length-b} trailing bytes.`);return{keyFrame:u,width:m,height:h,tileSize:g,tiles:x}}function u1(t,a,i,l){if(!(t instanceof Uint8ClampedArray)||t.length!==a*i*4||l.width!==a||l.height!==i)throw new Error("Mode 5 canvas state does not match the packet dimensions.");let c=a,u=i,m=0,h=0;const g=new Uint32Array(t.buffer,t.byteOffset,t.byteLength>>>2);for(const y of l.tiles){const x=Hx&&(y.pixels.byteOffset&1)===0?new Uint16Array(y.pixels.buffer,y.pixels.byteOffset,y.pixels.byteLength>>>1):null;let b=0;for(let w=0;w<y.height;w+=1){let j=(y.y+w)*a+y.x;for(let A=0;A<y.width;A+=1){const k=b<<1,T=x?x[b]:y.pixels[k]|y.pixels[k+1]<<8;g[j]=cp[T],b+=1,j+=1}}c=Math.min(c,y.x),u=Math.min(u,y.y),m=Math.max(m,y.x+y.width),h=Math.max(h,y.y+y.height)}return l.tiles.length>0?{x:c,y:u,width:m-c,height:h-u}:null}const $a=new WeakMap,Yu=new WeakMap,up=new WeakMap,Qu=new Set,ko=new Set,Nc=new WeakMap,Cc=new Set,Xu=new WeakMap,dp=new WeakMap,fp=new WeakMap,Of=new WeakMap,Fx=4,d1=2,f1=2,m1=2,h1=18,p1=40,g1=0,v1=250,Px=80,Py=5,y1=150,b1=1200,x1=18,w1=.65,S1=2e3,C1=500,Ip=250,k1=globalThis.LIVEDESK_ENABLE_CANVAS_VISUAL_SAMPLING===!0;let $x=1,Bx=0,Ux=0,qx=0,Gx,Vx,_i={h264DecodeAcceleration:"prefer-hardware"};function j1(t){t.h264DecodeAcceleration&&(_i={..._i,h264DecodeAcceleration:t.h264DecodeAcceleration})}function mp(t,a=_i.h264DecodeAcceleration){const i=Nc.get(t);return i?.requested===a?(i.actual!=="prefer-hardware"&&(ko.delete(t),Cc.add(t)),i.actual):(i&&(Nc.delete(t),Cc.delete(t)),a!=="prefer-hardware"?(ko.delete(t),Cc.delete(t),a):(ko.has(t)||ko.add(t),"prefer-hardware"))}function zp(t,a,i){if(a!=="prefer-hardware")return!1;const l=Nc.get(t),c=$a.get(t),u=Date.now();return Xu.has(t)||Xu.set(t,$x++),Nc.set(t,{requested:a,actual:"prefer-software",reason:i,failedAt:u,failureCount:(l?.requested===a?l.failureCount:0)+1,codec:c?.codec||l?.codec||"",latencyMode:c?.latencyMode||l?.latencyMode||"smooth",inputCount:c?.inputSerial??l?.inputCount??0,outputCount:c?.outputSerial??l?.outputCount??0,lastInputAt:c?.lastInputAt??l?.lastInputAt??0,lastOutputAt:c?.lastOutputAt??l?.lastOutputAt??0,lastPaintAt:c?.lastPaintAt??l?.lastPaintAt??0}),ko.delete(t),Cc.add(t),qx+=1,Gx=i,Vx=u,!0}function A1(t,a,i,l=64){try{let c=dp.get(t);c||(c={canvas:document.createElement("canvas"),lastHash:"",initialized:!1},dp.set(t,c));const u=Math.max(8,Math.min(64,Math.round(l))),m=Math.max(1,Math.round(u*Math.max(1,i)/Math.max(1,a)));(c.canvas.width!==u||c.canvas.height!==m)&&(c.canvas.width=u,c.canvas.height=m);const h=c.canvas.getContext("2d",{willReadFrequently:!0});if(!h)return{visualHash:"",visualChanged:!0};h.drawImage(t,0,0,Math.max(1,a),Math.max(1,i),0,0,u,m);const g=h.getImageData(0,0,u,m).data;let y=2166136261;for(let w=0;w<g.length;w+=4)y^=g[w],y=Math.imul(y,16777619),y^=g[w+1],y=Math.imul(y,16777619),y^=g[w+2],y=Math.imul(y,16777619);const x=(y>>>0).toString(16).padStart(8,"0"),b=!c.initialized||x!==c.lastHash;return c.initialized=!0,c.lastHash=x,{visualHash:x,visualChanged:b}}catch{return{visualHash:"",visualChanged:!0}}}function hp(t,a,i,l=Ip,c=64,u){if(!k1&&u)return Wx(t,u);let m=fp.get(t);m||(m={lastHash:"",initialized:!1,lastCanvasSampleAt:0},fp.set(t,m));const h=performance.now();if(m.initialized&&l>0&&h-m.lastCanvasSampleAt<l)return{visualHash:m.lastHash,visualChanged:!1};const g=A1(t,a,i,c);return m.initialized=!0,m.lastHash=g.visualHash,m.lastCanvasSampleAt=h,g}function Wx(t,a){let i=Of.get(t);i||(i={lastHash:"",initialized:!1},Of.set(t,i));const l=String(a.contentHash||""),c=!i.initialized||!l||l!==i.lastHash;return i.initialized=!0,i.lastHash=l,{visualHash:l,visualChanged:c}}function Kx(t,a){const i=up.get(t);if(i)return i;const l=t.getContext("2d",{alpha:!1,desynchronized:a==="interactive"});if(l){const c=l.getContextAttributes?.(),u={context:l,presentation:c?.desynchronized?"desync":"sync"};return up.set(t,u),u}return null}function M1(t){const a=String(t.frameMode||t.mode||"").toLowerCase(),i=String(t.compression||"").toLowerCase(),l=String(t.mimeType||"").toLowerCase();return a==="mode2-lzo"||i==="lzo1x"||l==="application/vnd.livedesk.lzo-rgb565"||a==="mode2-lz4"||String(t.compression||"").toLowerCase()==="lz4"||l==="application/vnd.livedesk.lz4-raw"}function N1(t){return String(t.frameMode||t.mode||"").toLowerCase()==="mode3-h264-hw"||String(t.codec||"").toLowerCase()==="h264"||String(t.mimeType||"").toLowerCase()==="video/h264"}function T1(t){const a=String(t.frameMode||t.mode||"").toLowerCase(),i=String(t.mimeType||"").toLowerCase();return a==="mode5-lzo-delta"||i==="application/vnd.livedesk.lzo-rgb565-delta"}function $y(t,a,i){let l=i,c=a;if(l===15){let u=255;for(;u===255;){if(c>=t.length)throw new Error("Invalid LZ4 block: length overrun.");u=t[c],c+=1,l+=u}}return{length:l,cursor:c}}function R1(t,a){const i=new Uint8Array(a);let l=0,c=0;for(;l<t.length;){const u=t[l];l+=1;const m=$y(t,l,u>>4);l=m.cursor;const h=m.length;if(l+h>t.length||c+h>i.length)throw new Error("Invalid LZ4 block: literal overrun.");if(i.set(t.subarray(l,l+h),c),l+=h,c+=h,l>=t.length)break;if(l+2>t.length)throw new Error("Invalid LZ4 block: missing offset.");const g=t[l]|t[l+1]<<8;if(l+=2,g<=0||g>c)throw new Error("Invalid LZ4 block: bad match offset.");const y=$y(t,l,u&15);l=y.cursor;const x=y.length+4;if(c+x>i.length)throw new Error("Invalid LZ4 block: match overrun.");let b=c-g;for(let w=0;w<x;w+=1)i[c]=i[b],c+=1,b+=1}if(c!==i.length)throw new Error("Invalid LZ4 block: incomplete output.");return i}function E1(t){const a=Math.max(1,Math.floor(t.width||0)),i=Math.max(1,Math.floor(t.height||0)),l=String(t.compression||"").toLowerCase(),c=String(t.pixelFormat||t.codec||"").toLowerCase();if(l==="lzo1x"||String(t.frameMode||t.mode||"").toLowerCase()==="mode2-lzo"||String(t.mimeType||"").toLowerCase()==="application/vnd.livedesk.lzo-rgb565"){const x=Math.max(1,Math.floor(t.bytesPerPixel||2)),b=a*i*2,w=Math.floor(t.uncompressedByteLength||b);if(x!==2||w!==b)throw new Error(`Invalid mode2 RGB565 frame size: ${w} for ${a}x${i}.`);if(c&&c!=="rgb565le"&&c!=="rgb565")throw new Error(`Unsupported mode2 pixel format: ${c}`);const j=Ox(t.payload,b),A=new Uint8ClampedArray(a*i*4);for(let k=0,T=0;k<j.length;k+=2,T+=4){const M=j[k]|j[k+1]<<8,N=M>>11&31,L=M>>5&63,z=M&31;A[T]=N<<3|N>>2,A[T+1]=L<<2|L>>4,A[T+2]=z<<3|z>>2,A[T+3]=255}return new ImageData(A,a,i)}const m=Math.max(1,Math.floor(t.bytesPerPixel||4)),h=Math.max(a*i*m,Math.floor(t.uncompressedByteLength||0)),g=R1(t.payload,h);if(m!==4)throw new Error(`Unsupported mode2 pixel size: ${m}`);const y=new Uint8ClampedArray(a*i*4);if(c==="rgba32"||c==="rgba")y.set(g.subarray(0,y.length));else for(let x=0,b=0;b<y.length;x+=4,b+=4)y[b]=g[x+2],y[b+1]=g[x+1],y[b+2]=g[x],y[b+3]=g[x+3];return new ImageData(y,a,i)}function By(t,a="smooth",i=_i.h264DecodeAcceleration){const l=window.VideoDecoder;if(!l||!window.EncodedVideoChunk)throw new Error("WebCodecs H.264 decode is not supported in this browser.");const c=$a.get(t);if(c&&c.decoder.state!=="closed"&&c.latencyMode===a)return c;c&&Fs(t);let u;const m=new l({output:h=>{if($a.get(t)!==u){h.close();return}const g=Number(h.timestamp||0);u.outputSerial+=1;let y=u.pendingFrames.get(g);if(y)u.pendingFrames.delete(g);else if(u.pendingFrames.size>0){const k=u.pendingFrames.entries().next().value;k&&(u.pendingFrames.delete(k[0]),y=k[1],u.timestampFallbacks+=1)}const x=h.displayWidth||h.codedWidth||t.width||960,b=h.displayHeight||h.codedHeight||t.height||540,w=Number(y?.frame.durationUs||0),j=Number(h.duration||0),A=Math.max(16,Math.min(250,(w>0?w:j||83333)/1e3));for(u.targetPaintIntervalMs=A,u.decodedFrames.push({videoFrame:h,pending:y,decodedAt:performance.now(),width:x,height:b,durationMs:A}),u.lastOutputAt=performance.now();u.decodedFrames.length>Op(u);)Hf(u,u.decodedFrames.shift());Qx(u),u.renderTimer!==null&&u.renderScheduledAt>0&&performance.now()-u.renderScheduledAt>C1&&(typeof document>"u"||document.visibilityState==="visible")&&(window.cancelAnimationFrame(u.renderTimer),u.renderTimer=null,u.renderScheduledAt=0),u.renderTimer!==null&&u.decodedFrames.length>=Fx&&(window.cancelAnimationFrame(u.renderTimer),u.renderTimer=null,u.renderScheduledAt=0),Ff(t,u)},error:()=>{$a.get(t)===u&&(zp(t,u.requestedAcceleration,"decoder-error"),Fs(t))}});return Bx+=1,Xu.has(t)||Xu.set(t,$x++),u={decoder:m,configured:!1,configKey:"",codec:"",requestedAcceleration:i,hardwareAcceleration:mp(t,i),latencyMode:a,keyFrameSeen:!1,droppedForLatency:0,pendingFrames:new Map,decodedFrames:[],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,lastInputFrameSeq:void 0,targetPaintIntervalMs:1e3/12,nextChunkTimestampUs:0,healthSampleStartedAt:performance.now(),healthInputSerial:0,healthOutputSerial:0},$a.set(t,u),Qu.add(t),u}function Yx(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;for(const a of t.decodedFrames)a.videoFrame.close();t.decodedFrames=[],t.interactiveBufferPrimed=!1,t.interactiveBufferStartedAt=0}function Hf(t,a){a&&(a.videoFrame.close(),t.droppedForLatency+=1)}function Op(t){return t.latencyMode==="interactive"?f1:String(t.decodedFrames[0]?.pending?.frame.frameMode||t.decodedFrames[0]?.pending?.frame.mode||"").toLowerCase()==="mode4-h264-atlas"?d1:Fx}function Qx(t,a=performance.now()){const i=Op(t);for(;t.decodedFrames.length>i;)Hf(t,t.decodedFrames.shift());const l=t.latencyMode==="interactive"?Px:v1;let c=t.decodedFrames[0];for(;t.decodedFrames.length>1&&c?.pending&&a-c.pending.queuedAt>l;)Hf(t,t.decodedFrames.shift()),c=t.decodedFrames[0]}function Xx(t,a){if(a.hardwareAcceleration!=="prefer-hardware"||a.latencyMode==="interactive"||a.flushTimer!==null||a.flushInFlight)return;const i=y1;a.flushTimer=window.setTimeout(async()=>{a.flushTimer=null;const l=performance.now();for(const[u,m]of a.pendingFrames.entries())l-m.queuedAt>S1&&a.pendingFrames.delete(u);if($a.get(t)!==a||a.decoder.state!=="configured"||a.pendingFrames.size===0||a.inputSerial<=a.lastFlushInputSerial||a.lastOutputAt>0&&l-a.lastOutputAt<i)return;const c=a.inputSerial;a.flushInFlight=!0,a.flushCount+=1,a.keyFrameSeen=!1;try{await a.decoder.flush(),a.lastFlushInputSerial=Math.max(a.lastFlushInputSerial,c)}catch{$a.get(t)===a&&Tf(a)}finally{a.flushInFlight=!1,$a.get(t)===a&&a.inputSerial>c&&a.pendingFrames.size>0&&performance.now()-a.lastOutputAt>=i&&Xx(t,a)}},i)}function Uy(t,a,i){const l=performance.now();try{(t.width!==i.width||t.height!==i.height)&&(t.width=i.width,t.height=i.height);const c=Kx(t,a.latencyMode);if(c?.context.drawImage(i.videoFrame,0,0,i.width,i.height),i.pending){const u=performance.now(),h=a.latencyMode==="interactive"?Wx(t,i.pending.frame):hp(t,i.width,i.height,Ip,64,i.pending.frame);try{a.onPaint?.(i.pending.frame,{deviceId:i.pending.frame.deviceId,frameSeq:i.pending.frame.frameSeq,mode:i.pending.frame.frameMode||i.pending.frame.mode||i.pending.frame.codec||i.pending.frame.mimeType,width:i.width,height:i.height,byteLength:i.pending.frame.byteLength,queuedForMs:Math.max(0,l-i.pending.queuedAt),decodedForMs:Math.max(0,i.decodedAt-i.pending.queuedAt),scheduledForMs:Math.max(0,l-i.decodedAt),drawMs:Math.max(0,u-l),queueSize:i.pending.queueSize,renderQueueSize:a.decodedFrames.length,droppedForLatency:a.droppedForLatency,h264DecodeAcceleration:a.hardwareAcceleration,decoderLabel:a.hardwareAcceleration,decoderFlushCount:a.flushCount,decoderTimestampFallbacks:a.timestampFallbacks,decoderInputCount:a.inputSerial,decoderOutputCount:a.outputSerial,targetPaintIntervalMs:a.targetPaintIntervalMs,canvasPresentation:c?.presentation||"sync",interactiveBufferWaitCount:a.interactiveBufferWaitCount,interactiveBufferWaitMs:a.interactiveBufferWaitMs,interactiveQueueDrainCount:a.interactiveQueueDrainCount,visualHash:h.visualHash,visualChanged:h.visualChanged,paintedAt:u})}catch{}}a.lastPaintAt=performance.now()}finally{i.videoFrame.close()}}function Ff(t,a){if(a.renderTimer!==null||a.decodedFrames.length===0)return;const i=Math.max(16,Math.min(250,a.targetPaintIntervalMs||1e3/12)),l=()=>{if(a.renderTimer=null,a.renderScheduledAt=0,a.decodedFrames.length===0)return;const c=performance.now();if(Qx(a,c),a.decodedFrames.length===0)return;if(a.latencyMode==="interactive"){const g=a.targetPaintIntervalMs<=p1,y=a.targetPaintIntervalMs<=20;if(y&&!a.interactiveBufferPrimed){a.interactiveBufferStartedAt<=0&&(a.interactiveBufferStartedAt=c,a.interactiveBufferWaitCount+=1);const k=a.decodedFrames.length>=m1,T=c-a.interactiveBufferStartedAt>=h1;if(!k&&!T){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}a.interactiveBufferWaitMs+=Math.max(0,c-a.interactiveBufferStartedAt),a.interactiveBufferPrimed=!0}else y||(a.interactiveBufferPrimed=!0);const x=a.decodedFrames[0],b=x?.pending?Math.max(0,c-x.pending.queuedAt):0,w=a.lastPaintAt>0?a.lastPaintAt+i:c;if(!(!g||c+Py>=w||b>=Px)){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}const A=a.decodedFrames.shift();if(A)try{Uy(t,a,A)}catch{}a.decodedFrames.length===0&&(a.interactiveQueueDrainCount+=1,a.interactiveBufferPrimed=!1,a.interactiveBufferStartedAt=0),Ff(t,a);return}const u=a.lastPaintAt>0?a.lastPaintAt+i:c+g1;if(!(c+Py>=u||a.decodedFrames.length>=Math.max(1,Op(a)-1))){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}const h=a.decodedFrames.shift();if(h)try{Uy(t,a,h)}catch{}Ff(t,a)};a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l)}function Zx(t,a){if($a.get(t)!==a||a.decoder.state==="closed")return!1;for(a.renderTimer!==null&&(window.cancelAnimationFrame(a.renderTimer),a.renderTimer=null),a.renderScheduledAt=0;a.decodedFrames.length>1;)Hf(a,a.decodedFrames.shift());return a.lastPaintAt=0,a.interactiveBufferPrimed=!1,a.interactiveBufferStartedAt=0,Ff(t,a),!0}function Th(){if(!(typeof document>"u"||document.visibilityState!=="visible"))for(const t of Qu){const a=$a.get(t);if(!a||a.decoder.state==="closed"){Qu.delete(t);continue}Zx(t,a)}}typeof document<"u"&&typeof window<"u"&&(document.addEventListener("visibilitychange",Th),window.addEventListener("focus",Th),window.addEventListener("pageshow",Th));function Fs(t){ko.delete(t),Qu.delete(t),Of.delete(t);const a=$a.get(t);if(a){$a.delete(t),Ux+=1;try{Yx(a),a.decoder.state!=="closed"&&a.decoder.close()}catch{}}}function vc(t){t&&(Nc.delete(t),Cc.delete(t),up.delete(t),fp.delete(t),dp.delete(t),Of.delete(t),Yu.delete(t),Fs(t))}function D1(t,a){const i=$a.get(t),l=Nc.get(t);if(!i&&!l)return null;const c=u=>u>0?Math.max(0,a-u):void 0;return{canvasId:Xu.get(t)||0,canvasWidth:Math.max(0,Number(t.width||0)),canvasHeight:Math.max(0,Number(t.height||0)),decoderState:i?.decoder.state||"fallback-pending",configured:i?.configured||!1,codec:i?.codec||l?.codec||"",requestedAcceleration:i?.requestedAcceleration||l?.requested||_i.h264DecodeAcceleration,configuredAcceleration:i?.hardwareAcceleration||l?.actual||_i.h264DecodeAcceleration,latencyMode:i?.latencyMode||l?.latencyMode||"smooth",decodeQueueSize:Math.max(0,Number(i?.decoder.decodeQueueSize||0)),pendingFrameCount:i?.pendingFrames.size||0,renderQueueSize:i?.decodedFrames.length||0,inputCount:i?.inputSerial??l?.inputCount??0,outputCount:i?.outputSerial??l?.outputCount??0,lastInputAgeMs:c(i?.lastInputAt??l?.lastInputAt??0),lastOutputAgeMs:c(i?.lastOutputAt??l?.lastOutputAt??0),lastPaintAgeMs:c(i?.lastPaintAt??l?.lastPaintAt??0),softwareFallbackReason:l?.reason,softwareFallbackAt:l?.failedAt,softwareFallbackCount:l?.failureCount||0}}function qy(t){const a=performance.now(),l=(t?[t]:[...new Set([...Qu,...Cc])]).map(c=>D1(c,a)).filter(c=>c!==null);return{capturedAt:Date.now(),hardwareRequestPolicy:"all-active",activeDecoderCount:l.filter(c=>c.decoderState!=="fallback-pending").length,hardwareLeaseCount:ko.size,activeSoftwareFallbackCount:l.filter(c=>c.configuredAcceleration==="prefer-software"&&c.requestedAcceleration==="prefer-hardware").length,decoderCreateCount:Bx,decoderCloseCount:Ux,softwareFallbackEventCount:qx,lastSoftwareFallbackReason:Gx,lastSoftwareFallbackAt:Vx,canvases:l}}function Tf(t,a=1){try{t.decoder.state!=="closed"&&t.decoder.reset()}catch{}t.configured=!1,t.configKey="",t.keyFrameSeen=!1,t.pendingFrames.clear(),Yx(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.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(a)))}function L1(t,a,i,l,c){t.decoder.configure(a),t.configured=!0,t.configKey=i,t.codec=a.codec,t.requestedAcceleration=c,t.hardwareAcceleration=l,t.keyFrameSeen=!1,t.nextChunkTimestampUs=0,t.lastInputFrameSeq=void 0}function _1(t,a){if(a.latencyMode!=="interactive"||a.hardwareAcceleration!=="prefer-hardware")return!1;const i=performance.now();if(i-a.healthSampleStartedAt<b1)return!1;const l=a.inputSerial-a.healthInputSerial,c=a.outputSerial-a.healthOutputSerial;return a.healthSampleStartedAt=i,a.healthInputSerial=a.inputSerial,a.healthOutputSerial=a.outputSerial,l<x1||c/Math.max(1,l)>=w1?!1:(zp(t,a.requestedAcceleration,"interactive-health"),Fs(t),!0)}function Eu(t,a=1){if(!t)return!1;const i=$a.get(t);return i?(i.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(a))),Fs(t),!0):!1}function I1(t){if(!t)return!1;const a=$a.get(t);return a?Zx(t,a):!1}function z1(t,a,i,l="interactive"){Fs(t);const c=performance.now(),u=c1(a.payload,a.uncompressedByteLength||0),m=String(a.streamId||"mode5");let h=Yu.get(t);if(!h||h.streamId!==m||h.width!==u.width||h.height!==u.height){const k=new Uint8ClampedArray(u.width*u.height*4);for(let T=3;T<k.length;T+=4)k[T]=255;h={streamId:m,width:u.width,height:u.height,rgba:k,imageData:new ImageData(k,u.width,u.height),keyFrameSeen:!1,inputSerial:0,outputSerial:0},Yu.set(t,h)}if(!h)throw new Error("Mode 5 canvas state could not be initialized.");h.inputSerial+=1;const y=Number(a.streamFrameSeq||0);if(y>0&&(h.lastStreamFrameSeq=y),!u.keyFrame&&!h.keyFrameSeen)return;u.keyFrame&&(h.keyFrameSeen=!0);const x=u1(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 w=Kx(t,l),j=performance.now();x&&w?.context.putImageData(h.imageData,0,0,x.x,x.y,x.width,x.height);const A=performance.now();h.outputSerial+=1,i?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.mimeType,width:h.width,height:h.height,byteLength:a.byteLength,queuedForMs:Math.max(0,A-c),decodedForMs:Math.max(0,b-c),scheduledForMs:0,drawMs:Math.max(0,A-j),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(a.durationUs||0)/1e3||1e3/30),canvasPresentation:w?.presentation||"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:String(a.contentHash||""),visualChanged:Number(a.deltaVisualTileCount||0)>0,paintedAt:A})}const Rh=[{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 Gy(t,a){for(let i=Math.max(0,a);i+3<t.length;i+=1)if(!(t[i]!==0||t[i+1]!==0)){if(t[i+2]===1)return{index:i,length:3};if(t[i+2]===0&&t[i+3]===1)return{index:i,length:4}}return null}function O1(t){let a=0;for(;a<t.length;){const i=Gy(t,a);if(!i)break;const l=i.index+i.length,c=Gy(t,l),u=c?.index??t.length;if(l<u&&(t[l]&31)===7){const m=[];let h=0;for(let g=l+1;g<u;g+=1){const y=t[g];if(h>=2&&y===3){h=0;continue}m.push(y),h=y===0?h+1:0}if(m.length>=3)return`avc1.${m.slice(0,3).map(g=>g.toString(16).toUpperCase().padStart(2,"0")).join("")}`}a=c?c.index:t.length}return""}function H1(t,a,i,l,c=""){const u=Math.ceil(t/16)*Math.ceil(a/16),m=i>0?1e6/i:30,h=u*m,g=Rh.find(y=>u<=y.maxFrameSize&&h<=y.maxMacroblocksPerSecond)||Rh[Rh.length-1];return O1(l)||c||`avc1.42E0${g.code.toString(16).toUpperCase().padStart(2,"0")}`}function Jx(t,a,i,l,c="smooth",u=!0){Yu.delete(t);const m=String(a.h264Format||"").toLowerCase()==="avc"?"avc":"annexb",h=Math.max(1,Math.floor(a.width||960)),g=Math.max(1,Math.floor(a.height||540)),y=Math.max(1,Math.floor(a.durationUs||1e6/12)),x=l||_i.h264DecodeAcceleration;let b=By(t,c,x);const w=H1(h,g,y,a.payload,b.codec),j=a.isKeyFrame===!0||String(a.chunkType||"").toLowerCase()==="key";let A=mp(t,x),k="";const T=()=>{k=[a.streamId||"",a.commandId||"",h,g,w,m,x,A,c].join("|")};T(),b.onPaint=i,b.configured&&b.decoder.state!=="configured"&&(b.configured=!1,b.configKey=""),b.configured&&b.configKey!==k&&(Fs(t),b=By(t,c,x),b.onPaint=i,A=mp(t,x),T());const M=()=>({codec:w,codedWidth:h,codedHeight:g,hardwareAcceleration:A,optimizeForLatency:!0,avc:{format:m}}),N=Y=>b.hardwareAcceleration!=="prefer-hardware"||!zp(t,b.requestedAcceleration,Y)?!1:(Fs(t),u&&j&&Jx(t,a,i,x,c,!1),!0),L=()=>{try{return L1(b,M(),k,A,x),!0}catch(Y){if(N("configure-error"))return!1;throw Fs(t),Y}};if(!b.configured&&!L())return;const z=Number(a.streamFrameSeq||0);if(z>0&&b.lastInputFrameSeq!==void 0&&(z<=b.lastInputFrameSeq&&(!j||z===b.lastInputFrameSeq||(Tf(b,b.lastInputFrameSeq-z+1),!L()))||z>b.lastInputFrameSeq+1&&(Tf(b,z-b.lastInputFrameSeq-1),!j||!L()))||(z>0&&(b.lastInputFrameSeq=z),!j&&!b.keyFrameSeen))return;j&&(b.keyFrameSeen=!0);const H=Number(b.decoder.decodeQueueSize||0);if(H>8){if(b.latencyMode==="interactive"&&b.hardwareAcceleration==="prefer-hardware"){N("decode-queue-overflow");return}if(Tf(b),!j||!L())return;b.keyFrameSeen=!0}const G=b.nextChunkTimestampUs;b.nextChunkTimestampUs+=y,b.pendingFrames.set(G,{frame:a,queuedAt:performance.now(),queueSize:H}),b.inputSerial+=1,b.lastInputAt=performance.now();const _=new EncodedVideoChunk({type:j?"key":"delta",timestamp:G,duration:y,data:a.payload});try{b.decoder.decode(_)}catch(Y){if(N("decode-error"))return;throw Fs(t),Y}Xx(t,b),_1(t,b)}async function Eh(t,a,i,l,c,u="smooth"){if(T1(a)){i()||z1(t,a,l,u);return}if(N1(a)){i()||Jx(t,a,l,c,u);return}if(Yu.delete(t),M1(a)){Fs(t);const b=E1(a);if(i())return;(t.width!==b.width||t.height!==b.height)&&(t.width=b.width,t.height=b.height);const w=t.getContext("2d"),j=performance.now();w?.putImageData(b,0,0);const A=performance.now(),k=hp(t,b.width,b.height,Ip,64,a);l?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.codec||a.mimeType,width:b.width,height:b.height,byteLength:a.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,A-j),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:_i.h264DecodeAcceleration,decoderLabel:"lzo-rgb565",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});return}Fs(t);const m=new Blob([a.payload],{type:a.mimeType}),h=await createImageBitmap(m);if(i()){h.close();return}const g=a.width||h.width||960,y=a.height||h.height||540;(t.width!==g||t.height!==y)&&(t.width=g,t.height=y);const x=t.getContext("2d");if(x){const b=performance.now();x.clearRect(0,0,g,y),x.drawImage(h,0,0,g,y);const w=performance.now(),j=hp(t,g,y);l?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.codec||a.mimeType,width:g,height:y,byteLength:a.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,w-b),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:_i.h264DecodeAcceleration,decoderLabel:"image",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:j.visualHash,visualChanged:j.visualChanged,paintedAt:w})}h.close()}const Vy="livedesk_remote_host_targets",F1="livedesk_entitlements",Hp=new TextDecoder;function P1(t){const i=(Array.isArray(t)?t:[t||En]).map(l=>Hl(l||En));return[...new Set(i.filter(Boolean))]}function $1(){const[t,a]=d.useState(null),[i,l]=d.useState(!0);return d.useEffect(()=>{let c=!0;const u=window.liveDesk?.auth?.onComplete?.(h=>{h.ok&&h.session&&St.auth.setSession(h.session)});(window.liveDesk?.auth?.getSession?.()||St.auth.getSession()).then(h=>{c&&(a(Tx(h)),l(!1))});const{data:{subscription:m}}=St.auth.onAuthStateChange((h,g)=>{a(g),l(!1),window.liveDesk?.auth?.persistSession?.(g)});return()=>{c=!1,u?.(),m.unsubscribe()}},[]),{session:t,loading:i}}function B1(t,a=!0){const[i,l]=d.useState(null),[c,u]=d.useState([]),[m,h]=d.useState(""),[g,y]=d.useState(""),[x,b]=d.useState(0),w=d.useRef(new Map),j=Array.isArray(t)?t.join(`
|
|
12
|
+
`):String(t||""),A=d.useMemo(()=>P1(t),[j]),k=d.useMemo(()=>A.find(N=>Uu(N)==="loopback")||A[0]||En,[A]),T=d.useCallback(async()=>{if(!a){l(null),u([]),y(""),h("");return}let N=null;const L=Date.now(),z=A.filter(H=>(w.current.get(H)||0)<=L);if(z.length===0)throw new Error("No LiveDesk Hub endpoint is reachable. Retrying shortly.");for(const H of z)try{const[G,_]=await Promise.all([We("/api/remote/status",void 0,H),We("/api/remote/devices",void 0,H)]);if(!Array.isArray(_.devices))throw new Error("Invalid Hub devices response.");w.current.delete(H),l(G),u(_.devices),y(H),h("");return}catch(G){N=G,w.current.set(H,Date.now()+1e4)}throw y(""),N||new Error("No LiveDesk Hub endpoint is reachable.")},[a,A]),M=d.useCallback(()=>{w.current.clear(),T().catch(N=>{h(N instanceof Error?N.message:String(N))}),b(N=>N+1)},[T]);return d.useEffect(()=>{if(!a){l(null),u([]),y(""),h("");return}let N=!0;const L=async()=>{try{await T()}catch(H){N&&h(H instanceof Error?H.message:String(H))}};L();const z=window.setInterval(L,2500);return()=>{N=!1,window.clearInterval(z)}},[a,T,x]),{status:i,devices:c,error:m,refresh:M,hubBaseUrl:g||k,hubCandidates:A}}function U1(t){const[a,i]=d.useState(null),[l,c]=d.useState(""),u=t?.user?.id||"",m=d.useCallback(async()=>{if(!u){i(null);return}const{data:h,error:g}=await St.from(Vy).select("*").eq("user_id",u).maybeSingle();if(g){c(g.message);return}i(h),c("")},[u]);return d.useEffect(()=>{m()},[m]),d.useEffect(()=>{if(!u)return;const h=St.channel(`livedesk-remote-host-targets-${u.replace(/[^a-zA-Z0-9]/g,"")}`).on("postgres_changes",{event:"*",schema:"public",table:Vy,filter:`user_id=eq.${u}`},g=>i(g.new)).subscribe();return()=>{St.removeChannel(h)}},[u]),{target:a,error:l,refresh:m}}function q1(t){const[a,i]=d.useState(null),[l,c]=d.useState(!1),[u,m]=d.useState(""),h=t?.user?.id||"",g=d.useCallback(async()=>{if(!h){i(null),m(""),c(!1);return}c(!0);const{data:x,error:b}=await St.from(F1).select("*").eq("user_id",h).eq("product_key","livedesk").maybeSingle();if(b){m(b.message),c(!1);return}i(x),m(""),c(!1)},[h]);d.useEffect(()=>{g()},[g]);const y=d.useMemo(()=>!a||a.status!=="active"?!1:a.expires_at?new Date(a.expires_at).getTime()>Date.now():!0,[a]);return{entitlement:a,licensed:y,loading:l,error:u,refresh:g}}const qu={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},G1=2500,V1=3e4,W1=64*1024,K1=6,Y1=K1,ew=new Map;function Q1(t){return ew.get(t)}const Wy={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function X1(t,a,i){const l=Number(a);if(!Number.isFinite(l)||l<=0)return 0;const c=i-l,u=t.minimumHubClockOffsetMs;if(!Number.isFinite(u)||c<Number(u))return t.minimumHubClockOffsetMs=c,0;const m=Math.max(0,c-Number(u));return m>V1?(t.minimumHubClockOffsetMs=c,0):m}function Du(t){if(t==null||t==="")return;const a=Number(t);return Number.isFinite(a)?a:void 0}function Ky(t,a,i=En,l={}){const[c,u]=d.useState(new Map),[m,h]=d.useState("idle"),[g,y]=d.useState(""),[x,b]=d.useState(qu),w=d.useRef(new Map),j=d.useRef(new Map),A=d.useRef(0),k=d.useRef(new Map),T=d.useRef({enabled:!1,token:"",reason:""}),M=d.useRef(new Set),[N,L]=d.useState(0),z=d.useRef(l.onFrame),H=d.useRef(l.onStreamReady),G=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),_=d.useMemo(()=>[...t].sort().join(","),[t]),Y=Number.isFinite(l.fps)?Number(l.fps):2,q=Number.isFinite(l.maxWidth)?Number(l.maxWidth):640,U=Number.isFinite(l.maxHeight)?Number(l.maxHeight):360,K=Number.isFinite(l.quality)?Number(l.quality):45,O=String(l.frameMode||l.mode||"mode3-h264-hw").trim()||"mode3-h264-hw",ve=l.streamPurpose==="control"?"control":"wall",me=l.forceRestart===!0,Z=String(l.forceRestartToken||"").trim(),I=String(l.restartReason||"").trim();T.current={enabled:me,token:Z,reason:I};const se=d.useMemo(()=>{const he=Object.entries(l.monitorSelections||{}).filter(([de])=>!!de).sort(([de],[ee])=>de.localeCompare(ee));return JSON.stringify(Object.fromEntries(he))},[l.monitorSelections]);d.useEffect(()=>{z.current=l.onFrame},[l.onFrame]),d.useEffect(()=>{H.current=l.onStreamReady},[l.onStreamReady]);const W=d.useCallback((he,de="livedesk-frame-socket-release")=>{he.disposed=!0;try{he.socket.readyState===WebSocket.CONNECTING||he.socket.readyState===WebSocket.OPEN?he.socket.close(1e3,de):he.socket.close()}catch{}},[]),F=d.useCallback(()=>{const he=[...j.current.values()].map(de=>de.socket);if(he.length===0){h("idle");return}if(he.some(de=>de.readyState===WebSocket.OPEN)){h("open");return}if(he.some(de=>de.readyState===WebSocket.CONNECTING)){h("connecting");return}h("closed")},[]),oe=d.useCallback((he,de,ee,Ce)=>{if(de.disposed||de.socket.readyState!==WebSocket.OPEN)return!1;try{return de.socket.send(JSON.stringify({...de.payload,type:"restart-live",deviceIds:[he],forceRestart:!0,restartReason:ee,restartToken:Ce})),!0}catch{return!1}},[]),le=d.useCallback((he,de)=>{if(!he||he.byteLength<5)return;const ee=Date.now(),Re=new DataView(he).getUint32(0,!1);if(Re<=0||Re+4>he.byteLength)return;const He=new Uint8Array(he,4,Re),te=JSON.parse(Hp.decode(He)),Ue=Du(te.hubPacketEpochMs),mt=Ue!==void 0&&Ue>0?Ue:void 0,ne=X1(de,mt,ee);if(ne>G1)return;const xe=new Uint8Array(he,4+Re),Oe={deviceId:String(te.deviceId||""),kind:te.kind==="thumbnail"?"thumbnail":"live",frameSeq:Number(te.frameSeq||0),streamFrameSeq:Number(te.streamFrameSeq||0)||void 0,streamId:String(te.streamId||""),commandId:te.commandId?String(te.commandId):void 0,sessionId:te.sessionId?String(te.sessionId):void 0,captureGeneration:Number(te.captureGeneration||0)||void 0,streamPurpose:te.streamPurpose?String(te.streamPurpose):void 0,width:Number(te.width||0),height:Number(te.height||0),sourceWidth:Number(te.sourceWidth||0)||void 0,sourceHeight:Number(te.sourceHeight||0)||void 0,mimeType:String(te.mimeType||"image/jpeg"),mode:te.mode?String(te.mode):void 0,frameMode:te.frameMode?String(te.frameMode):void 0,frameProfile:te.frameProfile?String(te.frameProfile):void 0,encoding:te.encoding?String(te.encoding):void 0,codec:te.codec?String(te.codec):void 0,compression:te.compression?String(te.compression):void 0,pixelFormat:te.pixelFormat?String(te.pixelFormat):void 0,bytesPerPixel:Number(te.bytesPerPixel||0)||0,uncompressedByteLength:Number(te.uncompressedByteLength||0)||0,h264Format:te.h264Format?String(te.h264Format):void 0,isKeyFrame:te.isKeyFrame===!0,chunkType:te.chunkType?String(te.chunkType):void 0,timestampUs:Number(te.timestampUs||0)||0,durationUs:Number(te.durationUs||0)||0,sourceGapMs:Number(te.sourceGapMs||0)||0,agentSendGapMs:Number(te.agentSendGapMs||0)||0,agentSendDurationMs:Number(te.agentSendDurationMs||0)||0,agentSendDurationFrameSeq:Number(te.agentSendDurationFrameSeq||0)||0,agentPaceMs:Number(te.agentPaceMs||0)||0,agentQueueBeforePaceMs:Number(te.agentQueueBeforePaceMs||0)||0,agentFrameAgeMs:Number(te.agentFrameAgeMs||0)||0,nativeCaptureTelemetryAvailable:te.nativeCaptureTelemetryAvailable===!0,nativeEncoderHardwareAccelerationKnown:te.nativeEncoderHardwareAccelerationKnown===!0,nativeEncoderHardwareAccelerated:typeof te.nativeEncoderHardwareAccelerated=="boolean"?te.nativeEncoderHardwareAccelerated:void 0,nativeEncoderHardwareQueryStatus:te.nativeEncoderHardwareQueryStatus?String(te.nativeEncoderHardwareQueryStatus):void 0,nativeCaptureFps:Number(te.nativeCaptureFps||0)||0,nativeEncodedFps:Number(te.nativeEncodedFps||0)||0,nativeCaptureSampleCount:Number(te.nativeCaptureSampleCount||0)||0,nativeEncodableFrameCount:Number(te.nativeEncodableFrameCount||0)||0,nativeSkippedFrameCount:Number(te.nativeSkippedFrameCount||0)||0,nativeEncodedFrameCount:Number(te.nativeEncodedFrameCount||0)||0,nativeEncodeFramesInFlight:Number(te.nativeEncodeFramesInFlight||0)||0,nativeBackpressureSkippedFrameCount:Number(te.nativeBackpressureSkippedFrameCount||0)||0,nativeIdleSkippedFrameCount:Number(te.nativeIdleSkippedFrameCount||0)||0,nativeCaptureTelemetryAt:te.nativeCaptureTelemetryAt?String(te.nativeCaptureTelemetryAt):void 0,droppedByAgent:Number(te.droppedByAgent||0)||0,hubIngressDropped:Number(te.hubIngressDropped||0)||0,hubClientDropped:Number(te.hubClientDropped||0)||0,transport:te.transport?String(te.transport):void 0,videoTransport:te.videoTransport?String(te.videoTransport):void 0,frameTransportActive:te.frameTransportActive?String(te.frameTransportActive):void 0,frameTransportProtocol:te.frameTransportProtocol?String(te.frameTransportProtocol):void 0,frameTransportState:te.frameTransportState?String(te.frameTransportState):void 0,frameTransportReason:te.frameTransportReason?String(te.frameTransportReason):void 0,frameTransportChangedAt:te.frameTransportChangedAt?String(te.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(te.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(te.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:te.frameTransportP2pReady===!0,hubClientQueueDepth:Number(te.hubClientQueueDepth||0)||0,hubClientQueueLimit:Number(te.hubClientQueueLimit||0)||0,hubClientBufferedBytes:Number(te.hubClientBufferedBytes||0)||0,udpIncompleteFrames:Number(te.udpIncompleteFrames||0)||0,hardwareEncoder:te.hardwareEncoder?String(te.hardwareEncoder):void 0,platformProfile:te.platformProfile?String(te.platformProfile):void 0,monitorIndex:Number.isFinite(Number(te.monitorIndex))?Number(te.monitorIndex):void 0,monitorCount:Number.isFinite(Number(te.monitorCount))?Number(te.monitorCount):void 0,requestedFps:Number(te.requestedFps||0)||0,effectiveFps:Number(te.effectiveFps||0)||0,captureTimingAvailable:te.captureTimingAvailable===!0,captureAverageMs:Du(te.captureAverageMs),captureP95Ms:Du(te.captureP95Ms),slowFrameCount:Number(te.slowFrameCount||0)||0,captureHelperRestarts:Number(te.captureHelperRestarts||0)||0,capturedAt:String(te.capturedAt||""),receivedAt:String(te.receivedAt||""),hubPacketAt:te.hubPacketAt?String(te.hubPacketAt):void 0,hubPacketEpochMs:mt,browserReceivedEpochMs:ee,hubPacketTransitAgeMs:mt!==void 0?ne:void 0,byteLength:Number(te.byteLength||xe.byteLength),contentHash:te.contentHash?String(te.contentHash):void 0,captureMs:Du(te.captureMs),captureStageMs:Du(te.captureStageMs),convertMs:Number(te.convertMs||0)||0,compressMs:Number(te.compressMs||0)||0,captureSourceSerial:Number(te.captureSourceSerial||0)||0,captureSourceSkipped:Number(te.captureSourceSkipped||0)||0,deltaTileSize:Number(te.deltaTileSize||0)||0,deltaTileCount:Number(te.deltaTileCount||0)||0,deltaVisualTileCount:Number(te.deltaVisualTileCount||0)||0,deltaRefreshTileCount:Number(te.deltaRefreshTileCount||0)||0,deltaTotalTiles:Number(te.deltaTotalTiles||0)||0,payload:xe};if(!Oe.deviceId)return;const $e=Number(de.payload.monitorSelections?.[Oe.deviceId]);if(Number.isFinite($e)&&Number.isFinite(Number(Oe.monitorIndex))&&Number(Oe.monitorIndex)!==$e)return;const ze={streamId:de.lastFrameStreamId,commandId:de.lastFrameCommandId,order:de.lastFrameOrder},Qe=Number(Oe.streamFrameSeq||Oe.frameSeq||0),qe=!!ze.commandId&&!!Oe.commandId,Ye=ze.streamId===Oe.streamId&&(!qe||ze.commandId===Oe.commandId),ot=ze.order;if(Ye&&ot>=Qe&&(ot===Qe||qe))return;de.lastFrameStreamId=Oe.streamId,de.lastFrameCommandId=Oe.commandId||"",de.lastFrameOrder=Qe;const B=G.current;B.totalFrames+=1,B.totalBytes+=xe.byteLength,B.sampleFrames+=1,B.sampleBytes+=xe.byteLength;const ye=!w.current.has(Oe.deviceId);w.current.set(Oe.deviceId,Oe),ye&&u(new Map(w.current)),z.current?.(Oe)},[]);d.useEffect(()=>{const he=window.setInterval(()=>{const de=performance.now(),ee=G.current,Ce=Math.max(1,de-ee.sampleStartedAt);b({totalFrames:ee.totalFrames,totalBytes:ee.totalBytes,framesPerSecond:ee.sampleFrames*1e3/Ce,bytesPerSecond:ee.sampleBytes*1e3/Ce,sampleMs:Ce,lastUpdatedAt:Date.now()}),u(new Map(w.current)),ee.sampleFrames=0,ee.sampleBytes=0,ee.sampleStartedAt=de},2e3);return()=>{window.clearInterval(he)}},[]),d.useEffect(()=>{const he=_?_.split(",").filter(Boolean):[],de=new Set(he),ee=performance.now();for(const[Ce,Re]of j.current.entries())de.has(Ce)||(W(Re,"livedesk-device-unsubscribed"),j.current.delete(Ce),k.current.delete(Ce),w.current.delete(Ce));if(he.length===0){for(const Ce of j.current.values())W(Ce,"livedesk-no-devices");j.current.clear(),k.current.clear(),w.current=new Map,u(new Map),y(""),G.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},b(qu),F();return}G.current.sampleStartedAt<=0&&(G.current.sampleStartedAt=ee,b({...qu,lastUpdatedAt:Date.now()}));for(const Ce of he){const Re=Number(l.monitorSelections?.[Ce]),He=Number.isInteger(Re)&&Re>=0?Re:0,te={[Ce]:He},Ue={type:"subscribe",deviceIds:[Ce],autoStartLive:a,fps:Y,maxWidth:q,maxHeight:U,quality:K,mode:O,frameMode:O,streamPurpose:ve,monitorSelections:te},mt=JSON.stringify(Ue),ne=j.current.get(Ce),xe=Number(ne?.payload.monitorSelections?.[Ce]),Oe=Number(te[Ce]),$e=!!ne&&Number.isFinite(xe)&&Number.isFinite(Oe)&&xe!==Oe;if(ne){const Ye=ne.socket.readyState===WebSocket.CONNECTING||ne.socket.readyState===WebSocket.OPEN;if(ne.payloadKey===mt&&Ye&&!ne.disposed)continue}const ze=ne&&(ne.socket.readyState===WebSocket.CONNECTING||ne.socket.readyState===WebSocket.OPEN)&&!ne.disposed?ne.handoffFrom&&!ne.handoffCompleted?ne.handoffFrom:ne:void 0;ne&&ne!==ze&&W(ne,"livedesk-subscription-superseded");const Qe=new WebSocket(Kf(`/api/remote/frames/ws?devices=${encodeURIComponent(Ce)}`,i));Qe.binaryType="arraybuffer";const qe={socket:Qe,payload:Ue,payloadKey:mt,generation:A.current+1,monitorRestartToken:$e?`monitor-${Ce}-${Oe}-${A.current+1}`:"",disposed:!1,handoffFrom:ze,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1};A.current=qe.generation,$e&&(w.current.delete(Ce),u(new Map(w.current))),j.current.set(Ce,qe),Qe.addEventListener("open",()=>{if(qe.disposed||j.current.get(Ce)!==qe){W(qe,"livedesk-stale-frame-socket");return}y("");const Ye=T.current,ot=Ye.enabled&&(!Ye.token||k.current.get(Ce)!==Ye.token),B=ot||qe.monitorRestartToken!=="",ye=ot?Ye.token:qe.monitorRestartToken,je=ot?Ye.reason:qe.monitorRestartToken?"monitor-selection-change":"";Qe.send(JSON.stringify({...qe.payload,forceRestart:B,restartReason:B?je:"",restartToken:B?ye:""})),ot&&Ye.token&&k.current.set(Ce,Ye.token);const Pe=qe.handoffFrom;qe.handoffFrom=void 0,qe.handoffCompleted=!0,Pe&&!Pe.disposed&&W(Pe,"livedesk-subscription-replaced"),F()}),Qe.addEventListener("message",Ye=>{if(qe.disposed||j.current.get(Ce)!==qe)return;if(typeof Ye.data=="string"){try{const B=JSON.parse(Ye.data);if(B?.type==="RemoteFrameSubscriptionError")y(String(B.error||"control-stream-start-failed"));else if(B?.type==="RemoteFrameLiveAutoStart"){const je=(Array.isArray(B.skipped)?B.skipped:[]).find(Pe=>Pe?.deviceId===Ce);if(je)y(String(je.reason||"control-stream-start-failed"));else if(Array.isArray(B.started)){const Pe=B.started.find(dt=>dt?.deviceId===Ce);Pe&&(y(""),Pe.ready===!0&&Pe.streamPurpose==="control"&&Pe.sessionId&&Pe.commandId&&Number(Pe.captureGeneration||0)>0&&H.current?.({deviceId:Ce,sessionId:String(Pe.sessionId),streamId:String(Pe.streamId||""),streamPurpose:"control",commandId:String(Pe.commandId),captureGeneration:Number(Pe.captureGeneration),monitorIndex:Number(Pe.monitorIndex||0)}))}}else B?.type==="RemoteFrameStreamReady"&&B.deviceId===Ce&&B.streamPurpose==="control"&&B.sessionId&&B.commandId&&Number(B.captureGeneration||0)>0&&(y(""),H.current?.({deviceId:Ce,sessionId:String(B.sessionId),streamId:String(B.streamId||""),streamPurpose:"control",commandId:String(B.commandId),captureGeneration:Number(B.captureGeneration),monitorIndex:Number(B.monitorIndex||0)}))}catch{}return}const ot=Ye.data instanceof ArrayBuffer?Ye.data:null;ot&&(y(""),le(ot,qe))}),Qe.addEventListener("error",()=>{qe.disposed||j.current.get(Ce)!==qe||h("connecting")}),Qe.addEventListener("close",()=>{const Ye=!qe.disposed;qe.disposed=!0;const ot=j.current.get(Ce);let B=!1;if(ot===qe){const ye=qe.handoffFrom;qe.handoffFrom=void 0,ye&&!ye.disposed&&(ye.socket.readyState===WebSocket.CONNECTING||ye.socket.readyState===WebSocket.OPEN)?(j.current.set(Ce,ye),B=!0):j.current.delete(Ce)}if(F(),Ye&&ot===qe&&!B){const ye=window.setTimeout(()=>{M.current.delete(ye),L(je=>je+1)},750);M.current.add(ye)}})}F()},[a,W,_,Y,O,le,i,U,q,se,l.monitorSelections,K,N,ve,F]),d.useEffect(()=>{if(!me||!Z)return;const he=_?_.split(",").filter(Boolean):[];for(const de of he){if(k.current.get(de)===Z)continue;const ee=j.current.get(de);!ee||!oe(de,ee,I,Z)||k.current.set(de,Z)}},[_,me,Z,I,oe]),d.useEffect(()=>()=>{for(const he of j.current.values())W(he,"livedesk-hook-unmount");j.current.clear();for(const he of M.current)window.clearTimeout(he);M.current.clear()},[W]);const Q=d.useCallback((he,de="browser-stale")=>{const ee=Array.isArray(he)&&he.length>0?he:_.split(",").filter(Boolean);if(ee.length===0)return!1;let Ce=!1;for(const Re of ee){const He=j.current.get(Re);!He||He.socket.readyState!==WebSocket.OPEN||(Ce=oe(Re,He,de,`${Date.now()}-${Math.random().toString(36).slice(2)}`)||Ce)}return Ce},[_,oe]),be=d.useCallback((he,de="browser-reconnect")=>{const ee=Array.isArray(he)&&he.length>0?he:_.split(",").filter(Boolean);if(ee.length===0)return!1;let Ce=!1;for(const Re of ee){const He=j.current.get(Re);He&&(W(He,`livedesk-${de}`),j.current.delete(Re),k.current.delete(Re),w.current.delete(Re),Ce=!0)}return Ce&&u(new Map(w.current)),L(Re=>Re+1),F(),!0},[W,_,F]);return{frames:c,state:m,error:g,stats:x,restartLive:Q,reconnectLive:be}}function Z1(t,a,i=En,l={}){const[c,u]=d.useState(null),[m,h]=d.useState(null),[g,y]=d.useState("idle"),[x,b]=d.useState(qu),w=d.useRef(null),j=d.useRef(l.onFrame),A=d.useRef(null),k=d.useRef(0),T=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),M=d.useMemo(()=>[...new Set(t.filter(Boolean))].join(","),[t]),N=d.useMemo(()=>[...new Set((l.captureDeviceIds||t).filter(Boolean))].join(","),[t,l.captureDeviceIds]),L=d.useMemo(()=>JSON.stringify(l.monitorSelections||{}),[l.monitorSelections]),z=d.useMemo(()=>({deviceIds:M.split(",").filter(Boolean),captureDeviceIds:N.split(",").filter(Boolean),fps:Number(l.fps||20),inputFps:Number(l.inputFps||8),width:Number(l.width||1920),height:Number(l.height||1080),tileWidth:Number(l.tileWidth||320),tileHeight:Number(l.tileHeight||180),monitorSelections:l.monitorSelections||{}}),[N,M,L,l.fps,l.height,l.inputFps,l.monitorSelections,l.tileHeight,l.tileWidth,l.width]),H=d.useMemo(()=>JSON.stringify(z),[z]),G=d.useRef(z);G.current=z;const _=a&&z.deviceIds.length>0,Y=d.useCallback(U=>U.readyState!==WebSocket.OPEN?!1:(U.send(JSON.stringify({type:"configure",...G.current})),!0),[]);d.useEffect(()=>{j.current=l.onFrame},[l.onFrame]),d.useEffect(()=>{const U=window.setInterval(()=>{const K=T.current,O=performance.now(),ve=Math.max(1,O-K.sampleStartedAt);b({totalFrames:K.totalFrames,totalBytes:K.totalBytes,framesPerSecond:K.sampleFrames*1e3/ve,bytesPerSecond:K.sampleBytes*1e3/ve,sampleMs:ve,lastUpdatedAt:Date.now()});const me=A.current;me&&me.frameSeq!==k.current&&(k.current=me.frameSeq,u(me)),K.sampleFrames=0,K.sampleBytes=0,K.sampleStartedAt=O},1e3);return()=>window.clearInterval(U)},[]),d.useEffect(()=>{if(!_){w.current?.close(),w.current=null,u(null),A.current=null,k.current=0,h(null),y("idle"),b(qu);return}let U=!1,K=0;const O=()=>{if(U)return;const ve=new WebSocket(Kf("/api/remote/atlas/ws",i));ve.binaryType="arraybuffer",w.current=ve,y("connecting"),ve.addEventListener("open",()=>{T.current.sampleStartedAt=performance.now(),y("open"),Y(ve)}),ve.addEventListener("message",me=>{if(typeof me.data=="string"){try{const I=JSON.parse(me.data);I?.type==="Mode4AtlasLayout"&&h({layoutVersion:Number(I.layoutVersion||0),width:Number(I.width||1920),height:Number(I.height||1080),columns:Number(I.columns||1),rows:Number(I.rows||1),tiles:Array.isArray(I.tiles)?I.tiles:[]})}catch{}return}const Z=me.data instanceof ArrayBuffer?me.data:null;if(!(!Z||Z.byteLength<5))try{const I=Date.now(),W=new DataView(Z).getUint32(0,!1);if(W<=0||W+4>Z.byteLength)return;const F=JSON.parse(Hp.decode(new Uint8Array(Z,4,W))),oe=new Uint8Array(Z,4+W),le={deviceId:String(F.deviceId||"__livedesk_mode4_atlas__"),kind:"live",frameSeq:Number(F.frameSeq||0),streamFrameSeq:Number(F.streamFrameSeq||0)||void 0,streamId:String(F.streamId||"mode4-atlas"),commandId:F.commandId?String(F.commandId):void 0,width:Number(F.width||1920),height:Number(F.height||1080),sourceWidth:Number(F.sourceWidth||F.width||1920),sourceHeight:Number(F.sourceHeight||F.height||1080),mimeType:String(F.mimeType||"video/h264"),mode:String(F.mode||"mode4-h264-atlas"),frameMode:String(F.frameMode||"mode4-h264-atlas"),frameProfile:String(F.frameProfile||"mode4-h264-atlas-v1"),encoding:String(F.encoding||"video-atlas"),codec:String(F.codec||"h264"),compression:String(F.compression||"video/h264"),h264Format:String(F.h264Format||"annexb"),isKeyFrame:F.isKeyFrame===!0,chunkType:String(F.chunkType||""),timestampUs:Number(F.timestampUs||0),durationUs:Number(F.durationUs||0),transport:F.transport?String(F.transport):void 0,videoTransport:F.videoTransport?String(F.videoTransport):void 0,frameTransportActive:F.frameTransportActive?String(F.frameTransportActive):void 0,frameTransportProtocol:F.frameTransportProtocol?String(F.frameTransportProtocol):void 0,frameTransportState:F.frameTransportState?String(F.frameTransportState):void 0,frameTransportReason:F.frameTransportReason?String(F.frameTransportReason):void 0,frameTransportChangedAt:F.frameTransportChangedAt?String(F.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(F.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(F.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:F.frameTransportP2pReady===!0,hubClientQueueDepth:Number(F.hubClientQueueDepth||0)||0,hubClientQueueLimit:Number(F.hubClientQueueLimit||0)||0,hubClientBufferedBytes:Number(F.hubClientBufferedBytes||0)||0,udpIncompleteFrames:Number(F.udpIncompleteFrames||0)||0,hardwareEncoder:F.hardwareEncoder?String(F.hardwareEncoder):void 0,platformProfile:F.platformProfile?String(F.platformProfile):void 0,capturedAt:String(F.capturedAt||""),receivedAt:String(F.receivedAt||""),hubPacketAt:F.hubPacketAt?String(F.hubPacketAt):void 0,hubPacketEpochMs:Number(F.hubPacketEpochMs||0)||void 0,browserReceivedEpochMs:I,byteLength:oe.byteLength,layoutVersion:Number(F.layoutVersion||0),atlasComposeMs:Number(F.atlasComposeMs||0),atlasPoolStarved:Number(F.atlasPoolStarved||0),atlasReadyTiles:Number(F.atlasReadyTiles||0),atlasTileCount:Number(F.atlasTileCount||0),atlasInputRevision:Number(F.atlasInputRevision||0),atlasSourceNewestAtEpochMs:Number(F.atlasSourceNewestAtEpochMs||0),atlasSourceOldestAtEpochMs:Number(F.atlasSourceOldestAtEpochMs||0),atlasSourceMaxAgeMs:Number(F.atlasSourceMaxAgeMs||0),payload:oe},Q=T.current;Q.totalFrames+=1,Q.totalBytes+=oe.byteLength,Q.sampleFrames+=1,Q.sampleBytes+=oe.byteLength,A.current=le,k.current===0&&(k.current=le.frameSeq,u(le)),j.current?.(le)}catch{}}),ve.addEventListener("error",()=>y("error")),ve.addEventListener("close",()=>{w.current===ve&&(w.current=null),!U&&(y("closed"),K=window.setTimeout(O,1200))})};return O(),()=>{U=!0,window.clearTimeout(K),w.current?.close(),w.current=null}},[_,i,Y]),d.useEffect(()=>{if(!_)return;const U=w.current;U&&Y(U)},[H,_,Y]);const q=d.useCallback(()=>{const U=w.current;return U?Y(U):!1},[Y]);return{frame:c,layout:m,state:g,stats:x,refreshInputs:q}}function J1(t,a=En){const i=d.useRef(null),l=d.useRef(0),c=d.useRef(0),u=d.useRef(new Map),m=d.useRef(""),[h,g]=d.useState("idle"),[y,x]=d.useState(""),[b,w]=d.useState(Wy),j=d.useRef({totalSent:0,totalDropped:0,sampleSent:0,sampleDropped:0,sampleStartedAt:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0});d.useEffect(()=>{if(!t){i.current?.close(),i.current=null,c.current=0,m.current="",u.current.clear(),g("idle"),x(""),w(Wy);return}let k=!1,T=0;const M=()=>{if(k)return;const N=new WebSocket(Kf("/api/remote/input/ws",a));i.current=N,j.current.sampleStartedAt=performance.now(),g("connecting"),x(""),N.addEventListener("open",()=>{k||i.current!==N||(x(""),g("open"))}),N.addEventListener("message",L=>{if(!(k||i.current!==N||typeof L.data!="string"))try{const z=JSON.parse(L.data),H=Number(z.inputSeq||z.result?.inputSeq||0),G=String(z.deviceId||z.result?.deviceId||""),_=String(z.inputEventId||z.result?.inputEventId||""),Y=u.current.get(H);if(G&&(Y&&Y.deviceId!==G||!Y&&m.current&&m.current!==G)||Y?.inputEventId&&_&&Y.inputEventId!==_)return;if(z?.type==="RemoteInputError"){H>0&&u.current.delete(H),x(String(z.error||z.result?.error||"Remote input failed.")),N.readyState===WebSocket.OPEN&&g("open");return}if(z?.type!=="RemoteInputApplied")return;Y&&(j.current.lastRoundTripMs=Math.max(0,performance.now()-Y.sentAt),u.current.delete(H)),j.current.lastInputSeq=H,j.current.lastAgentApplyMs=Math.max(0,Number(z.agentApplyMs||0)),x(""),g("open")}catch{}}),N.addEventListener("close",()=>{k||i.current!==N||(i.current=null,g("closed"),T=window.setTimeout(M,1200))}),N.addEventListener("error",()=>{!k&&i.current===N&&g("error")})};return M(),()=>{k=!0,window.clearTimeout(T);const N=i.current;i.current=null,N?.close(),u.current.clear()}},[t,a]),d.useEffect(()=>{if(!t)return;const k=window.setInterval(()=>{const T=performance.now(),M=j.current,N=Math.max(1,T-M.sampleStartedAt);w({totalSent:M.totalSent,totalDropped:M.totalDropped,sentPerSecond:M.sampleSent*1e3/N,droppedPerSecond:M.sampleDropped*1e3/N,bufferedAmount:i.current?.bufferedAmount||0,lastInputType:M.lastInputType,lastInputSeq:M.lastInputSeq,lastRoundTripMs:M.lastRoundTripMs,lastAgentApplyMs:M.lastAgentApplyMs,lastUpdatedAt:Date.now()}),M.sampleSent=0,M.sampleDropped=0,M.sampleStartedAt=T},1e3);return()=>window.clearInterval(k)},[t]);const A=d.useCallback((k,T)=>{const M=i.current;if(!M||M.readyState!==WebSocket.OPEN||!k)return!1;const N=String(T.type||"").toLowerCase(),L=N==="pointermove",H=L||N==="wheel",G=j.current;if(L&&M.bufferedAmount>W1)return G.totalDropped+=1,G.sampleDropped+=1,G.lastInputType="pointermove-drop",!1;const _=l.current+1;l.current=_;const Y=`${_}-${crypto.randomUUID()}`,q=Date.now(),U=!H||_-c.current>=Y1;for(U&&(u.current.set(_,{sentAt:performance.now(),deviceId:k,inputEventId:Y}),H&&(c.current=_)),m.current=k,L||ew.set(k,{inputSeq:_,inputType:N||"input",sentAt:performance.now()});u.current.size>256;){const K=u.current.keys().next().value;if(K===void 0)break;u.current.delete(K)}return M.send(JSON.stringify({type:"input",requestId:H?"":crypto.randomUUID(),fireAndForget:H,deviceId:k,input:{...T,inputEventId:Y,inputSeq:_,requestAck:U,issuedAtEpochMs:q,issuedAt:new Date(q).toISOString()}})),G.totalSent+=1,G.sampleSent+=1,G.lastInputType=N||"input",!0},[]);return{state:h,sendInput:A,stats:b,error:y}}function ek(t){const a=String(t||"").toLowerCase();return a.includes("audio/pcm")||a.includes("audio/l16")||a.includes("f32le")||a.includes("s16le")}const rf={queuedMs:0,browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:!1,helperAlive:!1,captureRestartCount:0,localProcessingAgeMs:0,lastPacketAgeMs:0,lastAcceptedAgeMs:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:"closed",stalledCount:0,automaticRestarts:0,lastUpdatedAt:0},tk=.08,nk=.25,ak=.02,Yy=300,sk=4,lf=1500,Dh=5e3,rk=2e3,ik=1e4,of=[0,1e3,3e3];function Qy(t){const a=Date.parse(String(t||""));return Number.isFinite(a)?Math.max(0,Date.now()-a):0}function lk(t,a,i){const l=Math.max(1,Math.min(8,Math.floor(a.channels||2))),c=Math.max(8e3,Math.min(192e3,Math.floor(a.sampleRate||48e3))),u=String(a.mimeType||"").toLowerCase(),m=u.includes("s16le")||u.includes("audio/l16"),h=m?2:4,g=Math.floor(i.byteLength/h),y=Math.floor(g/l),x=t.createBuffer(l,y,c),b=new DataView(i);for(let w=0;w<l;w+=1){const j=x.getChannelData(w);for(let A=0;A<y;A+=1){const T=(A*l+w)*h;j[A]=m?Math.max(-1,Math.min(1,b.getInt16(T,!0)/32768)):Math.max(-1,Math.min(1,b.getFloat32(T,!0)))}}return x}function ok(t,a,i=En){const l=d.useRef(null),c=d.useRef(0),[u,m]=d.useState("idle"),[h,g]=d.useState(null),[y,x]=d.useState(rf),[b,w]=d.useState("");return d.useEffect(()=>{if(!a||!t){m("idle"),g(null),x(rf),w("");return}m("connecting"),g(null),x(rf),w("");const j=window.AudioContext||window.webkitAudioContext;if(!j){m("unsupported"),x(rf),w("Audio playback is not supported in this browser.");return}const A=new j;l.current=A,c.current=A.currentTime;const k=new WebSocket(Kf("/api/remote/audio/ws?devices="+encodeURIComponent(t),i));k.binaryType="arraybuffer";const T=new Set,M={browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:!1,helperAlive:!1,captureRestartCount:0,localProcessingAgeMs:0,lastPacketAt:0,lastAcceptedAt:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:String(A.state),stalledCount:0,automaticRestarts:0,activeStreamId:"",lastCaptureStatusAt:0,lastPcmAtEpochMs:0};let N=!1,L=0,z=!1,H=0,G=0;const _=(I=!0)=>{for(const se of T)try{se.stop()}catch{}T.clear(),I&&(c.current=A.currentTime+tk)},Y=()=>{M.audioContextState=String(A.state),!N&&(M.audioContextState==="suspended"||M.audioContextState==="interrupted"?m("suspended"):M.audioContextState==="closed"&&(m("error"),w("The browser audio context is closed. Toggle Remote Audio off and on to recover.")))},q=async()=>{if(N||String(A.state)==="closed")return!1;try{if(String(A.state)!=="running"&&await A.resume(),M.audioContextState=String(A.state),!N&&!z&&M.audioContextState==="running"){const I=M.lastAcceptedAt>0&&performance.now()-M.lastAcceptedAt<=lf,se=M.lastCaptureStatusAt>0&&performance.now()-M.lastCaptureStatusAt<=Dh&&M.captureAlive&&M.helperAlive;m(I?"playing":se?"silent":"open")}return M.audioContextState==="running"}catch(I){return N||(m("suspended"),w(I instanceof Error?"Audio playback is suspended: "+I.message:"Audio playback is suspended.")),!1}},U=async()=>{if(N||z||k.readyState!==WebSocket.OPEN)return;if(H>=of.length){m("error"),w("Remote audio stopped sending frames. Toggle Audio off and on to retry.");return}const I=H;H+=1,z=!0,M.stalledCount+=1,M.automaticRestarts+=1,m("reconnecting");try{const se=await We("/api/remote/devices/"+encodeURIComponent(t)+"/audio/stop",{method:"POST",body:JSON.stringify({})},i);if(se.ok===!1)throw new Error(se.error||"Remote audio stop failed.");if(N)return;const W=await We("/api/remote/devices/"+encodeURIComponent(t)+"/audio/start",{method:"POST",body:JSON.stringify({streamId:"audio-restart-"+Date.now(),mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},i);if(W.ok===!1)throw new Error(W.error||"Remote audio start failed.");const F=performance.now();L=F,M.lastPacketAt=F,M.lastAcceptedAt=0,M.lastCaptureStatusAt=0,M.lastPcmAtEpochMs=0,M.captureAlive=!1,M.helperAlive=!1,M.silentForMs=0,G=F+(of[I+1]??3e3),w(""),N||m("open")}catch(se){N||(G=performance.now()+(of[I+1]??3e3),m("error"),w(se instanceof Error?"Remote audio restart failed: "+se.message:"Remote audio restart failed."))}finally{z=!1}},K=()=>{M.drops+=1},O=window.setInterval(()=>{if(N)return;const I=performance.now(),se=M.lastPacketAt>0?Math.max(0,I-M.lastPacketAt):L>0?Math.max(0,I-L):0,W=M.lastAcceptedAt>0?Math.max(0,I-M.lastAcceptedAt):0,F=M.lastCaptureStatusAt>0?Math.max(0,I-M.lastCaptureStatusAt):0,oe=k.readyState===WebSocket.OPEN,le=M.lastCaptureStatusAt>0,Q=le&&F<=Dh,be=le&&(!M.captureAlive||!M.helperAlive)&&F>rk,he=le&&F>Dh,de=!le&&L>0&&I-L>ik,ee=L>0&&(M.lastAcceptedAt<=0?I-L>lf:W>lf);oe&&L>0&&(be||he||de)?H>=of.length&&!z?(m("error"),w("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!z&&I>=G?U():z||m("stalled"):oe&&ee&&!z&&M.audioContextState!=="suspended"&&M.audioContextState!=="interrupted"&&m(Q?"silent":"open"),x({queuedMs:Math.max(0,(c.current-A.currentTime)*1e3),browserAgeMs:M.browserAgeMs,captureAgeMs:M.captureAgeMs,captureStatusAgeMs:F,silentForMs:M.silentForMs,captureAlive:M.captureAlive,helperAlive:M.helperAlive,captureRestartCount:M.captureRestartCount,localProcessingAgeMs:M.localProcessingAgeMs,lastPacketAgeMs:se,lastAcceptedAgeMs:W,framesReceived:M.framesReceived,drops:M.drops,resyncs:M.resyncs,pendingDecodes:M.pendingDecodes,lastFrameSeq:M.lastFrameSeq,audioContextState:M.audioContextState,stalledCount:M.stalledCount,automaticRestarts:M.automaticRestarts,lastUpdatedAt:Date.now()})},250),ve=()=>{Y(),(String(A.state)==="suspended"||String(A.state)==="interrupted")&&q()},me=()=>{document.visibilityState==="visible"&&q()},Z=()=>{q()};return A.addEventListener("statechange",ve),document.addEventListener("visibilitychange",me),window.addEventListener("pageshow",Z),window.addEventListener("pointerdown",Z),window.addEventListener("keydown",Z),m("connecting"),w(""),Y(),k.addEventListener("open",()=>{N||(L=performance.now(),M.lastPacketAt=L,M.lastAcceptedAt=0,M.lastCaptureStatusAt=0,M.lastPcmAtEpochMs=0,M.captureAlive=!1,M.helperAlive=!1,M.silentForMs=0,m("open"),k.send(JSON.stringify({type:"subscribe",deviceIds:[t]})),q())}),k.addEventListener("message",I=>{if(typeof I.data=="string")return;const se=I.data instanceof ArrayBuffer?I.data:null;if(!se||se.byteLength<5)return;const W=performance.now();M.lastPacketAt=W,(async()=>{try{const oe=new DataView(se).getUint32(0,!1);if(oe<=0||oe+4>se.byteLength){K();return}const le=new Uint8Array(se,4,oe),Q=JSON.parse(Hp.decode(le)),be=se.slice(4+oe),he=String(Q.frameKind||Q.kind||"").toLowerCase();if(Q.type==="remote.audio.status"||he==="audio-status"){if(M.lastCaptureStatusAt=W,M.captureAlive=Q.captureAlive===!0,M.helperAlive=Q.helperAlive===!0,M.captureRestartCount=Math.max(0,Number(Q.restartCount||0)||0),M.lastPcmAtEpochMs=Math.max(0,Number(Q.lastPcmAtEpochMs||0)||0),M.silentForMs=Math.max(0,Number(Q.silentForMs||0)||0),M.captureAgeMs=M.lastPcmAtEpochMs>0?Math.max(0,Date.now()-M.lastPcmAtEpochMs):M.silentForMs,M.captureAlive&&M.helperAlive){if(H=0,G=0,!z){w("");const ee=String(A.state)==="running",Ce=M.lastAcceptedAt>0&&performance.now()-M.lastAcceptedAt<=lf;m(ee?Ce?"playing":"silent":"suspended")}}else z||m("stalled");return}const de={deviceId:String(Q.deviceId||""),frameSeq:Number(Q.frameSeq||0),streamId:String(Q.streamId||""),mimeType:String(Q.mimeType||"audio/webm;codecs=opus"),sampleRate:Number(Q.sampleRate||48e3),channels:Number(Q.channels||2),capturedAt:String(Q.capturedAt||""),receivedAt:String(Q.receivedAt||""),byteLength:Number(Q.byteLength||be.byteLength),payload:be};if(!de.deviceId||N)return;if(performance.now()-W>Yy){K();return}if(M.pendingDecodes>=sk){K();return}M.pendingDecodes+=1;try{const ee=ek(de.mimeType)?lk(A,de,be):await A.decodeAudioData(be.slice(0));if(M.localProcessingAgeMs=Math.max(0,performance.now()-W),N)return;if(M.localProcessingAgeMs>Yy){K();return}if(de.frameSeq>0&&de.frameSeq<=M.lastFrameSeq){K();return}if(M.activeStreamId&&de.streamId!==M.activeStreamId&&de.frameSeq<=M.lastFrameSeq){K();return}de.streamId&&de.streamId!==M.activeStreamId&&(M.activeStreamId=de.streamId,M.lastFrameSeq=0,_());const Ce=A.currentTime;Math.max(0,c.current-Ce)>nk&&(_(),M.resyncs+=1);const He=A.createBufferSource();He.buffer=ee,He.connect(A.destination),T.add(He),He.onended=()=>{T.delete(He),He.onended=null};const te=Math.max(A.currentTime+ak,c.current);He.start(te),c.current=te+ee.duration,M.browserAgeMs=Qy(de.receivedAt),M.captureAgeMs=Qy(de.capturedAt),M.lastAcceptedAt=performance.now(),M.framesReceived+=1,M.lastFrameSeq=de.frameSeq,H=0,G=0,g(de),q();const Ue=String(A.state)==="running";Ue&&w(""),m(Ue?"playing":"suspended")}finally{M.pendingDecodes=Math.max(0,M.pendingDecodes-1)}}catch(F){N||(m("error"),w(F instanceof Error?F.message:String(F)))}})()}),k.addEventListener("error",()=>{N||(m("error"),w("Remote audio WebSocket error."))}),k.addEventListener("close",()=>{N||m("closed")}),()=>{N=!0,window.clearInterval(O),A.removeEventListener("statechange",ve),document.removeEventListener("visibilitychange",me),window.removeEventListener("pageshow",Z),window.removeEventListener("pointerdown",Z),window.removeEventListener("keydown",Z),_(!1),k.close(),A.close().catch(()=>{}),l.current===A&&(l.current=null)}},[t,a,i]),{state:u,lastFrame:h,stats:y,error:b}}const ck=3;function Xy(t,a,i){const l=Math.max(1,Number(i)||1),c=Math.max(0,Math.min(l,Number(t)-Number(a))),u=Math.min(l/2,ck);return c<=u?0:c>=l-u?1:c/l}function uk(t,a,i){return{normalizedX:Xy(t,i.left,i.width),normalizedY:Xy(a,i.top,i.height)}}const Pf=Object.freeze({shiftKey:Object.freeze(["ShiftLeft","ShiftRight"]),ctrlKey:Object.freeze(["ControlLeft","ControlRight"]),altKey:Object.freeze(["AltLeft","AltRight"]),metaKey:Object.freeze(["MetaLeft","MetaRight"])}),dk=Object.freeze({shiftKey:"ShiftLeft",ctrlKey:"ControlLeft",altKey:"AltLeft",metaKey:"MetaLeft"}),Zy=Object.freeze({OSLeft:"MetaLeft",OSRight:"MetaRight"}),pp=64;function Qf(t,a=80){return String(t||"").replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,a)}function gp(t){const a=Qf(t);return Object.prototype.hasOwnProperty.call(Zy,a)?Zy[a]:a}function fk(t={}){const a=Qf(t.key),i=Number.isFinite(Number(t.location))?Math.max(0,Math.min(3,Math.trunc(Number(t.location)))):0,l=i===2?"Right":"Left";return a==="Shift"?`Shift${l}`:a==="Control"?`Control${l}`:a==="Alt"||a==="AltGraph"?`Alt${l}`:a==="Meta"||a==="OS"?`Meta${l}`:a?`Key:${i}:${a}`.slice(0,80):""}function vp(t={}){return gp(t.code)||fk(t)}function Rf(t){for(const[a,i]of Object.entries(Pf))if(i.includes(t))return a;return""}function Dl(t,a){return Pf[a].some(i=>t.has(i))}function Jy(t,a,i={}){for(const l of Object.keys(Pf)){const c=i[l]===!0,u=Pf[l];if(c){!Dl(t,l)&&t.size<pp&&t.add(dk[l]);continue}for(const m of u)a.has(m)||t.delete(m)}}function mk(t,a){if(t.length!==a.size)return!1;let i=0;for(const l of a){if(t[i]!==l)return!1;i+=1}return!0}function eb(t){for(const a of[...t])Rf(a)||t.delete(a)}function yp(t){return{shiftKey:Dl(t,"shiftKey"),ctrlKey:Dl(t,"ctrlKey"),altKey:Dl(t,"altKey"),metaKey:Dl(t,"metaKey")}}function hk(t={},a={}){return{shiftKey:t.shiftKey===!0||a.shiftKey===!0,ctrlKey:t.ctrlKey===!0||a.ctrlKey===!0,altKey:t.altKey===!0||a.altKey===!0,metaKey:t.metaKey===!0||a.metaKey===!0}}function pk(t,a,i){const l=vp(t),c=Qf(t.key),u=Number(t.keyCode??t.which),m=Number(t.location);return{type:a,key:c,code:l,keyCode:Number.isFinite(u)?Math.max(0,Math.min(65535,Math.trunc(u))):0,location:Number.isFinite(m)?Math.max(0,Math.min(255,Math.trunc(m))):0,text:c.length===1?c:"",repeat:a==="keydown"&&t.repeat===!0,pressedCodes:[...i],...yp(i)}}function gk(){const t=new Set,a=new Set,i=()=>({pressedCodes:[...t]});return{event(l={},c=""){if(c!=="keydown"&&c!=="keyup")return null;const u=vp(l);if(!u)return null;const m=Rf(u),h=t.has(u),g=[...t];return m?(c==="keydown"?t.size<pp&&t.add(u):a.has(u)||t.delete(u),Jy(t,a,l)):(Jy(t,a,l),c==="keydown"?t.size<pp&&t.add(u):t.delete(u)),c==="keyup"&&m==="metaKey"&&!Dl(t,"metaKey")&&eb(t),c==="keydown"&&h&&l.repeat!==!0&&mk(g,t)?null:pk(l,c,t)},modifier(l,c){const u=gp(l),m=Rf(u);if(!m)return null;const h=a.has(u);return c===h?null:(c?(a.add(u),t.add(u)):(a.delete(u),t.delete(u),m==="metaKey"&&!Dl(t,"metaKey")&&eb(t)),{type:c?"keydown":"keyup",key:m==="metaKey"?"Meta":m==="ctrlKey"?"Control":m==="altKey"?"Alt":"Shift",code:u,keyCode:0,location:u.endsWith("Right")?2:1,text:"",repeat:!1,...i(),...yp(t)})},reset(l="keyboard-owner-reset",c=!1){const u=t.size>0;return t.clear(),a.clear(),!u&&!c?null:{type:"keyboard.reset",reason:Qf(l,120)||"keyboard-owner-reset",pressedCodes:[],shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1,repeat:!1}},isPressed(l={}){const c=typeof l=="string"?gp(l):vp(l);if(t.has(c))return!0;const u=Rf(c);return!!u&&Dl(t,u)},snapshot(){return{...i(),latchedCodes:[...a],...yp(t)}}}}const tw=64,vk=2;function nw(t){const a=Math.floor(Number(t));return Number.isFinite(a)?Math.max(1,Math.min(tw,a)):1}function Fp(t){const a=Math.floor(Number(t));return Number.isFinite(a)?Math.max(0,Math.min(tw-1,a)):0}function aw(t){const a=String(t||"").trim().toLowerCase();return a==="macos"||a==="darwin"||a==="mac"||a==="macosx"||a==="linux"||a.startsWith("linux ")}function yk(t,a,i){const l=String(a||"").trim();if(!l)return t||null;const c=String(i||"").trim();return t&&t.fingerprint===l&&(c?t.sampleId===c:t.sampleId==="")?t:{fingerprint:l,sampleId:c,consecutiveSamples:t?.fingerprint===l?t.consecutiveSamples+1:1}}function sw({platform:t,topologyFingerprint:a,consecutiveTopologySamples:i}){return aw(t)?!!String(a||"").trim()&&Number(i)>=vk:!0}function bk({requestedIndex:t,monitorCount:a,platform:i,topologyFingerprint:l,consecutiveTopologySamples:c}){const u=Fp(t),m=nw(a);return u<m||!sw({platform:i,topologyFingerprint:l,consecutiveTopologySamples:c})?u:m-1}function xk(t,a,i){const l=Fp(t),c=nw(a);return l<c||aw(i)?l:c-1}function Tc(t){const a=Number(t);return Number.isSafeInteger(a)&&a>0?a:0}function ta(t){return String(t||"").trim()}function cf(t,a,i={}){return{deviceId:ta(t),transitionGeneration:Tc(a),sessionId:ta(i.sessionId),streamId:ta(i.streamId),commandId:ta(i.commandId),captureGeneration:Tc(i.captureGeneration),monitorIndex:Math.max(0,Math.floor(Number(i.monitorIndex)||0))}}function vs(t,a){return!!t&&!!a&&ta(t.deviceId)===ta(a.deviceId)&&Tc(t.transitionGeneration)===Tc(a.transitionGeneration)}function tb(t,a){const i=Promise.resolve(t).catch(()=>{}).then(a);return{result:i,tail:i.then(()=>{},()=>{})}}function uf(t,a,i){const l=ta(t);return!l||!a||ta(a.deviceId)!==l?!1:!i||ta(i.deviceId)!==l}function nb(t,a){if(!t||!a)return!1;const i=Tc(a.captureGeneration),l=ta(a.commandId),c=ta(a.sessionId),u=ta(a.streamId),m=Number(t.monitorIndex);return!i||!l||!c||!u||!Number.isInteger(m)||m<0?!1:ta(t.deviceId)===ta(a.deviceId)&&ta(t.sessionId)===c&&ta(t.streamId)===u&&ta(t.commandId)===l&&Tc(t.captureGeneration)===i&&ta(t.streamPurpose).toLowerCase()==="control"&&m===a.monitorIndex}const xs=Object.freeze({automaticDirectH264:!0,interactiveDirectFps:30,directFullFpsDeviceLimit:6,directMinAdaptiveFps:8,controlWallReuseMaxFps:30,scalableAtlasMinInputFps:8,scalableAtlasMaxInputFps:20,scalableAtlasAggregateInputFps:120,atlasOutputFps:20,maxDirectFramesPerSecond:180,directDecodeAcceleration:"prefer-hardware",directLatencyMode:"interactive"});function wk(t,a){const i=Math.max(0,Math.floor(Number(a)||0));return t===!0&&i>0}function Lu({mode4Enabled:t,directMode4WallEnabled:a,isMac:i}){return"direct"}function Sk({mode4Enabled:t,directMode4WallEnabled:a,adaptiveFps:i,directDeviceCount:l,adaptive:c=!0}){const u=Math.max(1,Math.floor(Number(i)||1));if(!c)return u;const m=Math.max(1,Math.floor(Number(l)||1));return m<=xs.directFullFpsDeviceLimit?u:Math.max(xs.directMinAdaptiveFps,Math.min(u,Math.floor(xs.maxDirectFramesPerSecond/m)))}function Ck({deviceCount:t,targetFps:a,adaptive:i=!0}){const l=Math.max(1,Math.floor(Number(t)||1)),c=Math.max(1,Math.min(xs.scalableAtlasMaxInputFps,Math.floor(Number(a)||xs.scalableAtlasMaxInputFps)));if(!i)return c;const u=Math.max(xs.scalableAtlasMinInputFps,Math.min(xs.scalableAtlasMaxInputFps,Math.floor(xs.scalableAtlasAggregateInputFps/l)));return Math.min(c,u)}function kk(t,a){return{acceleration:xs.directDecodeAcceleration,latencyMode:xs.directLatencyMode}}const xo={revision:0,settings:{security:{accessMode:"trusted-only"},control:{allowKeyboardMouse:!0},filesAudio:{allowFileTransfer:!0,allowRemoteAudio:!0,rollingBufferEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0}}},jk=[{id:"connection",label:"Connection",icon:Vf},{id:"remote-access",label:"Remote Access",icon:Kn},{id:"capture-audio",label:"Capture & Audio",icon:tp},{id:"agent",label:"Agent",icon:Il}];function Ef(t,a){return t?.settings?.[a]||xo.settings[a]||{}}function ab(t,a){return{...t,settings:{...t.settings,[a.section]:{...Ef(t,a.section),[a.key]:a.value}}}}function Lh(t){return{revision:Number(t.revision||0),updatedAt:t.updatedAt,settings:t.settings}}function yc({icon:t,title:a,description:i,children:l,recommended:c=!1}){return r.jsxs("div",{className:"product-setting-row",children:[r.jsx("div",{className:"product-setting-control",children:l}),t&&r.jsx("span",{className:"product-setting-icon",children:r.jsx(t,{size:17})}),r.jsxs("div",{className:"product-setting-copy",children:[r.jsx("strong",{children:a}),c&&r.jsx("em",{children:"Recommended"}),r.jsx("small",{children:i})]})]})}function df({checked:t,onChange:a,label:i}){return r.jsxs("label",{className:"product-switch",children:[r.jsx("input",{"aria-label":i,type:"checkbox",checked:t,onChange:l=>a(l.target.checked)}),r.jsx("span",{})]})}function sb({value:t,onChange:a,options:i,label:l}){return r.jsx("select",{"aria-label":l,value:String(t),onChange:c=>a(c.target.value),children:i.map(([c,u])=>r.jsx("option",{value:c,children:u},c))})}function Ak({hubUrl:t="",runtimeRole:a="hub",runtimeDeviceId:i="",sessionAccessToken:l="",initialTab:c="connection",pin:u,agent:m,captureGallery:h}){const[g,y]=d.useState(c),[x,b]=d.useState(null),[w,j]=d.useState("loading"),[A,k]=d.useState(""),[T,M]=d.useState("idle"),[N,L]=d.useState(""),z=d.useRef(null),H=d.useRef(null),G=d.useRef([]),_=d.useRef(Promise.resolve()),Y=d.useRef(0),q=d.useRef(0);d.useEffect(()=>{const le=++q.current;let Q=!0;return G.current=[],H.current=null,z.current=null,_.current=Promise.resolve(),j("loading"),We("/api/settings",void 0,t).then(be=>{if(!Q||le!==q.current)return;const he=Lh(be);H.current=he,z.current=he,b(he),j("saved")}).catch(be=>{!Q||le!==q.current||(k(be instanceof Error?be.message:String(be)),H.current=xo,z.current=xo,b(xo),j("failed"))}),()=>{Q=!1}},[t]);const U=async(le,Q,be)=>{const he={id:++Y.current,section:le,key:Q,value:be},de=q.current;G.current.push(he);const ee=ab(z.current||H.current||xo,he);z.current=ee,b(ee),j("saving"),k(""),_.current=_.current.then(async()=>{if(de!==q.current)return;let Ce=null,Re=null;for(let Ue=0;Ue<2&&!Ce;Ue+=1){const mt=H.current||xo;try{const ne=await We("/api/settings",{method:"PATCH",body:JSON.stringify({revision:mt.revision,[he.section]:{[he.key]:he.value}})},t);Ce=Lh(ne)}catch(ne){if(Re=ne,Ue!==0||!String(ne instanceof Error?ne.message:ne).startsWith("409 "))break;try{const xe=await We("/api/settings",void 0,t);if(de!==q.current)return;H.current=Lh(xe)}catch(xe){Re=xe;break}}}if(de!==q.current)return;G.current=G.current.filter(Ue=>Ue.id!==he.id),Ce&&(H.current=Ce);const He=H.current||xo,te=G.current.reduce(ab,He);z.current=te,b(te),Ce?(k(""),j(G.current.length>0?"saving":"saved")):(j(G.current.length>0?"saving":"failed"),k(Re instanceof Error?Re.message:String(Re||"Settings could not be saved.")))}),await _.current},K=(le,Q)=>be=>{U(le,Q,be)},O=async()=>{if(a!=="hub"||!i||!l){M("failed"),L("Sign in to this Hub before changing its runtime role.");return}M("changing"),L("");try{const le=await We("/api/runtime/status",void 0,t);await We("/api/runtime/role",{method:"POST",headers:{Authorization:`Bearer ${l}`},body:JSON.stringify({role:"client"})},t),M("accepted"),await Rx({baseUrl:t,targetRole:"client",previousRuntimePid:Number(le.runtimePid||0),allowedStates:["running","waiting-auth"]}),VC(5179)}catch(le){M("failed"),L(le instanceof Error?le.message:String(le))}},ve=Ef(x,"security"),me=Ef(x,"control"),Z=Ef(x,"filesAudio"),I=`settings-panel-${g}`,se=r.jsxs("div",{className:"settings-tab-content product-settings-content",children:[u,r.jsxs("section",{className:"settings-section-card runtime-role-settings",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Runtime role"}),r.jsx("h3",{children:"Use this computer as a Client"})]}),r.jsx(wx,{size:20})]}),r.jsx("p",{className:"settings-help",children:"Stop hosting from this computer and reconnect it to the selected Hub."}),T==="accepted"?r.jsx("p",{className:"settings-help runtime-role-success",children:"LiveDesk is restarting as Client."}):N?r.jsx("p",{className:"settings-help runtime-role-error",role:"alert",children:N}):null,r.jsx("button",{className:"settings-reset",onClick:()=>{O()},disabled:T==="changing"||a!=="hub",type:"button",children:T==="changing"?"Switching role...":"Switch this computer to Client"})]})]}),W=r.jsxs("div",{className:"settings-tab-content product-settings-content",children:[r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Remote access"}),r.jsx("h3",{children:"Who may connect?"})]}),r.jsx(Di,{size:20})]}),r.jsx(yc,{icon:Kn,title:"Access mode",description:"Choose the default permission boundary for remote sessions.",recommended:!0,children:r.jsx(sb,{value:String(ve.accessMode),onChange:K("security","accessMode"),label:"Access mode",options:[["trusted-only","Trusted devices only"],["block-remote-access","Block remote access"]]})})]}),r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Session permissions"}),r.jsx("h3",{children:"What may remote users do?"})]}),r.jsx(Ea,{size:20})]}),r.jsx(yc,{icon:Ea,title:"Keyboard and mouse control",description:"Allow Control to send keyboard and pointer input.",recommended:!0,children:r.jsx(df,{checked:!!me.allowKeyboardMouse,onChange:K("control","allowKeyboardMouse"),label:"Keyboard and mouse control"})}),r.jsx(yc,{icon:tp,title:"File transfer",description:"Allow files to be delivered to connected computers.",children:r.jsx(df,{checked:!!Z.allowFileTransfer,onChange:K("filesAudio","allowFileTransfer"),label:"File transfer"})}),r.jsx(yc,{icon:Ao,title:"Remote audio",description:"Allow sound capture from connected computers.",children:r.jsx(df,{checked:!!Z.allowRemoteAudio,onChange:K("filesAudio","allowRemoteAudio"),label:"Remote audio"})})]})]}),F=r.jsxs("div",{className:"settings-tab-content product-settings-content",children:[r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Capture"}),r.jsx("h3",{children:"Recording defaults"})]}),r.jsx(tp,{size:20})]}),r.jsx(yc,{icon:Ao,title:"Keep a Last 30s buffer",description:"Keep recent video in memory until you explicitly save it.",children:r.jsx(df,{checked:!!Z.rollingBufferEnabled,onChange:K("filesAudio","rollingBufferEnabled"),label:"Keep a Last 30s buffer"})}),r.jsx(yc,{icon:Ao,title:"Timelapse interval",description:"Choose how often a timelapse frame is captured.",children:r.jsx(sb,{value:Number(Z.timelapseIntervalSeconds),onChange:le=>K("filesAudio","timelapseIntervalSeconds")(Number(le)),label:"Timelapse interval",options:[["5","5 seconds"],["10","10 seconds"],["30","30 seconds"],["60","60 seconds"]]})})]}),h]}),oe=g==="connection"?se:g==="remote-access"?W:g==="capture-audio"?F:m;return r.jsxs("section",{className:"settings-page",children:[r.jsx("div",{className:"settings-page-tabs",role:"tablist","aria-label":"LiveDesk settings",children:jk.map(({id:le,label:Q,icon:be})=>r.jsxs("button",{className:g===le?"active":"",id:`settings-tab-${le}`,role:"tab","aria-selected":g===le,"aria-controls":`settings-panel-${le}`,tabIndex:g===le?0:-1,onClick:()=>y(le),type:"button",children:[r.jsx(be,{size:16}),Q]},le))}),w==="saving"&&r.jsx("div",{className:"product-save-state",role:"status",children:"Saving settings..."}),A&&r.jsx("div",{className:"agent-settings-alert error",role:"alert",children:A}),r.jsx("section",{className:"settings-page-panel",id:I,role:"tabpanel","aria-labelledby":`settings-tab-${g}`,tabIndex:0,children:oe})]})}function Mk({children:t}){return r.jsx("div",{className:"settings-tab-content",children:t})}const bp={enabled:!1,provider:"codex",codexModelId:"",codexReasoningEffort:"medium",codexTaskTimeoutMs:6e5,codexMaxToolCalls:20,codexWorkingDirectory:"",codexResumeSessions:!0,codexShowDetailedEvents:!0,deterministicParserFirst:!0,generateSummary:!0,fallbackSummary:!0,includeRawDeviceDetails:!1,baseUrl:"https://opencode.ai/zen/go/v1",defaultModelId:"deepseek-v4-flash"};function rb(t){return{...bp,...t||{}}}async function Nk(t,a,i){let l=null;for(let c=0;c<2;c+=1){const u=await We("/api/settings",{signal:i},a);if(u.settings.agent?.enabled===t)return;try{await We("/api/settings",{method:"PATCH",signal:i,body:JSON.stringify({revision:u.revision,agent:{enabled:t}})},a);return}catch(m){if(l=m,c!==0||!String(m instanceof Error?m.message:m).startsWith("409 "))throw m}}throw l}function Tk({hubUrl:t}){const[a,i]=d.useState(bp),[l,c]=d.useState(null),[u,m]=d.useState(""),[h,g]=d.useState(""),[y,x]=d.useState(""),[b,w]=d.useState(""),j=d.useRef(0),A=d.useRef(null);d.useEffect(()=>{let q=!0;A.current?.abort();const U=new AbortController;A.current=U;const K=++j.current;return c(null),i(bp),m(""),g(""),w(""),x(""),We("/api/settings/agent",{signal:U.signal},t).then(O=>{!q||U.signal.aborted||K!==j.current||(c(O.settings),i(rb(O.settings)))}).catch(O=>{q&&!U.signal.aborted&&K===j.current&&w(O instanceof Error?O.message:String(O))}),()=>{q=!1,U.abort(),A.current===U&&(A.current=null)}},[t]);const k=(q,U)=>i(K=>({...K,[q]:U})),T=q=>{c(q),i(rb(q))},M=()=>({generation:j.current,controller:A.current}),N=q=>q.generation===j.current&&q.controller!==null&&q.controller===A.current&&!q.controller.signal.aborted,L=async()=>{if(!l){w("Agent settings are not available yet.");return}const q=M();if(N(q)){g("save"),w(""),x("");try{if(await Nk(a.enabled,t,q.controller.signal),!N(q))return;const{enabled:U,...K}=a,O={...K};u.trim()&&(O.apiKey=u.trim());const ve=await We("/api/settings/agent",{method:"PUT",signal:q.controller.signal,body:JSON.stringify(O)},t);if(!N(q))return;T(ve.settings),m(""),x("Agent settings saved.")}catch(U){N(q)&&w(U instanceof Error?U.message:String(U))}finally{N(q)&&g("")}}},z=async()=>{const q=M();if(N(q)){g("reset"),w("");try{const U=await We("/api/settings/agent/reset",{method:"POST",signal:q.controller.signal,body:JSON.stringify({})},t);if(!N(q))return;T(U.settings),x("Codex defaults restored.")}catch(U){N(q)&&w(U instanceof Error?U.message:String(U))}finally{N(q)&&g("")}}},H=async()=>{const q=M();if(N(q)){g("test"),w(""),x("");try{const U=await We("/api/settings/agent/test",{method:"POST",signal:q.controller.signal,body:JSON.stringify({})},t);if(!N(q))return;const K=await We("/api/settings/agent",{signal:q.controller.signal},t);if(!N(q))return;T(K.settings),x(`Codex connection verified with ${U.connection?.modelName||"the configured model"}${U.connection?.latencyMs?` in ${U.connection.latencyMs} ms.`:"."}`)}catch(U){N(q)&&w(U instanceof Error?U.message:String(U))}finally{N(q)&&g("")}}},G=async()=>{const q=M();if(N(q)){g("clear-key"),w("");try{const U=await We("/api/settings/agent/api-key",{method:"DELETE",signal:q.controller.signal},t);if(!N(q))return;T(U.settings),m(""),x("The optional OpenCode Go key was removed.")}catch(U){N(q)&&w(U instanceof Error?U.message:String(U))}finally{N(q)&&g("")}}},_=l?.codexInstallation==="installed"&&l.codexAuth==="signed-in",Y=l!==null;return r.jsxs("div",{className:"settings-tab-content agent-settings-content",children:[r.jsx("section",{className:"settings-section-card agent-enable-card",children:r.jsxs("label",{className:"settings-toggle agent-enable-toggle",children:[r.jsx("input",{type:"checkbox",checked:a.enabled,onChange:q=>k("enabled",q.target.checked),disabled:!Y||h!==""}),r.jsx("span",{children:"Enable Agent AI"})]})}),b&&r.jsx("div",{className:"agent-settings-alert error",role:"alert",children:b}),y&&r.jsx("div",{className:"agent-settings-alert success",role:"status",children:y}),r.jsxs("div",{className:"settings-section-grid",children:[r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Provider"}),r.jsx("h3",{children:"Choose the AI service"})]}),r.jsx(Kn,{size:20})]}),r.jsxs("label",{className:"settings-field",children:[r.jsx("span",{children:"Agent provider"}),r.jsxs("select",{value:a.provider,onChange:q=>k("provider",q.target.value),children:[r.jsx("option",{value:"codex",children:"Codex SDK"}),r.jsx("option",{value:"opencode-go",children:"OpenCode Go"})]})]}),a.provider==="codex"&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"agent-connection-row",children:[r.jsx("span",{className:`agent-connection-dot ${_?"connected":l?.codexAuth==="not-signed-in"?"unavailable":""}`}),r.jsx("span",{children:l?.codexInstallation==="not-installed"?"Codex SDK not installed":l?.codexAuth==="signed-in"?"Codex CLI signed in":l?.codexAuth==="not-signed-in"?"Codex CLI sign-in required":"Codex status not tested"}),r.jsxs("button",{className:"settings-reset",onClick:()=>{H()},disabled:h!=="",type:"button",children:[r.jsx(M0,{size:15})," ",h==="test"?"Testing":"Test connection"]})]}),r.jsxs("p",{className:"settings-help",children:[r.jsx(N0,{size:12})," Authentication uses the installed Codex CLI."]})]})]}),a.provider==="codex"?r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Codex"}),r.jsx("h3",{children:"Model and reasoning"})]}),r.jsx(T0,{size:20})]}),r.jsxs("label",{className:"settings-field",children:[r.jsx("span",{children:"Model"}),r.jsx("input",{value:a.codexModelId,onChange:q=>k("codexModelId",q.target.value),placeholder:"Codex default"})]}),r.jsxs("label",{className:"settings-field",children:[r.jsx("span",{children:"Reasoning effort"}),r.jsxs("select",{value:a.codexReasoningEffort,onChange:q=>k("codexReasoningEffort",q.target.value),children:[r.jsx("option",{value:"minimal",children:"Minimal"}),r.jsx("option",{value:"low",children:"Low"}),r.jsx("option",{value:"medium",children:"Medium"}),r.jsx("option",{value:"high",children:"High"}),r.jsx("option",{value:"xhigh",children:"Extra high"})]})]})]}):r.jsxs("section",{className:"settings-section-card agent-legacy-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"OpenCode Go"}),r.jsx("h3",{children:"Connection"})]}),r.jsx(xx,{size:20})]}),r.jsxs("label",{className:"settings-field",children:[r.jsx("span",{children:"Base URL"}),r.jsx("input",{value:a.baseUrl,onChange:q=>k("baseUrl",q.target.value)})]}),r.jsxs("label",{className:"settings-field",children:[r.jsx("span",{children:"API key"}),r.jsx("input",{type:"password",value:u,onChange:q=>m(q.target.value),placeholder:l?.hasApiKey?l.apiKeyPreview:"Stored only in the Hub",autoComplete:"new-password"})]}),r.jsxs("button",{className:"settings-reset",onClick:()=>{G()},disabled:h!==""||!l?.hasApiKey,type:"button",children:[r.jsx(Rp,{size:15})," Clear key"]})]})]}),r.jsxs("div",{className:"settings-action-row agent-settings-actions",children:[r.jsxs("button",{className:"settings-reset",onClick:()=>{z()},disabled:h!=="",type:"button",children:[r.jsx(Ep,{size:15})," Reset defaults"]}),r.jsxs("button",{className:"text-button primary",onClick:()=>{L()},disabled:!Y||h!=="",type:"button",children:[r.jsx(R0,{size:15})," ",h==="save"?"Saving":"Save Agent settings"]})]})]})}new Date().valueOf();function Fr(t){const[a,i]=d.useState(t),l=d.useRef(t);return d.useEffect(()=>{if(l.current!==t){if(Array.isArray(l.current)&&Array.isArray(t)&&l.current.length===0&&t.length===0)return;l.current=t,i(t)}},[t]),[a,i]}function Pp(t,a){return typeof t=="function"?typeof a=="object"?t(a):t():t}function Rc(t,a="data-id"){let i=t;for(!i.tagName&&t.target&&(i=t.target);i;){if(i.getAttribute&&i.getAttribute(a))return i;i=i.parentNode}return null}function Rk(t,a="data-id"){const i=Rc(t,a);return i?i.getAttribute(a):null}function Zu(t,a="data-id"){const i=Rc(t,a);return i?Xf(i,a):null}function Xf(t,a="data-id"){const i=t.getAttribute(a);return i?Ek(i):null}function na(t){return typeof t=="string"?":"+t:t}function Ek(t){if(t.startsWith(":"))return t.substring(1);const a=t*1;return isNaN(a)?t:a}function Dk(){return{detect:()=>!0,addEvent:function(t,a,i){return t.addEventListener(a,i),()=>t.removeEventListener(a,i)},addGlobalEvent:function(t,a){return document.addEventListener(t,a),()=>document.removeEventListener(t,a)},getTopNode:function(){return window.document.body}}}var is=Dk();function $p(t){Object.assign(is,t)}function ib(t,a,i){function l(c){const u=Rc(c);if(!u)return;const m=Xf(u);if(typeof a=="function")return a(m,c);let h,g=c.target;for(;g!=u;){if(h=g.dataset?g.dataset.action:null,h&&a[h]){a[h](m,c);return}g=g.parentNode}a[i]&&a[i](m,c)}is.addEvent(t,i,l)}function Ec(t,a){ib(t,a,"click"),a.dblclick&&ib(t,a.dblclick,"dblclick")}function Lk(t,a){for(let i=t.length-1;i>=0;i--)if(t[i]===a){t.splice(i,1);break}}function _k(t,a,i){for(let l=0;l<Li.length;l++){if(l===i)continue;const c=Li[l],u=c.props.parent?.();if(u&&t.contains(u)&&c.node.contains(a))return!0}return!1}var rw=new Date,$f=!1,ff=[],Li=[],lb=t=>{const a=t.target;if($f||!a.isConnected){$f=!1;return}for(let i=Li.length-1;i>=0;i--){const{node:l,date:c,props:u}=Li[i];if(!(c>rw)&&!l.contains(a)&&l!==a&&(_k(l,a,i)||(u.callback&&u.callback(t),u.modal||t.defaultPrevented)))break}},Ik=t=>{rw=new Date,$f=!0;for(let a=Li.length-1;a>=0;a--){const{node:i}=Li[a];if(!i.contains(t.target)&&i!==t.target){$f=!1;break}}};function Pr(t,a){ff.length||(ff=[is.addGlobalEvent("click",lb,t),is.addGlobalEvent("contextmenu",lb,t),is.addGlobalEvent("mousedown",Ik,t)]),typeof a!="object"&&(a={callback:a});const i={node:t,date:new Date,props:a};return Li.push(i),{destroy(){Lk(Li,i),Li.length||(ff.forEach(l=>l()),ff=[])}}}var mf=t=>t.indexOf("bottom")!==-1,hf=t=>t.indexOf("left")!==-1,pf=t=>t.indexOf("right")!==-1,_h=t=>t.indexOf("top")!==-1,ob=t=>t.indexOf("fit")!==-1,_u=t=>t.indexOf("overlap")!==-1,zk=t=>t.split("-").every(a=>["center","fit"].indexOf(a)>-1),Ok=t=>{const a=t.match(/(start|center|end)/);return a?a[0]:null};function Hk(t,a){let i=0;const l=is.getTopNode(t);for(;t&&t!==l;){const c=getComputedStyle(t).position;if((c==="absolute"||c==="relative"||c==="fixed")&&(i=parseInt(getComputedStyle(t).zIndex)||0),t=t.parentNode,t===a)break}return i}var Fn,ja,Iu,ga;function iw(t,a,i="bottom",l=0,c=0){if(!t)return null;Fn=l,ja=c,Iu="auto";let u=0,m=0,h=i;const g=lw(t),y=_u(i)?is.getTopNode(t):g;if(!g)return null;const x=g.getBoundingClientRect(),b=t.getBoundingClientRect(),w=y.getBoundingClientRect(),j=window.getComputedStyle(y),A={left:0,top:0,bottom:0,right:0};for(const z in A){const H=`border-${z}-width`;A[z]=parseFloat(j.getPropertyValue(H))}if(a){const z=Hk(a,g);u=Math.max(z+1,20)}if(a){if(ga=a.getBoundingClientRect(),ob(i)&&(Iu=ga.width+"px"),i!=="point")if(zk(i))ob(i)?Fn=0:(Fn=w.width/2,m=1),ja=(w.height-b.height)/2;else{const z=_u(i)?0:1;Fn=pf(i)?ga.right+z:ga.left-z,ja=mf(i)?ga.bottom+1:ga.top;const H=Ok(i);H&&(pf(i)||hf(i)?H==="center"?ja-=(b.height-ga.height)/2:H==="end"&&(ja-=b.height-ga.height):(mf(i)||_h(i))&&(H==="center"?Fn-=(b.width-ga.width)/2:H==="end"&&(Fn-=b.width-ga.width),_u(i)||(Fn+=1)))}}else ga={left:l,right:l,top:c,bottom:c};const k=(hf(i)||pf(i))&&(mf(i)||_h(i));hf(i)&&(m=2);const T=Fn-b.width-w.left;a&&hf(i)&&!k&&T<0&&(Fn=ga.right,m=0,h=h.replace("left","right"));const M=Fn+b.width*(1-m/2)-w.right;if(M>0)if(!pf(i))Fn=w.right-A.right-b.width;else{const z=ga.left-w.x-b.width;a&&!k&&z>=0?(Fn=ga.left-b.width,h=h.replace("right","left")):Fn-=M+A.right}m&&(Fn=Math.round(Fn-b.width*m/2));const N=T<0||M>0||!k;_h(i)&&(ja=ga.top-b.height,a&&ja<w.y&&N&&(ja=ga.bottom,h=h.replace("top","bottom")));const L=ja+b.height-w.bottom;return L>0&&(a&&mf(i)&&N?(ja-=b.height+ga.height+1,h=h.replace("bottom","top")):ja-=L+A.bottom),Fn-=x.left+A.left,ja-=x.top+A.top,Fn=(_u(i)?Fn:Math.max(Fn,0))+y.scrollLeft,ja=(_u(i)?ja:Math.max(ja,0))+y.scrollTop,Iu=Iu||"auto",{at:h,x:Fn,y:ja,z:u,width:Iu}}function lw(t){const a=is.getTopNode(t);for(t&&(t=t.parentElement);t;){const i=getComputedStyle(t).position;if(t===a||i==="relative"||i==="absolute"||i==="fixed")return t;t=t.parentNode}return null}function Fk(t){const a=[];let i=t;const l=is.getTopNode(t);for(;i&&i!==l&&!i.getAttribute("data-wx-portal-root");)getComputedStyle(i).position==="absolute"&&a.push(i),i=i.parentNode;return a}var cb=new Date().valueOf();function Bp(){return cb+=1,cb}function Ma(t){return t<10?"0"+t:t.toString()}function Pk(t){const a=Ma(t);return a.length==2?"0"+a:a}function ow(t){const a=Math.floor(t/11)*11;return{start:a,end:a+11}}function Ih(t){const a=(t.getDay()+6)%7,i=new Date(t.valueOf());i.setDate(t.getDate()+(3-a)),i.setHours(0,0,0,0);const l=new Date(i.getFullYear(),0,1),c=Math.round((i.getTime()-l.getTime())/864e5);return 1+Math.floor(c/7)}var ub=["",""];function $k(t,a,i){switch(t){case"%d":return Ma(a.getDate());case"%m":return Ma(a.getMonth()+1);case"%j":return a.getDate();case"%n":return a.getMonth()+1;case"%y":return Ma(a.getFullYear()%100);case"%Y":return a.getFullYear();case"%D":return i.dayShort[a.getDay()];case"%l":return i.dayFull[a.getDay()];case"%M":return i.monthShort[a.getMonth()];case"%F":return i.monthFull[a.getMonth()];case"%h":return Ma((a.getHours()+11)%12+1);case"%g":return(a.getHours()+11)%12+1;case"%G":return a.getHours();case"%H":return Ma(a.getHours());case"%i":return Ma(a.getMinutes());case"%a":return((a.getHours()>11?i.pm:i.am)||ub)[0];case"%A":return((a.getHours()>11?i.pm:i.am)||ub)[1];case"%s":return Ma(a.getSeconds());case"%S":return Pk(a.getMilliseconds());case"%W":return Ma(Ih(a));case"%w":{const l=i.weekStart??1;if(l===1)return Ma(Ih(a));const c=(a.getDay()-l+7)%7,u=(1-l+7)%7,m=new Date(a.valueOf());return m.setDate(a.getDate()+(u-c)),Ma(Ih(m))}case"%c":{let l=a.getFullYear()+"";return l+="-"+Ma(a.getMonth()+1),l+="-"+Ma(a.getDate()),l+="T",l+=Ma(a.getHours()),l+=":"+Ma(a.getMinutes()),l+=":"+Ma(a.getSeconds()),l}case"%Q":return Math.floor(a.getMonth()/3)+1;default:return t}}var Bk=/%[a-zA-Z]/g;function kc(t,a){return typeof t=="function"?t:function(i){return i?(i.getMonth||(i=new Date(i)),t.replace(Bk,l=>$k(l,i,a))):""}}function db(t){return t&&typeof t=="object"&&!Array.isArray(t)}function xp(t,a){for(const i in a){const l=a[i];db(t[i])&&db(l)?t[i]=xp({...t[i]},a[i]):t[i]=a[i]}return t}function ed(t){return{getGroup(a){const i=t[a];return l=>i&&i[l]||l},getRaw(){return t},extend(a,i){if(!a)return this;let l;return i?l=xp({...a},t):l=xp({...t},a),ed(l)}}}var Uk=Mx();const qk="en-US",Gk={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},Vk={ok:"OK",cancel:"Cancel",select:"Select","No data":"No data","Rows per page":"Rows per page","Total pages":"Total pages"},Wk={timeFormat:"%H:%i",dateFormat:"%m/%d/%Y",monthYearFormat:"%F %Y",yearFormat:"%Y"},cw={core:Vk,calendar:Gk,formats:Wk,lang:qk},Up=d.createContext(""),uw=d.createContext({}),fr=d.createContext(null),dw=d.createContext(null),sa=Object.freeze(Object.defineProperty({__proto__:null,fieldId:dw,helpers:uw,i18n:fr,theme:Up},Symbol.toStringTag,{value:"Module"}));function fw(t){const a=d.useContext(dw),[i]=d.useState(()=>t||a||Bp());return i}function Gu({type:t="",css:a="",icon:i="",disabled:l=!1,title:c="",tooltip:u,text:m="",children:h,onClick:g}){const y=d.useMemo(()=>{let b=t?t.split(" ").filter(w=>w!=="").map(w=>"wx-"+w).join(" "):"";return a+(a?" ":"")+b},[t,a]),x=b=>{g&&g(b)};return r.jsxs("button",{title:c,className:`wx-2ZWgb4 wx-button ${y} ${i&&!h?"wx-icon":""}`,disabled:l,onClick:x,"data-tooltip-text":u,children:[i&&r.jsx("i",{className:"wx-2ZWgb4 "+i}),h||m||" "]})}function Kk({id:t,label:a="",inputValue:i="",value:l=!1,onChange:c,disabled:u=!1,css:m=""}){const h=fw(t),[g,y]=Fr(l),x=({target:b})=>{const w=b.checked;y(w),c&&c({value:w,inputValue:i})};return r.jsxs("div",{className:`wx-2IvefP wx-checkbox ${m}`,children:[r.jsx("input",{type:"checkbox",id:h,disabled:u,className:"wx-2IvefP wx-check",checked:g,value:i,onChange:x}),r.jsxs("label",{htmlFor:h,className:"wx-2IvefP wx-label",children:[r.jsx("span",{className:"wx-2IvefP wx-before"}),a&&r.jsx("span",{className:"wx-2IvefP wx-after",children:a})]})]})}function qp({theme:t="",target:a,children:i}){const l=d.useRef(null),c=d.useRef(null),[u,m]=d.useState(null);l.current||(l.current=document.createElement("div"));const h=d.useContext(Up);return d.useEffect(()=>{m(a||Yk(c.current)||is.getTopNode(c.current))},[c.current]),r.jsxs(r.Fragment,{children:[r.jsx("span",{ref:c,style:{display:"none"}}),c.current&&u?Uk.createPortal(r.jsx("div",{className:`wx-3ZWsT0 wx-${t||h}-theme`,children:i}),u):null]})}function Yk(t){const a=is.getTopNode(t);for(;t&&t!==a&&!t.getAttribute("data-wx-portal-root");)t=t.parentNode;return t}function Qk({left:t=0,top:a=0,at:i="bottom",parent:l=null,width:c="auto",css:u="",onCancel:m,children:h,trackScroll:g=!1}){const[y,x]=d.useState(0),[b,w]=d.useState(0),[j,A]=d.useState("auto"),[k,T]=d.useState(!1),M=d.useRef(null),N=d.useRef(null),L=d.useRef(m);d.useEffect(()=>{L.current=m},[m]);function z(G){return l&&(c+"").indexOf("%")>-1?c.replace(/(\d+)%/,(_,Y)=>(Y=Y*l.offsetWidth/100+"px",c.replace(_,Y))):c&&c!=="auto"?c:G}const H=d.useCallback(()=>{if(!M.current)return;const G=iw(M.current,l,i,t,a);G&&(x(G.x),w(G.y),A(z(G.width)))},[M,l,i,t,a,c]);return d.useLayoutEffect(()=>{const G=Y=>{L.current&&Y.target!==N.current&&M.current&&!M.current.contains(Y.target)&&L.current(Y)};let _;return requestAnimationFrame(()=>{H(),T(!0),g&&M.current&&(N.current=lw(M.current),N.current&&N.current.addEventListener("scroll",G,!0)),l&&(_=new ResizeObserver(H),_.observe(l))}),()=>{g&&N.current&&N.current.removeEventListener("scroll",G,!0),_?.disconnect()}},[]),d.useLayoutEffect(()=>{H()},[l,i,t,a]),d.useEffect(()=>{const G=_=>{L.current&&L.current(_)};if(M.current)return Pr(M.current,{callback:G,parent:()=>l}).destroy},[l]),r.jsx("div",{ref:M,className:["wx-37M6Fj","wx-popup",u].filter(Boolean).join(" "),style:{position:"absolute",visibility:k?"visible":"hidden",top:b+"px",left:y+"px",width:j},children:h})}function Xk({position:t="bottom",align:a="start",autoFit:i=!0,onCancel:l=null,width:c="100%",css:u="",children:m}){const h=d.useRef(null),[g,y]=d.useState(t),[x,b]=d.useState(a),w=d.useRef(l);return d.useEffect(()=>{w.current=l},[l]),d.useEffect(()=>{if(i){const j=h.current;if(j){const A=j.getBoundingClientRect(),k=document.body.getBoundingClientRect();A.right>=k.right&&b("end"),A.bottom>=k.bottom&&y("top")}}},[]),d.useEffect(()=>{if(h.current){const j=A=>{w.current&&w.current(A)};return Pr(h.current,j).destroy}},[]),r.jsx("div",{ref:h,className:["wx-dropdown",`wx-${g}-${x}`,u||"","wx-aaaVytZW"].filter(Boolean).join(" "),style:{width:c},children:m})}function Gp({position:t="bottom",align:a="start",autoFit:i=!0,inline:l=!1,onCancel:c,width:u="100%",children:m,...h}){const[g,y]=d.useState(void 0),x=d.useRef(null),b=d.useMemo(()=>`${t}-${a}`,[t,a]);return d.useLayoutEffect(()=>{x.current&&y(x.current.parentNode)},[]),r.jsxs(r.Fragment,{children:[g&&(l?r.jsx(Xk,{onCancel:c,position:t,align:a,autoFit:i,width:u,...h,children:m}):r.jsx(qp,{children:r.jsx(Qk,{parent:g,at:b,onCancel:c,width:u,...h,children:m})})),r.jsx("span",{ref:x,className:"wx-portal-node wx-32GZ52"})]})}function Zf(){return ed(cw)}function Zk(){let t=null,a=!1,i=!1,l,c,u,m;const h=(b,w,j,A,k)=>{l=b,c=w,u=j,m=A,i=k},g=b=>{t=b,a=t!==null,u(t)},y=(b,w)=>{if(!i&&b!==null&&l){const j=l.querySelectorAll(".wx-list > .wx-item")[b];j&&(j.scrollIntoView({block:"nearest"}),w&&w.preventDefault())}},x=(b,w)=>{const j=b===null?null:Math.max(0,Math.min(t+b,c.length-1));j!==t&&(g(j),l?y(j,w):requestAnimationFrame(()=>y(j,w)))};return{move:b=>{const w=Zu(b),j=c.findIndex(A=>A.id===w);j!==t&&g(j)},keydown:(b,w)=>{switch(b.code){case"Enter":a?m():g(0);break;case"Space":a||g(0);break;case"Escape":u(t=null);break;case"Tab":u(t=null);break;case"ArrowDown":x(a?1:w||0,b);break;case"ArrowUp":x(a?-1:w||0,b);break}},init:h,navigate:x}}const fb=10,Jk=d.memo(function({data:t,checkboxes:a,itemTemplate:i,value:l}){return r.jsxs(r.Fragment,{children:[a&&r.jsx(Kk,{id:t.id,css:"wx-list-checkbox",value:l&&l.includes(t.id)}),i?Pp(i,{option:t}):t.label]})});function mb({visibleItems:t,visibleRange:a,navIndex:i,checkboxes:l,itemTemplate:c,value:u,measureRefCallback:m}){return t.map((h,g)=>{const y=a.start+g;return r.jsx("div",{ref:g===0?m:void 0,className:`wx-233fr7 wx-item ${y===i?"wx-focus":""}`,"data-id":h.id,children:r.jsx(Jk,{data:h,checkboxes:l,itemTemplate:c,value:u})},h.id)})}function Jf({items:t=[],children:a,onSelect:i,onReady:l,virtualized:c=!1,checkboxes:u,multiselect:m,value:h,...g}){const y=d.useRef(),x=d.useRef(!1),b=d.useRef(Zk()),[w,j]=d.useState(null),A=d.useRef(w),[k,T]=d.useState(0),[M,N]=d.useState(24),L=d.useRef(!1),z=(d.useContext(fr)||Zf()).getGroup("core"),H=d.useRef(t);d.useEffect(()=>{H.current=t},[t]);const G=d.useRef(h);d.useEffect(()=>{G.current=h},[h]);const _=d.useRef(0);d.useEffect(()=>{_.current=M},[M]);const Y=d.useCallback(Q=>{Q&&Q.stopPropagation();const be=H.current,he=G.current,de=A.current;let ee;const Ce=be[de]?.id;m?he&&he.includes(Ce)?ee=he.filter(Re=>Re!==Ce):ee=[...he||[],Ce]:ee=Ce,i&&i({id:ee})},[m,i]),q=d.useRef(Y);d.useEffect(()=>{q.current=Y},[Y]);const U=d.useCallback(Q=>{if(y.current){let be=Q*_.current-y.current.clientHeight+_.current;T(be),y.current.scrollTop=be}},[_.current]),K=d.useCallback(Q=>{y.current=Q,c&&(Q&&!x.current&&A.current!==null&&requestAnimationFrame(()=>{y.current&&(U(A.current),x.current=!0)}),Q||(x.current=!1))},[U]),O=d.useCallback(Q=>{if(!Q||L.current)return;const be=Q.getBoundingClientRect().height;be&&(N(be),_.current=be,L.current=!0)},[]);d.useEffect(()=>{b.current.init(y.current,t,Q=>{j(Q),A.current=Q},Q=>q.current(Q),c)},[t,y.current,c]),d.useEffect(()=>{const Q=(he,de)=>{b.current.navigate(he,de),U(A.current)},be=(he,de)=>{const ee=A.current,Ce=H.current;if(ee!==0&&ee!==Ce.length-1&&(he.key==="ArrowDown"||he.key==="ArrowUp")&&he.preventDefault(),b.current.keydown(he,de),y.current){const Re=y.current.scrollTop<=A.current*_.current,He=y.current.scrollTop+y.current.clientHeight>=A.current*_.current+_.current;Re?He||U(A.current):(y.current.scrollTop=A.current*_.current,T(y.current.scrollTop))}};l&&l({navigate:c?Q:b.current.navigate,keydown:c?be:b.current.keydown,move:b.current.move})},[]);const ve=d.useRef(0),me=d.useRef(t);me.current!==t&&(me.current=t,ve.current+=1);const Z=d.useCallback(()=>{b.current.navigate(null)},[b]),I=d.useCallback(Q=>{c&&T(Q.target.scrollTop)},[c]),se=d.useMemo(()=>Math.ceil((y.current?.clientHeight||0)/M),[M,k]),W=d.useMemo(()=>{if(!c)return{start:0,end:t.length};if(!t.length)return{start:0,end:0};const Q=Math.floor(k/M),be=Q+se;return{start:Math.max(0,Q-fb),end:Math.min(t.length,be+fb)}},[c,t,k,M,se]),F=d.useMemo(()=>{if(!c)return t;const{start:Q,end:be}=W;return t.slice(Q,be).map(he=>({...he}))},[c,t,W]),oe=W.start*M,le=t.length*M;return d.useEffect(()=>{c&&T(0)},[t,c]),d.useEffect(()=>{w===null&&(x.current=!1)},[w]),w===null?null:r.jsx(Gp,{onCancel:Z,...g,children:r.jsx("div",{className:"wx-233fr7 wx-list",ref:K,onClick:Y,onMouseMove:b.current.move,onScroll:I,children:t.length?c?r.jsx("div",{className:"wx-233fr7 wx-list-wrapper",style:{height:`${le}px`},children:r.jsx("div",{className:"wx-233fr7 wx-list-content",style:{transform:`translateY(${oe}px)`},children:r.jsx(mb,{visibleRange:W,visibleItems:F,navIndex:w,measureRefCallback:O,checkboxes:u,itemTemplate:a,value:h})})}):r.jsx(mb,{visibleRange:W,visibleItems:F,navIndex:w,measureRefCallback:O,checkboxes:u,itemTemplate:a,value:h}):r.jsx("div",{className:"wx-233fr7 wx-no-data",children:z("No data")})})},ve.current)}function Vp({value:t="",id:a,readonly:i=!1,focus:l=!1,select:c=!1,type:u="text",placeholder:m="",disabled:h=!1,error:g=!1,title:y="",tooltip:x,css:b="",icon:w="",clear:j=!1,onChange:A}){const k=fw(a),[T,M]=Fr(t),N=d.useRef(null),L=d.useMemo(()=>w&&b.indexOf("wx-icon-left")===-1?"wx-icon-right "+b:b,[w,b]),z=d.useMemo(()=>w&&b.indexOf("wx-icon-left")!==-1,[w,b]);d.useEffect(()=>{const q=setTimeout(()=>{l&&N.current&&N.current.focus(),c&&N.current&&N.current.select()},1);return()=>clearTimeout(q)},[l,c]);const H=d.useCallback(q=>{const U=q.target.value;M(U),A&&A({value:U,input:!0})},[A]),G=d.useCallback(q=>A&&A({value:q.target.value}),[A]);function _(q){q.stopPropagation(),M(""),A&&A({value:""})}let Y=u;return u!=="password"&&u!=="number"&&(Y="text"),d.useEffect(()=>{const q=G,U=N.current;return U.addEventListener("change",q),()=>{U&&U.removeEventListener("change",q)}},[G]),r.jsxs("div",{className:`wx-hQ64J4 wx-text ${L} ${g?"wx-error":""} ${h?"wx-disabled":""} ${j?"wx-clear":""}`,"data-tooltip-text":x,children:[r.jsx("input",{className:"wx-hQ64J4 wx-input",ref:N,id:k,readOnly:i,disabled:h,placeholder:m,type:Y,title:y,value:T,onInput:H}),j&&!h&&T?r.jsxs(r.Fragment,{children:[r.jsx("i",{className:"wx-hQ64J4 wx-icon wxi-close",onClick:_}),z&&r.jsx("i",{className:`wx-hQ64J4 wx-icon ${w}`})]}):w?r.jsx("i",{className:`wx-hQ64J4 wx-icon ${w}`}):null]})}function ej({date:t,type:a,part:i,onShift:l}){const{calendar:c,formats:u}=d.useContext(fr).getRaw(),m=t.getFullYear(),h=d.useMemo(()=>{switch(a){case"month":return kc(u.monthYearFormat,c)(t);case"year":return kc(u.yearFormat,c)(t);case"duodecade":{const{start:y,end:x}=ow(m),b=kc(u.yearFormat,c);return`${b(new Date(y,0,1))} - ${b(new Date(x,11,31))}`}default:return""}},[t,a,m,c,u]);function g(){l&&l({diff:0,type:a})}return r.jsxs("div",{className:"wx-8HQVQV wx-header",children:[i!=="right"?r.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-left",onClick:()=>l&&l({diff:-1,type:a})}):r.jsx("span",{className:"wx-8HQVQV wx-spacer"}),r.jsx("span",{className:"wx-8HQVQV wx-label",onClick:g,children:h}),i!=="left"?r.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-right",onClick:()=>l&&l({diff:1,type:a})}):r.jsx("span",{className:"wx-8HQVQV wx-spacer"})]})}function Wp({onClick:t,children:a}){return r.jsx("button",{className:"wx-3s8W4d wx-button",onClick:t,children:a})}function tj({value:t,current:a,part:i="",markers:l=null,css:c="",onCancel:u,onChange:m}){const h=(d.useContext(fr)||Zf()).getRaw().calendar,g=(h.weekStart||7)%7,y=h.dayShort.slice(g).concat(h.dayShort.slice(0,g)),x=(H,G,_)=>new Date(H.getFullYear(),H.getMonth()+(G||0),H.getDate()+(_||0));let b=i!=="normal";function w(H){const G=H.getDay();return G===0||G===6}function j(){const H=x(a,0,1-a.getDate());return H.setDate(H.getDate()-(H.getDay()-(g-7))%7),H}function A(){const H=x(a,1,-a.getDate());return H.setDate(H.getDate()+(6-H.getDay()+g)%7),H}const k=d.useRef(0);function T(H,G){G.timeStamp!==k.current&&(k.current=G.timeStamp,G.stopPropagation(),m&&m(new Date(H)),u&&u())}const M=d.useMemo(()=>i=="normal"?[t?x(t).valueOf():0]:t?[t.start?x(t.start).valueOf():0,t.end?x(t.end).valueOf():0]:[0,0],[i,t]),N=d.useMemo(()=>{const H=j(),G=A(),_=a.getMonth();let Y=[];for(let q=H;q<=G;q.setDate(q.getDate()+1)){const U={day:q.getDate(),in:q.getMonth()===_,date:q.valueOf()};let K="";if(K+=U.in?"":" wx-inactive",K+=M.indexOf(U.date)>-1?" wx-selected":"",b){const O=U.date==M[0],ve=U.date==M[1];O&&!ve?K+=" wx-left":ve&&!O&&(K+=" wx-right"),U.date>M[0]&&U.date<M[1]&&(K+=" wx-inrange")}if(K+=w(q)?" wx-weekend":"",l){const O=l(q);O&&(K+=" "+O)}Y.push({...U,css:K})}return Y},[a,M,b,l]),L=d.useRef(null);let z=d.useRef({});return z.current.click=T,d.useEffect(()=>{Ec(L.current,z.current)},[]),r.jsxs("div",{className:`wx-398RBS wx-month ${c}`,children:[r.jsx("div",{className:"wx-398RBS wx-weekdays",children:y.map(H=>r.jsx("div",{className:"wx-398RBS wx-weekday",children:H},H))}),r.jsx("div",{className:"wx-398RBS wx-days",ref:L,children:N.map(H=>r.jsx("div",{className:`wx-398RBS wx-day ${H.css} ${H.in?"":"wx-out"}`,"data-id":H.date,children:H.day},H.date))})]})}function nj({value:t,current:a,part:i,onCancel:l,onChange:c,onShift:u}){const m=d.useRef(new Date),[h,g]=Fr(t||m.current),[y,x]=Fr(a||m.current),b=d.useContext(fr).getRaw().calendar,w=b.monthShort||[],j=d.useMemo(()=>y.getMonth(),[y]),A=d.useCallback((M,N)=>{if(M!=null){N.stopPropagation();const L=new Date(y);L.setMonth(M),x(L),u&&u({current:L})}i==="normal"&&g(new Date(y)),l&&l()},[y,i,u,l]),k=d.useCallback(()=>{const M=new Date(mw(h,i)||y);M.setMonth(y.getMonth()),M.setFullYear(y.getFullYear()),c&&c(M)},[h,y,i,c]),T=d.useCallback(M=>{const N=M.target.closest("[data-id]");if(N){const L=parseInt(N.getAttribute("data-id"),10);A(L,M)}},[A]);return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-34U8T8 wx-months",onClick:T,children:w.map((M,N)=>r.jsx("div",{className:"wx-34U8T8 wx-month"+(j===N?" wx-current":""),"data-id":N,children:M},N))}),r.jsx("div",{className:"wx-34U8T8 wx-buttons",children:r.jsx(Wp,{onClick:k,children:b.done})})]})}const zh="wx-1XEF33",aj=({value:t,current:a,onCancel:i,onChange:l,onShift:c,part:u})=>{const m=d.useContext(fr).getRaw().calendar,[h,g]=Fr(a),[y,x]=Fr(t),b=d.useMemo(()=>h.getFullYear(),[h]),w=d.useMemo(()=>{const{start:M,end:N}=ow(b),L=[];for(let z=M;z<=N;++z)L.push(z);return L},[b]),j={click:A};function A(M,N){if(M){N.stopPropagation();const L=new Date(h);L.setFullYear(M),g(L),c&&c({current:L})}u==="normal"&&x(new Date(h)),i&&i()}function k(){const M=new Date(mw(y,u)||h);M.setFullYear(h.getFullYear()),l&&l(M)}const T=d.useRef(null);return d.useEffect(()=>{T.current&&Ec(T.current,j)},[]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:zh+" wx-years",ref:T,children:w.map((M,N)=>r.jsx("div",{className:zh+` wx-year ${b==M?"wx-current":""} ${N===0?"wx-prev-decade":""} ${N===11?"wx-next-decade":""}`,"data-id":M,children:M},N))}),r.jsx("div",{className:zh+" wx-buttons",children:r.jsx(Wp,{onClick:k,children:m.done})})]})},hb={month:{component:tj,next:rj,prev:sj},year:{component:nj,next:lj,prev:ij},duodecade:{component:aj,next:cj,prev:oj}};function sj(t){return t=new Date(t),t.setMonth(t.getMonth()-1),t}function rj(t){return t=new Date(t),t.setMonth(t.getMonth()+1),t}function ij(t){return t=new Date(t),t.setFullYear(t.getFullYear()-1),t}function lj(t){return t=new Date(t),t.setFullYear(t.getFullYear()+1),t}function oj(t){return t=new Date(t),t.setFullYear(t.getFullYear()-10),t}function cj(t){return t=new Date(t),t.setFullYear(t.getFullYear()+10),t}function mw(t,a){let i;if(a==="normal")i=t;else{const{start:l,end:c}=t;a==="left"?i=l:a=="right"?i=c:i=l&&c}return i}const uj=["clear","today"];function dj(t){if(t==="done")return-1;if(t==="clear")return null;if(t==="today")return new Date}function fj({value:t,current:a,onCurrentChange:i,part:l="normal",markers:c=null,buttons:u,css:m="",onShift:h,onChange:g}){const y=d.useContext(fr).getGroup("calendar"),[x,b]=d.useState("month"),w=Array.isArray(u)?u:u?uj:[],j=(N,L)=>{N.preventDefault(),g&&g({value:L})},A=()=>{x==="duodecade"?b("year"):x==="year"&&b("month")},k=N=>{const{diff:L,current:z}=N;if(L===0){x==="month"?b("year"):x==="year"&&b("duodecade");return}if(L){const H=hb[x];i(L>0?H.next(a):H.prev(a))}else z&&i(z);h&&h()},T=N=>{b("month"),g&&g({select:!0,value:N})},M=d.useMemo(()=>hb[x].component,[x]);return r.jsx("div",{className:`wx-2Gr4AS wx-calendar ${l!=="normal"&&l!=="both"?"wx-part":""} ${m}`,children:r.jsxs("div",{className:"wx-2Gr4AS wx-wrap",children:[r.jsx(ej,{date:a,part:l,type:x,onShift:k}),r.jsxs("div",{children:[r.jsx(M,{value:t,current:a,onCurrentChange:i,part:l,markers:c,onCancel:A,onChange:T,onShift:k}),x==="month"&&w.length>0&&r.jsx("div",{className:"wx-2Gr4AS wx-buttons",children:w.map(N=>r.jsx("div",{className:"wx-2Gr4AS wx-button-item",children:r.jsx(Wp,{onClick:L=>j(L,dj(N)),children:y(N)})},N))})]})]})})}function Kp(t){let{words:a=null,optional:i=!1,children:l}=t,c=d.useContext(fr);const u=d.useMemo(()=>{let m=c;return(!m||!m.extend)&&(m=ed(cw)),a!==null&&(m=m.extend(a,i)),m},[a,i,c]);return r.jsx(fr.Provider,{value:u,children:l})}function pb(t,a,i,l){if(!t||l){const c=a?new Date(a):new Date;c.setDate(1),i(c)}else if(t.getDate()!==1){const c=new Date(t);c.setDate(1),i(c)}}const mj=["clear","today"];function hw({value:t,current:a,markers:i=null,buttons:l=mj,css:c="",onChange:u}){const[m,h]=Fr(t),[g,y]=Fr(a);d.useEffect(()=>{pb(g,m,y,!1)},[m,g]);const x=d.useCallback(w=>{const j=w.value;j?(h(new Date(j)),pb(g,new Date(j),y,!0)):h(null),u&&u({value:j?new Date(j):null})},[u,g]),b=d.useCallback(w=>{y(w)},[y]);return g?r.jsx(Kp,{children:r.jsx(fj,{value:m,current:g,markers:i,buttons:l,css:c,onChange:x,onCurrentChange:b})}):null}function hj(t){return t||(t={}),t.width||(t.width="unset"),t}const pj=["clear","today"];function gj({value:t,id:a,disabled:i=!1,error:l=!1,placeholder:c="",format:u="",buttons:m=pj,css:h="",title:g="",tooltip:y,editable:x=!1,clear:b=!1,onChange:w,dropdown:j={}}){const{calendar:A,formats:k}=(d.useContext(fr)||Zf()).getRaw(),T=u||k?.dateFormat;let M=typeof T=="function"?T:kc(T,A);const[N,L]=d.useState(t),[z,H]=d.useState(!1);d.useEffect(()=>{L(t)},[t]);function G(){H(!1)}function _(U){const K=U===N||U&&N&&U.valueOf()===N.valueOf()||!U&&!N;L(U),K||w&&w({value:U}),setTimeout(G,1)}const Y=d.useMemo(()=>N?M(N):"",[N,M]);function q({value:U,input:K}){if(!x&&!b||K)return;let O=typeof x=="function"?x(U):U?new Date(U):null;O=isNaN(O)?N||null:O||null,_(O)}return d.useEffect(()=>{const U=G;return window.addEventListener("scroll",U),()=>window.removeEventListener("scroll",U)},[]),r.jsxs("div",{className:"wx-1lKOFG wx-datepicker",onClick:()=>H(!0),children:[r.jsx(Vp,{css:`wx-date-input ${h}`,title:g,tooltip:y,value:Y,id:a,readonly:!x,disabled:i,error:l,placeholder:c,onInput:G,onChange:q,icon:"wxi-calendar",clear:b}),z&&!i&&r.jsx(Gp,{onCancel:G,...hj(j),children:r.jsx(hw,{buttons:m,value:N,onChange:U=>_(U.value)})})]})}function vj({value:t="",options:a=[],textOptions:i=null,placeholder:l="",disabled:c=!1,error:u=!1,title:m="",tooltip:h,textField:g="label",clear:y=!1,css:x="",children:b,onChange:w,dropdown:j={}}){const A=d.useRef(null),k=d.useRef(null);let[T,M]=Fr(t);function N(_){A.current=_.navigate,k.current=_.keydown}const L=d.useMemo(()=>T||T===0?(i||a).find(_=>_.id===T):null,[T,i,a]),z=d.useCallback(({id:_})=>{(_||_===0)&&(M(_),A.current(null),w&&w({value:_}))},[M,w]),H=d.useCallback(_=>{_.stopPropagation(),M(""),w&&w({value:""})},[M,w]),G=d.useCallback(()=>a.findIndex(_=>_.id===T),[a,T]);return r.jsxs("div",{className:`wx-2YgblL wx-richselect ${x} ${u?"wx-2YgblL wx-error":""} ${c?"wx-2YgblL wx-disabled":""} ${b?"":"wx-2YgblL wx-nowrap"}`,title:m,onClick:()=>A.current(G()),onKeyDown:_=>k.current(_,G()),tabIndex:0,"data-tooltip-text":h,children:[r.jsx("div",{className:"wx-2YgblL wx-label",children:L?b?b(L):L[g]:l?r.jsx("span",{className:"wx-2YgblL wx-placeholder",children:l}):" "}),y&&!c&&T?r.jsx("i",{className:"wx-2YgblL wx-icon wxi-close",onClick:H}):r.jsx("i",{className:"wx-2YgblL wx-icon wxi-angle-down"}),!c&&r.jsx(Jf,{items:a,onReady:N,onSelect:z,...j,children:({option:_})=>b?b(_):_[g]})]})}const yj=({options:t=[],value:a="",css:i="",children:l,onChange:c})=>{const[u,m]=d.useState(a),h=g=>{m(g),c&&c({value:g})};return d.useEffect(()=>{m(a)},[a]),r.jsx("div",{className:`wx-0hMO7P wx-segmented ${i}`,children:t.map(g=>r.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:l?Pp(l,{option:g}):r.jsxs(r.Fragment,{children:[g.icon&&r.jsx("i",{className:`wx-0hMO7P wx-icon ${g.icon} ${g.label?"":"wx-only"}`}),g.label&&r.jsx("span",{className:"wx-0hMO7P wx-label",children:g.label})]})},g.id))})};function bj({notice:t={}}){function a(){t.remove&&t.remove()}return r.jsxs("div",{className:`wx-11sNg5 wx-notice wx-${t.type?t.type:""}`,role:"status","aria-live":"polite",children:[r.jsx("div",{className:"wx-11sNg5 wx-text",children:t.text}),r.jsx("div",{className:"wx-11sNg5 wx-button",children:r.jsx("i",{className:"wx-11sNg5 wxi-close",onClick:a})})]})}function xj({data:t=[]}){return r.jsx("div",{className:"wx-3nwoO9 wx-notices",children:t.map(a=>r.jsx(bj,{notice:a},a.id))})}function wp({title:t="",buttons:a=["cancel","ok"],header:i,children:l,footer:c,css:u="",onConfirm:m,onCancel:h}){const g=(d.useContext(fr)||Zf()).getGroup("core"),y=d.useRef(null);d.useEffect(()=>{y.current?.focus()},[]);function x(w){switch(w.code){case"Enter":{const j=w.target.tagName;if(j==="TEXTAREA"||j==="BUTTON")return;m&&m({event:w});break}case"Escape":h&&h({event:w});break}}function b(w,j){const A={event:w,button:j};j==="cancel"?h&&h(A):m&&m(A)}return r.jsx("div",{className:`wx-1FxkZa wx-modal ${u}`,ref:y,tabIndex:0,onKeyDown:x,children:r.jsxs("div",{className:"wx-1FxkZa wx-window",children:[i||(t?r.jsx("div",{className:"wx-1FxkZa wx-header",children:t}):null),r.jsx("div",{children:l}),c||a&&r.jsx("div",{className:"wx-1FxkZa wx-buttons",children:a.map(w=>r.jsx("div",{className:"wx-1FxkZa wx-button",children:r.jsx(Gu,{type:`block ${w==="ok"?"primary":"secondary"}`,onClick:j=>b(j,w),children:g(w)})},w))})]})})}function wj({children:t},a){const[i,l]=d.useState(null),[c,u]=d.useState([]);return d.useImperativeHandle(a,()=>({showModal:m=>{const h={...m};return l(h),new Promise((g,y)=>{h.resolve=x=>{l(null),g(x)},h.reject=x=>{l(null),y(x)}})},showNotice:m=>{m={...m},m.id=m.id||Bp(),m.remove=()=>u(h=>h.filter(g=>g.id!==m.id)),m.expire!=-1&&setTimeout(m.remove,m.expire||5100),u(h=>[...h,m])}}),[]),r.jsxs(r.Fragment,{children:[t,i&&r.jsx(wp,{title:i.title,buttons:i.buttons,onConfirm:i.resolve,onCancel:i.reject,children:i.message}),r.jsx(xj,{data:c})]})}const Sj=d.forwardRef(wj);function Cj(t){let{children:a}=t,i=d.useRef();const l=d.useMemo(()=>({showNotice:c=>i.current.showNotice(c),showModal:c=>i.current.showModal(c)}),[]);return r.jsx(uw.Provider,{value:l,children:r.jsx(Sj,{ref:i,children:a})})}const kj=({value:t=!1,type:a="",icon:i="",disabled:l=!1,iconActive:c="",onClick:u,title:m="",tooltip:h,css:g="",text:y="",textActive:x="",children:b,active:w,onChange:j})=>{const[A,k]=Fr(t),T=d.useMemo(()=>(A?"pressed":"")+(a?" "+a:""),[A,a]),M=d.useCallback(N=>{let L=!A;u&&u(N),N.defaultPrevented||(k(L),j&&j({value:L}))},[A,u,j]);return A&&w?r.jsx(Gu,{title:m,tooltip:h,text:A&&x||y,css:g,type:T,icon:A&&c||i,onClick:M,disabled:l,children:Pp(w,{value:A})}):b?r.jsx(Gu,{title:m,tooltip:h,text:A&&x||y,css:g,type:T,icon:A&&c||i,onClick:M,disabled:l,children:b}):r.jsx(Gu,{title:m,tooltip:h,text:A&&x||y,css:g,type:T,icon:A&&c||i,onClick:M,disabled:l})};function jj(){return r.jsx(r.Fragment,{})}function gb(t){const{fonts:a=!0,children:i}=t;return r.jsx(Up.Provider,{value:"willow",children:r.jsxs(r.Fragment,{children:[i&&i&&r.jsx("div",{className:"wx-theme wx-willow-theme",children:i}),a&&r.jsxs(r.Fragment,{children:[r.jsx("link",{rel:"preconnect",href:"https://cdn.svar.dev",crossOrigin:"true"}),r.jsx(jj,{}),r.jsx("link",{rel:"stylesheet",href:"https://cdn.svar.dev/fonts/wxi/wx-icons.css"})]})]})})}$p(is);const Yp={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 pw=class{constructor(t){this._nextHandler=null,this._dispatch=t,this.exec=this.exec.bind(this)}async exec(t,a){return this._dispatch(t,a),this._nextHandler&&await this._nextHandler.exec(t,a),a}setNext(t){return this._nextHandler=t}};new Date().valueOf();var Aj=class{constructor(t){const a={id:0,$level:0,data:[],parent:null},i=new Map;i.set(0,a),this._pool=i,t&&t.length&&this.parse(t,0)}parse(t,a){const i=this._pool;for(let c=0;c<t.length;c++){const u=t[c];u.parent=u.parent||a,u.data=null,i.set(u.id,u)}for(let c=0;c<t.length;c++){const u=t[c],m=i.get(u.parent);m&&(m.data||(m.data=[]),m.data.push(u))}const l=i.get(a);this.setLevel(l,l.$level+1,!1)}add(t,a){const i=this._pool.get(t.parent||0);t.$level=i.$level+1,this._pool.set(t.id,t),i.data?a===-1?i.data=[...i.data,t]:vb(i,a,t):i.data=[t]}addAfter(t,a){if(!a)return this.add(t,-1);const i=this.byId(a),l=this.byId(i.parent),c=gf(l,i.id)+1;t.parent=l.id,t.$level=l.$level+1,this.add(t,c)}remove(t){const a=this._pool.get(t);this._remove(a);const i=this._pool.get(a.parent);i.data=i.data.filter(l=>l.id!=t),this._clearBranch(i)}_remove(t){t.data&&t.data.forEach(a=>this._remove(a)),this._pool.delete(t.id)}update(t,a){let i=this._pool.get(t);const l=this._pool.get(i.parent),c=gf(l,i.id);i={...i,...a},l&&c>=0&&(l.data[c]=i,l.data=[...l.data]),this._pool.set(i.id,i)}move(t,a,i){const l=this._pool.get(t),c=a==="child",u=this._pool.get(i),m=u.$level+(c?1:0);if(!l||!u)return;const h=this._pool.get(l.parent),g=c?u:this._pool.get(u.parent);g.data||(g.data=[]);const y=gf(h,l.id);Mj(h,y);const x=c?g.data.length:gf(g,u.id)+(a==="after"?1:0);if(vb(g,x,l),h.id===g.id&&y===x)return null;l.parent=g.id,l.$level!==m&&(l.$level=m,this.setLevel(l,m+1,!0)),this.update(l.id,l),this._clearBranch(h)}_clearBranch(t){t.data&&!t.data.length&&(t.open&&delete t.open,this.update(t.id,{data:null}))}toArray(){const t=[],a=this._pool.get(0).data;return a&&gw(a,t),t}byId(t){return this._pool.get(t)}getBranch(t){return this._pool.get(t).data}forEach(t){this._pool.forEach((a,i)=>{i!==0&&t(a)})}eachChild(t,a){const i=this.byId(a);!i||!i.data||i.data.forEach((l,c)=>{t(this.byId(l.id),c),this.eachChild(t,l.id)})}setLevel(t,a,i){t.data&&(t.data=t.data.map(l=>(i&&(l={...l},this._pool.set(l.id,l)),l.$level=a,l.data&&this.setLevel(l,a+1,i),l)))}};function gw(t,a){t.forEach(i=>{a.push(i),i.open===!0&&gw(i.data,a)})}function Mj(t,a){const i=[...t.data];i.splice(a,1),t.data=i}function vb(t,a,i){const l=[...t.data];l.splice(a,0,i),t.data=l}function gf(t,a){return t?.data.findIndex(i=>i.id===a)}var vw=2,Nj=class{constructor(a){a&&(this._writable=a.writable,this._async=a.async),this._values={},this._state={}}setState(a,i=0){const l={};return this._wrapProperties(a,this._state,this._values,"",l,i),l}getState(){return this._values}getReactive(){return this._state}_wrapProperties(a,i,l,c,u,m){for(const h in a){const g=i[h],y=l[h],x=a[h];if(g&&(y===x&&typeof x!="object"||x instanceof Date&&y instanceof Date&&y.getTime()===x.getTime()))continue;const b=c+(c?".":"")+h;g?(g.__parse(x,b,u,m)&&(l[h]=x),m&vw?u[b]=g.__trigger:g.__trigger()):(x&&x.__reactive?i[h]=this._wrapNested(x,x,b,u):i[h]=this._wrapWritable(x),l[h]=x),u[b]=u[b]||null}}_wrapNested(a,i,l,c){const u=this._wrapWritable(a);return this._wrapProperties(a,u,i,l,c,0),u.__parse=(m,h,g,y)=>(this._wrapProperties(m,u,i,h,g,y),!1),u}_wrapWritable(a){const i=[],l=function(){for(let c=0;c<i.length;c++)i[c](a)};return{subscribe:c=>(i.push(c),this._async?setTimeout(c,1,a):c(a),()=>{const u=i.indexOf(c);u>=0&&i.splice(u,1)}),__trigger:()=>{i.length&&(this._async?setTimeout(l,1):l())},__parse:function(c){return a=c,!0}}}};function yb(t,a){return Object.defineProperty(t,"__reactive",{value:!0,enumerable:!1,writable:!1}),t}var Tj=class{constructor(a,i,l,c){typeof a=="function"?this._setter=a:this._setter=a.setState.bind(a),this._routes=i,this._parsers=l,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(u=>{u.in.forEach(m=>{const h=this._triggers.get(m)||[];h.push(u),this._triggers.set(m,h)}),u.out.forEach(m=>{const h=this._sources.get(m)||{};u.in.forEach(g=>h[g]=!0),this._sources.set(m,h)})}),this._routes.forEach(u=>{u.length=Math.max(...u.in.map(m=>yw(m,this._sources,1)))}),this._bus=c}init(a){const i={};for(const l in a)if(this._prev[l]!==a[l]){const c=this._parsers[l];i[l]=c?c(a[l]):a[l]}this._prev=this._prev?{...this._prev,...a}:{...a},this.setState(i),this._bus&&this._bus.exec("init-state",i)}setStateAsync(a){const i=this._setter(a,vw);return this._async?Object.assign(this._async.signals,i):this._async={signals:i,timer:setTimeout(this._applyState.bind(this),1)},i}_applyState(){const a=this._async;if(a){this._async=null,this._triggerUpdates(a.signals,[]);for(const i in a.signals){const l=a.signals[i];l&&l()}}}setState(a,i=[]){const l=this._setter(a);return this._triggerUpdates(l,i),l}_triggerUpdates(a,i){const l=Object.keys(a),c=!i.length;i=i||[];for(let u=0;u<l.length;u++){const m=l[u],h=this._triggers.get(m);h&&h.forEach(g=>{i.indexOf(g)==-1&&i.push(g)})}c&&this._execNext(i)}_execNext(a){for(;a.length;){a.sort((l,c)=>l.length<c.length?1:-1);const i=a[a.length-1];a.splice(a.length-1),i.exec(a)}}};function yw(t,a,i){const l=a.get(t);if(!l)return i;const c=Object.keys(l).map(u=>yw(u,a,i+1));return Math.max(...c)}var Rj=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(a,i,l){let c=this._handlers[a];c?l&&l.intercept?c.unshift(i):c.push(i):c=this._handlers[a]=[i],l&&l.tag&&this._tag.set(i,l.tag)}intercept(a,i,l){this.on(a,i,{...l,intercept:!0})}detach(a){for(const i in this._handlers){const l=this._handlers[i];for(let c=l.length-1;c>=0;c--)this._tag.get(l[c])===a&&l.splice(c,1)}}async exec(a,i){const l=this._handlers[a];if(l)for(let c=0;c<l.length;c++){const u=l[c](i);if(u===!1||u&&u.then&&await u===!1)return}return this._nextHandler&&await this._nextHandler.exec(a,i),i}setNext(a){return this._nextHandler=a}};const bc=1024;function Ju(t){return t<bc?`${t} B`:t<bc**2?`${(t/bc).toFixed(1)} KB`:t<bc**3?`${(t/bc**2).toFixed(1)} MB`:`${(t/bc**3).toFixed(1)} GB`}function bb(t,a){a||(a={key:"name",order:"asc"});const i=t.filter(m=>m.type==="folder"),l=t.filter(m=>m.type!=="folder"),c=i.sort(xb(a)),u=l.sort(xb(a));return[...c,...u]}function Ej(t,a){return typeof t=="string"?t.localeCompare(a,void 0,{numeric:!0}):typeof t=="object"?t.getTime()-a.getTime():(t??0)-(a??0)}function Dj(t,a){return typeof t=="string"?-t.localeCompare(a,void 0,{numeric:!0}):typeof a=="object"?a.getTime()-t.getTime():(a??0)-(t??0)}function xb({key:t,order:a}){const i=a==="asc"?Ej:Dj;return(l,c)=>i(l[t],c[t])}function Qp(t,a){const i=t==="/"?1:t.split("/").length;return i>=a.length?null:a[i].id}function Lj(t){return t.length>1?t[t.length-2].id:null}let _j=class extends Aj{constructor(a){const i={id:"/",name:"My files",open:!0,$level:1,parent:0,ext:"",type:"folder"};super([i]),this.parse(a,"/")}parse(a,i,l){!a||!a.length||(a.forEach(c=>this.parseId(c,l?i:void 0)),super.parse(a,i))}parseId(a,i){if(a.parent===0)return;const l=a.id,c=l.lastIndexOf("/");if(a.parent=i??(c===0?"/":l.slice(0,c)),a.name=l.slice(c+1),a.type=a.type||"file",a.type!=="folder"){const u=a.name.lastIndexOf("."),m=u!==-1?a.name.slice(u+1):"";a.ext=m!=="new"?m?.toLocaleLowerCase():""}}getParents(a){const i=[];let l=this.byId(a);if(!l)return i;for(;l.id!==0;)i.push(l),l=this.byId(l.parent);return i.reverse()}findFiles(a,i="/"){const l=[],c=a.toLocaleLowerCase();return this.eachChild(u=>{u.name.toLowerCase().indexOf(c)!==-1&&l.push(u)},i),l}add(a,i){const l=this.byId(a.parent||"/"),c=a.data?[...a.data]:null;a.data=null,super.add(a,i??l.data?l.data.length:0),c&&c.forEach(u=>this.add(u))}renameFiles(a,i,l){const c=this.byId(a),u=this.normalizeFile(c,i),m=[];return u.data?.forEach(h=>m.push(this.renameFiles(h.id,u.id,l))),m.length&&(u.data=m),l[a]=u.id,u}copyFiles(a,i,l){const c={};return a.forEach(u=>{const m=this.renameFiles(u,i,c);this.add(m),l&&this.remove(u),c[u]=m.id}),c}moveFiles(a,i){if(this.byId(a[0]).parent!==i)return this.copyFiles(a,i,!0)}serialize(a="/"){const i=[],l=this.byId(a);return l?(l.data?.forEach(c=>{const{id:u,date:m,type:h,size:g,lazy:y}=c,x={id:u,date:m,type:h??"file"};y&&(x.lazy=y),g&&(x.size=g),i.push(x);const b=this.serialize(u);b.length&&i.push(...b)}),i):null}normalizeFile(a,i){const l=a.name,c=l.lastIndexOf("."),u=c!==-1?l.slice(c+1):"",m=u?`.${u}`:"";let h=c!==-1?l.slice(0,c):l,g=i+(i==="/"?"":"/")+h;for(;this.byId(g+m);){const y=".new";g+=y,h+=y}return{...a,id:g+m,name:h+m,parent:i,ext:u.toLocaleLowerCase()}}},Ij=class extends Nj{in;_router;constructor(a){super({writable:a,async:!1});const i=[];for(let u=0;u<2;u++)i.push({in:["data",`panels.${u}.path`],out:[`panels.${u}._crumbs`],exec:m=>{const{data:h,panels:g}=this.getState(),y=[];y[u]={_crumbs:h.getParents(g[u].path)},this.setState({panels:y},m)}}),i.push({in:["data",`panels.${u}.path`,`panels.${u}._sorts`,"search"],out:[`panels.${u}._files`],exec:m=>{const{data:h,panels:g,search:y}=this.getState();let x;y?x=h.findFiles(y,g[u].path):x=h.byId(g[u].path)?.data||[];const{path:b,_sorts:w}=g[u];x=bb(x,w[b]);const j=[];j[u]={_files:x},this.setState({panels:j},m)}}),i.push({in:["data",`panels.${u}.selected`,`panels.${u}._sorts`],out:[`panels.${u}._selected`],exec:m=>{const{data:h,panels:g}=this.getState(),y=[];g[u].selected.forEach(A=>{const k=h.byId(A);k&&y.push(k)});const{path:x,_sorts:b}=g[u],w=bb(y,b[x]),j=[];j[u]={_selected:w},this.setState({panels:j},m)}});this._router=new Tj(super.setState.bind(this),i,{data:u=>new _j(u)});const l=this.in=new Rj;l.on("select-file",({id:u,toggle:m,range:h,panel:g,type:y})=>{const{panels:x,activePanel:b}=this.getState();typeof g>"u"&&(g=b),u||(m=h=!1);let w=[...x[g].selected];if(m){const A=w.indexOf(u);A===-1?w.push(u):w.splice(A,1)}else if(h&&x[g]._lastSelected){const A=x[g]._files;let k=A.findIndex(N=>N.id==x[g]._lastSelected),T=A.findIndex(N=>N.id==u);T<k&&([k,T]=[T,k]);const M=A.slice(k,T+1).map(N=>N.id);w=[...new Set([...w,...M])]}else w=u?[u]:[];const j=[];j[g]={selected:w,_lastSelected:u,_selectNavigation:y==="navigation"},this.setState({panels:j})}),l.on("set-path",({id:u,panel:m,selected:h})=>{const{data:g,activePanel:y}=this.getState(),x=g.byId(u);if(x){const b=[];typeof m>"u"&&(m=y),b[m]={path:u},this.setState({panels:b}),l.exec("select-file",{panel:m}),h&&h.forEach(w=>l.exec("select-file",{id:w,panel:m,toggle:!0})),x.lazy&&l.exec("request-data",{id:u})}}),l.on("provide-data",({id:u,data:m})=>{const{mode:h,data:g}=this.getState(),y=g.byId(u);y&&(y.lazy||(y.data=[]),y.lazy=!1,g.parse(m,u,h==="search"),this.setState({data:g}))}),l.on("open-tree-folder",({id:u,mode:m})=>{const{data:h}=this.getState();h.update(u,{open:m}),this.setState({data:h})}),l.on("show-preview",({mode:u})=>{this.setState({preview:u})}),l.on("rename-file",u=>{const{id:m,name:h}=u,{data:g,panels:y}=this.getState(),x=g.byId(m);if(x.name!==h){x.name=h;const b=g.normalizeFile(x,x.parent);u.newId=b.id,b.data=null,g.add(b);let w={[m]:b.id};x.data?.forEach(A=>w={...g.moveFiles([A.id],b.id),...w});const j=y.map(A=>({selected:A.selected,_crumbs:A._crumbs,_lastSelected:A._lastSelected,_sorts:A._sorts}));g.remove(m),this._updatePanels(j,w),this.setState({data:g,panels:j})}}),l.on("create-file",u=>{const{file:m,parent:h}=u,{data:g}=this.getState(),y=g.normalizeFile(m,h);y.type=m.type||"file",u.newId=y.id,g.add(y),this.setState({data:g}),l.exec("select-file",{id:y.id})}),l.on("delete-files",({ids:u})=>{const{data:m,panels:h}=this.getState(),g=h.map(y=>({selected:y.selected,_crumbs:y._crumbs,_lastSelected:y._lastSelected,_sorts:y._sorts}));u.forEach(y=>m.remove(y)),this._updatePanels(g,{}),this.setState({data:m,panels:g})}),l.on("copy-files",u=>{const{ids:m,target:h}=u;if(this._isPlacedIntoSelf(m,h)){console.error("You cannot copy a folder into itself"),u.skipProvider=!0;return}const{data:g,panels:y,activePanel:x}=this.getState(),b=g.copyFiles(m,h);u.newIds=m.map(w=>b[w]),this.setState({data:g}),y[x].path==h&&(l.exec("select-file",{}),m.forEach(w=>{l.exec("select-file",{id:b[w],toggle:!0})}))}),l.on("move-files",u=>{const{ids:m,target:h}=u;if(this._isPlacedIntoSelf(m,h)){console.error("You cannot move a folder into itself"),u.skipProvider=!0;return}const{data:g,panels:y,activePanel:x}=this.getState(),b=g.moveFiles(m,h);if(b){u.newIds=m.map(j=>b[j]);const w=y.map(j=>({selected:j.selected,_crumbs:j._crumbs,_lastSelected:j._lastSelected,_sorts:j._sorts}));this._updatePanels(w,b,!0),this.setState({data:g,panels:w}),y[x].path==h&&(l.exec("select-file",{}),m.forEach(j=>{l.exec("select-file",{id:b[j],toggle:!0})}))}});let c=null;l.on("filter-files",({text:u})=>{if(!u){c&&this.setState({...c});return}l.exec("select-file",{});const{panels:m,mode:h}=this.getState();c||(c={panels:m,mode:h,search:""}),this.setState({mode:"search",search:u})}),l.on("set-mode",({mode:u})=>{const{activePanel:m}=this.getState(),h=[];h[m]={_selectNavigation:!1};const g={mode:u,search:"",panels:h};c=null,this.setState(g)}),l.on("set-active-panel",({panel:u})=>{this.setState({activePanel:u})}),l.on("sort-files",({key:u,order:m,panel:h,path:g})=>{const{activePanel:y,panels:x}=this.getState();h=h??y,g=g??x[h].path;const b=[];b[h]={_sorts:{...x[h]._sorts,[g]:{key:u,order:m}}},this.setState({panels:b})}),this.initOnce()}initOnce(){const a=[];for(let l=0;l<2;l++)a[l]=yb({_crumbs:[],_files:[],_selected:[],_sorts:{},path:"/",selected:[],...a[l]});const i={panels:yb(a),data:[],search:""};this._router.init(i)}init(a){const i={...a};this._router.init(i)}setState(a,i){return this._router.setState(a,i)}getFile(a){const{data:i}=this.getState();return i.byId(a)||null}serialize(a){const{data:i}=this.getState();return i.serialize(a)}_updatePanels(a,i,l){const{data:c}=this.getState();a.forEach(u=>{const m=[];u.selected.forEach(y=>{c.byId(y)?m.push(y):!l&&i[y]&&m.push(i[y])}),u.selected=m,c.byId(u._lastSelected)||(u._lastSelected=l?null:i[u._lastSelected]||null);const h={};Object.keys(u._sorts).forEach(y=>{c.byId(y)?h[y]=u._sorts[y]:i[y]&&!l&&(h[i[y]]=u._sorts[y])}),u._sorts=h;const g=u._crumbs[u._crumbs.length-1];g?.id!=="/"&&(i[g.id]?u.path=i[g.id]:c.byId(g.id)||(u.path="/"))})}_isPlacedIntoSelf(a,i){return a.some(l=>l===i||this.getState().data.getParents(i).some(c=>c.id===l))}};function zj(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(a=>a!==null)}}function Oj(t,a="data-id"){let i=t;for(!i.tagName&&t.target&&(i=t.target);i;){if(i.getAttribute&&i.getAttribute(a))return i;i=i.parentNode}return null}function Hj(t,a="data-id"){const i=Oj(t,a);return i?i.getAttribute(a):null}new Date().valueOf();function Fj(t,a){const{api:i}=a;function l(u,m){const h=a.getPanel(),g=h.selected,y=m.ctrlKey||m.metaKey,x=m.shiftKey;let b;const w=g?.[0]?i.getFile(g[0]):null;g?.length?g.length>1?b=a.menuOptions("multiselect"):b=a.menuOptions(w.type,w):b=a.menuOptions("body");const j=`${y?"ctrl+":""}${x?"shift+":""}${u}`,A=b?b.find(T=>T.hotkey?.toLowerCase()===j):!1,k=a.performAction;if(A)switch(j){case"ctrl+c":k("copy");break;case"ctrl+x":k("move");break;case"ctrl+v":k("paste",w);break;case"delete":k("delete");break;case"ctrl+r":m.preventDefault(),k("rename",w);break;case"ctrl+d":m.preventDefault(),k("download",w);break;default:A.handler?.({context:w})}switch(u){case"enter":{if(y||x)break;const{_crumbs:T,_selectNavigation:M}=h;if(M){const N=Lj(T);if(N){const L=Qp(N,T);i.exec("set-path",{id:N,selected:[L]})}}else if(g.length===1){const N=i.getFile(g[0]);N&&i.exec(N.type==="folder"?"set-path":"open-file",{id:N.id})}break}case"arrowup":case"arrowleft":{const{_files:T,_selected:M,path:N,_selectNavigation:L}=h;let z;if(M.length){const H=M.at(0).id,G=T.findIndex(_=>_.id===H);if(G!==-1){const _=G-1;T[_]?z=T[_].id:N!=="/"&&!(y||x)&&i.exec("select-file",{type:"navigation"})}}else{if(L)break;if(N!=="/"){i.exec("select-file",{type:"navigation"});break}z=T.at(0)?.id}z&&i.exec("select-file",{id:z,toggle:y,range:x});break}case"arrowdown":case"arrowright":{const{_files:T,_selected:M,path:N,_selectNavigation:L}=h;let z;if(M.length){const H=M.at(-1).id,G=T.findIndex(_=>_.id===H);if(G!==-1){const _=G+1;T[_]&&(z=T[_].id)}}else{if(N!=="/"&&!L){i.exec("select-file",{type:"navigation"});break}z=T.at(0)?.id}z&&i.exec("select-file",{id:z,toggle:y,range:x});break}}}function c(u){const m=u.code.replace("Key","").toLowerCase();l(m,u),m=="tab"&&setTimeout(()=>{const h=document.activeElement;h.className.indexOf("table")!=-1&&i.exec("set-active-panel",{panel:+Hj(h,"data-panel")})})}return t.addEventListener("keydown",c),{destroy:()=>{t.removeEventListener("keydown",c)}}}function Pj(t,a="data-id"){let i=t;for(!i.tagName&&t.target&&(i=t.target);i;){if(i.getAttribute&&i.getAttribute(a))return i;i=i.parentNode}return null}function $j(t,a="data-id"){const i=t.getAttribute(a);return i?Bj(i):null}function Bj(t){if(t.startsWith(":"))return t.substring(1);const a=t*1;return isNaN(a)?t:a}function Uj(){return{detect:()=>!0,addEvent:function(t,a,i){return t.addEventListener(a,i),()=>t.removeEventListener(a,i)},addGlobalEvent:function(t,a){return document.addEventListener(t,a),()=>document.removeEventListener(t,a)},getTopNode:function(){return window.document.body}}}var qj=Uj();new Date().valueOf();function bw(t){const[a,i]=d.useState(t),l=d.useRef(t);return d.useEffect(()=>{if(l.current!==t){if(Array.isArray(l.current)&&Array.isArray(t)&&l.current.length===0&&t.length===0)return;l.current=t,i(t)}},[t]),[a,i]}function Gj(t,a,i){const[l,c]=d.useState(()=>a);return t||console.warn(`Writable ${i} is not defined`),d.useEffect(()=>t?t.subscribe(m=>{c(()=>m)}):void 0,[t]),l}function gt(t,a){const i=t.getState(),l=t.getReactiveState();return Gj(l[a],i[a],a)}function Vj(t,a){const i=d.useRef(a);i.current=a;const[l,c]=d.useState(1);return d.useEffect(()=>t.subscribe(m=>{i.current=m,c(h=>h+1)}),[t]),[i.current,l]}function Ps(t,a){const i=t.getState(),l=t.getReactiveState();return Vj(l[a],i[a])}function xw(t){const a={};return t.split(";").forEach(i=>{const[l,c]=i.split(":");if(c){let u=l.trim();u.indexOf("-")&&(u=u.replace(/-([a-z])/g,(m,h)=>h.toUpperCase())),a[u]=c.trim()}}),a}function ww(t){let a=t,i=[];return{subscribe:h=>{i.push(h),h(a)},unsubscribe:h=>{i=i.filter(g=>g!==h)},set:h=>{a=h,i.forEach(g=>g(a))},update:h=>{a=h(a),i.forEach(g=>g(a))}}}function wb(t,a,i){function l(c){const u=Pj(c);if(!u)return;const m=$j(u);if(typeof a=="function")return a(m,c);let h,g=c.target;for(;g!=u;){if(h=g.dataset?g.dataset.action:null,h&&a[h]){a[h](m,c);return}g=g.parentNode}a[i]&&a[i](m,c)}return qj.addEvent(t,i,l)}function Wj(t,a){const i=[wb(t,a,"click")];return a.dblclick&&i.push(wb(t,a.dblclick,"dblclick")),()=>{i.forEach(l=>l())}}function Sw(t,a){return t.map((i,l)=>{const c=a(i,l);return i.data&&i.data.length&&(c.data=Sw(i.data,a)),c}).filter(Boolean)}function Cw(t,a){const i=[];return t.forEach(l=>{if(l.data){const c=Cw(l.data,a);c.length&&i.push({...l,data:c})}else a(l)&&i.push(l)}),i}function Kj(t){return Sw(t,(a,i)=>{const l={...a,id:a.id||Bp()};return l.type&&(l.comp=l.type),l.comp==="separator"&&t[i-1]?.comp==="separator"?null:l})}const kw={};function Yj(t){return kw[t]||t}function Qj(t,a){kw[t]=a}function Xj({onClick:t,onShow:a,option:i}){const l=d.useRef(null),c=d.useCallback(()=>{a(i.data?i.id:!1,l.current)},[a,i]),u=d.useCallback(h=>{if(i.data){h.stopPropagation(),a(i.id,l.current);return}t(h)},[t,a,i]),m=d.useMemo(()=>i&&i.comp?Yj(i.comp):null,[i]);return r.jsxs("div",{ref:l,className:`wx-cDCz9rZQ wx-option ${i.css||""} ${i.disabled?"wx-disabled":""}`,"data-id":na(i.id),onMouseEnter:c,onClick:u,children:[i.icon?r.jsx("i",{className:`wx-cDCz9rZQ wx-icon ${i.icon}`}):null,i.comp?m?r.jsx(m,{item:i,option:i}):null:r.jsxs("span",{className:"wx-cDCz9rZQ wx-value",children:[" ",i.text," "]}),i.subtext?r.jsx("span",{className:"wx-cDCz9rZQ wx-subtext",children:i.subtext}):null,i.data?r.jsx("i",{className:"wx-cDCz9rZQ wx-sub-icon wxi-angle-right"}):null]})}function Xp({options:t,left:a=0,top:i=0,at:l="bottom",parent:c=null,mount:u=null,context:m=null,css:h="",onClick:g,onCancel:y}){const[x,b]=d.useState(-1e4),[w,j]=d.useState(-1e4),[A,k]=d.useState(20),[T,M]=d.useState(),N=d.useRef(null),[L,z]=d.useState(!1),[H,G]=d.useState(null),_=d.useCallback(()=>{const me=iw(N.current,c,l,a,i);me&&(b(me.x),j(me.y),M(me.width));let Z=me?.z??20;const I=c?Fk(c):[];let se=0;for(const W of I){const F=parseInt(getComputedStyle(W).zIndex,10);F>se&&(se=F)}se>=Z&&(Z=se+1),k(Z)},[c,l,a,i]);d.useEffect(()=>{u&&u(_)},[]);const Y=d.useCallback(()=>{z(!1)},[]),q=d.useCallback((me,Z)=>{z(me),G(Z)},[]),U=d.useMemo(()=>Kj(t),[t]);d.useEffect(()=>{_()},[c,_]);const K=d.useRef(g),O=d.useRef(y),ve=d.useRef(c);return d.useEffect(()=>{K.current=g},[g]),d.useEffect(()=>{O.current=y},[y]),d.useEffect(()=>{ve.current=c},[c]),d.useEffect(()=>{if(!N.current)return;function me(Z){O.current?O.current(Z):K.current&&K.current({action:null,option:null})}return Pr(N.current,{callback:me,modal:!0,parent:()=>ve.current}).destroy},[]),r.jsx("div",{ref:N,"data-wx-menu":"true",className:`wx-XMmAGqVx wx-menu ${h}`,style:{position:"absolute",top:w+"px",left:x+"px",width:T,zIndex:A},onMouseLeave:Y,children:U.map(me=>r.jsxs(d.Fragment,{children:[me.comp==="separator"?r.jsx("div",{className:"wx-XMmAGqVx wx-separator"}):r.jsx(Xj,{option:me,onShow:q,onClick:Z=>{if(!me.data&&!Z.defaultPrevented){const I={context:m,action:me,option:me,event:Z};me.handler&&me.handler(I),g&&g(I),Z.stopPropagation()}}}),me.data&&L===me.id?r.jsx(Xp,{css:h,options:me.data,at:"right-overlap",parent:H,context:m,onClick:g,onCancel:y}):null]},me.id))})}const jw=d.forwardRef(function(t,a){const{options:i,at:l="bottom",resolver:c=null,dataKey:u="contextId",filter:m=null,css:h="",children:g,onClick:y}=t,[x,b]=d.useState(null),[w,j]=d.useState(null),[A,k]=d.useState(0),[T,M]=d.useState(0),N=d.useRef(null),L=d.useMemo(()=>`data-${u.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,[u]),z=d.useMemo(()=>x!==null&&m?Cw(i,Y=>m(Y,x)):i,[x,m,i]);function H(Y){j(null),y&&y(Y)}function G(Y){if(N.current===Y){N.current=null;return}j(null),y&&y({action:null,option:null})}const _=d.useCallback((Y,q)=>{if(!Y){j(null);return}if(Y.defaultPrevented)return;const U=Y.target;if(U&&U.dataset&&U.dataset.menuIgnore)return;if(w&&w===U){j(null),Y.preventDefault();return}k(Y.clientX+1),M(Y.clientY+1);let K=typeof q<"u"?q:Zu(U,L);c&&(K=c(K,Y),!K)||(b(K),j(U),N.current=Y.nativeEvent||Y,Y.preventDefault())},[w,L,c]);return d.useImperativeHandle(a,()=>({show:_}),[_]),r.jsxs(r.Fragment,{children:[g?r.jsx("span",{onClick:_,"data-menu-ignore":"true",children:typeof g=="function"?g():g}):null,w?r.jsx(qp,{children:r.jsx(Xp,{css:h,at:l,top:T,left:A,parent:w,context:x,onClick:H,onCancel:G,options:z},w)}):null]})}),Zj=d.forwardRef(function(t,a){const{options:i,at:l="bottom",css:c="",children:u,onClick:m}=t,[h,g]=d.useState(null),y=d.useRef(null);function x(A){g(null),m&&m(A)}function b(A){if(y.current===A){y.current=null;return}g(null),m&&m({action:null,option:null})}const w=d.useCallback(A=>{g(A.target),y.current=A.nativeEvent||A,A.preventDefault()},[]);d.useImperativeHandle(a,()=>({show:w}),[w]);function j(A){let k=A.target;for(;!k.dataset.menuIgnore;)g(k),k=k.parentNode}return r.jsxs(r.Fragment,{children:[r.jsx("span",{onClick:j,"data-menu-ignore":"true",children:u}),h?r.jsx(qp,{children:r.jsx(Xp,{css:c,at:l,parent:h,options:i,onClick:x,onCancel:b})}):null]})}),Jj=d.forwardRef(function(t,a){const{options:i,at:l="bottom",resolver:c=null,dataKey:u="contextId",filter:m=null,css:h="",children:g,onClick:y}=t,x=d.useRef(null),b=d.useCallback((w,j)=>{x.current.show(w,j)},[]);return d.useImperativeHandle(a,()=>({show:b}),[b]),r.jsxs(r.Fragment,{children:[g?r.jsx("span",{onContextMenu:b,"data-menu-ignore":"true",children:g}):null,r.jsx(jw,{css:h,at:l,options:i,resolver:c,dataKey:u,filter:m,ref:x,onClick:y})]})}),eA={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 tA=class{constructor(a,i,l,c,u){this.setFiles=a,this.setReady=i,this.setSignal=l,this.setDrag=c,u&&u.length&&this.setFiles(u)}open(a){this.setSignal(["click",a||{}])}getState(){let a="server";const i=this.files;for(let l=0;l<i.length;l++){if(i[l].status==="client")return"client";i[l].status==="error"&&(a="error")}return a}droparea(a,i){i=i||{};const l=()=>{i.dragEnter&&i.dragEnter(),this.setDrag(!0)},c=()=>{i.dragLeave&&i.dragLeave(),this.setDrag(!1)},u=h=>{h.preventDefault()},m=h=>{h.preventDefault(),this.setDrag(!1),this.setSignal(["drop",i,h]),i.dragLeave&&i.dragLeave(),i.drop&&i.drop()};return a.addEventListener("dragenter",l),a.addEventListener("dragleave",c),a.addEventListener("dragover",u,!0),a.addEventListener("drop",m,!0),()=>{a.removeEventListener("dragenter",l),a.removeEventListener("dragleave",c),a.removeEventListener("dragover",u,!0),a.removeEventListener("drop",m,!0)}}updateFile(a,i){const l=this.files.findIndex(u=>u.id===a);if(l===-1)return;const c=[...this.files];return c[l]={...c[l],...i},this.files=c,this.setFiles(this.files),this.files[l]}deleteFile(a){this.files=this.files.filter(i=>i.id!==a),this.setFiles(this.files)}addFile(a,i){i?this.files=[...this.files,a]:this.files=[a],this.setFiles(this.files)}deleteAll(){this.files=[],this.setFiles(this.files)}};function Aw(t){const[a,i]=d.useState([]),[l,c]=d.useState(Promise.resolve(null)),[u,m]=d.useState(null),[h,g]=d.useState(!1),y=d.useRef();return y.current||(y.current=new tA(i,c,m,g,t)),y.current.files=a,y.current.ready=l,y.current.signal=u,y.current.drag=h,y.current}function nA(t,a){{if(t){const i=t.getGroup(a);if(i)return i}return ed(eA).getGroup(a)}}const aA=()=>Math.random().toString(36).substr(2,9),sA=({data:t,accept:a="",multiple:i=!0,folder:l=!1,uploadURL:c="",apiOnly:u=!1,disabled:m=!1,children:h,onChange:g,onUpload:y})=>{const x=d.useRef(null),b=d.useRef(null),[w,j]=d.useState({}),A=Aw(),k=t||A,T=d.useContext(sa.i18n),M=nA(T,"uploader");d.useEffect(()=>{x.current&&l&&(x.current.webkitdirectory=!0)},[l]),d.useEffect(()=>{if(!u&&b.current&&!m)return k.droparea(b.current)},[u,m,b]);const N=U=>{const K=new FormData;return K.append("upload",U.file),fetch(c,{method:"POST",body:K}).then(O=>O.json()).then(O=>({id:U.id,...O}),()=>({id:U.id,status:"error"})).catch(O=>(console.log(O),{id:U.id,status:"error"}))},L=(U,K)=>{const O=k.updateFile(U,K),ve={...O,status:k.getState()};O&&O.uploaded&&O.uploaded(ve),y&&y(ve),O.temp&&k.deleteFile(O.id)},z=U=>{if(!U)return;const K=typeof c=="function"?c(U):N(U);k.setReady(K.then(O=>{O.status=O.status||"server",L(U.id,O)}).catch(O=>{L(U.id,{status:"error",error:O})}))},H=(U,K)=>{const O={...K||w,id:aA(),status:"client",name:U.name,file:U};O.selected&&O.selected(O),g&&g(O),k.addFile(O,i),z(O),x.current&&(x.current.value="")},G=(U,K,O)=>{U.isFile?U.file(ve=>{H(ve,O)}):U.isDirectory&&U.createReader().readEntries(ve=>{ve.forEach(me=>{G(me,K+me.name+"/",O)})})},_=U=>{Array.from(U.target.files).forEach(K=>H(K))},Y=(U,K)=>{Array.from(U.dataTransfer.items).forEach(O=>{const ve=O.webkitGetAsEntry();ve&&G(ve,"",K)})},q=()=>{x.current&&x.current.click()};return d.useEffect(()=>{if(k.signal){const[U,K,O]=k.signal;j(K),U==="click"?q():U==="drop"&&Y(O,K),k.setSignal(null)}},[k.signal]),u?r.jsxs(r.Fragment,{children:[r.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:x,onChange:_,accept:a,multiple:i,disabled:m}),h]}):r.jsxs("div",{className:`wx-at1A8tb8 wx-label ${k.drag?"wx-active":""} ${m?"wx-disabled":""}`,ref:b,children:[r.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:x,onChange:_,accept:a,multiple:i,disabled:m}),h||r.jsx("div",{className:"wx-at1A8tb8 wx-dropzone",children:r.jsxs("span",{children:[M("Drop files here or")," ",r.jsx("span",{className:"wx-at1A8tb8 wx-action",onClick:q,children:M("select files")})]})})]})};new Date().valueOf();function rA(t,a){if(Object.keys(t).length!==Object.keys(a).length)return!1;for(const i in a){const l=t[i],c=a[i];if(!em(l,c))return!1}return!0}function em(t,a){if(typeof t=="number"||typeof t=="string"||typeof t=="boolean"||t===null)return t===a;if(typeof t!=typeof a||(t===null||a===null)&&t!==a||t instanceof Date&&a instanceof Date&&t.getTime()!==a.getTime())return!1;if(typeof t=="object")if(Array.isArray(t)&&Array.isArray(a)){if(t.length!==a.length)return!1;for(let i=t.length-1;i>=0;i--)if(!em(t[i],a[i]))return!1;return!0}else return rA(t,a);return t===a}function Sp(t){if(typeof t!="object"||t===null)return t;if(t instanceof Date)return new Date(t);if(t instanceof Array)return t.map(Sp);const a={};for(const i in t)a[i]=Sp(t[i]);return a}var Mw=2,iA=class{constructor(t){t&&(this._writable=t.writable,this._async=t.async),this._values={},this._state={}}setState(t,a=0){const i={};return this._wrapProperties(t,this._state,this._values,"",i,a),i}getState(){return this._values}getReactive(){return this._state}_wrapProperties(t,a,i,l,c,u){for(const m in t){const h=a[m],g=i[m],y=t[m];if(h&&(g===y&&typeof y!="object"||y instanceof Date&&g instanceof Date&&g.getTime()===y.getTime()))continue;const x=l+(l?".":"")+m;h?(h.__parse(y,x,c,u)&&(i[m]=y),u&Mw?c[x]=h.__trigger:h.__trigger()):(y&&y.__reactive?a[m]=this._wrapNested(y,y,x,c):a[m]=this._wrapWritable(y),i[m]=y),c[x]=c[x]||null}}_wrapNested(t,a,i,l){const c=this._wrapWritable(t);return this._wrapProperties(t,c,a,i,l,0),c.__parse=(u,m,h,g)=>(this._wrapProperties(u,c,a,m,h,g),!1),c}_wrapWritable(t){const a=[],i=function(){for(let l=0;l<a.length;l++)a[l](t)};return{subscribe:l=>(a.push(l),this._async?setTimeout(l,1,t):l(t),()=>{const c=a.indexOf(l);c>=0&&a.splice(c,1)}),__trigger:()=>{a.length&&(this._async?setTimeout(i,1):i())},__parse:function(l){return t=l,!0}}}},lA=class{constructor(t,a,i,l){typeof t=="function"?this._setter=t:this._setter=t.setState.bind(t),this._routes=a,this._parsers=i,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(c=>{c.in.forEach(u=>{const m=this._triggers.get(u)||[];m.push(c),this._triggers.set(u,m)}),c.out.forEach(u=>{const m=this._sources.get(u)||{};c.in.forEach(h=>m[h]=!0),this._sources.set(u,m)})}),this._routes.forEach(c=>{c.length=Math.max(...c.in.map(u=>Nw(u,this._sources,1)))}),this._bus=l}init(t){const a={};for(const i in t)if(this._prev[i]!==t[i]){const l=this._parsers[i];a[i]=l?l(t[i]):t[i]}this._prev=this._prev?{...this._prev,...t}:{...t},this.setState(a),this._bus&&this._bus.exec("init-state",a)}setStateAsync(t){const a=this._setter(t,Mw);return this._async?Object.assign(this._async.signals,a):this._async={signals:a,timer:setTimeout(this._applyState.bind(this),1)},a}_applyState(){const t=this._async;if(t){this._async=null,this._triggerUpdates(t.signals,[]);for(const a in t.signals){const i=t.signals[a];i&&i()}}}setState(t,a=[]){const i=this._setter(t);return this._triggerUpdates(i,a),i}_triggerUpdates(t,a){const i=Object.keys(t),l=!a.length;a=a||[];for(let c=0;c<i.length;c++){const u=i[c],m=this._triggers.get(u);m&&m.forEach(h=>{a.indexOf(h)==-1&&a.push(h)})}l&&this._execNext(a)}_execNext(t){for(;t.length;){t.sort((i,l)=>i.length<l.length?1:-1);const a=t[t.length-1];t.splice(t.length-1),a.exec(t)}}};function Nw(t,a,i){const l=a.get(t);if(!l)return i;const c=Object.keys(l).map(u=>Nw(u,a,i+1));return Math.max(...c)}var oA=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(t,a,i){let l=this._handlers[t];l?i&&i.intercept?l.unshift(a):l.push(a):l=this._handlers[t]=[a],i&&i.tag&&this._tag.set(a,i.tag)}intercept(t,a,i){this.on(t,a,{...i,intercept:!0})}detach(t){for(const a in this._handlers){const i=this._handlers[a];for(let l=i.length-1;l>=0;l--)this._tag.get(i[l])===t&&i.splice(l,1)}}async exec(t,a){const i=this._handlers[t];if(i)for(let l=0;l<i.length;l++){const c=i[l](a);if(c===!1||c&&c.then&&await c===!1)return}return this._nextHandler&&await this._nextHandler.exec(t,a),a}setNext(t){return this._nextHandler=t}};function cA(t){return a=>a[t]}function uA(t){return(a,i)=>a[t]=i}function Ol(t,a){return(a.getter||cA(a.id))(t)}function Oh(t,a,i){return(a.setter||uA(a.id))(t,i)}function dA(t,a){const i=document.createElement("a");i.href=URL.createObjectURL(t),i.download=a,document.body.appendChild(i),i.click(),document.body.removeChild(i)}function zl(t,a){let i=Ol(t,a)??"";return a.template?i=a.template(i,t,a):a.optionsMap&&(Array.isArray(i)?i=i.map(l=>a.optionsMap.get(l)).join(", "):i=a.optionsMap.get(i)),typeof i>"u"?"":i+""}function fA(t,a){const i=/\n|"|;|,/;let l="";const c=a.rows||`
|
|
13
|
+
`,u=a.cols||" ",m=t._columns,h=t.flatData;a.header!==!1&&m[0].header&&(l=Sb("header",m,l,u,c));for(let g=0;g<h.length;g++){const y=[];for(let x=0;x<m.length;x++){let b=zl(h[g],m[x]);i.test(b)&&(b='"'+b.replace(/"/g,'""')+'"'),y.push(b)}l+=(l?c:"")+y.join(u)}return a.footer!==!1&&m[0].footer&&(l=Sb("footer",m,l,u,c)),l}function Sb(t,a,i,l,c){const u=/\n|"|;|,/;for(let m=0;m<a[0][t].length;m++){const h=[];for(let g=0;g<a.length;g++){let y=(a[g][t][m].text||"")+"";u.test(y)&&(y='"'+y.replace(/"/g,'""')+'"'),h.push(y)}i+=(i?c:"")+h.join(l)}return i}const mA="portrait",hA=100,pA="a4",gA={a3:{width:11.7,height:16.5},a4:{width:8.27,height:11.7},letter:{width:8.5,height:11}};function vA(t,a){const i=[];let l=[],c=0;const u=t.filter(h=>!h.hidden),m=yA(a);return u.forEach((h,g)=>{c+h.width<=m?(c+=h.width,l.push(h)):(l.length&&i.push(l),l=[h],c=h.width),g===u.length-1&&l.length&&i.push(l)}),i}function Cb(t,a,i){const l=[];return t.forEach((c,u)=>{const m=c[a];for(let h=0;h<i.length;h++){l[h]||(l[h]=[]);const g={...m[h]};if(l[h][u]!==null){if(!u&&!g.rowspan&&!g.colspan){let y=1,x=t[u+y][a][h],b=g.width;for(;!x.rowspan&&!x.colspan;)y++,x=t[u+y][a][h],b+=x.width;g.colspan=y,g.width=b,g.height=i[h]}if(l[h].push(g),!g.collapsed&&g.colspan>1){let y=g.colspan-1;if(g.colspan+u>t.length){const x=g.colspan-(g.colspan+u-t.length);g.colspan=x,g.width=t.slice(u,u+y+1).reduce((b,w)=>b+w.width,0),x>1&&(y=x-1)}for(let x=0;x<y;x++)l[h].push(null)}if(g.rowspan>1){const y=g.rowspan;for(let x=1;x<y;x++)l[h+x]||(l[h+x]=[]),l[h+x].push(null)}}}if(c.collapsed)for(let h=0;h<l.length;h++){const g=l[h],y=g[u];if(y&&y.collapsed){if(g[u]=null,!h)break}else{const x=y||g.findLast(b=>b?.colspan>=1);x&&(x.colspan=x.colspan-1,x.width=x.width-c.width)}}}),l.map(c=>c.filter(u=>u&&u.colspan!==0))}function yA(t){const{mode:a,ppi:i,paper:l}=t,{width:c,height:u}=gA[l];return bA(a==="portrait"?c:u,i)}function bA(t,a){return t*a}function xA(t={}){const{mode:a,ppi:i,paper:l}=t;return{mode:a||mA,ppi:i||hA,paper:l||pA}}function Tw(t,a){return t.flexgrow?`min-width:${a}px;width:auto`:`width:${t.width}px; max-width:${t.width}px; height:${t.height}px`}function wA(t,a,i){let l=t[i.id];if(i.filter.type==="richselect"&&l){const c=i.filter.config?.options||a.find(({id:u})=>u==i.id).options;c&&(l=c.find(({id:u})=>u==l).label)}return l??""}const kb=["resize-column","hide-column","update-cell"],SA=["delete-row","update-row","update-cell"],CA=["move-item"],kA=["resize-column","move-item"];class jA{undo=[];redo=[];progress={};in;getState;setState;_previousValues={};constructor(a,i,l){this.in=a,this.getState=i,this.setState=l,this.setHandlers(),this.resetStateHistory()}getHandlers(){return{"add-row":{handler:a=>({action:"delete-row",data:{id:a.id},source:{action:"add-row",data:a}})},"delete-row":{handler:a=>{const{id:i}=a,{data:l}=this.getPrev(),c=l.findIndex(u=>u.id===i);return{action:"add-row",data:{id:i,row:l[c],before:c<l.length-1?l[c+1].id:void 0},source:{action:"delete-row",data:a}}}},"update-cell":{handler:a=>{const{id:i,column:l}=a,c=this.getRow(i),u=this.getColumn(l),m=Ol(c,u);return em(m,a.value)?null:{action:"update-cell",data:{id:i,column:l,value:m},source:{action:"update-cell",data:a}}}},"update-row":{handler:a=>{const{id:i,row:l}=a,c=this.getRow(i);for(const u in l)Object.keys(c).includes(u)||(c[u]=void 0);return{action:"update-row",data:{id:i,row:c},source:{action:"update-row",data:a}}}},"copy-row":{handler:a=>{const{id:i}=a,{data:l}=this.getState(),c=l.findIndex(m=>m.id===i),u=l[c];return{action:"delete-row",data:{id:i},source:{action:"add-row",data:{id:i,row:u,before:c<l.length-1?l[c+1].id:void 0}}}}},"resize-column":{handler:a=>{const{id:i,width:l}=a,c=this.getColumn(i),{_sizes:u}=this.getState();return{action:"resize-column",data:{id:i,width:c.width??u.columnWidth},source:{action:"resize-column",data:{id:i,width:l}}}}},"hide-column":{handler:a=>{const{id:i}=a,l=this.getColumn(i);return{action:"hide-column",data:{id:i,mode:l.hidden},source:{action:"hide-column",data:a}}}},"collapse-column":{handler:a=>{const{id:i,row:l,mode:c}=a;return{action:"collapse-column",data:{id:i,row:l,mode:typeof c=="boolean"?!c:c},source:{action:"collapse-column",data:a}}}},"move-item":{handler:a=>{const{id:i,target:l,mode:c}=a,{flatData:u}=this.getPrev(),m=u.findIndex(h=>h.id===i);return{action:"move-item",data:{id:i,target:u[m+(m?-1:1)].id,mode:m?"after":"before"},source:{action:"move-item",data:{id:i,target:l,mode:c}}}}},"open-row":{handler:a=>{const{id:i,nested:l}=a;return{action:"close-row",data:{id:i,nested:l},source:{action:"open-row",data:a}}}},"close-row":{handler:a=>{const{id:i,nested:l}=a;return{action:"open-row",data:{id:i,nested:l},source:{action:"close-row",data:a}}}}}}resetHistory(){this.undo=[],this.redo=[],this.progress={},this.resetStateHistory()}getPrev(){return this._previousValues}setHandlers(){const a=this.getHandlers();for(const i in a)this.in.intercept(i,l=>{if(!(l.eventSource==="undo"||l.eventSource==="redo"||l.skipUndo)){if(kA.includes(i)){(l.inProgress&&!this.progress[i]||typeof l.inProgress!="boolean")&&(CA.includes(i)&&this.setPrev("flatData"),kb.includes(i)&&this.setPrev("columns")),this.progress[i]=l.inProgress;return}SA.includes(i)&&this.setPrev("data"),kb.includes(i)&&this.setPrev("columns")}}),this.in.on(i,l=>{if(l.eventSource==="undo"||l.eventSource==="redo"||l.skipUndo||l.inProgress)return;const c=a[i].handler(l);c&&this.addToHistory(c)})}setPrev(a){this._previousValues[a]=Sp(this.getState()[a])}addToHistory(a){this.undo.push(a),this.redo=[],this.setStateHistory()}handleUndo(){if(!this.undo.length)return;const a=this.undo.pop();this.redo.push({...a.source,source:a}),this.in.exec(a.action,{...a.data,eventSource:"undo"}),this.setStateHistory()}handleRedo(){if(!this.redo.length)return;const a=this.redo.pop();this.undo.push({...a.source,source:a}),this.in.exec(a.action,{...a.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(a){const{data:i}=this.getPrev();return this.getState().tree?this.getTreeRow(i,a):i.find(l=>l.id===a)}getTreeRow(a,i){for(let l=0;l<a.length;l++){if(a[l].id===i)return a[l];if(a[l].data){const c=this.getTreeRow(a[l].data,i);if(c)return c}}return null}getColumn(a){const{columns:i}=this.getPrev();return i.find(l=>l.id===a)}}function Rw(t,a){return typeof t>"u"||t===null?-1:typeof a>"u"||a===null?1:t===a?0:t>a?1:-1}function AA(t,a){return-Rw(t,a)}function MA(t,a){if(typeof a.sort=="function")return function(l,c){const u=a.sort(l,c);return t==="asc"?u:-u};const i=t==="asc"?Rw:AA;return function(l,c){return i(Ol(l,a),Ol(c,a))}}function NA(t,a){if(!t||!t.length)return;const i=t.map(l=>{const c=a.find(u=>u.id==l.key);return MA(l.order,c)});return t.length===1?i[0]:function(l,c){for(let u=0;u<i.length;u++){const m=i[u](l,c);if(m!==0)return m}return 0}}const vf=28,TA=20;function RA(){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 Bf(t,a,i,l,c){const u=document.createElement("div"),m=document.createElement("div"),h=document.body;c=c?`${c}px`:"auto";let g,y;m.className=a,u.classList.add(`wx-${i}-theme`),u.style.cssText=`height:auto;position:absolute;top:0px;left:100px;overflow:hidden;width=${c};white-space:nowrap;`,u.appendChild(m),h.appendChild(u),typeof t!="object"&&(t=[t]);for(let x=0;x<t.length;x++){m.innerText=t[x]+"";const b=u.getBoundingClientRect(),w=Math.ceil(b.width)+(l&&l.length?l[x]:0),j=Math.ceil(b.height);g=Math.max(g||0,w),y=Math.max(y||0,j)}return u.remove(),{width:g,height:y}}function jb(t,a,i,l,c){const u=[];for(let m=0;m<t.length;m++){const h=t[m][a],g=h.length;for(let y=0;y<g;y++){const{text:x,vertical:b,collapsed:w,rowspan:j,css:A}=h[y];if(!x){u[y]=Math.max(u[y]||0,l);continue}let k=0;if(b&&!w){let T=`wx-measure-cell-${a}`;if(T+=A?` ${A}`:"",k=Bf(x,T,c).width,(j>1||!h[y+1])&&i>y+1){const M=j||i-y,N=u.slice(y,y+M).reduce((L,z)=>L+z,0);if(N<k){const L=Math.ceil((k-N)/M);for(let z=y;z<y+M;z++)u[z]=(u[z]||l)+L}continue}}u[y]=Math.max(u[y]||l,k)}}return u}function EA(t,a,i){const l=[],c=[];let u="wx-measure-cell-body";u+=t.css?` ${t.css}`:"";for(let m=0;m<a.length;m++){const h=a[m],g=zl(h,t);g&&(l.push(g),t.treetoggle?c.push(a[m].$level*vf+(a[m].$count?vf:0)+(t.draggable?vf:0)):t.draggable&&c.push(vf))}return Bf(l,u,i,c).width}function DA(t,a){const i="wx-measure-cell-header",l=t.sort?TA:0;let c=t.header;if(typeof c=="string")return Bf(c,i,a).width+l;let u;Array.isArray(c)||(c=[c]);for(let m=0;m<c.length;m++){const h=c[m],g=typeof h=="string"?h:h.text,y=i+(typeof h=="string"?"":` ${h.css}`);let x=Bf(g,y,a).width;m===c.length-1&&(x+=l),u=Math.max(u||0,x)}return u}const LA={text:(t,a)=>t?t.toString().toLowerCase().indexOf(a.toLowerCase())!==-1:!a,richselect:(t,a)=>typeof a!="number"&&!a?!0:t==a,datepicker:(t,a)=>a?t&&IA(t,a):!0,multiselect:(t,a)=>!a||a?.length===0?!0:Array.isArray(t)?t?.some(i=>a.includes(i)):t&&a.includes(t)};function Ew(t){return LA[t]}function _A(t,a){const i=[];for(const l in t){const c=a.find(g=>g.id==l),{config:u,type:m}=c.header.find(g=>g.filter).filter,h=t[l];i.push(g=>{const y=Ol(g,c);return u?.handler?u.handler(y,h):Ew(m)(y,h)})}return l=>{for(let c=0;c<i.length;c++)if(!i[c](l))return!1;return!0}}function IA(t,a){return t.getFullYear()===a.getFullYear()&&t.getMonth()===a.getMonth()&&t.getDate()===a.getDate()}let zA=class extends iA{in;_router;_branches;_xlsxWorker;_historyManager;constructor(a){super({writable:a,async:!1});const i={rowHeight:37,columnWidth:160,headerHeight:36,footerHeight:36};this._router=new lA(super.setState.bind(this),[{in:["columns","sizes","_skin"],out:["_columns","_sizes"],exec:c=>{const{columns:u,sizes:m,_skin:h}=this.getState(),g=this.copyColumns(u),y=g.reduce((w,j)=>Math.max(j.header.length,w),0),x=g.reduce((w,j)=>Math.max(j.footer.length,w),0);g.forEach(this.setCollapsibleColumns);const b=this.normalizeSizes(g,m,y,x,h);for(let w=0;w<g.length;w++)this.normalizeColumns(g,w,"header",y,b),this.normalizeColumns(g,w,"footer",x,b);this.setState({_columns:g,_sizes:b},c)}},{in:["data","tree","_filterIds"],out:["flatData","_rowHeightFromData"],exec:c=>{const{data:u,tree:m,dynamic:h,_filterIds:g}=this.getState(),y=g&&new Set(g),x=m?this.flattenRows(u,[],g):y?u.filter(w=>y.has(w.id)):u,b=!h&&x.some(w=>w.rowHeight);this.setState({flatData:x,_rowHeightFromData:b},c)}}],{sizes:c=>({...i,...c})});const l=this.in=new oA;l.on("close-editor",({ignore:c})=>{const{editor:u}=this.getState();u&&(c||l.exec("update-cell",u),this.setState({editor:null}))}),l.on("open-editor",({id:c,column:u})=>{let m=this.getState().editor;m&&l.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;m={column:g.id,id:c,value:Ol(h,g)??"",renderedValue:zl(h,g),type:y.type||y},typeof y=="object"&&y.config&&(m.config=y.config,y.config.options&&(m.options=y.config.options)),g.options&&!m.options&&(m.options=g.options),this.setState({editor:m})}}),l.on("editor",({value:c})=>{let u=this.getState().editor;if(u){u={...u},u.value=c;const m=this.getColumn(u.column),h={...this.getRow(u.id)};Oh(h,m,c),u.renderedValue=zl(h,m),this.setState({editor:u})}}),l.on("add-row",c=>{const u=this.getState();let{data:m}=u;const{select:h,_filterIds:g}=u,{row:y,before:x,after:b,select:w}=c;if(c.id=y.id=c.id||y.id||yf(),x||b){const A=x||b,k=m.findIndex(T=>T.id===A);m=[...m],m.splice(k+(b?1:0),0,c.row)}else m=[...m,c.row];const j={data:m};g&&(j._filterIds=[...g,c.id]),this.setState(j),!(typeof w=="boolean"&&!w)&&(w||h)&&l.exec("select-row",{id:y.id,show:!0})}),l.on("delete-row",c=>{const{data:u,selectedRows:m,focusCell:h,editor:g}=this.getState(),{id:y}=c,x={data:u.filter(b=>b.id!==y)};this.isSelected(y)&&(x.selectedRows=m.filter(b=>b!==y)),g?.id===y&&(x.editor=null),this.setState(x),h?.row===y&&this.in.exec("focus-cell",{eventSource:"delete-row"})}),l.on("update-cell",c=>{const u=this.getState();let{data:m}=u;m=[...m];const{tree:h}=u,{id:g,column:y,value:x}=c,b=this.getColumn(y);if(h){const w={...this._branches[g]};Oh(w,b,x);const j=this.updateTreeRow(w);w.$parent===0&&(m=j)}else{const w=m.findIndex(A=>A.id===g),j={...m[w]};Oh(j,b,x),m[w]=j}this.setState({data:m})}),l.on("update-row",c=>{let{data:u}=this.getState();const{id:m,row:h}=c,g=u.findIndex(y=>y.id===m);u=[...u],u[g]={...u[g],...h},this.setState({data:u})}),l.on("select-row",({id:c,toggle:u,range:m,mode:h,show:g,column:y})=>{const x=this.getState(),{focusCell:b}=x;let{selectedRows:w}=x;if(w.length||(m=u=!1),m){const{data:j}=this.getState();let A=j.findIndex(T=>T.id===w[w.length-1]),k=j.findIndex(T=>T.id===c);A>k&&([A,k]=[k,A]),j.slice(A,k+1).forEach(T=>{this.isSelected(T.id)||w.push(T.id)})}else if(u&&this.isSelected(c)){if(h===!0)return;w=w.filter(j=>j!==c)}else if(u){if(h===!1)return;w.push(c)}else w=[c];this.setState({selectedRows:[...w]}),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:m,eventSource:h}=c,{_columns:g,split:y}=this.getState();u&&m?(this.setState({focusCell:{row:u,column:m}}),h!=="click"&&((!y.left||g.findIndex(x=>x.id===c.column)>=y.left)&&(!y.right||g.findIndex(x=>x.id===c.column)<g.length-y.right)?this.in.exec("scroll",{row:u,column:m}):this.in.exec("scroll",{row:u}))):this.setState({focusCell:null})}),l.on("resize-column",c=>{const{id:u,auto:m,maxRows:h,inProgress:g}=c;if(g===!1)return;let y=c.width||0;const x=[...this.getState().columns],b=this.getColumn(u);if(m){if(m==="data"||m===!0){const{flatData:w,_skin:j}=this.getState();let A=w.length;h&&(A=Math.min(h,A));const k=w.slice(0,A);y=EA(b,k,j)}if(m==="header"||m===!0){const{_skin:w}=this.getState();y=Math.max(DA(b,w),y)}}b.width=Math.max(17,y),delete b.flexgrow,this.setState({columns:x})}),l.on("hide-column",c=>{const{id:u,mode:m}=c,h=[...this.getState().columns],g=this.getColumn(u),y=h.reduce((x,b)=>x+(b.hidden?0:1),0);!m||y>1?(g.hidden=!g.hidden,this.setState({columns:h})):c.skipUndo=!0}),l.on("sort-rows",c=>{const{key:u,add:m,sort:h}=c,g=this.getState(),{columns:y,data:x,tree:b}=g;if(h){const N=[...x];N.sort(h),this.setState({data:N});return}const{order:w="asc"}=c;let j=g.sortMarks;const A=Object.keys(j),k=A.length;!m||!k||k===1&&j[u]?j={[u]:{order:w}}:(k===1&&(j[A[0]]={...j[A[0]],index:0}),j={...j,[u]:{order:w,index:typeof m=="number"?m:j[u]?.index??k}});const T=Object.keys(j).sort((N,L)=>j[N].index-j[L].index).map(N=>({key:N,order:j[N].order}));this.setState({sortMarks:j});const M=NA(T,y);if(M){const N=[...x];b?this.sortTree(N,M):N.sort(M),this.setState({data:N})}}),l.on("filter-rows",c=>{const{value:u,key:m,filter:h}=c;if(!Object.keys(c).length){this.setState({filterValues:{},_filterIds:null});return}const g=this.getState(),{data:y,tree:x,_columns:b}=g;let w=g.filterValues;const j={};m&&(w={...w,[m]:u},j.filterValues=w);const A=h??_A(w,b);let k=[];x?k=this.filterTree(y,A,k):y.forEach(T=>{A(T)&&k.push(T.id)}),j._filterIds=k,this.setState(j)}),l.on("collapse-column",c=>{const{id:u,row:m,mode:h}=c,g=[...this.getState().columns],y=this.getColumn(u).header,x=Array.isArray(y)?y[m]:y;typeof x=="object"&&(x.collapsed=h??!x.collapsed,this.setState({columns:g}))}),l.on("move-item",c=>{const{id:u,inProgress:m}=c;let{target:h,mode:g="after"}=c;const{data:y,flatData:x,tree:b}=this.getState(),w=x.findIndex(k=>k.id===u);let j;if(g==="up"||g==="down"){if(g==="up"){if(w===0)return;j=w-1,g="before"}else if(g==="down"){if(w===x.length-1)return;j=w+1,g="after"}h=x[j]&&x[j].id}else j=x.findIndex(k=>k.id===h);if(w===-1||j===-1||m===!1)return;let A;b||(A=this.moveItem(u,h,y,g)),this.setState({data:b?this.normalizeTreeRows(A):A})}),l.on("copy-row",c=>{const{id:u,target:m,mode:h="after"}=c,g=this.getState(),{flatData:y,_filterIds:x}=g;let{data:b}=g;const w=this.getRow(u);if(!w)return;const j={...w,id:yf()};c.id=j.id;const A=y.findIndex(T=>T.id===m);if(A===-1)return;b.splice(A+(h==="after"?1:0),0,j),b=[...b];const k={data:b};x&&(k._filterIds=[...x,j.id]),this.setState(k)}),l.on("open-row",c=>{const{id:u,nested:m}=c;this.toggleBranch(u,!0,m)}),l.on("close-row",c=>{const{id:u,nested:m}=c;this.toggleBranch(u,!1,m)}),l.on("export-data",c=>new Promise((u,m)=>{const h=c.format||"csv",g=`${c.fileName||"data"}.${h}`;if(h==="csv"){const y=fA(this.getState(),c.csv||{});c.download!==!1?dA(new Blob(["\uFEFF"+y],{type:"text/csv"}),g):c.result=y,u(!0)}else m()})),l.on("hotkey",({key:c,event:u,isInput:m})=>{switch(c){case"arrowup":{const{flatData:h,focusCell:g,select:y}=this.getState();if(u.preventDefault(),m)return;const x=g?g.column:this._getFirstVisibleColumn()?.id,b=g?this.getPrevRow(g.row)?.id:h[h.length-1]?.id;x&&b&&(this.in.exec("focus-cell",{row:b,column:x,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(),m)return;const x=g?g.column:this._getFirstVisibleColumn()?.id,b=g?this.getNextRow(g.row)?.id:h[0]?.id;x&&b&&(this.in.exec("focus-cell",{row:b,column:x,eventSource:"key"}),y&&this.in.exec("select-row",{id:b}));break}case"arrowright":{const{focusCell:h}=this.getState();if(m)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(m)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 x=h.column;let b=h.id,w=this.getNextEditor(this.getRow(b),this.getColumn(x));if(!w){const j=this.getNextRow(b);j&&(b=j.id,w=this.getNextEditor(j))}w&&(this.in.exec("open-editor",{id:b,column:w.id}),this.in.exec("focus-cell",{row:b,column:w.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 x=h.column;let b=h.id,w=this.getPrevEditor(this.getRow(b),this.getColumn(x));if(!w){const j=this.getPrevRow(b);j&&(b=j.id,w=this.getPrevEditor(j))}w&&(this.in.exec("open-editor",{id:b,column:w.id}),this.in.exec("focus-cell",{row:b,column:w.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(!m&&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:x}=this.getState();if(!h&&g){u.preventDefault();const b=y[0]?.id,w=this._getFirstVisibleColumn()?.id;b&&w&&(this.in.exec("focus-cell",{row:b,column:w,eventSource:"key"}),x&&!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,x=g.row;this.in.exec("focus-cell",{row:x,column:y,eventSource:"key"})}break}case"ctrl+end":{const{editor:h,focusCell:g,flatData:y,select:x}=this.getState();if(!h&&g){u.preventDefault();const b=y.at(-1).id,w=this._getLastVisibleColumn()?.id;b&&w&&(this.in.exec("focus-cell",{row:b,column:w,eventSource:"key"}),x&&!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}}}),l.on("scroll",c=>{const{_columns:u,split:m,_sizes:h,flatData:g,dynamic:y,_rowHeightFromData:x}=this.getState();let b=-1,w=-1,j=0,A=0;if(c.column){b=0;const k=u.findIndex(T=>T.id===c.column);j=u[k].width;for(let T=m.left??0;T<k;T++){const M=u[T];M.hidden||(b+=M.width)}}if(c.row&&!y){const k=g.findIndex(T=>T.id===c.row);k>=0&&(x?(w=g.slice(0,k).reduce((T,M)=>T+(M.rowHeight||h.rowHeight),0),A=g[k].rowHeight):w=h.rowHeight*k)}this.setState({scroll:{top:w,left:b,width:j,height:A||h.rowHeight}})}),l.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)}),l.on("print",c=>{const u=xA(c);this.setState({_print:u}),this.setStateAsync({_print:null})}),l.on("undo",()=>{this._historyManager?.handleUndo()}),l.on("redo",()=>{this._historyManager?.handleRedo()}),this.initOnce()}getXlsxWorker(a){if(!this._xlsxWorker){const i=window.URL.createObjectURL(new Blob([`importScripts('${a}');`],{type:"text/javascript"}));this._xlsxWorker=new Promise(l=>{const c=new Worker(i);c.addEventListener("message",u=>{u.data.type==="init"&&l(c)})})}return this._xlsxWorker}initOnce(){const a={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(a)}init(a){a.hasOwnProperty("_skin")&&!a._skin&&(a._skin=RA()),a.columns&&a.columns.forEach(i=>{i.options&&(i.optionsMap=new Map(i.options.map(l=>[l.id,l.label])))}),em(this.getState().data,a.data)||(a.tree?a.data=this.normalizeTreeRows(a.data):a.data=this.normalizeRows(a.data),this.setState({_filterIds:null,filterValues:{},sortMarks:{},search:null}),this._historyManager&&this._historyManager.resetHistory()),a.tree&&(a.undo=!1,a.reorder=!1),a.split?.right&&(a.split.right=0),a.undo&&!this._historyManager&&(this._historyManager=new jA(this.in,this.getState.bind(this),this.setState.bind(this))),this._router.init({...a})}setState(a,i){return this._router.setState(a,i)}setStateAsync(a){this._router.setStateAsync(a)}getRow(a){const{tree:i}=this.getState();return i?this._branches[a]:this.getState().data.find(l=>l.id===a)}getRowIndex(a,i){return i||(i=this.getState().flatData),i.findIndex(l=>l.id===a)}getNextRow(a){const i=this.getState().flatData,l=this.getRowIndex(a,i);return i[l+1]}getPrevRow(a){const i=this.getState().flatData,l=this.getRowIndex(a,i);return i[l-1]}getColumn(a){return this.getState().columns.find(i=>i.id===a)}getNextColumn(a,i){const l=this.getState()._columns,c=l.findIndex(u=>u.id===a);return i?this._getFirstVisibleColumn(c+1):l[c+1]}getPrevColumn(a,i){const l=this.getState()._columns,c=l.findIndex(u=>u.id===a);return i?this._getLastVisibleColumn(c-1):l[c-1]}_getFirstVisibleColumn(a){const i=this.getState()._columns;let l=a??0;for(;l<i.length&&(i[l]?.hidden||i[l]?.collapsed);)l++;return i[l]}_getLastVisibleColumn(a){const i=this.getState()._columns;let l=a??i.length-1;for(;l<i.length&&(i[l]?.hidden||i[l]?.collapsed);)l--;return i[l]}isCellEditable(a,i){const{editor:l,hidden:c}=i;return!l||c?!1:typeof l=="function"?l(a,i):!0}getNextEditor(a,i){let l=this.getState().columns;if(i){const c=l.findIndex(u=>u.id===i.id);l=l.slice(c+1)}return l.find(c=>this.isCellEditable(a,c))}getPrevEditor(a,i){let l=this.getState().columns;if(i){const c=l.findLastIndex(u=>u.id===i.id);l=l.slice(0,c)}return l.findLast(c=>this.isCellEditable(a,c))}toggleBranch(a,i,l){let c=this._branches[a],{data:u}=this.getState();if(u=[...u],a!==0){c={...c,open:i};const m=this.updateTreeRow(c);c.$parent===0&&(u=m)}l&&c.data?.length&&c.data.forEach(m=>{const h=this.toggleKids(m,i,l);a===0&&(u=h)}),this.setState({data:u})}toggleKids(a,i,l){a={...a,open:i};const c=this.updateTreeRow(a);return l&&a.data?.length&&a.data.forEach(u=>{this.toggleKids(u,i,l)}),c}updateTreeRow(a){const i=a.id;this._branches[i]=a;const l=this._branches[a.$parent],c=l.data.findIndex(u=>u.id===i);return l.data=[...l.data],l.data[c]=a,l.data}isSelected(a){return this.getState().selectedRows.indexOf(a)!==-1}findAndRemove(a,i){for(let l=0;l<a.length;l++){if(a[l].id===i)return a.splice(l,1)[0];if(a[l].data){const c=[...a[l].data],u=this.findAndRemove(c,i);if(u)return a[l]={...a[l],data:c},u}}return null}insertItem(a,i,l,c){for(let u=0;u<a.length;u++){if(a[u].id===i){const m=a[u],h=c==="before"?u:u+1;if(m.data){if(c==="before"){const g=u>0?a[u-1]:null;return g?.data&&g.open?a[u-1]={...g,data:[...g.data,l]}:a.splice(h,0,l),!0}else if(m.open)return a[u]={...m,data:[l,...m.data]},!0}return a.splice(h,0,l),!0}if(a[u].data&&(a[u]={...a[u],data:[...a[u].data]},this.insertItem(a[u].data,i,l,c)))return!0}return!1}moveItem(a,i,l,c){const u=[...l],m=this.findAndRemove(u,a);return this.insertItem(u,i,m,c),u}copyColumns(a){const i=[];for(let l=0;l<a.length;l++){const c={...a[l]};this.copyHeaderFooter(c,"header"),this.copyHeaderFooter(c,"footer"),i[l]=c}return i}copyHeaderFooter(a,i){let l=a[i];l=Array.isArray(l)?[...l]:[l],l.forEach((c,u)=>{l[u]=typeof c=="string"?{text:c}:{...c}}),a[i]=l}setCollapsibleColumns(a,i,l){let c=a.header;for(let u=0;u<c.length;u++){const m=c[u];if(m.collapsible&&m.collapsed){if(m.collapsible!=="first"){a.collapsed=!0,a.width=36,m.vertical=!0;const g=c.length-u;c=c.slice(0,u+1),c[u].rowspan=g}const h=m.colspan;if(h){const g=c[u+1];let y=1;g&&g.colspan&&!g.collapsed&&(y=g.colspan);for(let x=y;x<h;x++){const b=l[i+x];b&&(b.hidden=!0)}}}}}normalizeColumns(a,i,l,c,u){const m=a[i];m.width||(m.width=m.flexgrow?17:u.columnWidth),m._colindex=i+1;const h=m[l],g=u[`${l}RowHeights`];for(let y=0;y<c;y++){const x=h[y];x.id=m.id,y===h.length-1&&(x.rowspan=x.rowspan?Math.min(x.rowspan,c-y):c-y);for(let b=1;b<x.rowspan;b++){h.splice(y+b,0,{_hidden:!0});for(let w=1;w<x.colspan;w++)a[i+w][l].splice(y+b,0,{})}if(x.rowspan){const b=(x.rowspan===c?g:g.slice(y,x.rowspan+y)).reduce((w,j)=>w+j,0);x.height=b,y+x.rowspan!=c&&x.height--}if(x.colspan){let b=m.width,w=m.flexgrow||0;const j=x.colspan;for(let A=1;A<j;A++){const k=a[i+A];k&&(k.hidden?x.colspan-=1:k.flexgrow?w+=k.flexgrow:b+=k.width||u.columnWidth),w?x.flexgrow=w:x.width=b}}else x.width=m.width,x.flexgrow=m.flexgrow;l==="header"&&x.filter&&typeof x.filter=="string"&&(x.filter={type:x.filter})}h.length>c&&(h.length=c),m[l]=h}normalizeRows(a){for(let i=0;i<a.length;i++)a[i].id||(a[i].id=yf());return a}normalizeTreeRows(a,i,l){return!i&&!l&&(this._branches={0:{data:a}}),a.forEach(c=>{c.id||(c.id=yf()),c.$level=i||0,c.$parent=l||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))}),a}sortTree(a,i){a.sort(i),a.forEach(l=>{l.data&&this.sortTree(l.data,i)})}filterTree(a,i,l){return a.forEach(c=>{i(c)&&l.push(c.id),c.data&&this.filterTree(c.data,i,l)}),l}flattenRows(a,i,l){const c=i;return a.forEach(u=>{(!l||l.includes(u.id))&&c.push(u),u.data?.length&&u.open!==!1&&this.flattenRows(u.data,c,l)}),c}createFilter(a){const{_columns:i}=this.getState(),l=[];for(const c in a){const u=i.find(y=>y.id==c),{config:m,type:h}=u.header.find(y=>y.filter).filter,g=a[c];l.push(y=>{const x=Ol(y,u);return m?.handler?m.handler(x,g):Ew(h)(x,g)})}return c=>{for(let u=0;u<l.length;u++)if(!l[u](c))return!1;return!0}}searchRows(a,i){a=a.trim().toLowerCase();const l={};if(!a)return l;const{flatData:c,columns:u}=this.getState(),m=i?u.filter(h=>i[h.id]):u;return c.forEach(h=>{const g={};m.forEach(y=>{const x=zl(h,y);String(x).toLowerCase().includes(a)&&(g[y.id]=!0)}),Object.keys(g).length&&(l[h.id]=g)}),l}normalizeSizes(a,i,l,c,u){const m=jb(a,"header",l,i.headerHeight,u),h=jb(a,"footer",c,i.footerHeight,u),g=m.reduce((x,b)=>x+b,0),y=h.reduce((x,b)=>x+b,0);return{...i,headerRowHeights:m,footerRowHeights:h,headerHeight:g,footerHeight:y}}},OA=new Date().valueOf();function yf(){return"temp://"+OA++}function HA(t,a="data-id"){let i=t;for(!i.tagName&&t.target&&(i=t.target);i;){if(i.getAttribute&&i.getAttribute(a))return i;i=i.parentNode}return null}new Date().valueOf();var FA=class{constructor(){this.store=new Map}configure(t,a){this.node=a;for(const i in t)if(t[i]){const l=i.toLowerCase().replace(/[ ]/g,""),c=t[i];this.store.set(l,c)}}},jc=[],PA={subscribe:t=>{$A();const a=new FA;return jc.push(a),t(a),()=>{const i=jc.findIndex(l=>l===a);i>=0&&jc.splice(i,1)}}},Ab=!1;function $A(){Ab||(Ab=!0,document.addEventListener("keydown",t=>{if(jc.length&&(t.ctrlKey||t.altKey||t.metaKey||t.shiftKey||t.key.length>1||t.key===" ")){const a=[];t.ctrlKey&&a.push("ctrl"),t.altKey&&a.push("alt"),t.metaKey&&a.push("meta"),t.shiftKey&&a.push("shift");let i=t.code.replace("Key","").toLocaleLowerCase();t.key===" "&&(i="space"),a.push(i);const l=a.join("+");for(let c=jc.length-1;c>=0;c--){const u=jc[c],m=u.store.get(l)||u.store.get(i);m&&u.node.contains(t.target)&&m(t,{key:l,evKey:i})}}}))}const BA={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 UA(t,{keys:a,exec:i}){if(!a)return;function l(m){const h=m.target;return h.tagName==="INPUT"||h.tagName==="TEXTAREA"||HA(h,"data-header-id")?.classList.contains("wx-filter")||!!h.closest(".wx-cell.wx-editor")}const c={};for(const m in a){const h=a[m];typeof h<"u"&&(typeof h=="function"?c[m]=h:h&&(c[m]=g=>{const y=l(g);i({key:m,event:g,isInput:y})}))}const u=PA.subscribe(m=>{m.configure(c,t)});return{destroy:()=>{u()}}}function qA(t,a){let i=null;a.scroll.subscribe(l=>{if(!l||l===i)return;i=l;const{left:c,top:u,height:m,width:h}=l,g=a.getHeight(),y=a.getWidth(),x=a.getScrollMargin();if(u>=0){const b=t.scrollTop;u<b?t.scrollTop=u:u+m>b+g&&(t.scrollTop=u-g+m)}if(c>=0){const b=t.scrollLeft;c<b?t.scrollLeft=c:c+h>b+y-x&&(t.scrollLeft=c-y+h+x)}}),a.scrollLeft?.subscribe?.(l=>{requestAnimationFrame(()=>{Math.abs(t.scrollLeft-l)>1&&(t.scrollLeft=l)})}),a.scrollTop?.subscribe?.(l=>{requestAnimationFrame(()=>{Math.abs(t.scrollTop-l)>1&&(t.scrollTop=l)})})}const ws=d.createContext(null);function GA(t,a){const i=new ResizeObserver(l=>{requestAnimationFrame(()=>a(l[0].contentRect))});return i.observe(t.parentNode),{destroy(){i.disconnect()}}}const Mb=5,VA=700;function Df(t){const a=t.getBoundingClientRect(),i=document.body,l=a.top+i.scrollTop-i.clientTop||0,c=a.left+i.scrollLeft-i.clientLeft||0;return{y:Math.round(l),x:Math.round(c),width:t.offsetWidth,height:t.offsetHeight}}function Cp(t,a){const i=Df(a);return{x:t.clientX-i.x,y:t.clientY-i.y}}function WA(t,a){const i=a.current;let l=null,c,u,m=!1,h=!1;const g=document.createElement("DIV");g.className="wx-drag-zone",g.setAttribute("tabindex",-1);function y(){clearTimeout(c),c=null}function x(_){const Y=Rc(_);Y&&(l={container:g,sourceNode:_.target,from:Xf(Y),pos:Cp(_,t)},u=l.pos,b(_))}function b(_){if(!l)return;const Y=l.pos=Cp(_,t);if(!m){if(!h&&!_?.target?.getAttribute("draggable-data")&&Math.abs(u.x-Y.x)<Mb&&Math.abs(u.y-Y.y)<Mb)return;if(H(_)===!1)return G()}if(h){const q=window.scrollX||document.documentElement.scrollLeft||document.body.scrollLeft,U=window.scrollY||document.documentElement.scrollTop||document.body.scrollTop;l.targetNode=document.elementFromPoint(_.pageX-q,_.pageY-U)}else l.targetNode=_.target;i.move&&i.move(_,l),g.style.left=-(l.offset?l.offset.x:0)+"px",g.style.top=l.pos.y+(l.offset?l.offset.y:0)+"px"}function w(_){g.parentNode&&g.parentNode.removeChild(g),g.innerHTML="",m&&i.end&&i.end(_,l),l=u=null,G()}function j(_){i.getReorder&&!i.getReorder()||_.button===0&&(z(_),window.addEventListener("mousemove",A),window.addEventListener("mouseup",k),x(_))}function A(_){b(_)}function k(_){w(_)}function T(_){if(i.getReorder&&!i.getReorder())return;c=setTimeout(()=>{h=!0,x(_.touches[0])},VA),z(_);function Y(){c&&y(),_.target.removeEventListener("touchmove",M),_.target.removeEventListener("touchend",Y),w(_)}_.target.addEventListener("touchmove",M),_.target.addEventListener("touchend",Y),t.addEventListener("contextmenu",N)}function M(_){m?(_.preventDefault(),b(_.touches[0])):c&&y()}function N(_){if(m||c)return _.preventDefault(),!1}function L(_){_.preventDefault()}function z(_){if(!i.getDraggableInfo)return;const{hasDraggable:Y}=i.getDraggableInfo();(!Y||_.target.getAttribute("draggable-data"))&&(document.body.style.userSelect="none",document.body.style.webkitUserSelect="none")}function H(_){if(m=!0,i.start){if(i.start(_,l)===!1)return!1;t.appendChild(g),document.body.style.cursor="move"}}function G(_){m=h=!1,document.body.style.cursor="",document.body.style.userSelect="",document.body.style.webkitUserSelect="",window.removeEventListener("mousemove",A),window.removeEventListener("mouseup",k),_&&(t.removeEventListener("mousedown",j),t.removeEventListener("touchstart",T),t.removeEventListener("dragstart",L))}return t.addEventListener("mousedown",j),t.addEventListener("touchstart",T),t.addEventListener("dragstart",L),{destroy(){G(!0)}}}const KA=.004;function YA(){return{dirX:0,dirY:0,scrollSpeedFactor:1}}function QA(t,a,i,l){const{node:c,left:u,top:m,bottom:h,sense:g,xScroll:y,yScroll:x}=l,b=Cp(t,c);i.scrollState||(i.scrollState=YA());let w=0,j=0;b.x<u+g?w=-1:b.x>a.width-g&&(w=1),b.y<m+Math.round(g/2)?j=-1:b.y>a.height-h-Math.round(g/2)&&(j=1),(i.scrollState.dirX!==w||i.scrollState.dirY!==j)&&(Dw(i),i.scrollState.dirX=w,i.scrollState.dirY=j),(y&&i.scrollState.dirX!==0||x&&i.scrollState.dirY!==0)&&XA(i,l,{x:i.scrollState.dirX,y:i.scrollState.dirY})}function XA(t,a,i){t.autoScrollTimer||(t.autoScrollTimer=setTimeout(()=>{t.activeAutoScroll=setInterval(ZA,15,t,a,i)},250))}function Dw(t){t.scrollSpeedFactor=1,t.autoScrollTimer&&(t.autoScrollTimer=clearTimeout(t.autoScrollTimer),t.activeAutoScroll=clearInterval(t.activeAutoScroll))}function ZA(t,a,i){const{x:l,y:c}=i;t.scrollSpeedFactor+=KA,l!==0&&eM(t,a,l),c!==0&&JA(t,a,c)}function JA(t,a,i){const l=a.node.scrollTop;Lw(l+Math.round(a.sense/3)*t.scrollSpeedFactor*i,"scrollTop",a)}function eM(t,a,i){const l=a.node.scrollLeft;Lw(l+Math.round(a.sense/3)*t.scrollSpeedFactor*i,"scrollLeft",a)}function Lw(t,a,i){i.node[a]=t}function tm(t,a,i,l,c,u){const m={};return t&&(m.width=`${t}px`,m.minWidth=`${t}px`),a&&(m.flexGrow=a),u&&(m.height=`${u}px`),i&&(m.position="sticky",i.left&&(m.left=`${l}px`),i.right&&(m.right=`${c}px`)),m}function _w(t,a,i){let l="";if(t.fixed)for(const c in t.fixed){let u=t.fixed[c]===-1;!u&&t.fixed.leftSize&&a.colspan&&(u=a.colspan+t._colindex-1===t.fixed.leftSize),l+=u?"wx-shadow ":"wx-fixed "}return l+=a.rowspan>1?"wx-rowspan ":"",l+=a.colspan>1?"wx-colspan ":"",l+=a.vertical?"wx-vertical ":"",l+=i?i(t)+" ":"",l}function tM(t){const{row:a,column:i,cellStyle:l=null,columnStyle:c=null,children:u,focusable:m}=t,h=d.useContext(ws),g=gt(h,"focusCell"),y=gt(h,"search"),x=gt(h,"reorder"),b=d.useMemo(()=>y?.rows[a.id]&&y.rows[a.id][i.id],[y,a.id,i.id]),w=d.useMemo(()=>tm(i.width,i.flexgrow,i.fixed,i.left,i.right),[i.width,i.flexgrow,i.fixed,i.left,i.right]);function j(H,G){let _="wx-cell";return _+=i.fixed?" "+(i.fixed===-1?"wx-shadow":"wx-fixed"):"",_+=H?" "+H(i):"",_+=G?" "+G(a,i):"",_+=i.treetoggle?" wx-tree-cell":"",_}const A=d.useMemo(()=>j(c,l),[c,l,i,a]),k=d.useMemo(()=>typeof i.draggable=="function"?i.draggable(a,i)!==!1:i.draggable,[i,a]),T=d.useRef(null);d.useEffect(()=>{T.current&&m&&g?.row===a.id&&g?.column===i.id&&T.current.focus()},[g,m,a.id,i.id]);const M=d.useCallback(()=>{m&&!g&&h.exec("focus-cell",{row:a.id,column:i.id,eventSource:"focus"})},[h,m,g,a.id,i.id]);function N(H){const G=new RegExp(`(${y.value.trim()})`,"gi");return String(H).split(G).map(_=>({text:_,highlight:G.test(_)}))}const L=d.useMemo(()=>{const H=i.fixed&&i.fixed.left===-1||i.fixed.right===-1,G=i.fixed&&i.fixed.right;return[A,H?"wx-shadow":"",G?"wx-fixed-right":""].filter(Boolean).join(" ")},[A,i]),z=i.cell;return r.jsxs("div",{className:"wx-TSCaXsGV "+L,ref:T,onFocus:M,style:w,"data-row-id":na(a.id),"data-col-id":na(i.id),tabIndex:m?"0":"-1",role:"gridcell","aria-colindex":i._colindex,"aria-readonly":i.editor?void 0:!0,children:[x&&i.draggable?k?r.jsx("i",{"draggable-data":"true",className:"wx-TSCaXsGV wx-draggable wxi-drag"}):r.jsx("i",{className:"wx-TSCaXsGV wx-draggable-stub"}):null,i.treetoggle?r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{marginLeft:`${a.$level*28}px`}}),a.$count?r.jsx("i",{"data-action":"toggle-row",className:`wx-TSCaXsGV wx-table-tree-toggle wxi-menu-${a.open!==!1?"down":"right"}`}):null]}):null,z?r.jsx(z,{api:h,row:a,column:i,onAction:({action:H,data:G})=>h.exec(H,G)}):u?u():b?r.jsx("span",{children:N(zl(a,i)).map(({highlight:H,text:G},_)=>H?r.jsx("mark",{className:"wx-TSCaXsGV wx-search",children:G},_):r.jsx("span",{children:G},_))}):zl(a,i)]})}function Nb(t,a){let i,l;function c(h){i=h.clientX,t.style.opacity=1,document.body.style.cursor="ew-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",u),window.addEventListener("mouseup",m),a&&a.down&&a.down(t)}function u(h){l=h.clientX-i,a&&a.move&&a.move(l)}function m(){t.style.opacity="",document.body.style.cursor="",document.body.style.userSelect="",a&&a.up&&a.up(l),window.removeEventListener("mousemove",u),window.removeEventListener("mouseup",m)}return t.addEventListener("mousedown",c),{destroy(){t.removeEventListener("mousedown",c)}}}function nM({filter:t,column:a,action:i,filterValue:l}){function c({value:u}){i({value:u,key:a.id})}return r.jsx(Vp,{...t.config??{},value:l,onChange:c})}function aM({filter:t,column:a,action:i,filterValue:l}){const c=d.useContext(ws),u=gt(c,"flatData"),m=d.useMemo(()=>t?.config?.options||a?.options||g(),[t,a,u]),h=d.useMemo(()=>t?.config?.template,[t]);function g(){const b=[];return u.forEach(w=>{const j=Ol(w,a);b.includes(j)||b.push(j)}),b.map(w=>({id:w,label:w}))}function y({value:b}){i({value:b,key:a.id})}function x(b){b.key!=="Tab"&&b.preventDefault()}return r.jsx("div",{style:{width:"100%"},onKeyDown:x,children:r.jsx(vj,{placeholder:"",clear:!0,...t?.config??{},options:m,value:l,onChange:y,children:b=>h?h(b):b.label})})}function sM({filter:t,column:a,action:i,filterValue:l}){function c({value:u}){i({value:u,key:a.id})}return r.jsx("div",{className:"wx-aaaK5VYO",style:{width:"100%"},children:r.jsx(gj,{placeholder:"",clear:!0,...t?.config??{},value:l,onChange:c})})}function Iw(t){const{value:a,options:i=[],placeholder:l="",clear:c=!1,text:u=null,template:m=null,cell:h=null,dropdown:g={},autoOpen:y=!1,onChange:x,onAction:b}=t,[w,j]=bw(a||[]),A=d.useMemo(()=>(w||[]).map(U=>i.find(K=>K.id===U)).filter(Boolean),[w,i]),k=d.useRef(null),T=d.useRef(null),[M,N]=d.useState(null),L=()=>{const U=w||[];if(!U.length)return 0;const K=i.find(O=>U.includes(O.id));return K?i.indexOf(K):0};function z(U){T.current=U.navigate,N(()=>U.keydown),y&&U.navigate(L())}d.useEffect(()=>{y&&(k.current?.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges())},[]);function H({id:U}){j(U),x&&x({value:U})}function G(U){U.stopPropagation(),j([]),x&&x({value:[]})}function _(){T.current?.(L())}function Y(){T.current?.(null)}function q(U){M?.(U,L())}return r.jsxs("div",{ref:k,className:"wx-multiselect wx-aadNNOwy",onClick:_,onKeyDown:q,tabIndex:0,children:[r.jsx("div",{className:"wx-label wx-aadNNOwy",children:m?m(A):h?r.jsx(h,{data:A,onAction:b}):u?r.jsx("span",{className:"wx-text wx-aadNNOwy",children:u}):A.length?r.jsx("span",{className:"wx-text wx-aadNNOwy",children:A.map(U=>U.label).join(", ")}):l?r.jsx("span",{className:"wx-placeholder wx-aadNNOwy",children:l}):" "}),c&&w?.length?r.jsx("i",{className:"wx-icon wxi-close wx-aadNNOwy",onClick:G}):r.jsx("i",{className:"wx-icon wxi-angle-down wx-aadNNOwy"}),r.jsx(Jf,{items:i,onReady:z,onSelect:H,multiselect:!0,checkboxes:!0,value:w||[],onCancel:Y,...g,children:({option:U})=>r.jsx("div",{className:"wx-option wx-aadNNOwy",children:m?m(U):h?r.jsx(h,{data:U,onAction:b}):U.label})})]})}function rM({filter:t,column:a,action:i,filterValue:l}){const c=d.useContext(sa.i18n)?.getGroup("grid")||ed(Yp).getGroup("grid"),u=d.useMemo(()=>({clear:!0,...t?.config||{}}),[t]),m=d.useMemo(()=>u.options||a.options,[u,a]),h=d.useMemo(()=>{const x=l?.length;return x?x<3?l.map(b=>a.optionsMap.get(b)).join(", "):x+" "+c("selected"):""},[l,a,c]);function g({value:x}){i({value:x,key:a.id})}function y(x){x.key!=="Tab"&&x.preventDefault()}return r.jsx("div",{style:{width:"100%"},onKeyDown:y,children:r.jsx(Iw,{placeholder:"",...u,options:m,value:l||[],text:h,onChange:g})})}const iM={text:nM,richselect:aM,datepicker:sM,multiselect:rM};function lM({filter:t,column:a}){const i=d.useContext(ws),l=gt(i,"filterValues");function c(m){i.exec("filter-rows",m)}const u=d.useMemo(()=>iM[t.type],[t.type]);return r.jsx(u,{filter:t,column:a,action:c,filterValue:l[a.id]})}function oM(t){const{cell:a,column:i,row:l,lastRow:c,sortRow:u,columnStyle:m,bodyHeight:h,hasSplit:g}=t,y=d.useContext(ws),x=gt(y,"sortMarks"),b=d.useMemo(()=>x?x[i.id]:void 0,[x,i.id]),w=d.useRef(),j=d.useCallback(me=>{w.current=a.flexgrow?me.parentNode.clientWidth:a.width},[a.flexgrow,a.width]),A=d.useCallback((me,Z)=>{y.exec("resize-column",{id:a.id,width:Math.max(1,(w.current||0)+me),inProgress:Z})},[y,a.id]),k=d.useCallback(me=>A(me,!0),[A]),T=d.useCallback(me=>A(me,!1),[A]),M=d.useCallback(me=>{if(!i.sort||a.filter)return;let Z=b?.order;Z&&(Z=Z==="asc"?"desc":"asc"),y.exec("sort-rows",{key:a.id,add:me.ctrlKey||me.metaKey,order:Z})},[y,a.id,a.filter,i.sort,b?.order]),N=d.useCallback(me=>{me&&me.stopPropagation(),y.exec("collapse-column",{id:a.id,row:l})},[y,a.id,l]),L=d.useCallback(me=>{me.key==="Enter"&&N()},[N]),z=d.useCallback(me=>{me.key==="Enter"&&!a.filter&&M(me)},[M,a.filter]),H=d.useMemo(()=>a.collapsed&&i.collapsed,[a.collapsed,i.collapsed]),G=d.useMemo(()=>H&&!g&&a.collapsible!=="header",[H,g,a.collapsible]),_=d.useMemo(()=>G?{top:-h/2,position:"absolute"}:{},[G,h]),Y=d.useMemo(()=>tm(a.width,a.flexgrow,i.fixed,i.left,a.right??i.right,a.height+(H&&G?h:0)),[a.width,a.flexgrow,i.fixed,i.left,a.right,i.right,a.height,H,G,h]),q=d.useMemo(()=>_w(i,a,m),[i,a,m]),U=d.useCallback(()=>Object.fromEntries(Object.entries(a).filter(([me])=>me!=="cell")),[a]),K=`wx-cell ${q} ${a.css||""} wx-collapsed`,O=["wx-cell",q,a.css||"",a.filter?"wx-filter":"",i.fixed&&i.fixed.right?"wx-fixed-right":""].filter(Boolean).join(" "),ve=d.useRef(null);return d.useEffect(()=>{const me=ve.current;if(!me)return;const Z=Nb(me,{down:j,move:k,up:T});return()=>{typeof Z=="function"&&Z()}},[j,k,T,Nb]),H?r.jsx("div",{className:"wx-RsQD74qC "+K,style:Y,role:"button","aria-label":`Expand column ${a.text||""}`,"aria-expanded":!a.collapsed,tabIndex:0,onKeyDown:L,onClick:N,"data-header-id":na(i.id),children:r.jsx("div",{className:"wx-RsQD74qC wx-text",style:_,children:a.text||""})}):r.jsxs("div",{className:"wx-RsQD74qC "+O,style:Y,onClick:M,"data-header-id":na(i.id),tabIndex:!a._hidden&&i.sort&&!a.filter?0:void 0,role:"columnheader","aria-colindex":i._colindex,"aria-colspan":a.colspan>1?a.colspan:void 0,"aria-rowspan":a.rowspan>1?a.rowspan:void 0,"aria-sort":!b?.order||a.filter?"none":b?.order==="asc"?"ascending":"descending",onKeyDown:z,children:[a.collapsible?r.jsx("div",{className:"wx-RsQD74qC wx-collapse",role:"button","aria-label":a.collapsed?"Expand column":"Collapse column","aria-expanded":!a.collapsed,tabIndex:0,onKeyDown:L,onClick:N,children:r.jsx("i",{className:`wx-RsQD74qC wxi-angle-${a.collapsed?"down":"right"}`})}):null,a.cell?(()=>{const me=a.cell;return r.jsx(me,{api:y,cell:U(),column:i,row:l,onAction:({action:Z,data:I})=>y.exec(Z,I)})})():a.filter?r.jsx(lM,{filter:a.filter,column:i}):r.jsx("div",{className:"wx-RsQD74qC wx-text",children:a.text||""}),i.resize&&c&&!a._hidden?r.jsx("div",{className:"wx-RsQD74qC wx-grip",role:"presentation","aria-label":"Resize column",ref:ve,onClick:me=>me.stopPropagation(),children:r.jsx("div",{})}):null,u?r.jsx("div",{className:"wx-RsQD74qC wx-sort",children:b?r.jsxs(r.Fragment,{children:[typeof b.index<"u"?r.jsx("div",{className:"wx-RsQD74qC wx-order",children:b.index+1}):null,r.jsx("i",{className:`wx-RsQD74qC wxi-arrow-${b.order==="asc"?"up":"down"}`})]}):null}):null]})}function cM({cell:t,column:a,row:i,columnStyle:l}){const c=d.useContext(ws),u=d.useMemo(()=>tm(t?.width,t?.flexgrow,a?.fixed,a?.left,t?.right??a?.right,t?.height),[t?.width,t?.flexgrow,a?.fixed,a?.left,t?.right,a?.right,t?.height]),m=d.useMemo(()=>_w(a,t,l),[a,t,l]),h=d.useCallback(()=>Object.fromEntries(Object.entries(t||{}).filter(([y])=>y!=="cell")),[t]),g=`wx-6Sdi3Dfd wx-cell ${m||""} ${t?.css||""}`+(a?.fixed&&a?.fixed.right?" wx-fixed-right":"");return r.jsx("div",{className:g,style:u,children:!a?.collapsed&&!t?.collapsed?t?.cell?Dp.createElement(t.cell,{api:c,cell:h(),column:a,row:i,onAction:({action:y,data:x})=>c.exec(y,x)}):r.jsx("div",{className:"wx-6Sdi3Dfd wx-text",children:t?.text||""}):null})}function Tb({deltaLeft:t,contentWidth:a,columns:i,type:l="header",columnStyle:c,bodyHeight:u}){const m=d.useContext(ws),h=gt(m,"_sizes"),g=gt(m,"split"),y=d.useMemo(()=>h?.[`${l}RowHeights`],[h,l]),x=d.useMemo(()=>{let k=[];if(i&&i.length){const T=i[0][l].length;for(let M=0;M<T;M++){let N=0;k.push([]),i.forEach((L,z)=>{const H={...L[l][M]};N||k[M].push(H),H.colspan>1?N=H.colspan-1:N&&N--})}}return k},[i,l]),b=d.useMemo(()=>g?.left||g?.right,[g]);function w(k){return i.find(T=>T.id===k)}function j(k,T){let M=T;return k.rowspan&&(M+=k.rowspan-1),M===x.length-1}function A(k,T,M){if(!M.sort)return!1;for(let N=x.length-1;N>=0;N--){const L=M.header[N];if(!L.filter&&!L._hidden)return T===N}return j(k,T)}return r.jsx("div",{className:`wx-sAsPVaUK wx-${l}`,style:{paddingLeft:`${t}px`,width:`${a}px`},role:"rowgroup",children:x.map((k,T)=>r.jsx("div",{className:l==="header"?"wx-sAsPVaUK wx-h-row":"wx-sAsPVaUK wx-f-row",style:{height:`${y?.[T]}px`,display:"flex"},role:"row",children:k.map(M=>{const N=w(M.id);return l==="header"?r.jsx(oM,{cell:M,columnStyle:c,column:N,row:T,lastRow:j(M,T),bodyHeight:u,sortRow:A(M,T,N),hasSplit:b},M.id):r.jsx(cM,{cell:M,columnStyle:c,column:w(M.id),row:T},M.id)})},T))})}function uM({overlay:t}){const a=d.useContext(ws);function i(c){return typeof c=="function"}const l=t;return r.jsx("div",{className:"wx-1ty666CQ wx-overlay",children:i(t)?r.jsx(l,{onAction:({action:c,data:u})=>a.exec(c,u)}):t})}function dM(t){const{editor:a,onSave:i,onApply:l}=t,[c,u]=d.useState(a?.value||""),{type:m="text"}=d.useMemo(()=>a?.config||{},[a]),h=d.useRef(null);d.useEffect(()=>{h.current&&h.current.focus()},[]),d.useEffect(()=>{if(!h.current)return;const x=Pr(h.current,()=>i(!0));return()=>x.destroy()},[i]);function g(){h.current&&(u(h.current.value),l(h.current.value))}function y({key:x}){x==="Enter"&&i()}return r.jsx("input",{className:"wx-e7Ao5ejY wx-text",onInput:g,onKeyDown:y,ref:h,type:m,value:c})}function fM({editor:t,onAction:a,onSave:i,onApply:l,onCancel:c}){const[u,m]=d.useState(t?.value),[h,g]=d.useState(t?.renderedValue),[y,x]=d.useState(t?.options||[]),b=d.useMemo(()=>t?.config?.template,[t]),w=d.useMemo(()=>t?.config?.cell,[t]),j=d.useMemo(()=>t?.config?.dropdown||{},[t]),A=d.useMemo(()=>({trackScroll:!0,...j}),[j]),k=d.useMemo(()=>(y||[]).findIndex(_=>_.id===u),[y,u]),T=d.useRef(null),M=d.useRef(null),N=d.useCallback(_=>{T.current=_.navigate,M.current=_.keydown,T.current(k)},[k,T]),L=d.useCallback(_=>{const Y=_?.target?.value??"";g(Y);const q=Y?(t?.options||[]).filter(U=>(U.label||"").toLowerCase().includes(Y.toLowerCase())):t?.options||[];x(q),q.length?T.current(-1/0):T.current(null)},[t]),z=d.useRef(null);d.useEffect(()=>{z.current&&z.current.focus()},[]);const H=d.useRef(i);d.useEffect(()=>{H.current=i},[i]),d.useEffect(()=>{if(!z.current)return;const _=Pr(z.current,()=>H.current(!0));return()=>_.destroy()},[]),d.useEffect(()=>{m(t?.value),g(t?.renderedValue),x(t?.options||[])},[t]);const G=d.useCallback(({id:_})=>{l(_),i()},[l,i]);return r.jsxs(r.Fragment,{children:[r.jsx("input",{className:"wx-0UYfSd1x wx-input",ref:z,value:h??"",onChange:L,onKeyDown:_=>M.current?M.current(_,k):void 0}),r.jsx(Jf,{items:y,onReady:N,onSelect:G,...A,onCancel:c,children:({option:_})=>b?b(_):w?r.jsx(w,{data:_,onAction:a}):_.label})]})}function mM({editor:t,onAction:a,onSave:i,onApply:l,onCancel:c}){const[u]=d.useState(()=>t.value||new Date),{template:m,cell:h,dropdown:g={}}=t?.config||{},y=d.useMemo(()=>({trackScroll:!0,width:"auto",...g}),[g]);function x({value:A}){l(A),i()}const b=d.useRef(null),[w,j]=d.useState(null);return d.useEffect(()=>{b.current&&b.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),d.useEffect(()=>{if(!w)return;const A=Pr(w,()=>i(!0));return()=>A.destroy()},[w,i]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-lNWNYUb6 wx-value",ref:b,tabIndex:0,onClick:c,onKeyDown:A=>A.preventDefault(),children:m?m(u):h?r.jsx(h,{data:t.value,onAction:a}):r.jsx("span",{className:"wx-lNWNYUb6 wx-text",children:t.renderedValue})}),r.jsx(Gp,{...y,onCancel:c,children:r.jsx("div",{ref:j,className:"wx-lNWNYUb6",children:r.jsx(hw,{value:u,onChange:x,buttons:t.config?.buttons})})})]})}function hM(t){const{editor:a}=t,i=t.onAction??t.onaction,l=t.onSave??t.onsave,c=t.onApply??t.onapply,u=t.onCancel??t.oncancel,m=a.config||{},{dropdown:h={}}=m,g=d.useMemo(()=>({trackScroll:!0,...h}),[h]),[y]=d.useState(a.options.find(L=>L.id===a.value)),[x]=d.useState(a.value),[b]=d.useState(a.options),w=d.useMemo(()=>b.findIndex(L=>L.id===x),[b,x]);function j({id:L}){c(L),l()}let A;const[k,T]=d.useState();function M(L){A=L.navigate,T(()=>L.keydown),A(w)}const N=d.useRef(null);return d.useEffect(()=>{N.current&&N.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),d.useEffect(()=>{if(!N.current)return;const L=Pr(N.current,()=>l(!0));return()=>L.destroy()},[l]),r.jsxs(r.Fragment,{children:[r.jsx("div",{ref:N,className:"wx-ywGRk611 wx-value",tabIndex:0,onClick:u,onKeyDown:L=>{k(L,w),L.preventDefault()},children:m.template?m.template(y):m.cell?(()=>{const L=m.cell;return r.jsx(L,{data:y,onAction:i})})():r.jsx("span",{className:"wx-ywGRk611 wx-text",children:a.renderedValue})}),r.jsx(Jf,{items:b,onReady:M,onSelect:j,...g,onCancel:u,children:({option:L})=>m.template?m.template(L):m.cell?(()=>{const z=m.cell;return r.jsx(z,{data:L,onAction:i})})():L.label})]})}function pM(t){const{editor:a,onAction:i,onSave:l,onApply:c}=t,u=a?.config||{},m=a?.options??[],h=a?.value||[],g=a?.renderedValue,y=d.useMemo(()=>({trackScroll:!0,...u.dropdown||{}}),[u]);function x({value:w}){c(w)}const b=d.useRef(null);return d.useEffect(()=>{if(!b.current)return;const w=Pr(b.current,()=>l(!0));return()=>w.destroy()},[l]),r.jsx("div",{ref:b,className:"wx-value wx-aacZ4gNU",onClick:()=>l(!0),children:r.jsx(Iw,{value:h,options:m,text:g,template:u.template,cell:u.cell,clear:u.clear,dropdown:y,autoOpen:!0,onChange:x,onAction:i})})}const gM={text:dM,combo:fM,datepicker:mM,richselect:hM,multiselect:pM};function vM({column:t,row:a}){const i=d.useContext(ws),l=gt(i,"editor"),c=d.useCallback((A,k)=>{i.exec("close-editor",{ignore:A}),k&&i.exec("focus-cell",{...k,eventSource:"click"})},[i]),u=d.useCallback(A=>{const k=A?null:{row:l?.id,column:l?.column};c(!1,k)},[l,c]),m=d.useCallback(()=>{c(!0,{row:l?.id,column:l?.column})},[l,c]),h=d.useCallback(A=>{i.exec("editor",{value:A})},[i]),g=d.useCallback(A=>{A.key==="Enter"&&l&&(t.editor.type==="multiselect"?h(l.value):m())},[l,t.editor,m,h]),y=d.useMemo(()=>tm(t.width,t.flexgrow,t.fixed,t.left,t.right),[t.width,t.flexgrow,t.fixed,t.left,t.right]),x=d.useMemo(()=>{let A=t.editor;if(typeof A=="function"&&(A=A(a,t)),!A)return null;let k=typeof A=="string"?A:A.type;return gM[k]},[t,a]),b=d.useRef(null);d.useEffect(()=>{b.current&&typeof y=="string"&&b.current.setAttribute("style",y)},[y]);const w=typeof a.$parent<"u"?"gridcell":"cell",j=typeof a.$parent<"u"?!t.editor:void 0;return r.jsx("div",{className:"wx-8l724t2g wx-cell wx-editor",ref:b,style:typeof y=="object"&&y!==null?y:void 0,role:w,"aria-readonly":j,tabIndex:-1,onClick:A=>A.stopPropagation(),onDoubleClick:A=>A.stopPropagation(),onKeyDown:g,children:x?r.jsx(x,{editor:l,onSave:u,onApply:h,onCancel:m,onAction:({action:A,data:k})=>i.exec(A,k)}):null})}function Rb(t){const{columns:a,type:i,columnStyle:l}=t,c=d.useContext(ws),{filterValues:u,_columns:m,_sizes:h}=c.getState();function g(y){return l?" "+l(y):""}return r.jsx(r.Fragment,{children:a.map((y,x)=>r.jsx("tr",{children:y.map(b=>{const w=m.find(k=>k.id===b.id),j=`wx-print-cell-${i}${g(w)}${b.filter?" wx-print-cell-filter":""}${b.vertical?" wx-vertical":""}`,A=b.cell;return r.jsx("th",{style:xw(Tw(b,h.columnWidth)),className:"wx-Gy81xq2u "+j,rowSpan:b.rowspan,colSpan:b.colspan,children:A?r.jsx(A,{api:c,cell:Object.fromEntries(Object.entries(b).filter(([k])=>k!=="cell")),column:w,row:x}):b.filter?r.jsx("div",{className:"wx-Gy81xq2u wx-print-filter",children:wA(u,m,b)}):r.jsx("div",{className:"wx-Gy81xq2u wx-text",children:b.text??""})},b.id)})},x))})}function yM(t){const{columns:a,rowStyle:i,columnStyle:l,cellStyle:c,header:u,footer:m,reorder:h}=t,g=d.useContext(ws),{flatData:y,_sizes:x}=g.getState(),b=u&&Cb(a,"header",x.headerRowHeights),w=m&&Cb(a,"footer",x.footerRowHeights);function j(k,T){let M="";return M+=l?" "+l(T):"",M+=c?" "+c(k,T):"",M}function A(k,T){return typeof T.draggable=="function"?T.draggable(k,T)!==!1:T.draggable}return r.jsxs("table",{className:`wx-8NTMLH0z wx-print-grid ${a.some(k=>k.flexgrow)?"wx-flex-columns":""}`,children:[u?r.jsx("thead",{children:r.jsx(Rb,{columns:b,type:"header",columnStyle:l})}):null,r.jsx("tbody",{children:y.map((k,T)=>r.jsx("tr",{className:"wx-8NTMLH0z wx-row"+(i?" "+i(k):""),style:{height:`${k.rowHeight||x.rowHeight}px`},children:a.map(M=>M.collapsed?null:r.jsxs("td",{className:`wx-8NTMLH0z wx-print-cell wx-cell ${j(k,M)}`,style:xw(Tw(M,x.columnWidth)),children:[h&&M.draggable?r.jsx("span",{className:"wx-8NTMLH0z wx-print-draggable",children:A(k,M)?r.jsx("i",{className:"wx-8NTMLH0z wxi-drag"}):null}):null,M.treetoggle?r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{marginLeft:k.$level*28+"px"}}),k.$count?r.jsx("i",{className:`wx-8NTMLH0z wx-print-grid-tree-toggle wxi-menu-${k.open!==!1?"down":"right"}`}):null]}):null,M.cell?(()=>{const N=M.cell;return r.jsx(N,{api:g,row:k,column:M})})():r.jsx("span",{children:zl(k,M)})]},M.id))},T))}),m?r.jsx("tfoot",{children:r.jsx(Rb,{columns:w,type:"footer",columnStyle:l})}):null]})}function bM(t){const{config:a,...i}=t,l=d.useContext(ws),{_skin:c,_columns:u}=l.getState(),m=d.useMemo(()=>vA(u,a),[]),h=d.useRef(null);return d.useEffect(()=>{const g=document.body;g.classList.add("wx-print");const y=h.current;if(!y)return;const x=y.cloneNode(!0);g.appendChild(x);const b=`@media print { @page { size: ${a.paper} ${a.mode}; }`,w=document.createElement("style");w.setAttribute("type","text/css"),w.setAttribute("media","print"),document.getElementsByTagName("head")[0].appendChild(w),w.appendChild(document.createTextNode(b)),window.print(),w.remove(),g.classList.remove("wx-print"),x.remove()},[]),r.jsx("div",{className:`wx-4zwCKA7C wx-${c}-theme wx-print-container`,ref:h,children:m.map((g,y)=>r.jsx("div",{className:"wx-4zwCKA7C wx-print-grid-wrapper",children:r.jsx(yM,{columns:g,...i})},y))})}function xM(t){const{header:a,footer:i,overlay:l,multiselect:c,onreorder:u,rowStyle:m,columnStyle:h,cellStyle:g,autoRowHeight:y,resize:x,clientWidth:b,clientHeight:w,responsiveLevel:j,hotkeys:A}=t,k=d.useContext(ws),T=gt(k,"dynamic"),M=gt(k,"_columns"),N=gt(k,"flatData"),L=gt(k,"split"),z=gt(k,"_sizes"),[H,G]=Ps(k,"selectedRows"),_=gt(k,"select"),Y=gt(k,"editor"),q=gt(k,"scrollLeft"),U=gt(k,"scrollTop"),K=gt(k,"tree"),O=gt(k,"focusCell"),ve=gt(k,"_print"),me=gt(k,"undo"),Z=gt(k,"reorder"),I=gt(k,"_rowHeightFromData"),[se,W]=d.useState(0);d.useEffect(()=>{W(nn())},[]);const[F,oe]=d.useState(0),le=d.useMemo(()=>(M||[]).some(re=>!re.hidden&&re.flexgrow),[M]),Q=d.useMemo(()=>z?.rowHeight||0,[z]),be=d.useRef(null),[he,de]=d.useState(null),[ee,Ce]=d.useState(null),Re=d.useMemo(()=>{let re=[],Ee=0;return L&&L.left&&(re=(M||[]).slice(0,L.left).filter(Ge=>!Ge.hidden).map(Ge=>({...Ge})),re.forEach(Ge=>{Ge.fixed={left:1,leftSize:L.left},Ge.left=Ee,Ee+=Ge.width}),re.length&&(re[re.length-1].fixed.left=-1)),{columns:re,width:Ee}},[L,M]),He=d.useMemo(()=>{let re=[],Ee=0;if(L&&L.right){re=(M||[]).slice(L.right*-1).filter(Ge=>!Ge.hidden).map(Ge=>({...Ge}));for(let Ge=re.length-1;Ge>=0;Ge--){const vt=re[Ge];vt.fixed={right:1},vt.right=Ee,Ee+=vt.width}re.length&&(re[0].fixed={right:-1})}return{columns:re,width:Ee}},[L,M]),te=d.useMemo(()=>{const re=(M||[]).slice(L?.left||0,(M||[]).length-(L?.right??0)).filter(Ee=>!Ee.hidden);return re.forEach(Ee=>{Ee.fixed=0}),re},[M,L]),Ue=d.useMemo(()=>(M||[]).reduce((re,Ee)=>(Ee.hidden||(re+=Ee.width),re),0),[M]),mt=1;function ne(re,Ee,Ge){let vt=Ee,Bt=re;if(te.length){let Vt=te.length;for(let at=re;at>=0;at--)te[at][Ge].forEach(Rt=>{Rt.colspan>1&&at>re-Rt.colspan&&at<Vt&&(Vt=at)});if(Vt!==te.length&&Vt<re){for(let at=Vt;at<re;at++)vt-=te[at].width;Bt=Vt}}return{index:Bt,delta:vt}}const xe=d.useMemo(()=>{let re,Ee,Ge;const vt=q||0,Bt=(q||0)+(b||0);let Vt=0,at=0,Rt=0,ra=0;te.forEach((jn,Ln)=>{vt>Rt&&(Vt=Ln,ra=Rt),Rt=Rt+jn.width,Bt>Rt&&(at=Ln+mt)});const $n={header:0,footer:0};for(let jn=at;jn>=Vt;jn--)["header","footer"].forEach(Ln=>{te[jn]&&te[jn][Ln].forEach($r=>{const Br=$r.colspan;if(Br&&Br>1){const Dt=Br-(at-jn+1);Dt>0&&($n[Ln]=Math.max($n[Ln],Dt))}})});const bn=ne(Vt,ra,"header"),en=ne(Vt,ra,"footer"),Ke=bn.delta,At=bn.index,Us=en.delta,Ht=en.index;return le&&Ue>(b||0)?re=Ee=Ge=[...Re.columns,...te,...He.columns]:(re=[...Re.columns,...te.slice(Vt,at+1),...He.columns],Ee=[...Re.columns,...te.slice(At,at+$n.header+1),...He.columns],Ge=[...Re.columns,...te.slice(Ht,at+$n.footer+1),...He.columns]),{data:re||[],header:Ee||[],footer:Ge||[],d:ra,df:Us,dh:Ke}},[te,Re,He,q,b,le,Ue]),Oe=d.useMemo(()=>a&&z?.headerHeight||0,[a,z]),$e=d.useMemo(()=>i&&z?.footerHeight||0,[i,z]),ze=d.useMemo(()=>b&&w?Ue>=b:!1,[b,w,Ue]),[Qe,qe]=d.useState(!1),Ye=d.useMemo(()=>(w||0)-Oe-$e-(ze?se:0),[w,Oe,$e,ze,se]),ot=d.useMemo(()=>Math.ceil((Ye||0)/(Q||1))+1,[Ye,Q]),B=d.useRef([]),[ye,je]=d.useState(0),[Pe,dt]=d.useState(void 0),nt=d.useMemo(()=>{let re=0,Ee=0;const Ge=2,vt=U||0;if(y){let at=vt;for(;at>0;)at-=B.current[re]||Q,re++;Ee=vt-at;for(let Rt=Math.max(0,re-Ge-1);Rt<re;Rt++)Ee-=B.current[re-Rt]||Q;re=Math.max(0,re-Ge)}else{if(I){let at=0,Rt=0;for(let en=0;en<(N||[]).length;en++){const Ke=N[en].rowHeight||Q;if(Rt+Ke>vt){at=en;break}Rt+=Ke}re=Math.max(0,at-Ge);for(let en=0;en<re;en++)Ee+=N[en].rowHeight||Q;let ra=0,$n=0;for(let en=at+1;en<(N||[]).length;en++){const Ke=N[en].rowHeight||Q;if(ra++,$n+Ke>Ye)break;$n+=Ke}const bn=Math.min(T?T.rowCount:(N||[]).length,at+ra+Ge);return{d:Ee,start:re,end:bn}}re=Math.floor(vt/(Q||1)),re=Math.max(0,re-Ge),Ee=re*(Q||0)}const Bt=T?T.rowCount:(N||[]).length,Vt=Math.min(Bt,re+(ot||0)+Ge);return{d:Ee,start:re,end:Vt}},[y,I,U,Q,T,N,ot,Ye]),bt=d.useMemo(()=>{const re=T?T.rowCount:(N||[]).length;if(y)return ye+nt.d+(re-(Pe||0))*(Q||0);if(!I)return re*(Q||0);let Ee=0;for(let Ge=0;Ge<re;Ge++)Ee+=N[Ge]?.rowHeight||Q;return Ee},[T,N,Q,y,I,ye,nt.d,Pe]),it=d.useRef({});it.current={clientWidth:b,clientHeight:w,fullHeight:bt,headerHeight:Oe,footerHeight:$e,fullWidth:Ue,SCROLLSIZE:se};const Ct=d.useCallback(()=>{const re=it.current;qe(re.clientWidth&&re.clientHeight?re.fullHeight+re.headerHeight+re.footerHeight>=re.clientHeight-(re.fullWidth>=re.clientWidth?re.SCROLLSIZE:0):!1)},[]);d.useEffect(()=>{const re=requestAnimationFrame(Ct);return()=>window.cancelAnimationFrame(re)},[F,Ct]),d.useEffect(()=>{Ct()},[w,Ct]);const pe=d.useMemo(()=>le&&Ue<=(b||0)?(b||0)-0-(Qe?se:0):Ue,[le,Ue,b,Qe,se,ze]),De=d.useMemo(()=>le&&Ue<=(b||0)?b||0:pe<(b||0)?Ue+(Qe?se:0):-1,[le,Ue,b,pe,Qe,se]),Fe=d.useRef({});d.useEffect(()=>{if(T&&(Fe.current.start!==nt.start||Fe.current.end!==nt.end)){const{start:re,end:Ee}=nt;Fe.current={start:re,end:Ee},k&&k.exec&&k.exec("request-data",{row:{start:re,end:Ee}})}},[T,nt,k]);const Ae=d.useMemo(()=>T?N||[]:(N||[]).slice(nt.start,nt.end),[T,N,nt]),ct=d.useMemo(()=>(H||[]).filter(re=>(Ae||[]).some(Ee=>Ee.id===re)),[G,Ae]),ht=d.useMemo(()=>nt.start,[nt.start]),Le=d.useRef({top:U,left:q});Le.current={top:U,left:q};const Dn=d.useCallback(re=>{const Ee=re.target.scrollTop,Ge=re.target.scrollLeft,vt=Le.current;(Ee!==vt.top||Ge!==vt.left)&&k.exec("scroll-to",{top:Ee,left:Ge})},[k]),yn=d.useCallback(re=>{re.shiftKey&&re.preventDefault(),be.current&&be.current.focus&&be.current.focus()},[]),et=d.useCallback(()=>!!(M||[]).find(re=>!!re.draggable),[M]),xt=d.useRef(null),kn=d.useRef(null),Pn=d.useRef({dblclick:(re,Ee)=>{const Ge={id:re,column:Zu(Ee,"data-col-id")};k.exec("open-editor",Ge)},click:(re,Ee)=>{if(Ee.target.closest("input")||xt.current)return;const Ge=Zu(Ee,"data-col-id");if(O?.id!==re&&k.exec("focus-cell",{row:re,column:Ge,eventSource:"click"}),_===!1)return;const vt=c&&(Ee.ctrlKey||Ee.metaKey),Bt=c&&Ee.shiftKey;(vt||H.length>1||!H.includes(re))&&k.exec("select-row",{id:re,toggle:vt,range:Bt})},"toggle-row":re=>{const Ee=k.getRow(re);k.exec(Ee.open!==!1?"close-row":"open-row",{id:re})},"ignore-click":()=>!1}),_e=d.useMemo(()=>({top:Oe,bottom:$e,left:Re.width,xScroll:ze,yScroll:Qe,sense:y&&ee?ee.offsetHeight:Math.max(z?.rowHeight||0,40),node:be.current&&be.current.firstElementChild}),[Oe,$e,Re.width,ze,Qe,y,ee,z]);function tn(re,Ee){const{container:Ge,sourceNode:vt,from:Bt}=Ee;if(et()&&!vt.getAttribute("draggable-data"))return!1;de(Bt),K&&k.getRow(Bt).open&&k.exec("close-row",{id:Bt,nested:!0});const Vt=Rc(vt),at=Vt.cloneNode(!0);at.classList.remove("wx-selected"),at.querySelectorAll("[tabindex]").forEach(bn=>bn.setAttribute("tabindex","-1")),Ge.appendChild(at),Ce(at);const Rt=(q||0)-xe.d,ra=Qe?se:0;Ge.style.width=Math.min((b||0)-ra,le&&Ue<=(b||0)?pe:pe-ra)+Rt+"px";const $n=Df(Vt);Ee.offset={x:Rt,y:-Math.round($n.height/2)},kn.current||(kn.current=re.clientY)}function on(re,Ee){const{from:Ge}=Ee,vt=Ee.pos,Bt=Df(be.current);vt.x=Bt.x;const Vt=_e.top;if(vt.y<Vt)vt.y=Vt;else{const at=Bt.height-(ze&&se>0?se:Math.round(_e.sense/2))-_e.bottom;vt.y>at&&(vt.y=at)}if(be.current.contains(Ee.targetNode)){const at=Rc(Ee.targetNode),Rt=at&&Xf(at);if(Rt&&Rt!==Ge){Ee.to=Rt;const ra=y?ee?.offsetHeight:z?.rowHeight;if(ee&&((U||0)===0||vt.y>Vt+ra-1)){const $n=at.getBoundingClientRect(),bn=Df(ee).y,en=$n.y,Ke=bn>en?-1:1,At=Ke===1?"after":"before",Us=k.getState().flatData,Ht=Math.abs(Us.findIndex(Ln=>Ln.id===Ge)-Us.findIndex(Ln=>Ln.id===Rt)),jn=Ht!==1?At==="before"?"after":"before":At;if(Ht===1&&(Ke===-1&&re.clientY>kn.current||Ke===1&&re.clientY<kn.current))return;kn.current=re.clientY,k.exec("move-item",{id:Ge,target:Rt,mode:jn,inProgress:!0})}}u&&u({event:re,context:Ee})}QA(re,Bt,Ee,_e)}function Da(re,Ee){const{from:Ge,to:vt}=Ee;k.exec("move-item",{id:Ge,target:vt,inProgress:!1}),xt.current=setTimeout(()=>{xt.current=0},1),de(null),Ce(null),kn.current=null,Dw(Ee)}function nn(){const re=document.createElement("div");re.style.cssText="position:absolute;left:-1000px;width:100px;padding:0px;margin:0px;min-height:100px;overflow-y:scroll;",document.body.appendChild(re);const Ee=re.offsetWidth-re.clientWidth;return document.body.removeChild(re),Ee}const $s=d.useMemo(()=>De>0?{width:`${De}px`}:void 0,[De]),Yn=d.useRef(null);function Bs(){Promise.resolve().then(()=>{let re=0,Ee=ht;const Ge=Yn.current;Ge&&(Array.from(Ge.children).forEach((vt,Bt)=>{B.current[ht+Bt]=vt.offsetHeight,re+=vt.offsetHeight,Ee++}),je(re),dt(Ee))})}d.useEffect(()=>{Ae&&y&&Bs()},[Ae,y,ht]);let[$,Xe]=d.useState();d.useEffect(()=>{if(O&&(!_||!ct.length||ct.includes(O.row)))Xe({...O});else if(Ae.length&&xe.data.length){if(!$||ct.length&&!ct.includes($.row)||Ae.findIndex(re=>re.id===$.row)===-1||xe.data.findIndex(re=>re.id===$.column&&!re.collapsed)===-1){const re=ct[0]||Ae[0].id,Ee=xe.data.findIndex(Ge=>!Ge.collapsed);Xe(Ee!==-1?{row:re,column:xe.data[Ee].id}:null)}}else Xe(null)},[O]);const ft=d.useRef(null);d.useEffect(()=>{const re=be.current;if(!re)return;const Ee=GA(re,x);return()=>{typeof Ee=="function"&&Ee()}},[x]);const mn=d.useRef({});Object.assign(mn.current,{start:tn,move:on,end:Da,getReorder:()=>Z,getDraggableInfo:()=>({hasDraggable:et()})}),d.useEffect(()=>{const re=be.current;return re?WA(re,mn).destroy:void 0},[Z,be.current]),d.useEffect(()=>{const re=be.current;return re?UA(re,{keys:A!==!1&&{...BA,"ctrl+z":me,"ctrl+y":me,...A},exec:Ee=>k.exec("hotkey",Ee)}).destroy:void 0},[k,me,A]);const Ba=d.useRef({scroll:k.getReactiveState().scroll,scrollLeft:k.getReactiveState().scrollLeft,scrollTop:k.getReactiveState().scrollTop});Ba.current.getWidth=()=>(b||0)-(Qe?se:0),Ba.current.getHeight=()=>Ye,Ba.current.getScrollMargin=()=>Re.width+He.width,d.useEffect(()=>{qA(ft.current,Ba.current)},[]);const Ii=d.useRef(null);d.useEffect(()=>{const re=Ii.current;if(!re)return;const Ee=[];Ee.push(Pr(re,()=>O&&k.exec("focus-cell",{eventSource:"click"})).destroy),Ee.push(Wj(re,Pn.current)),oe(re.clientHeight);const Ge=new ResizeObserver(()=>{oe(re.clientHeight)});return Ge.observe(re),Ee.push(()=>Ge.disconnect()),()=>Ee.forEach(vt=>vt())},[]);const Ss=`wx-grid ${j?`wx-responsive-${j}`:""}`;return d.useEffect(()=>{O&&(Ae.some(re=>re.id===O.row)&&xe.data.some(re=>re.id===O.column&&!re.collapsed)||k.exec("focus-cell",{eventSource:"destroy"}))},[O,Ae,xe.data,k]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-4VuBwK2D "+Ss,style:{"--header-height":`${Oe}px`,"--footer-height":`${$e}px`,"--split-left-width":`${Re.width}px`,"--split-right-width":`${He.width}px`},children:r.jsx("div",{ref:be,className:"wx-4VuBwK2D wx-table-box",style:$s,role:K?"treegrid":"grid","aria-colcount":xe.data.length,"aria-rowcount":Ae.length,"aria-multiselectable":K&&c?!0:void 0,tabIndex:-1,children:r.jsxs("div",{ref:ft,className:"wx-4VuBwK2D wx-scroll",style:{overflowX:ze?"scroll":"hidden",overflowY:Qe?"scroll":"hidden"},onScroll:Dn,children:[a?r.jsx("div",{className:"wx-4VuBwK2D wx-header-wrapper",children:r.jsx(Tb,{contentWidth:pe,deltaLeft:xe.dh,columns:xe.header,columnStyle:h,bodyHeight:Ye-+i})}):null,r.jsxs("div",{ref:Ii,className:"wx-4VuBwK2D wx-body",style:{width:`${pe}px`,height:`${bt}px`},onMouseDown:re=>yn(re),children:[l?r.jsx(uM,{overlay:l}):null,r.jsx("div",{ref:Yn,className:"wx-4VuBwK2D wx-data",style:{paddingTop:`${nt.d}px`,paddingLeft:`${xe.d}px`},children:Ae.map((re,Ee)=>{const Ge=H.indexOf(re.id)!==-1,vt=he===re.id,Bt="wx-row"+(y?" wx-autoheight":"")+(m?" "+m(re):"")+(Ge?" wx-selected":"")+(vt?" wx-inactive":""),Vt=y?{minHeight:`${re.rowHeight||Q}px`}:{height:`${re.rowHeight||Q}px`};return r.jsx("div",{className:"wx-4VuBwK2D "+Bt,"data-id":na(re.id),"data-context-id":na(re.id),style:Vt,role:"row","aria-rowindex":Ee,"aria-expanded":re.open,"aria-level":K?re.$level+1:void 0,"aria-selected":K?Ge:void 0,tabIndex:-1,children:xe.data.map(at=>at.collapsed?r.jsx("div",{className:"wx-4VuBwK2D wx-cell wx-collapsed"},at.id):Y?.id===re.id&&Y.column===at.id?r.jsx(vM,{row:re,column:at},at.id):r.jsx(tM,{row:re,column:at,columnStyle:h,cellStyle:g,reorder:Z,focusable:$?.row===re.id&&$?.column===at.id},at.id))},re.id)})})]}),i&&(N||[]).length?r.jsx(Tb,{type:"footer",contentWidth:pe,deltaLeft:xe.df,columns:xe.footer,columnStyle:h}):null]})})}),ve?r.jsx(bM,{config:ve,rowStyle:m,columnStyle:h,cellStyle:g,header:a,footer:i,reorder:Z}):null]})}const wM=t=>t.split("-").map(a=>a?a.charAt(0).toUpperCase()+a.slice(1):"").join(""),SM=d.forwardRef(function({data:t=[],columns:a=[],rowStyle:i=null,columnStyle:l=null,cellStyle:c=null,selectedRows:u,select:m=!0,multiselect:h=!1,header:g=!0,footer:y=!1,dynamic:x=null,overlay:b=null,reorder:w=!1,onReorder:j=null,autoRowHeight:A=!1,sizes:k,split:T,tree:M=!1,autoConfig:N=!1,init:L=null,responsive:z=null,sortMarks:H,undo:G=!1,hotkeys:_=null,filterValues:Y,...q},U){const K=d.useRef();K.current=q;const O=d.useMemo(()=>new zA(ww),[]),ve=d.useMemo(()=>O.in,[O]),me=d.useRef(null);me.current===null&&(me.current=new pw((He,te)=>{const Ue="on"+wM(He);K.current&&K.current[Ue]&&K.current[Ue](te)}),ve.setNext(me.current));const Z=d.useMemo(()=>({getState:O.getState.bind(O),getReactiveState:O.getReactive.bind(O),getStores:()=>({data:O}),exec:ve.exec,setNext:He=>(me.current=me.current.setNext(He),me.current),intercept:ve.intercept.bind(ve),on:ve.on.bind(ve),detach:ve.detach.bind(ve),getRow:O.getRow.bind(O),getColumn:O.getColumn.bind(O)}),[O,ve]),[I,se]=d.useState(0),[W,F]=d.useState(0),[oe,le]=d.useState(null),[Q,be]=d.useState(null),he=d.useMemo(()=>{if(N&&!a.length&&t.length){const He=t[0],te=[];for(let Ue in He)if(Ue!=="id"&&Ue[0]!=="$"){let mt={id:Ue,header:Ue[0].toUpperCase()+Ue.slice(1)};typeof N=="object"&&(mt={...mt,...N}),te.push(mt)}return te}return(Q&&Q.columns)??a},[N,a,t,Q]),de=d.useMemo(()=>(Q&&Q.sizes)??k,[Q,k]),ee=d.useCallback(He=>{if(se(He.width),F(He.height),z){const te=Object.keys(z).map(Number).sort((Ue,mt)=>Ue-mt).find(Ue=>He.width<=Ue)??null;te!==oe&&(be(z[te]),le(te))}},[z,oe]),Ce=d.useContext(sa.theme),Re=d.useRef(0);return d.useEffect(()=>{if(!Re.current)L&&L(Z);else{const He=O.getState();O.init({data:t,columns:he,split:T||He.split,sizes:de||He.sizes,selectedRows:u||He.selectedRows,dynamic:x,tree:M,sortMarks:H||He.sortMarks,filterValues:Y||He.filterValues,undo:G,reorder:w,_skin:Ce,_select:m})}Re.current++},[O,t,he,T,de,u,x,M,H,Y,G,w,Ce,m,L,Z]),Re.current===0&&O.init({data:t,columns:he,split:T||{left:0},sizes:de||{},selectedRows:u||[],dynamic:x,tree:M,sortMarks:H||{},filterValues:Y||{},undo:G,reorder:w,_skin:Ce,select:m}),d.useImperativeHandle(U,()=>({...Z}),[Z]),r.jsx(ws.Provider,{value:Z,children:r.jsx(Kp,{words:Yp,optional:!0,children:r.jsx(xM,{header:g,footer:y,overlay:b,rowStyle:i,columnStyle:l,cellStyle:c,onReorder:j,multiselect:h,autoRowHeight:A,clientWidth:I,clientHeight:W,responsiveLevel:oe,resize:ee,hotkeys:_})})})});$p(is);const aa=d.createContext(null),Zp=d.createContext(null),Jp=d.createContext(null);function CM({children:t}){const a=d.useContext(sa.i18n),i=d.useMemo(()=>a.getGroup("filemanager"),[a]),l=d.useContext(aa),[c]=Ps(l,"panels"),u=gt(l,"activePanel"),m=c[u].path,[h,g]=d.useState(null),[y,x]=d.useState(null),[b,w]=d.useState(""),[j,A]=d.useState(""),[k,T]=d.useState(!1);function M(){const H=b.trim();if(!H){T(!0);return}h.add?l.exec("create-file",{file:{...h.item,name:H},parent:m}):j!==H&&l.exec("rename-file",{id:h.item.id,name:H}),N()}function N(){g(null),T(null),A(""),w("")}function L(){l.exec("delete-files",{ids:y.selected}),x(null)}const z=d.useMemo(()=>({showPrompt(H){const G=H.item.name||(H.item.type==="folder"?i("New folder"):`${i("New file")}.txt`);A(G),w(G),g({...H})},showConfirm(H){x({...H})}}),[i]);return r.jsxs(Zp.Provider,{value:z,children:[r.jsx(Cj,{children:t}),h?r.jsx(wp,{title:i(`Enter ${h.item.type} name`),onConfirm:M,onCancel:N,children:r.jsx(Vp,{error:k,select:!0,focus:!0,value:b,onChange:({value:H})=>w(H)})}):null,y?r.jsx(wp,{title:i("Are you sure you want to delete these items:"),onConfirm:L,onCancel:()=>x(null),children:y.selected?r.jsx("ul",{className:"wx-gq7BMzEP wx-list",children:y.selected.map((H,G)=>r.jsx("li",{children:H},G))}):null}):null]})}let Eb={"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 kM(t){const a=t.lastIndexOf("."),i=a>0&&a<t.length-1?Math.min(10,t.length-a):Math.min(5,t.length),l=t.slice(0,-i),c=t.slice(-i);return[l,c]}function jM({item:t}){const a=d.useContext(aa),i=d.useContext(sa.i18n).getGroup("filemanager"),l=d.useContext(aa).templates,[c]=Ps(a,"panels"),u=gt(a,"activePanel"),m=gt(a,"mode"),h=c[u].selected,g=d.useMemo(()=>l.preview(t,214,163),[l,t]),y=d.useMemo(()=>l.icon(t,"big"),[l,t]),[x,b]=d.useMemo(()=>kM(t.name),[t.name]);return r.jsx(r.Fragment,{children:t.id==="/wx-filemanager-parent-link"?m!=="search"?r.jsx("div",{className:"wx-GAOa4kDV wx-back-item",children:r.jsxs("div",{className:`wx-GAOa4kDV wx-back ${t.navigation?"wx-selected":""}`,"data-id":na("/wx-filemanager-parent-link"),children:[r.jsx("i",{className:"wx-GAOa4kDV wxi-arrow-left"}),r.jsx("span",{children:i("Back to parent folder")})]})}):null:r.jsxs("div",{className:`wx-GAOa4kDV wx-item ${h?.length&&h.indexOf(t.id)>=0?"wx-selected":""}`,"data-id":na(t.id),children:[g?r.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-preview",children:r.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:i("A miniature file preview"),src:g})}):y?r.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-icon",children:r.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:"",src:y})}):r.jsx("div",{className:"wx-GAOa4kDV wx-preview",children:r.jsx("i",{className:`wx-GAOa4kDV wxi-${t.type}`})}),t.type==="folder"?r.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[r.jsxs("div",{className:"wx-GAOa4kDV wx-folder-name",children:[r.jsx("span",{className:"wx-GAOa4kDV wx-type",children:i("Folder")}),r.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[r.jsx("span",{children:x}),r.jsx("span",{children:b})]})]}),r.jsx("div",{"data-action-id":na(t.id),className:"wx-GAOa4kDV wx-more",children:r.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]}):r.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[r.jsx("div",{className:"wx-GAOa4kDV wx-file-name",children:r.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[r.jsx("span",{children:x}),r.jsx("span",{children:b})]})}),r.jsx("div",{"data-action-id":na(t.id),className:"wx-GAOa4kDV wx-more",children:r.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]})]})})}function zw(){const t=d.useContext(aa),a=d.useContext(sa.i18n),i=d.useMemo(()=>a.getGroup("filemanager"),[a]),[l]=Ps(t,"panels"),c=gt(t,"activePanel"),u=gt(t,"mode"),m=l[c]._files,h=l[c].selected,g=l[c].path,y=l[c]._crumbs,x=l[c]._selectNavigation,b=d.useCallback((N,L)=>{const z=L&&(L.ctrlKey||L.metaKey),H=L&&L.shiftKey;if(N==="/wx-filemanager-parent-link"){if(h.length&&(z||H))return;t.exec("select-file",{type:"navigation"});return}let G=N==="body"&&L?null:N;const _=L.target.className.indexOf("wx-more")!==-1||L.target.className.indexOf("wxi-dots-v")!==-1;setTimeout(()=>{t.exec("select-file",{id:G,toggle:z&&!_,range:H&&!_,panel:c})},1)},[t,h,c]),w=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]),j=d.useCallback(N=>{if(N==="/wx-filemanager-parent-link")return w();u==="search"&&t.exec("filter-files",{text:""});const L=m.find(z=>z.id===N);L&&(L.type=="folder"?t.exec("set-path",{id:L.id,panel:c}):t.exec("open-file",{id:L.id}))},[t,w,u,m,c]),A=d.useCallback((N,L)=>{(!h?.length||!h.filter(z=>z?.id===N).length>0)&&b(N,L)},[h,b]),k=d.useMemo(()=>g!=="/"?[{id:"/wx-filemanager-parent-link",name:i("Back to parent folder"),navigation:x},...m]:m,[g,i,x,m]),T=d.useRef(null),M=d.useRef();return d.useEffect(()=>{T.current&&(M.current?(M.current.click=b,M.current._dblclick=j,M.current.context=A):(M.current={click:b,dblclick:N=>M.current._dblclick(N),_dblclick:j,context:A},Ec(T.current,M.current)))},[b,j,A]),u=="search"&&!k.length?r.jsx("div",{className:"wx-iyjASZCY wx-not-found",children:r.jsx("div",{className:"wx-iyjASZCY wx-not-found-text",children:i("Looks like nothing is here")})}):r.jsx("div",{tabIndex:0,className:"wx-iyjASZCY "+("wx-cards"+(g!=="/"&&u!=="search"?" wx-has-back-link":"")),"data-id":na("body"),ref:T,children:k.map(N=>r.jsx(jM,{item:N},N.id))})}function Mo({name:t="",spin:a=!1,onClick:i}){return r.jsx("i",{"data-menu-ignore":"true",className:`wx-uwcvNSAG wx-icon wxi-${t} ${a?"wx-spin":""} ${i?"wx-clickable":""}`,onClick:()=>{i&&i()}})}function AM(){const t=d.useContext(sa.i18n).getGroup("filemanager"),a=d.useContext(aa),i=gt(a,"activePanel"),[l]=Ps(a,"panels"),c=d.useMemo(()=>l[i]._crumbs,[l,i]);function u(){a.exec("filter-files",{text:""})}return r.jsxs("div",{className:"wx-GDJvtROw wx-search",children:[r.jsxs("div",{className:"wx-GDJvtROw wx-toolbar",children:[r.jsx("div",{className:"wx-GDJvtROw wx-back-icon",children:r.jsx(Mo,{name:"angle-left",onClick:u})}),r.jsxs("div",{className:"wx-GDJvtROw wx-text",children:[t("Search results in")," ",Array.isArray(c)&&c.map((m,h)=>r.jsxs(d.Fragment,{children:[h?"/":null,m.id=="/"?t(m.name):m.name]},h))]})]}),r.jsx(zw,{})]})}function Hh({narrowMode:t,extraInfo:a}){const i=d.useContext(aa),{preview:l,icon:c}=i.templates,u=d.useContext(sa.i18n),m=d.useMemo(()=>u.getGroup("filemanager"),[u]),h=d.useMemo(()=>kc("%D, %d %F %Y, %H:%i",u.getRaw().calendar),[u]),[g,y]=Ps(i,"panels"),x=gt(i,"activePanel"),b=gt(i,"preview"),w=gt(i,"search"),j=d.useMemo(()=>{const _=g&&x!=null&&g[x]?._selected?.length||0;return w&&!_},[w,y,x]),A=d.useMemo(()=>{const _=g&&x!=null?g[x]:null;return _?j?_._files:_._selected:[]},[j,y,x]),k=d.useCallback((_,Y)=>(_?`${_} ${m(_>1?"folders":"folder")} `:"")+(Y?`${Y} ${m(Y>1?"files":"file")}`:""),[m]),T=d.useCallback(()=>{i.exec("show-preview",{mode:!b})},[i,b]),M=d.useCallback(_=>_.type==="folder"?m("Folder"):_.ext||m("Unknown file"),[m]),N=d.useMemo(()=>{let _,Y,q,U,K,O,ve,me;if(A.length===1&&!j){Y=A[0],_=Y.name;const Z=l(Y,400,500);Z?(q=Z,U=""):(U=c(Y,"big"),q=""),K=Y.type!=="folder"}else{if(Y=K=null,_="",A.length){let Z=0,I=0,se=0,W=[],F;A.forEach(le=>{typeof le.size>"u"&&(F=!0,Z=void 0),F||(Z+=le.size),W.push(M(le)),le.type==="folder"?I++:se++});const oe=new Set(W);O=oe.size>1?m("multiple"):[...oe][0],ve=k(I,se),me=Z,j||(_=m("Multiple files"))}U=c({type:j?"search":A.length?"multiple":"none"},"big"),q=""}return{name:_,item:Y,previewSrc:q,iconSrc:U,showDownloadIcon:K,type:O,totalCount:ve,totalSize:me}},[A,j,l,c,m,M,k]),L=d.useCallback(()=>{i.exec("download-file",{id:A[0].id})},[i,A]),z=d.useCallback(async _=>{if(!a||!_)return null;try{return await a(_)}catch(Y){return console.log(Y),null}},[a]),[H,G]=d.useState(null);return d.useEffect(()=>{let _=!1;return G(null),Promise.resolve(z(N.item)).then(Y=>{_||G(Y)}).catch(()=>{_||G(null)}),()=>{_=!0}},[z,N.item]),r.jsx("div",{className:"wx-O0BTtRrH wx-wrapper",children:A&&A.length?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"wx-O0BTtRrH wx-preview",children:[r.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[r.jsx("div",{className:"wx-O0BTtRrH wx-name",children:N.name}),r.jsxs("div",{className:"wx-O0BTtRrH wx-icons",children:[N.showDownloadIcon?r.jsx(Mo,{name:"download",onClick:L}):null,t?r.jsx(Mo,{name:"close",onClick:T}):null]})]}),N.previewSrc?r.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:r.jsx("img",{src:N.previewSrc,alt:m("A miniature file preview")})}):N.iconSrc?r.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:r.jsx("img",{src:N.iconSrc,alt:m("A miniature file preview")})}):r.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:N.item?r.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${N.item.type}`}):r.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${j?"search":"file-multiple-outline"}`})})]}),r.jsxs("div",{className:"wx-O0BTtRrH wx-info-panel",children:[r.jsx("div",{className:"wx-O0BTtRrH wx-title",children:m(j?"Found":"Information")}),r.jsxs("div",{className:"wx-O0BTtRrH wx-list",children:[N.item?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Type")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:M(N.item)}),typeof N.item.size<"u"?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Size")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:Ju(N.item.size)})]}):null,r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Date")}),r.jsxs("span",{className:"wx-O0BTtRrH wx-value",children:[h(N.item.date)," "]})]}):r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Count")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:N.totalCount}),r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Type")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:N.type}),typeof N.totalSize<"u"?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Size")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:Ju(N.totalSize)})]}):null]}),H?Object.entries(H).map(([_,Y])=>r.jsxs(Dp.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:_}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:Y})]},_)):null]})]})]}):r.jsxs("div",{className:"wx-O0BTtRrH wx-no-info-panel",children:[r.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[r.jsx("div",{className:"wx-O0BTtRrH wx-name",children:N.name}),r.jsx("div",{className:"wx-O0BTtRrH wx-icons",children:t?r.jsx(Mo,{name:"close",onClick:T}):null})]}),r.jsx("div",{className:"wx-O0BTtRrH wx-no-info-wrapper",children:r.jsxs("div",{className:"wx-O0BTtRrH wx-no-info",children:[N.previewSrc?r.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:r.jsx("img",{src:N.previewSrc,alt:m("A miniature file preview")})}):N.iconSrc?r.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:r.jsx("img",{src:N.iconSrc,alt:m("A miniature file preview")})}):r.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:r.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${j?"search":"message-question-outline"}`})}),r.jsx("span",{className:"wx-O0BTtRrH wx-text",children:j?"":m("Select file or folder to view details")})]})})]})})}function Ow({panel:t}){const a=d.useContext(aa),i=d.useContext(sa.i18n),l=d.useMemo(()=>i.getGroup("filemanager"),[i]),[c,u]=Ps(a,"panels"),m=d.useMemo(()=>c[t]._files,[u,t]),h=d.useMemo(()=>c[t]._crumbs||[],[u,t]);function g(A){const k=Qp(A,h);a.exec("set-path",{id:A,panel:t,...k&&{selected:[k]}})}const[y,x]=d.useState(null);d.useEffect(()=>{m&&x(null)},[m]);function b(){x(!0),a.exec("request-data",{id:h[h.length-1].id}),setTimeout(()=>{x(null)},5e3)}const w=d.useRef(null),j=d.useRef();return d.useEffect(()=>{j.current?j.current.click=g:(j.current={click:g},Ec(w.current,j.current))},[g]),r.jsxs("div",{className:"wx-SNY5LTYx wx-breadcrumbs","data-menu-ignore":"true",ref:w,children:[r.jsx("div",{className:"wx-SNY5LTYx wx-refresh-icon",children:r.jsx(Mo,{name:"refresh",spin:!!y,onClick:b})}),h.map((A,k)=>r.jsxs(Dp.Fragment,{children:[k?r.jsx(Mo,{name:"angle-right"}):null,r.jsx("div",{className:"wx-SNY5LTYx wx-item","data-id":na(A.id),"data-menu-ignore":"true",children:A.id=="/"?l(A.name):A.name})]},k))]})}function MM({row:t}){const a=d.useContext(sa.i18n),[i]=d.useState(()=>a.getGroup("filemanager")),l=d.useContext(aa).templates,[c]=d.useState(()=>l.icon(t,"small"));return r.jsx("div",{className:"wx-qgAqG6sL wx-name-cell",children:t.id==="/wx-filemanager-parent-link"?r.jsxs(r.Fragment,{children:[r.jsx("i",{className:"wx-qgAqG6sL wxi-arrow-left"}),r.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",i("Back to parent folder")]})]}):r.jsxs(r.Fragment,{children:[c?r.jsx("img",{className:"wx-qgAqG6sL wx-icon",alt:"",src:c,height:"24px",width:"24px"}):r.jsx("i",{className:`wx-qgAqG6sL wxi-${t.type}`}),r.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",t.name," "]})]})})}function Hw({children:t}){const a=d.useContext(aa),i=gt(a,"activePanel"),l=d.useContext(Jp),c=d.useRef(null);let u=d.useRef({});return u.current.drop=()=>{const m=c.current,h=Rk(m,"data-panel");h&&h!=i&&a.exec("set-active-panel",{panel:h*1})},u.current.dragEnter=()=>{const m=c.current;m&&m.classList.toggle("wx-active")},u.current.dragLeave=()=>{const m=c.current;m&&m.classList.toggle("wx-active")},d.useEffect(()=>{const m=c.current;return l.droparea(m,u.current)},[]),r.jsx("div",{className:"wx-LT9X7tb7 wx-upload-area",ref:c,children:t})}function kp({panel:t,active:a=!1,onClick:i,onContextMenu:l}){const c=d.useContext(aa),u=d.useContext(sa.i18n),m=d.useMemo(()=>u.getGroup("filemanager"),[u]),h=d.useMemo(()=>kc("%d %M %Y",u.getRaw().calendar),[u]),[g]=Ps(c,"panels"),y=g[t].selected,x=g[t].path,b=g[t]._crumbs,w=g[t]._sorts,j=g[t]._selectNavigation,A=g[t]._files,k=d.useMemo(()=>[{id:"name",header:m("Name"),flexgrow:3,sort:!0,resize:!0,cell:MM},{id:"size",header:m("Size"),width:100,sort:!0,resize:!0,template:O=>typeof O=="number"?Ju(O):""},{id:"date",header:m("Date"),width:120,sort:!0,resize:!0,template:O=>O?h(O):""}],[m,h]),T=d.useRef(null),M=d.useRef(null),N=d.useMemo(()=>j?["/wx-filemanager-parent-link"]:[...y],[j,y]);function L(O,ve){if(ve&&ve.target&&ve.target.className&&ve.target.className.indexOf("wx-grip")!==-1)return;const me=ve&&(ve.ctrlKey||ve.metaKey),Z=ve&&ve.shiftKey;if(O==="/wx-filemanager-parent-link"){if(y.length&&(me||Z))return;c.exec("select-file",{type:"navigation"});return}let I=O==="body"&&ve?null:O;!T.current&&!M.current?c.exec("select-file",{id:I,toggle:me,range:Z,panel:t}):(T.current=null,M.current=null)}function z(){b.length>1&&c.exec("set-path",{id:b[b.length-2].id,panel:t,selected:[b[b.length-1].id]})}function H(O){if(O==="/wx-filemanager-parent-link")return z();const ve=A.find(me=>me.id===O);ve&&(ve.type==="folder"?c.exec("set-path",{id:ve.id,panel:t}):c.exec("open-file",{id:ve.id}))}function G(O){const ve=O.key,me=w[x];let Z=me?"asc":"desc";me&&me.key===ve&&(Z=me.order==="asc"?"desc":"asc"),c.exec("sort-files",{key:ve,order:Z,panel:t,path:x})}function _(O){O.intercept("sort-rows",ve=>(T.current=!0,G(ve),!1)),O.intercept("select-row",()=>!1),O.on("resize-column",()=>M.current=!0),O.intercept("hotkey",()=>!1)}const Y=d.useMemo(()=>x!=="/"?[{id:"/wx-filemanager-parent-link",name:m("Back to parent folder")},...A]:A,[x,A,m]),q=d.useMemo(()=>{if(Y&&w&&w[x]){const{key:O,order:ve}=w[x];return{[O]:{order:ve}}}},[Y,w,x]),U=d.useRef(null),K=d.useRef();return d.useEffect(()=>{K.current?(K.current.click=L,K.current._dblclick=H):(K.current={click:L,dblclick:O=>K.current._dblclick(O),_dblclick:H},Ec(U.current,K.current))},[L,H]),r.jsxs("div",{onClick:i,onContextMenu:l,className:"wx-SSaVhET7 wx-wrapper",children:[r.jsx(Ow,{panel:t}),r.jsx("div",{"data-id":na("body"),className:`wx-SSaVhET7 wx-list ${a?"wx-active":""}`,ref:U,children:r.jsx(Hw,{children:r.jsx(SM,{init:_,data:Y,columns:k,selectedRows:N,columnStyle:()=>"wx-SSaVhET7 wx-each-cell",sizes:{rowHeight:42,headerHeight:42},sortMarks:q})})})]})}function NM(){const t=d.useContext(aa),a=gt(t,"activePanel");function i(l){t.exec("set-active-panel",{panel:l})}return r.jsxs("div",{className:"wx-L55BfJa2 wx-panels","data-id":na("body"),children:[r.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":0,children:r.jsx(kp,{panel:0,active:a==0,onClick:()=>i(0),onContextMenu:()=>i(0)})}),r.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":1,children:r.jsx(kp,{panel:1,active:a==1,onClick:()=>i(1),onContextMenu:()=>i(1)})})]})}function Fw({folderIcon:t=!1,folder:a={}}){const i=d.useContext(aa),[l,c]=Ps(i,"panels"),u=gt(i,"activePanel"),m=d.useMemo(()=>l[u].path,[c,u]),h=d.useContext(sa.i18n),g=d.useMemo(()=>h.getGroup("filemanager"),[h]),y=d.useMemo(()=>!!a.data?.find(j=>j.type==="folder"),[a]),x=d.useMemo(()=>a.id=="/"?g(a.name):a.name,[a,g]),b=d.useMemo(()=>a.$level>1?(a.$level-1)*20:0,[a]),w=a.open;return r.jsxs(r.Fragment,{children:[r.jsxs("li",{"data-id":na(a.id),className:`wx-NYfhvGIt wx-folder${m===a.id?" wx-selected":""}`,style:{paddingLeft:`${b}px`},children:[y?r.jsx("i",{className:`wx-NYfhvGIt wx-toggle wxi-${w?"angle-down":"angle-right"}`,"data-action":"toggle"}):r.jsx("span",{className:"wx-NYfhvGIt wx-toggle-placeholder"}),r.jsx("i",{className:"wx-NYfhvGIt "+(t||"wxi-folder")}),r.jsxs("span",{className:"wx-NYfhvGIt wx-name",children:[" ",x," "]})]}),w&&a.data&&a.data.length&&y?r.jsx(r.Fragment,{children:a.data.map(j=>j.type==="folder"?r.jsx(Fw,{folder:j},j.id):null)}):null]})}function TM(){const t=d.useContext(aa),[a,i]=Ps(t,"data"),[l,c]=Ps(t,"panels"),u=gt(t,"activePanel"),m=d.useMemo(()=>l[u]._crumbs,[c,u]),h=d.useCallback(j=>{t.exec("open-tree-folder",{id:j,mode:!a.byId(j).open})},[t,i]),g=d.useCallback(j=>{const A=Qp(j,m);t.exec("set-path",{id:j,panel:u,...A&&{selected:[A]}})},[t,m,u]),[y,x]=d.useState([]);d.useEffect(()=>{x(a.byId(0).data)},[i]);const b=d.useRef(null),w=d.useRef();return d.useEffect(()=>{w.current?(w.current.click=g,w.current.toggle=h):(w.current={click:g,toggle:h},Ec(b.current,w.current))},[g,h]),r.jsx("ul",{ref:b,className:"wx-LyHJ6R6A",children:y.map(j=>j.type==="folder"?r.jsx(Fw,{folder:j},j.id):null)})}function RM(){const t=d.useContext(aa),a=d.useContext(sa.i18n),i=d.useMemo(()=>a.getGroup("filemanager"),[a]),l=gt(t,"drive"),c=l?l.used:"",u=l?l.total:"";return c&&u?r.jsxs("div",{className:"wx-DetSyKGG wx-drive",children:[r.jsx("progress",{value:c,max:u,className:"wx-DetSyKGG wx-progress"}),r.jsxs("p",{children:[Ju(c)," ",i("of")," ",Ju(u)," ",i("used")]})]}):null}function EM({option:t}){const a=d.useContext(sa.i18n).getGroup("filemanager"),i=d.useContext(Jp),l=d.useCallback(()=>{i.open({})},[i]);return r.jsx("div",{className:"wx-9XiKcxq5 wx-upload-button",onClick:l,children:r.jsx("span",{children:a(t.text)})})}function DM({readonly:t,menuOptions:a}){const i=d.useContext(sa.i18n).getGroup("filemanager"),{showPrompt:l}=d.useContext(Zp);d.useEffect(()=>{Qj("upload",EM)},[]);function c({action:m}){m&&(m.id==="add-file"?l({item:{type:"file",size:0,date:new Date},add:!0}):m.id==="add-folder"&&l({item:{type:"folder",date:new Date},add:!0}))}const u=d.useMemo(()=>a("add").map(m=>(m.text=i(m.text),m)),[a,i]);return r.jsxs("div",{className:"wx-FlucfALM wx-wrapper",children:[!t&&r.jsx("div",{className:"wx-FlucfALM wx-button",children:r.jsx(Zj,{options:u,at:"bottom-fit",onClick:c,children:r.jsx(Gu,{type:"primary block",children:i("Add New")})})}),r.jsx("div",{className:"wx-FlucfALM wx-tree",children:r.jsx(TM,{})}),r.jsx(RM,{})]})}function LM({value:t="",onSearch:a}){const[i,l]=bw(t),c=d.useContext(sa.i18n).getGroup("filemanager"),u=d.useRef(null),m=d.useMemo(()=>i!==""?"wxi-close":"wxi-search",[i]);function h(y){const x=y.target.value;l(x),a&&a({value:x})}function g(){l(""),u.current&&u.current.focus(),a&&a({value:""})}return r.jsxs("div",{className:"wx-lUZMtgT1 wx-search-input",children:[r.jsx("i",{className:`wx-lUZMtgT1 wx-icon ${m}`,onClick:g}),r.jsx("input",{type:"text",className:"wx-lUZMtgT1 wx-text",ref:u,value:i,onInput:h,placeholder:c("Search")})]})}function _M({narrowMode:t=!1,onShowTree:a}){const i=d.useContext(aa),l=d.useContext(sa.i18n).getGroup("filemanager"),c=gt(i,"mode"),u=gt(i,"preview"),m=gt(i,"search"),h=[{icon:"wxi-view-sequential",id:"table"},{icon:"wxi-view-grid",id:"cards"},{icon:"wxi-view-column",id:"panels"}];function g({value:b}){i.exec("set-mode",{mode:b})}function y(b){b.preventDefault(),i.exec("show-preview",{mode:!u})}function x(b){i.exec("filter-files",{text:b.value})}return r.jsxs("div",{className:"wx-5PZQQztG wx-toolbar",children:[r.jsxs("div",{className:"wx-5PZQQztG wx-left "+(t?"wx-left-narrow":""),children:[t?c==="panels"||c==="search"?null:r.jsx("div",{className:"wx-5PZQQztG wx-sidebar-icon","data-id":na("toggle-tree"),children:r.jsx(Mo,{onClick:()=>a&&a(),name:"subtask"})}):r.jsx("div",{className:"wx-5PZQQztG wx-name",children:l("Files")}),r.jsx(LM,{onSearch:x,value:m})]}),r.jsxs("div",{className:"wx-5PZQQztG wx-right",children:[t?null:r.jsx("div",{className:"wx-5PZQQztG wx-preview-icon",children:r.jsx(kj,{onClick:y,value:u,children:r.jsx("i",{className:"wx-5PZQQztG wxi-eye"})})}),r.jsx("div",{className:"wx-5PZQQztG wx-modes",children:r.jsx(yj,{value:c,options:h,onChange:g})})]})]})}function IM(){const t=d.useContext(aa),a=gt(t,"activePanel");return r.jsxs("div",{className:"wx-NwohNJzN wx-wrapper",children:[r.jsx(Ow,{panel:a}),r.jsx(Hw,{children:r.jsx(zw,{})})]})}function zM({readonly:t=!1,menuOptions:a,extraInfo:i}){const l=d.useRef(null),c=d.useRef(null),[u,m]=d.useState(void 0),[h,g]=d.useState(void 0),[y,x]=d.useState(!1),b=Aw(),w=d.useContext(aa),{showPrompt:j,showConfirm:A}=d.useContext(Zp),k=d.useContext(sa.i18n),T=d.useMemo(()=>k.getGroup("filemanager"),[k]),M=gt(w,"mode"),N=gt(w,"preview"),L=gt(w,"activePanel"),[z,H]=Ps(w,"panels"),G=d.useMemo(()=>(z&&L!=null?z[L]:null)?.selected??[],[H,L]),_=d.useMemo(()=>(z&&L!=null?z[L]:null)?.path,[H,L]),[Y,q]=d.useState([]);d.useEffect(()=>{const oe=l.current;if(!oe)return;const le=new ResizeObserver(Q=>{const be=Q[0]?.borderBoxSize?.[0]?.inlineSize;typeof be=="number"&&g(be<768)});return le.observe(oe),()=>{le.disconnect()}},[]);const U=d.useCallback(()=>{x(oe=>!oe)},[]),K=d.useCallback(oe=>{h&&Zu(oe)!=="toggle-tree"&&x(!1)},[h]);d.useEffect(()=>{const oe=c.current;if(oe)return Pr(oe,K).destroy},[K]),d.useEffect(()=>{const oe=c.current;if(!oe)return;const le=new ResizeObserver(()=>{oe&&m(oe.clientWidth)});return le.observe(oe),oe&&m(oe.clientWidth),()=>{le.disconnect()}},[]);const O=d.useMemo(()=>({icon:"wxi-eye",text:"Preview",id:"preview"}),[]),ve=d.useCallback(oe=>{let le=h?[O]:[];return oe==="file"&&(le=[...le,...a().filter(Q=>Q.id==="download")]),le},[h,O,a]),me=d.useRef(null),Z=d.useCallback((oe,le,Q)=>{const be=Q?[le.id]:G;switch(oe){case"download":w.exec("download-file",{id:le.id});break;case"copy":case"move":me.current={action:oe,ids:be};break;case"paste":me.current&&w.exec(me.current.action==="copy"?"copy-files":"move-files",{ids:me.current.ids,target:le?.type==="folder"?le.id:_});break;case"rename":j({item:le});break;case"delete":A({selected:be});break;case"preview":w.exec("show-preview",{mode:!N});break}},[w,G,_,j,A,N]),I=d.useCallback(()=>z?.[L],[z,L]);d.useEffect(()=>{const oe=l.current;if(!oe)return;const le=Fj(oe,{api:w,menuOptions:t?ve:a,performAction:Z,getPanel:I});return()=>{typeof le=="function"?le():le&&typeof le.destroy=="function"&&le.destroy()}},[w,t,ve,a,Z,I]);const se=d.useCallback((oe,le)=>{const Q=oe?w.getFile(oe):null,be=le.target.closest(".tree-item.folder");let he;if(t)he=ve(Q?.type);else{switch(oe){case"body":he=a(oe);break;default:if(Q)if(!be&&G.length>1)he=h?[O,...a("multiselect")]:a("multiselect");else if(oe==="/")he=a("folder",Q).filter(de=>de.id==="paste");else{const de=a(Q.type,Q);de&&(he=h?[O,...de]:de)}}M==="search"&&(he=he?.filter(de=>de.id!=="paste"))}if(Q?.id&&(!G.length||!G.some(de=>de===Q.id))&&!be&&w.exec("select-file",{id:Q.id}),he?.length)return he.forEach(de=>{be&&(de.hotkey=""),de.text&&(de.text=T(de.text)),de.hotkey&&(de.subtext=de.hotkey)}),q(he),Q||{}},[w,t,ve,a,G,h,O,M,T]),W=d.useCallback(oe=>{const{action:le,context:Q}=oe;le&&Z(le.id,Q,!le.hotkey)},[Z]);async function F(oe){await Promise.resolve();const{name:le,size:Q}=oe.file;w.exec("create-file",{file:{name:le,size:Q,date:new Date,file:oe.file},parent:_})}return r.jsx("div",{className:"wx-RJbNonjJ wx-filemanager wx-flex",ref:l,"data-menu-ignore":"false",children:h&&N?r.jsx("div",{className:"wx-RJbNonjJ wx-info-narrow",children:r.jsx(Hh,{narrowMode:h,extraInfo:i})}):r.jsxs(r.Fragment,{children:[r.jsx(_M,{narrowMode:h,onShowTree:U}),r.jsx(Jj,{dataKey:"id",at:"point",options:Y,resolver:se,onClick:W,children:r.jsxs(jw,{dataKey:"actionId",options:Y,resolver:se,onClick:W,children:[r.jsx(sA,{data:b,apiOnly:!0,uploadURL:F}),r.jsx(Jp.Provider,{value:b,children:r.jsx("div",{className:"wx-RJbNonjJ wx-content-wrapper wx-flex",children:M!=="panels"&&M!=="search"?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-RJbNonjJ "+["wx-sidebar",h?"wx-sidebar-narrow":"",y?"wx-sidebar-visible":""].filter(Boolean).join(" "),ref:c,children:r.jsx(DM,{readonly:t,menuOptions:a})}),r.jsxs("div",{className:"wx-RJbNonjJ wx-content",style:{width:`calc(100% - ${u||0}px - 10px)`},children:[r.jsx("div",{className:`wx-RJbNonjJ wx-content-item${N?"":"-fit"}`,"data-id":na("body"),children:M==="table"?r.jsx(kp,{panel:L}):r.jsx(IM,{})}),N?r.jsx("div",{className:"wx-RJbNonjJ wx-info",children:r.jsx(Hh,{extraInfo:i})}):null]})]}):r.jsxs(r.Fragment,{children:[r.jsx("div",{className:`wx-RJbNonjJ wx-content-item${N?"":"-fit"}`,children:M==="panels"?r.jsx(NM,{}):r.jsx(AM,{})}),N?r.jsx("div",{className:"wx-RJbNonjJ wx-info",children:r.jsx(Hh,{extraInfo:i})}):null]})})})]})})]})})}const OM=t=>t.split("-").map(a=>a?a.charAt(0).toUpperCase()+a.slice(1):"").join("");function HM(t,a){const{type:i,ext:l}=t;if(i==="folder")return!1;let c;return i&&i!=="file"&&Eb[i]?c=i:l?c=Eb[l]?l:"file":c="unknown",`https://cdn.svar.dev/icons/filemanager/vivid/${a}/${c}.svg`}const FM=d.forwardRef(function(t,a){const{data:i=[],mode:l="cards",drive:c=null,preview:u=!1,panels:m=null,activePanel:h=0,readonly:g=!1,menuOptions:y=zj,extraInfo:x=null,init:b=null,icons:w=HM,previews:j=null,...A}=t,k=d.useRef();k.current=A;const T=d.useMemo(()=>new Ij(ww),[]),M=d.useMemo(()=>T.in,[T]),N=d.useRef(null);N.current===null&&(N.current=new pw((H,G)=>{const _="on"+OM(H);k.current&&k.current[_]&&k.current[_](G)}),M.setNext(N.current));const L=d.useMemo(()=>({getState:T.getState.bind(T),getReactiveState:T.getReactive.bind(T),getStores:()=>({data:T}),exec:M.exec,setNext:H=>(N.current=N.current.setNext(H),N.current),intercept:M.intercept.bind(M),on:M.on.bind(M),detach:M.detach.bind(M),getFile:T.getFile.bind(T),serialize:T.serialize.bind(T),templates:{preview:j||(()=>null),icon:w==="simple"?(()=>null):w}}),[T,M]),z=d.useRef(0);return d.useEffect(()=>{if(!z.current)b&&b(L);else{const H=T.getState();T.init({data:i,mode:l,drive:c,preview:u,panels:m||H.panels||[],activePanel:h})}z.current++},[T,i,l,c,u,m,h,b,L]),z.current===0&&T.init({data:i,mode:l,drive:c,preview:u,panels:m||[],activePanel:h}),d.useImperativeHandle(a,()=>({...L}),[L]),r.jsx(aa.Provider,{value:L,children:r.jsx(Kp,{words:Yp,optional:!0,children:r.jsx(CM,{children:r.jsx(zM,{readonly:g,menuOptions:y,extraInfo:x})})})})});function PM({fonts:t=!0,children:a}){return a?r.jsx(gb,{fonts:t,children:a}):r.jsx(gb,{fonts:t})}$p(is);function eg(t,a){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Hub ${a} response.`);return t}function td(t,a,i){const l=eg(t,i);if(!Array.isArray(l[a]))throw new Error(`Invalid Hub ${i} response: ${a} must be an array.`);return l[a]}function $M(t,a,i){const l=eg(t,i);if(!l[a]||typeof l[a]!="object"||Array.isArray(l[a]))throw new Error(`Invalid Hub ${i} response: ${a} must be an object.`);return l[a]}async function BM(t,a=!1){return td(await We(`/api/remote/filesystem/roots${a?"?refresh=1":""}`,void 0,t),"roots","filesystem roots")}async function Fh(t,a){const i=await We(`/api/remote/filesystem/entries?id=${encodeURIComponent(t)}`,void 0,a);return{folder:$M(i,"folder","filesystem entries"),entries:td(i,"entries","filesystem entries")}}async function UM(t,a){return We("/api/remote/filesystem/selection/scan",{method:"POST",body:JSON.stringify({itemIds:t})},a)}async function qM(t,a,i,l){return We("/api/remote/files/from-hub",{method:"POST",body:JSON.stringify({itemIds:t,deviceIds:a,remoteDirectory:i})},l)}async function GM(t,a=!1){const i=await We(`/api/remote/files/jobs?active=${a?"1":"0"}`,void 0,t);return{jobs:td(i,"jobs","file transfer jobs")}}async function VM(t,a){return We(`/api/remote/files/jobs/${encodeURIComponent(t)}`,void 0,a)}async function WM(t,a){return We(`/api/remote/files/jobs/${encodeURIComponent(t)}/cancel`,{method:"POST"},a)}async function Db(t){return td(await We("/api/remote/filesystem/shared-folders",void 0,t),"folders","shared folders")}async function KM(t,a){return We("/api/remote/filesystem/shared-folders",{method:"POST",body:JSON.stringify({sourceId:t})},a)}async function YM(t,a,i){return We(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(a)},i)}async function QM(t,a){return We(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}`,{method:"DELETE"},a)}async function XM(t,a,i,l){const c=await We(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}/sync`,{method:"POST",body:JSON.stringify({deviceIds:a,remoteDirectory:i})},l),u=eg(c,"shared folder sync");return{ok:u.ok===!0,jobs:td(c,"jobs","shared folder sync"),files:Number(u.files||0),totalBytes:Number(u.totalBytes||0)}}function ZM(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 Lb(t){if(!Number.isFinite(t)||t<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let i=t,l=0;for(;i>=1024&&l<a.length-1;)i/=1024,l+=1;return`${i.toFixed(l===0||i>=100?0:1)} ${a[l]}`}function Lf(t){return t.driveType==="network"?"network":t.driveType==="removable"?"removable":"local"}function JM(t){const a=t.filter(i=>Lf(i)==="local");return a.find(i=>/\bC:/i.test(`${i.name} ${i.displayPath||""}`))||a[0]||t[0]||null}function eN({hubUrl:t,roots:a,loading:i,error:l,onRefreshRoots:c,onImportFiles:u,onImportFolder:m,onSelectionChange:h,onShareItem:g,onAddSyncFolder:y,onNotice:x}){const b=d.useRef(null),w=d.useRef("/"),j=d.useRef(0),A=d.useRef([]),k=d.useRef(new Map),[T,M]=d.useState(null),[N,L]=d.useState([]),[z,H]=d.useState([]),[G,_]=d.useState(0),[Y,q]=d.useState(null),[U,K]=d.useState(!1),[O,ve]=d.useState(""),[me,Z]=d.useState(new Set),I=a.find(ne=>ne.id===T)||null,se=N[N.length-1]||null,W=I?se?.svarPath||`/${I.name}`:null,F=W;d.useEffect(()=>{A.current=N,w.current=F||"/"},[F,N]);const oe=d.useMemo(()=>(k.current.clear(),!I||!F||N.length===0?[]:(N.forEach(ne=>k.current.set(ne.svarPath,ne.hubId)),[...N.map((ne,xe)=>({id:ne.svarPath,parent:xe===0?"/":N[xe-1].svarPath,type:"folder",name:ne.name,date:ne.modifiedAt?new Date(ne.modifiedAt):void 0,lazy:!1})),...z.map(ne=>{const xe=`${F}/${ne.name}`;return k.current.set(xe,ne.id),{id:xe,parent:F,name:ne.name,type:ne.type==="file"?"file":"folder",...ne.type==="file"?{size:ne.size}:{},date:ne.modifiedAt?new Date(ne.modifiedAt):void 0,lazy:ne.type!=="file"&&ne.hasChildren===!0,displayPath:ne.displayPath,locked:ne.locked,driveType:ne.driveType,totalBytes:ne.totalBytes,freeBytes:ne.freeBytes}})])),[I,z,F,N]),le=ne=>k.current.get(String(ne))||String(ne),Q=ne=>ZM({...ne,id:le(String(ne.id)),parent:le(String(ne.parent))}),be=async(ne,xe)=>{const Oe=ne[ne.length-1];if(!Oe)return;const $e=++j.current;K(!0),ve("");try{const ze=await Fh(Oe.hubId,t);if($e!==j.current)return;if(!Array.isArray(ze.entries))throw new Error("Invalid Hub filesystem entries response.");const Qe={...Oe,displayPath:ze.folder.displayPath||Oe.displayPath,modifiedAt:ze.folder.modifiedAt||Oe.modifiedAt},qe=[...ne.slice(0,-1),Qe];A.current=qe,L(qe),H(ze.entries),_(Ye=>Ye+1)}catch(ze){if($e!==j.current)return;console.error("[LiveDesk FS] folder navigation failed",{folderId:Oe.hubId,error:ze}),ve(ze instanceof Error?`${xe}: ${ze.message}`:`${xe}: Unable to read this folder.`)}finally{$e===j.current&&K(!1)}},he=async ne=>{const xe={svarPath:`/${ne.name}`,hubId:ne.id,name:ne.name,displayPath:ne.displayPath,modifiedAt:ne.modifiedAt},Oe=++j.current;M(ne.id),A.current=[xe],L([xe]),w.current=xe.svarPath,H([]),ve(""),K(!0),q(ne.id),Z($e=>{const ze=new Set($e);return ze.delete(ne.id),ze});try{const $e=await Fh(ne.id,t);if(Oe!==j.current)return;if(!Array.isArray($e.entries))throw new Error("Invalid Hub filesystem entries response.");const ze={...xe,displayPath:$e.folder.displayPath||xe.displayPath,modifiedAt:$e.folder.modifiedAt||xe.modifiedAt};A.current=[ze],L([ze]),H($e.entries),_(Qe=>Qe+1)}catch($e){if(Oe!==j.current)return;console.error("[LiveDesk FS] getEntries failed",{rootId:ne.id,error:$e}),Z(ze=>new Set(ze).add(ne.id)),ve($e instanceof Error?`${ne.name}: ${$e.message}`:`${ne.name}: Unable to read this drive.`),x($e instanceof Error?`${ne.name}: ${$e.message}`:`${ne.name}: Unable to read this drive.`)}finally{Oe===j.current&&(q(null),K(!1))}},de=ne=>{const xe=A.current;ne<0||ne>=xe.length||ne===xe.length-1||be(xe.slice(0,ne+1),xe[ne].name)},ee=(ne,xe)=>{if(ne.type!=="folder")return;const Oe=A.current,$e=Oe.findIndex(Qe=>Qe.svarPath===xe);if($e<0)return;const ze={svarPath:`${xe}/${ne.name}`,hubId:ne.id,name:ne.name,displayPath:ne.displayPath,modifiedAt:ne.modifiedAt};be([...Oe.slice(0,$e+1),ze],ne.name)},Ce=()=>de(A.current.length-2),Re=ne=>{if(ne.key!=="Enter"&&ne.code!=="Enter"&&ne.code!=="NumpadEnter"||ne.target?.closest('button, input, textarea, [contenteditable="true"]'))return;const Oe=b.current;if(!Oe)return;const $e=Oe.getState().panels?.flatMap(Qe=>Qe.selected||[])||[];if($e.length!==1)return;const ze=Oe.getFile(String($e[0]));ze?.type==="folder"&&(ne.preventDefault(),ne.stopPropagation(),ee(Q(ze),String(ze.parent||w.current)))};d.useEffect(()=>{const ne=a.find(xe=>xe.id===T)||JM(a);if(Z(xe=>new Set([...xe].filter(Oe=>a.some($e=>$e.id===Oe)))),!ne){M(null),A.current=[],L([]),H([]);return}he(ne)},[a]);const He=ne=>{b.current=ne,ne.on("request-data",async({id:xe})=>{const Oe=String(xe),$e=le(Oe);try{const ze=await Fh($e,t);if(!Array.isArray(ze.entries))throw new Error("Invalid Hub filesystem entries response.");const Qe=ze.entries.map(qe=>{const Ye=`${Oe}/${qe.name}`;return k.current.set(Ye,qe.id),{id:Ye,parent:Oe,name:qe.name,type:qe.type==="file"?"file":"folder",...qe.type==="file"?{size:qe.size}:{},date:qe.modifiedAt?new Date(qe.modifiedAt):void 0,lazy:qe.type!=="file"&&qe.hasChildren===!0,displayPath:qe.displayPath,locked:qe.locked,driveType:qe.driveType,totalBytes:qe.totalBytes,freeBytes:qe.freeBytes}});await ne.exec("provide-data",{id:Oe,data:Qe})}catch(ze){console.error("[LiveDesk FS] nested getEntries failed",{id:$e,error:ze}),x(ze instanceof Error?ze.message:"Unable to read this folder.")}}),ne.intercept("set-path",({id:xe})=>{const Oe=String(xe),$e=A.current.findIndex(Qe=>Qe.svarPath===Oe);if($e>=0)return de($e),!1;const ze=ne.getFile(Oe);if(ze?.type==="folder")return ee(Q(ze),String(ze.parent||w.current)),!1}),ne.intercept("open-file",()=>!1),ne.on("select-file",()=>{window.setTimeout(()=>{const $e=(ne.getState().panels?.flatMap(ze=>ze.selected||[])||[]).map(ze=>ne.getFile(ze)).filter(Boolean).map(ze=>Q(ze));h($e.map(ze=>ze.id),$e)},0)})},te=(ne,xe)=>{const Oe=xe?Q(xe):null,$e=()=>{const ze=Oe?.type==="file"?String(xe?.parent||w.current):String(xe?.id||w.current);b.current?.exec("request-data",{id:ze})};return ne==="body"?[{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:$e},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>x("Select a file or folder to view its properties.")}]:ne==="multiselect"?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>{(b.current?.getState().panels?.flatMap(Qe=>Qe.selected||[])||[]).forEach(Qe=>{const qe=b.current?.getFile(Qe);qe&&g(Q(qe))})}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:$e}]:Oe?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>g(Oe)},...Oe.type==="folder"?[{id:"sync",text:"Add folder to Sync",icon:"mdi mdi-folder-sync-outline",handler:()=>y(Oe)}]:[],{id:"copy-path",text:"Copy path",icon:"mdi mdi-content-copy",handler:()=>{Nf(Oe.displayPath||Oe.name)}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:$e},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>x(`${Oe.name}
|
|
14
|
+
${Oe.displayPath||""}`)}]:[]},Ue=async()=>{try{await c()}catch(ne){x(ne instanceof Error?ne.message:"Unable to refresh Hub drives.")}},mt=[{id:"local",label:"Local drives",icon:So,roots:a.filter(ne=>Lf(ne)==="local")},{id:"removable",label:"Removable drives",icon:E0,roots:a.filter(ne=>Lf(ne)==="removable")},{id:"network",label:"Network drives",icon:Lp,roots:a.filter(ne=>Lf(ne)==="network")}];return r.jsxs("section",{className:"hub-file-explorer-panel","aria-label":"Hub file explorer",children:[r.jsxs("div",{className:"hub-file-explorer-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Hub file explorer"}),r.jsxs("strong",{children:[r.jsx(So,{size:16})," Browse files on this Hub"]})]}),r.jsxs("div",{className:"hub-file-explorer-heading-actions",children:[r.jsx("button",{className:"icon-button",onClick:u,title:"Import files from this browser",type:"button",children:r.jsx(Sx,{size:16})}),r.jsx("button",{className:"icon-button",onClick:m,title:"Import folder from this browser",type:"button",children:r.jsx(D0,{size:16})}),r.jsx("button",{className:"icon-button",onClick:()=>{Ue()},title:"Refresh drives",type:"button",children:r.jsx(Mc,{size:16})})]})]}),i?r.jsxs("div",{className:"hub-file-explorer-state",children:[r.jsx(So,{size:24}),r.jsx("strong",{children:"Connecting to LiveDesk Hub file system..."})]}):l?r.jsxs("div",{className:"hub-file-explorer-state error",role:"alert",children:[r.jsx(Di,{size:24}),r.jsx("strong",{children:l})]}):r.jsxs("div",{className:"hub-file-explorer-content",children:[r.jsxs("aside",{className:"hub-file-explorer-drive-sidebar","aria-label":"Hub drives",children:[r.jsxs("div",{className:"hub-drive-sidebar-title",children:[r.jsx(So,{size:15}),r.jsx("strong",{children:"This PC"})]}),mt.map(ne=>ne.roots.length>0&&r.jsxs("section",{className:"hub-drive-group",children:[r.jsxs("h3",{children:[r.jsx(ne.icon,{size:13}),ne.label]}),r.jsx("div",{className:"hub-drive-list",children:ne.roots.map(xe=>{const Oe=ne.icon,$e=me.has(xe.id)||xe.locked===!0;return r.jsxs("button",{className:`hub-drive-item ${T===xe.id?"active":""} ${$e?"unavailable":""}`,onClick:()=>{he(xe)},"aria-pressed":T===xe.id,type:"button",children:[r.jsx("span",{className:"hub-drive-item-icon",children:r.jsx(Oe,{size:16})}),r.jsxs("span",{className:"hub-drive-item-copy",children:[r.jsx("strong",{children:xe.name}),r.jsx("small",{children:xe.displayPath||xe.name}),r.jsxs("em",{children:[Lb(xe.freeBytes||0)," free / ",Lb(xe.totalBytes||0)]})]}),Y===xe.id?r.jsx(zr,{className:"hub-drive-item-status spin",size:15}):$e?r.jsx(xy,{className:"hub-drive-item-status",size:15}):null]},xe.id)})})]},ne.id)),a.length===0&&r.jsxs("div",{className:"hub-drive-sidebar-empty",children:[r.jsx(Di,{size:17}),r.jsx("span",{children:"No drives available."})]})]}),r.jsxs("div",{className:"hub-file-explorer-browser",children:[r.jsxs("div",{className:"hub-file-explorer-navigation",children:[r.jsx("nav",{className:"hub-file-explorer-breadcrumbs","aria-label":"Current Hub folder",children:N.map((ne,xe)=>r.jsxs("span",{className:"hub-file-explorer-breadcrumb-item",children:[xe>0&&r.jsx(_p,{size:13,"aria-hidden":"true"}),r.jsx("button",{className:`hub-file-explorer-breadcrumb ${xe===N.length-1?"current":""}`,onClick:()=>de(xe),"aria-current":xe===N.length-1?"location":void 0,type:"button",children:ne.name})]},ne.svarPath))}),r.jsxs("div",{className:"hub-file-explorer-navigation-actions",children:[U&&r.jsx(zr,{className:"hub-file-explorer-loading-icon spin",size:15,"aria-label":"Loading folder"}),r.jsx("button",{className:"icon-button",onClick:Ce,disabled:N.length<=1||U,title:"Back to parent folder",type:"button",children:r.jsx(px,{size:16})})]})]}),O&&r.jsxs("div",{className:"hub-file-explorer-folder-error",role:"alert",children:[r.jsx(xy,{size:15}),r.jsx("span",{children:O})]}),r.jsx("div",{className:"hub-file-explorer-svar",onKeyDownCapture:Re,children:r.jsx(PM,{fonts:!1,children:r.jsx(FM,{data:oe,panels:W?[{path:W,selected:[]}]:void 0,readonly:!0,mode:"table",preview:!1,init:He,icons:"simple",menuOptions:te},`${I?.id||"no-root"}:${G}`)})})]})]})]})}class tN extends d.Component{state={error:null};static getDerivedStateFromError(a){return{error:a}}componentDidCatch(a,i){console.error("[LiveDesk] Share Files runtime error",a,i.componentStack)}render(){return this.state.error?r.jsxs("section",{className:"file-share-error-boundary",role:"alert",children:[r.jsx(Wf,{size:24}),r.jsx("strong",{children:"Share Files could not be opened."}),r.jsx("span",{children:this.state.error.message||"An unexpected file explorer error occurred."}),r.jsxs("button",{className:"text-button",onClick:this.props.onRetry,type:"button",children:[r.jsx(Mc,{size:15})," Retry"]})]}):this.props.children}}function nN(t){return t.deviceName||t.hostname||t.deviceId}function aN({devices:t,mode:a,selectedIds:i,onModeChange:l,onToggle:c}){const u=new Set(i);return r.jsxs("section",{className:"distribution-targets",children:[r.jsxs("div",{className:"file-share-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Target"}),r.jsx("strong",{children:a==="all"?`${t.length} connected`:`${i.length} selected`})]}),r.jsxs("div",{className:"file-share-tabs compact","aria-label":"File transfer targets",children:[r.jsxs("button",{className:a==="all"?"active":"",onClick:()=>l("all"),type:"button",children:[r.jsx(Ku,{size:14})," All connected"]}),r.jsxs("button",{className:a==="selected"?"active":"",onClick:()=>l("selected"),type:"button",children:[r.jsx(Ea,{size:14})," Selected"]})]})]}),r.jsx("div",{className:"file-share-device-list","aria-label":"Connected Client targets",children:t.length===0?r.jsx("div",{className:"file-share-empty-inline",children:"No connected Clients."}):t.map(m=>{const h=a==="all"||u.has(m.deviceId);return r.jsxs("label",{className:`file-share-device-option ${h?"selected":""}`,children:[r.jsx("input",{type:"checkbox",checked:h,disabled:a==="all",onChange:()=>c(m.deviceId)}),r.jsx(Ea,{size:20,"aria-hidden":"true"}),r.jsxs("span",{children:[r.jsx("strong",{children:nN(m)}),r.jsxs("small",{children:["Slot ",m.slotNumber?String(m.slotNumber).padStart(3,"0"):"-"," / ",m.platform||"unknown OS"]})]}),r.jsx(ea,{size:17,"aria-hidden":"true"})]},m.deviceId)})})]})}function sN(t){if(!Number.isFinite(t)||t<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let i=t,l=0;for(;i>=1024&&l<a.length-1;)i/=1024,l+=1;return`${i.toFixed(l===0||i>=100?0:1)} ${a[l]}`}function rN({folders:t,loading:a,busy:i,canSync:l,onSyncAll:c,onSync:u,onToggleAuto:m,onRemove:h,onAdd:g}){return r.jsxs("section",{className:"file-share-sync-panel",children:[r.jsxs("div",{className:"file-share-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Hub folders"}),r.jsx("strong",{children:"Continuous sync"})]}),r.jsxs("button",{className:"text-button compact",onClick:c,disabled:i||!l||t.length===0,type:"button",children:[r.jsx(Mf,{size:15})," ",i?"Syncing":"Sync all"]})]}),a?r.jsx("div",{className:"file-share-empty-state",children:"Loading Hub sync folders..."}):t.length===0?r.jsxs("button",{className:"file-share-empty-state interactive",onClick:g,type:"button",children:[r.jsx(Mf,{size:28}),r.jsx("strong",{children:"Add a selected Hub folder"}),r.jsx("span",{children:"Hub keeps the manifest and can sync while this browser is closed."})]}):r.jsx("div",{className:"file-share-sync-list",children:t.map(y=>r.jsxs("article",{className:`file-share-sync-row state-${y.status}`,children:[r.jsx("div",{className:"file-share-sync-icon",children:r.jsx(Mf,{size:19})}),r.jsxs("div",{className:"file-share-sync-info",children:[r.jsx("strong",{children:y.name}),r.jsx("span",{children:y.displayPath}),r.jsxs("small",{children:[y.fileCount," files / ",sN(y.totalBytes)," · ",y.lastSyncedAt?`Last sync ${Ex(y.lastSyncedAt)} ago`:y.message||"Not synced yet"]})]}),r.jsxs("label",{className:"file-share-auto-sync",children:[r.jsx("input",{type:"checkbox",checked:y.autoSync,onChange:()=>m(y)}),r.jsx("span",{children:"Auto"})]}),r.jsxs("button",{className:"text-button compact",onClick:()=>u(y),disabled:i||!l||y.status==="syncing",type:"button",children:[r.jsx(Mc,{size:14})," Sync now"]}),r.jsx("button",{className:"icon-button",onClick:()=>h(y),title:"Remove sync folder",type:"button",children:r.jsx(Rp,{size:15})})]},y.id))})]})}function iN(t){const i=(t.targetMode==="all"?t.devices.map(l=>l.deviceId):t.selectedTargetIds).length>0;return r.jsxs("aside",{className:"file-share-distribution-panel",children:[r.jsxs("div",{className:"file-share-distribution-head",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Distribution"}),r.jsx("strong",{children:"Hub → Clients"})]}),r.jsx(Wu,{size:18})]}),r.jsxs("div",{className:"file-share-tabs",role:"tablist","aria-label":"Distribution mode",children:[r.jsx("button",{className:t.tab==="send"?"active":"",onClick:()=>t.onTabChange("send"),role:"tab","aria-selected":t.tab==="send",type:"button",children:"Send"}),r.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"?r.jsxs(r.Fragment,{children:[r.jsx(aN,{devices:t.devices,mode:t.targetMode,selectedIds:t.selectedTargetIds,onModeChange:t.onTargetModeChange,onToggle:t.onTargetToggle}),r.jsxs("label",{className:"file-share-destination",children:[r.jsx("span",{children:"Destination folder"}),r.jsxs("div",{children:[r.jsx(Sc,{size:15}),r.jsx("input",{value:t.remoteDirectory,onChange:l=>t.onRemoteDirectoryChange(l.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),r.jsx("small",{children:"Blank uses Desktop/LiveDeskFiles."})]}),r.jsxs("div",{className:"file-share-selection-summary",children:[r.jsx("span",{children:"Selected"}),r.jsx("strong",{children:t.selectedSummary})]}),r.jsxs("button",{className:"file-share-share-button",onClick:t.onShare,disabled:!t.canShare,type:"button",children:[r.jsx(Wu,{size:17})," Share selected"]}),r.jsxs("button",{className:"file-share-secondary-button",onClick:t.onAddSync,disabled:!t.canAddSync,type:"button",children:[r.jsx(Sc,{size:16})," Add selected folder to Sync"]})]}):r.jsx(rN,{folders:t.folders,loading:t.foldersLoading,busy:t.syncBusy,canSync:i,onSyncAll:t.onSyncAll,onSync:t.onSync,onToggleAuto:t.onToggleAuto,onRemove:t.onRemove,onAdd:t.onAddFolder})]})}function lN(t){if(!Number.isFinite(t)||t<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let i=t,l=0;for(;i>=1024&&l<a.length-1;)i/=1024,l+=1;return`${i.toFixed(l===0||i>=100?0:1)} ${a[l]}`}function _b(t){if(t.state==="completed")return 100;const a=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(jp(t.state)?100:99,a))}function Ib(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 jp(t){return["completed","partially-failed","failed","cancelled"].includes(t)}function oN({hubUrl:t,devices:a,localFeatureAccess:i,upgradeNotice:l,remoteDirectory:c,onRemoteDirectoryChange:u,targetMode:m,selectedTargetIds:h,onTargetModeChange:g,onTargetToggle:y,filePickerRef:x,folderPickerRef:b,onBrowserFileImport:w,onBrowserFolderImport:j,onNotice:A,onTransferChange:k}){const T=Array.isArray(a)?a:[],[M,N]=d.useState([]),[L,z]=d.useState(!0),[H,G]=d.useState(""),[_,Y]=d.useState([]),[q,U]=d.useState([]),[K,O]=d.useState(null),[ve,me]=d.useState(!1),[Z,I]=d.useState([]),[se,W]=d.useState(!0),[F,oe]=d.useState(!1),[le,Q]=d.useState("send"),[be,he]=d.useState([]),de=d.useRef(new Set),ee=d.useRef(!1),Ce=d.useMemo(()=>m==="all"?T.map(B=>B.deviceId):h.filter(B=>T.some(ye=>ye.deviceId===B)),[T,h,m]),Re=be.find(B=>!jp(B.state)),He=q.length===1&&q[0].type==="folder"?q[0]:null,te=q.length===0?"Select files or folders from the Hub explorer.":ve?"Calculating selection size...":K?`${K.files} files, ${K.folders} folders · ${lN(K.totalBytes)}`:`${q.length} item${q.length===1?"":"s"} selected`,Ue=B=>{k({id:B.jobId,state:B.state,progress:_b(B),message:Ib(B)})},mt=d.useCallback(async()=>{const B=await BM(t,!0);return N(B),G(""),B},[t]),ne=async()=>{if(!ee.current){ee.current=!0;try{const ye=(await GM(t,!0)).jobs||[],je=await Promise.all([...de.current].map(async nt=>{try{return await VM(nt,t)}catch{return null}})),Pe=[...ye,...je.filter(Boolean)],dt=[...new Map(Pe.map(nt=>[nt.jobId,nt])).values()];he(dt),dt.forEach(Ue),dt.filter(nt=>jp(nt.state)).forEach(nt=>de.current.delete(nt.jobId))}catch{}finally{ee.current=!1}}};d.useEffect(()=>{let B=!0;z(!0),G(""),Promise.all([mt(),Db(t).then(je=>{B&&I(je)})]).catch(je=>{B&&(G(je instanceof Error?"Hub file system is unavailable. Make sure LiveDesk Hub is running on this computer.":"Hub file system is unavailable."),A(je instanceof Error?je.message:"Hub file system is unavailable."))}).finally(()=>{B&&(z(!1),W(!1))}),ne();const ye=window.setInterval(()=>{ne()},800);return()=>{B=!1,window.clearInterval(ye)}},[t,mt]),d.useEffect(()=>{if(_.length===0){O(null);return}let B=!1;return me(!0),UM(_,t).then(ye=>{B||O(ye)}).catch(ye=>{B||A(ye instanceof Error?ye.message:"Unable to calculate selected size.")}).finally(()=>{B||me(!1)}),()=>{B=!0}},[t,_.join("|")]);const xe=(B,ye)=>{Y(B),U(ye)},Oe=B=>{B.forEach(ye=>de.current.add(ye.jobId)),he(ye=>[...new Map([...ye,...B].map(je=>[je.jobId,je])).values()]),B.forEach(Ue)},$e=async()=>{if(!i){A(l);return}if(_.length===0){A("Select files or folders from the Hub explorer.");return}if(Ce.length===0){A("Choose at least one connected Client.");return}if(Re){A("A Hub transfer is already running.");return}try{const B=await qM(_,Ce,c.trim(),t);de.current.add(B.jobId),A("Hub transfer queued."),await ne()}catch(B){A(B instanceof Error?B.message:"Unable to start Hub transfer.")}},ze=async B=>{const ye=B||He;if(!ye||ye.type!=="folder"){A("Select one folder to add it to Sync.");return}try{const je=await KM(ye.id,t);I(Pe=>[...Pe.filter(dt=>dt.id!==je.folder.id),je.folder]),Q("sync"),A(`${ye.name} is ready for Hub sync.`)}catch(je){A(je instanceof Error?je.message:"Unable to add the Hub folder to Sync.")}},Qe=async B=>{if(Ce.length===0){A("Choose at least one connected Client.");return}oe(!0),I(ye=>ye.map(je=>je.id===B.id?{...je,status:"syncing"}:je));try{const ye=await XM(B.id,Ce,c.trim(),t);Oe(ye.jobs||[]),A(ye.jobs?.length?"Hub sync queued.":"No changed files to sync.");const je=await Db(t);I(je)}catch(ye){A(ye instanceof Error?ye.message:"Unable to sync the Hub folder."),I(je=>je.map(Pe=>Pe.id===B.id?{...Pe,status:"error",message:"Sync failed"}:Pe))}finally{oe(!1)}},qe=async()=>{oe(!0);try{for(const B of Z)await Qe(B)}finally{oe(!1)}},Ye=async B=>{try{const ye=await YM(B.id,{autoSync:!B.autoSync},t);I(je=>je.map(Pe=>Pe.id===B.id?ye.folder:Pe))}catch(ye){A(ye instanceof Error?ye.message:"Unable to update auto sync.")}},ot=async B=>{try{await QM(B.id,t),I(ye=>ye.filter(je=>je.id!==B.id))}catch(ye){A(ye instanceof Error?ye.message:"Unable to remove the sync folder.")}};return r.jsxs("section",{className:"livedesk-file-explorer",children:[r.jsx("input",{ref:x,className:"hidden-file-input",type:"file",multiple:!0,onChange:B=>{B.currentTarget.files&&w(B.currentTarget.files),B.currentTarget.value=""}}),r.jsx("input",{ref:b,className:"hidden-file-input",type:"file",multiple:!0,webkitdirectory:"",directory:"",onChange:B=>{B.currentTarget.files&&j(B.currentTarget.files),B.currentTarget.value=""}}),r.jsx("div",{className:"file-share-workspace",children:r.jsxs(tN,{onRetry:()=>window.location.reload(),children:[r.jsx(eN,{hubUrl:t,roots:M,loading:L,error:H,onRefreshRoots:mt,onImportFiles:()=>x.current?.click(),onImportFolder:()=>b.current?.click(),onSelectionChange:xe,onShareItem:B=>{Y([B.id]),U([B]),Q("send")},onAddSyncFolder:B=>{Y([B.id]),U([B]),ze(B)},onNotice:A}),r.jsx(iN,{devices:T,targetMode:m,selectedTargetIds:h,onTargetModeChange:g,onTargetToggle:y,remoteDirectory:c,onRemoteDirectoryChange:u,selectedEntries:q,selectedSummary:te,canShare:i&&!Re&&_.length>0&&Ce.length>0&&!ve,onShare:()=>{$e()},canAddSync:!!He,onAddSync:()=>{ze()},tab:le,onTabChange:Q,folders:Z,foldersLoading:se,syncBusy:F,onSyncAll:()=>{qe()},onSync:B=>{Qe(B)},onToggleAuto:B=>{Ye(B)},onRemove:B=>{ot(B)},onAddFolder:()=>{ze()}})]})}),Re&&r.jsx("footer",{className:"file-share-workspace-footer",children:r.jsxs("span",{children:[Ib(Re)," · ",_b(Re),"% ",r.jsx("button",{className:"icon-button",onClick:()=>{WM(Re.jobId,t).then(B=>{he(ye=>ye.map(je=>je.jobId===B.jobId?B:je)),Ue(B)})},title:"Cancel transfer",type:"button",children:r.jsx(Ra,{size:14})})]})})]})}const cN=d.forwardRef(function({value:a,onChange:i,onSubmit:l,onOpenSuggestedTasks:c,suggestedOpen:u=!1,suggestedTaskCount:m,disabled:h=!1,placeholder:g="Ask LiveDesk to work across your machines...",compact:y=!1},x){return r.jsxs("form",{className:"agents-composer",onSubmit:b=>{b.preventDefault(),l()},children:[r.jsx("button",{className:`agents-suggested-trigger ${u?"active":""}`,type:"button","aria-label":m===void 0?"Open Suggested tasks":`Open Suggested tasks (${m} available)`,"aria-expanded":u,onClick:c,disabled:h,children:r.jsx(L0,{size:17})}),r.jsx("textarea",{ref:x,value:a,onChange:b=>i(b.target.value.slice(0,4e3)),placeholder:g,"aria-label":"Ask LiveDesk",rows:y?1:2,disabled:h}),r.jsxs("button",{className:"agents-run-button",type:"submit",disabled:h||!a.trim(),children:[h?r.jsx(zr,{className:"spin",size:16}):r.jsx(Wu,{size:16}),h?"Running":"Run"]})]})}),uN=["read","processControl","serviceControl","applicationControl","fileRead","fileWrite","fileDelete","shell","script","softwareInstall","network","systemPower","systemConfiguration","userAccount"];function Uf(t){return t.deviceName?.trim()||t.hostname?.trim()||t.deviceId}function qf(t){return t.connected!==!0?!1:t.synthetic===!0?!0:!t.channels||t.channels.control===!0}function dN(t){return t==="running"||t==="completed"||t==="failed"||t==="cancelled"?t:"queued"}function fN(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 mN(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function ys(t){return typeof t=="number"&&Number.isFinite(t)?t:null}function bf(t){const a=ys(t);return a===null?"":a<1024**2?`${Math.round(a/1024)}K`:a<1024**3?`${(a/1024**2).toFixed(0)}M`:`${(a/1024**3).toFixed(1)}G`}function hN(t){const a=ys(t);return a===null?"":`${Math.round((a<=1?a:a/100)*100)}%`}function pN(t){return!t||/^(?:[\w .-]+ )?collected(?:\.)?$/i.test(t.trim())?"":t.trim()}function Gf(t,a){if(a.error)return a.error;const i=mN(a.data),l=pN(a.result||"");if(!i)return l||a.stage||a.status;if(t==="system.health"){const c=typeof i.machine=="string"?i.machine:"",u=bf(i.freeMemoryBytes),m=bf(i.totalMemoryBytes),h=ys(i.totalMemoryBytes)&&ys(i.freeMemoryBytes)!==null?`${Math.round(ys(i.freeMemoryBytes)/ys(i.totalMemoryBytes)*100)}% RAM free`:"";return[c,u&&m?`RAM ${u}/${m}`:"",h,typeof i.platform=="string"?i.platform:""].filter(Boolean).join(" · ")||l||a.status}if(t==="disk.status"){const c=typeof i.root=="string"?i.root:"",u=bf(i.freeBytes),m=ys(i.totalBytes)&&ys(i.freeBytes)!==null?`${Math.round(ys(i.freeBytes)/ys(i.totalBytes)*100)}% free`:"";return[c,u&&`${u} free`,m].filter(Boolean).join(" · ")||l||a.status}if(t==="gpu.status"){const c=typeof i.name=="string"&&i.name?i.name:"No GPU provider",u=hN(i.usageRatio),m=ys(i.temperatureC)!==null?`${Math.round(ys(i.temperatureC))}°C`:"",h=bf(i.freeMemoryBytes);return[c,u&&`GPU ${u}`,m,h&&`${h} free`].filter(Boolean).join(" · ")||l||a.status}if(t==="process.list"){const c=ys(i.count);return c!==null?`${c} matching process${c===1?"":"es"}`:l||a.status}if(t==="network.status"){const c=Array.isArray(i.adapters)?i.adapters.length:null;return c!==null?`${c} active adapter${c===1?"":"s"}`:l||a.status}return l||a.stage||a.status}function zb(t,a){const i=Gf(t,a);return a.status==="failed"||a.status==="cancelled"||/\b(?:warning|failed|error|offline|not running|low|timeout|timed out)\b/i.test(`${a.result||""} ${i}`)}function gN({state:t,operation:a}){const i=t.status==="completed"?Or:t.status==="failed"||t.status==="cancelled"?Ra:t.status==="running"?zr:Cx,l=t.status==="running"?t.stage||"Working":t.status==="completed"?a?Gf(a,t):t.result||"Completed":t.status==="failed"?t.error||"Failed":t.status==="cancelled"?"Cancelled":"Queued";return r.jsxs("div",{className:`agent-target-row status-${t.status}`,"data-agent-target-id":t.deviceId,children:[r.jsx("span",{className:"agent-target-status","aria-hidden":"true",children:r.jsx(i,{size:15})}),r.jsx("strong",{children:t.deviceName}),r.jsx("span",{className:"agent-target-state",children:t.status[0].toUpperCase()+t.status.slice(1)}),r.jsx("small",{children:l})]})}function vN({operation:t,states:a,status:i,onCancel:l,onRetry:c,busy:u=!1}){const m=["running","queued"].includes(i),[h,g]=d.useState(!1),[y,x]=d.useState("all"),b=d.useMemo(()=>({total:a.length,completed:a.filter(L=>L.status==="completed").length,failed:a.filter(L=>L.status==="failed").length,running:a.filter(L=>L.status==="running").length,queued:a.filter(L=>L.status==="queued").length,cancelled:a.filter(L=>L.status==="cancelled").length}),[a]),w=a.filter(L=>zb(t,L)),j=w.filter(L=>L.status==="completed").length,A=b.failed>0,k=w.length>0,T=a.filter(L=>y==="issues"?zb(t,L):y==="running"?L.status==="running"||L.status==="queued":y==="completed"?L.status==="completed":y==="failed"?L.status==="failed":!0),M=k&&!m||i==="completed-with-failures"?"Completed with issues":i[0]?.toUpperCase()+i.slice(1),N=a.filter(L=>L.status==="completed").map(L=>Gf(t,L)).filter(Boolean).filter((L,z,H)=>H.indexOf(L)===z).slice(0,2);return r.jsxs("section",{className:"agent-task-block","aria-label":"Task execution",children:[r.jsxs("div",{className:"agent-task-head",children:[r.jsxs("div",{children:[r.jsx("span",{children:"LiveDesk Agent"}),r.jsx("strong",{children:fN(t)})]}),r.jsx("span",{className:`agent-task-status status-${k?"completed-with-failures":i}`,children:M})]}),r.jsxs("div",{className:"agent-task-summary","aria-label":"Task summary",children:[r.jsxs("strong",{children:[b.total," targets"]}),r.jsxs("span",{className:"summary-completed",children:[b.completed," completed"]}),b.running>0&&r.jsxs("span",{className:"summary-running",children:[b.running," running"]}),b.queued>0&&r.jsxs("span",{children:[b.queued," queued"]}),A&&r.jsxs("span",{className:"summary-failed",children:[b.failed," failed"]}),j>0&&r.jsxs("span",{className:"summary-cancelled",children:[j," warning"]}),b.cancelled>0&&r.jsxs("span",{className:"summary-cancelled",children:[b.cancelled," cancelled"]})]}),N.length>0&&r.jsxs("div",{className:"agent-task-result-preview",title:N.join(" · "),children:[r.jsx("span",{children:"Result"}),N.join(" · ")]}),r.jsx("div",{className:"agent-target-chips","aria-label":"Target status overview",children:a.map((L,z)=>{const H=L.status==="completed"?"✓":L.status==="failed"?"×":L.status==="cancelled"?"!":L.status==="running"?"…":"·";return r.jsxs("span",{className:`agent-target-chip status-${L.status}`,title:`${L.deviceName}: ${Gf(t,L)}`,"aria-label":`${z+1}. ${L.deviceName}: ${L.status}`,children:[r.jsx("b",{children:String(z+1).padStart(2,"0")}),r.jsx("span",{children:H})]},L.deviceId)})}),a.length>0&&r.jsx("div",{className:"agent-task-details-toggle",children:r.jsxs("button",{type:"button",onClick:()=>g(L=>!L),"aria-expanded":h,children:[h?r.jsx(_0,{size:14}):r.jsx(kx,{size:14}),h?"Hide details":"Show details"]})}),h&&r.jsxs("div",{className:"agent-task-details",children:[r.jsx("div",{className:"agent-task-filters",role:"tablist","aria-label":"Task result filter",children:["all","issues","running","completed","failed"].map(L=>r.jsx("button",{className:y===L?"active":"",onClick:()=>x(L),role:"tab","aria-selected":y===L,type:"button",children:L==="all"?"All":L==="issues"?"Issues only":L[0].toUpperCase()+L.slice(1)},L))}),r.jsx("div",{className:"agent-task-rows",children:T.length>0?T.map(L=>r.jsx(gN,{operation:t,state:L},L.deviceId)):r.jsx("small",{className:"agent-task-no-results",children:"No targets match this filter."})})]}),(m||A)&&r.jsxs("div",{className:"agent-task-actions",children:[m&&l&&r.jsxs("button",{onClick:l,disabled:u,type:"button",children:[r.jsx(I0,{size:14})," Cancel"]}),!m&&A&&c&&r.jsxs("button",{onClick:c,disabled:u,type:"button",children:[r.jsx(Ep,{size:14})," Retry failed"]})]})]})}function yN(t){try{return JSON.stringify(t,null,2).slice(0,6e3)}catch{return"{}"}}function bN({approval:t,busy:a=!1,onApprove:i,onReject:l}){return r.jsxs("article",{className:"agent-approval-card","aria-label":"Agent approval required",children:[r.jsxs("div",{className:"agent-approval-head",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Approval required"}),r.jsx("strong",{children:t.toolName})]}),r.jsx("span",{className:`agent-approval-risk risk-${t.risk}`,children:t.risk})]}),r.jsx("p",{children:t.description}),r.jsx("pre",{children:yN(t.arguments)}),r.jsxs("small",{children:["Permission: ",t.permissionMode," · Scope: selected devices only · Expires in 5 minutes"]}),r.jsxs("div",{className:"agent-approval-actions",children:[r.jsxs("button",{className:"reject",disabled:a,onClick:l,type:"button",children:[r.jsx(Ra,{size:14})," Reject"]}),r.jsxs("button",{disabled:a,onClick:()=>i("once"),type:"button",children:[r.jsx(Or,{size:14})," Once"]}),r.jsx("button",{disabled:a,onClick:()=>i("same-action-this-run"),type:"button",children:"Allow same action"}),r.jsx("button",{disabled:a,onClick:()=>i("category-this-run"),type:"button",children:"Allow category"})]}),r.jsxs("div",{className:"agent-approval-scope",children:[r.jsx(Wf,{size:13})," Approval is bound to this run, tool, arguments, selected devices, and policy hash."]})]})}function xN(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 wN({items:t,onCancel:a,onRetry:i,busyBatchId:l,approvals:c,onApprove:u,onReject:m,busyApprovalId:h,progress:g,emptyTitle:y="Ask LiveDesk to work across your machines.",emptyBody:x="Start with a read-only request such as “모든 PC에서 ComfyUI가 실행 중인지 확인해줘”."}){const b=d.useRef(null),w=d.useRef(!0),j=d.useRef(""),A=t[t.length-1];return d.useLayoutEffect(()=>{const k=b.current;k&&(A?.type==="user"&&A.id!==j.current&&(w.current=!0),j.current=A?.id||"",w.current&&(k.scrollTop=k.scrollHeight))},[c,t,A?.id,A?.type,g?.message,g?.stage]),r.jsxs("section",{className:"agents-conversation","aria-live":"polite",ref:b,onScroll:k=>{const T=k.currentTarget;w.current=T.scrollHeight-T.scrollTop-T.clientHeight<72},children:[c.filter(k=>k.status==="pending").map(k=>r.jsx(bN,{approval:k,busy:h===k.approvalId,onApprove:T=>u(k,T),onReject:()=>m(k)},k.approvalId)),t.length===0&&r.jsxs("div",{className:"agents-empty-conversation",children:[r.jsx("strong",{children:y}),r.jsx("span",{children:x})]}),t.map(k=>{if(k.type==="task"){const T=k;return r.jsx(vN,{operation:T.operation,states:T.states,status:T.status,onCancel:()=>a(T.batchId,T.agentRunId),onRetry:()=>i(T.batchId),busy:l===T.batchId},T.id)}return r.jsxs("article",{className:`agents-message ${k.type}`,children:[r.jsx("span",{children:k.type==="user"?"You":"LiveDesk Agent"}),r.jsx("p",{children:k.text})]},k.id)}),g&&r.jsxs("article",{className:"agents-message agent agents-progress-message",role:"status",children:[r.jsxs("span",{children:[r.jsx(zr,{"aria-hidden":"true",size:15}),xN(g.stage)]}),r.jsx("p",{children:g.message})]})]})}const Ob=["Recommended","Health & capacity","Processes & services","AI workloads","Files & configuration","Software & automation","Network & connectivity","Power & maintenance","Troubleshooting & recovery"],Rn=["windows","macos","linux"],Ll={"system.health":{label:"system health",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Rn},"gpu.status":{label:"GPU status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Rn},"disk.status":{label:"disk status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Rn},"process.list":{label:"process inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Rn},"service.status":{label:"service inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Rn},"diagnostics.collect":{label:"diagnostics collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Rn},"process.control":{label:"process control",permissionCategory:"processControl",readOnly:!1,risk:"high",supportedPlatforms:Rn},"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:Rn},"application.close":{label:"application close",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:Rn},"file.read":{label:"file reading",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:Rn},"file.write":{label:"file writing",permissionCategory:"fileWrite",readOnly:!1,risk:"high",supportedPlatforms:Rn},"file.delete":{label:"file deletion",permissionCategory:"fileDelete",readOnly:!1,risk:"critical",supportedPlatforms:Rn},"file.list":{label:"directory listing",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:Rn},"command.run":{label:"command execution",permissionCategory:"shell",readOnly:!1,risk:"critical",supportedPlatforms:Rn},"script.run":{label:"script execution",permissionCategory:"script",readOnly:!1,risk:"high",supportedPlatforms:Rn},"software.install":{label:"software installation",permissionCategory:"softwareInstall",readOnly:!1,risk:"high",supportedPlatforms:Rn},"network.status":{label:"network inspection",permissionCategory:"network",readOnly:!0,risk:"low",supportedPlatforms:Rn},"system.power":{label:"power control",permissionCategory:"systemPower",readOnly:!1,risk:"critical",supportedPlatforms:Rn},"system.configure":{label:"system configuration",permissionCategory:"systemConfiguration",readOnly:!1,risk:"critical",supportedPlatforms:Rn},"logs.collect":{label:"log collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Rn}};new Set(Object.keys(Ll));const SN={Recommended:["recommended","overview","fleet","요약","추천"],"Health & capacity":["health","capacity","performance","상태","성능","용량"],"Processes & services":["process","service","application","프로세스","서비스","앱"],"AI workloads":["ai","gpu","comfyui","ollama","인공지능","모델"],"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","문제해결","복구","장애"]},Hb=["low","medium","high","critical"];function CN(t){return t.reduce((a,i)=>{const l=Ll[i].risk;return Hb.indexOf(l)>Hb.indexOf(a)?l:a},"low")}function kN(t){return Rn.filter(a=>t.every(i=>Ll[i].supportedPlatforms.includes(a)))}function Ve(t,a,i,l,c,u,m={}){const h=m.description||l,g=c.flatMap(x=>x.split(".")),y=[...new Set([...SN[a],...u,...g])];return{id:t,category:a,title:i,prompt:l,description:h,requiredOperations:c,risk:m.risk||CN(c),targetSupport:m.targetSupport||"single-or-multiple",supportedPlatforms:m.supportedPlatforms||kN(c),keywords:y,recommended:m.recommended??!1,enabled:!0}}const Pw=[Ve("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}),Ve("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}),Ve("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}),Ve("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}),Ve("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}),Ve("recommended-ai-workers","Recommended","Verify ComfyUI and Ollama workers","Check whether ComfyUI and Ollama workers and their services are available on the current targets.",["process.list","service.status"],["comfyui","ollama","worker"],{recommended:!0}),Ve("recommended-recover-ai","Recommended","Recover stopped AI workers","Find stopped AI workers and relaunch the registered worker application or service on the target Client.",["process.list","application.launch","service.control"],["recover","start","ai worker"],{targetSupport:"single",recommended:!0}),Ve("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}),Ve("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","높은 사용량"]),Ve("health-uptime","Health & capacity","Review Client uptime","Show uptime, boot time, and current system health for the target Clients.",["system.health"],["uptime","boot","가동시간"]),Ve("health-gpu-temperature","Health & capacity","Check GPU temperature","Check GPU temperature and thermal warnings on the current targets.",["gpu.status"],["thermal","temperature","발열"]),Ve("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"]),Ve("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","디스크"]),Ve("health-gpu-compare","Health & capacity","Compare GPU capacity","Compare GPU model, memory, temperature, and utilization across the current targets.",["gpu.status"],["compare","graphics","capacity"]),Ve("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","경고"]),Ve("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"]),Ve("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","실행 중"]),Ve("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"]),Ve("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"}),Ve("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"}),Ve("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"}),Ve("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"}),Ve("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","서비스 상태"]),Ve("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"}),Ve("ai-comfyui-status","AI workloads","Check ComfyUI availability","Check the ComfyUI process, service state, and GPU readiness on the current targets.",["process.list","service.status","gpu.status"],["comfyui","stable diffusion","image generation"]),Ve("ai-start-comfyui","AI workloads","Start ComfyUI","If ComfyUI is stopped, launch its registered application or service and verify it is running.",["process.list","application.launch","service.status"],["comfyui","start","launch"],{targetSupport:"single"}),Ve("ai-restart-ollama","AI workloads","Restart Ollama","Check Ollama, restart its registered application or service, and verify the worker is ready.",["process.list","application.close","application.launch","service.status"],["ollama","restart","llm"],{targetSupport:"single"}),Ve("ai-stable-diffusion","AI workloads","Check Stable Diffusion workers","Check Stable Diffusion or Automatic1111 processes and their GPU usage on the current targets.",["process.list","gpu.status"],["stable diffusion","automatic1111","sd"]),Ve("ai-gpu-readiness","AI workloads","Check GPU readiness for AI","Check GPU temperature, VRAM, utilization, and system health before an AI workload starts.",["gpu.status","system.health"],["readiness","inference","training"]),Ve("ai-worker-logs","AI workloads","Collect AI worker logs","Collect recent logs and relevant log files for the AI worker on the target Client.",["logs.collect","file.list","file.read"],["logs","diagnostics","worker"],{targetSupport:"single"}),Ve("ai-llama-cpp","AI workloads","Check llama.cpp workers","Find llama.cpp or local model worker processes and inspect their recent logs.",["process.list","logs.collect"],["llama.cpp","local model","inference"]),Ve("ai-recover-orphan-python","AI workloads","Recover an orphaned Python worker","Find an orphaned Python AI worker, stop the stale process, then launch its registered worker again.",["process.list","process.control","application.launch"],["python","orphaned","recovery"],{targetSupport:"single"}),Ve("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"}),Ve("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","구성"]),Ve("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"]),Ve("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"}),Ve("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"}),Ve("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"]),Ve("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"}),Ve("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"}),Ve("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"]}),Ve("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"]}),Ve("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"]}),Ve("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"}),Ve("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"}),Ve("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"}),Ve("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"]),Ve("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"}),Ve("network-adapter-status","Network & connectivity","Check network adapters","Show adapter state, address, and link information for the current targets.",["network.status"],["adapter","ethernet","wifi","네트워크 상태"]),Ve("network-disconnected","Network & connectivity","Find disconnected targets","Find current targets with disconnected or degraded network adapters.",["network.status"],["disconnected","offline","연결 끊김"]),Ve("network-link-speed","Network & connectivity","Check link speed","Report network link speed and duplex information for the current targets.",["network.status"],["speed","bandwidth","duplex"]),Ve("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"]),Ve("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"]),Ve("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"]),Ve("network-compare","Network & connectivity","Compare target connectivity","Compare adapter state, addresses, and link speed across the current targets.",["network.status"],["compare","inventory","connectivity"]),Ve("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"]),Ve("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"}),Ve("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"}),Ve("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"}),Ve("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"}),Ve("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"}),Ve("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"}),Ve("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"}),Ve("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"}),Ve("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"}),Ve("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"}),Ve("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"}),Ve("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"}),Ve("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"}),Ve("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"}),Ve("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"}),Ve("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","장애 보고서"])],Ph={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 jN(t,a){return t==="safe-auto"?Ph:t==="full-access"?{...Ph,processControl:"allow",serviceControl:"allow",applicationControl:"allow",fileDelete:"allow",shell:"allow",script:"allow",softwareInstall:"allow",systemPower:"allow",systemConfiguration:"allow"}:t==="custom"&&a?a:{...Ph,processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileWrite:"ask",network:"ask"}}function AN(t,a,i){const l=jN(a,i),c=t.requiredOperations.map(u=>l[Ll[u].permissionCategory]);if(c.includes("deny")){const u=t.requiredOperations.find(m=>l[Ll[m].permissionCategory]==="deny");return{state:"blocked",label:"Blocked",reason:`This task requires ${Ll[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=>Ll[u].readOnly)?{state:"read-only",label:"Read only"}:a==="full-access"?{state:"full-access",label:"Full Access"}:{state:"auto",label:"Auto allowed"}}function MN(t){const a=String(t||"").trim().toLowerCase();return a==="windows"||a==="win32"||a==="win32nt"?"windows":a==="macos"||a==="macosx"||a==="darwin"||a==="osx"?"macos":a==="linux"?"linux":null}function NN(t,a,i){const l=new Set(i);return t.filter(c=>c.connected&&(a==="all"||a==="auto"||l.has(c.deviceId)))}function TN(t,a){const i=MN(t.platform);if(!i||!a.supportedPlatforms.includes(i))return!1;const l=t.capabilities?.agentTools;return!Array.isArray(l)||l.length===0?a.requiredOperations.every(c=>Ll[c].readOnly):a.requiredOperations.every(c=>l.includes(c))}function $w(t,a,i,l,c,u){const m=AN(t,c,u),h=NN(a,i,l),g=h.map(j=>j.deviceId),y={...m,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(m.state==="blocked")return y;const x=h.filter(j=>TN(j,t)),b=x.map(j=>j.deviceId),w=g.filter(j=>!b.includes(j));return x.length===0?{...y,unsupportedDeviceIds:w,reason:"No current target supports the required platform and client capabilities."}:{...y,available:!0,availableDeviceIds:b,unsupportedDeviceIds:w}}function RN(t,a,i,l,c,u){return t.filter(m=>m.enabled&&$w(m,a,i,l,c,u).available).length}const $h="livedesk.agentPromptRecent",Bh="livedesk.agentPromptFavorites",EN={Recommended:Il,"Health & capacity":Ao,"Processes & services":F0,"AI workloads":ep,"Files & configuration":H0,"Software & automation":wx,"Network & connectivity":Lp,"Power & maintenance":Kn,"Troubleshooting & recovery":O0};function Fb(t){if(typeof window>"u")return[];try{const a=JSON.parse(window.localStorage.getItem(t)||"[]");return Array.isArray(a)?a.filter(i=>typeof i=="string"):[]}catch{return[]}}function xf(t,a){try{window.localStorage.setItem(t,JSON.stringify(a))}catch{}}function Uh(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 DN(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","AI workloads":"AI","Files & configuration":"Files","Software & automation":"Software","Network & connectivity":"Network","Power & maintenance":"Power","Troubleshooting & recovery":"Recovery"}[t]}function LN(t,a,i){if(!i.trim())return!0;const l=i.trim().toLowerCase();return[t.title,t.prompt,t.description,t.category,t.risk,a.label,...t.keywords,...t.requiredOperations,...t.supportedPlatforms].join(" ").toLowerCase().includes(l)}function _N(t){return`permission-${t}`}function IN(t){return t==="low"?"Low risk":t==="medium"?"Medium risk":t==="high"?"High risk":"Critical risk"}function zN(t){return t==="windows"?"Windows":t==="macos"?"macOS":"Linux"}function ON({devices:t,targetMode:a,selectedIds:i,permissionMode:l,customCategories:c,onSelectPrompt:u,onClose:m}){const[h,g]=d.useState(""),[y,x]=d.useState("all"),[b,w]=d.useState(()=>Fb($h)),[j,A]=d.useState(()=>Fb(Bh)),[k,T]=d.useState(0),[M,N]=d.useState(""),L=d.useRef(null),z=d.useRef(null),H=d.useMemo(()=>Pw.filter(Z=>Z.enabled),[]),G=d.useMemo(()=>new Map(H.map(Z=>[Z.id,$w(Z,t,a,i,l,c)])),[c,t,l,i,a,H]),_=d.useMemo(()=>[...G.values()].filter(Z=>Z.available).length,[G]),Y=d.useMemo(()=>t.filter(Z=>Z.connected&&(a==="all"||a==="auto"||i.includes(Z.deviceId))).length,[t,i,a]),q=d.useMemo(()=>{const Z=H.filter(I=>LN(I,G.get(I.id),h));return y==="recent"?b.map(I=>Z.find(se=>se.id===I)).filter(I=>!!I):y==="favorites"?j.map(I=>Z.find(se=>se.id===I)).filter(I=>!!I):y==="all"?Z:Z.filter(I=>{const se=G.get(I.id);return y==="read-only"?se.state==="read-only":y==="auto"?se.state==="auto":y==="approval"?se.state==="approval":y==="full-access"?se.state==="full-access":y==="available"?se.available:y==="unavailable"?!se.available:I.category===y})},[G,j,y,b,h,H]),U=d.useMemo(()=>y!=="all"?[{category:Uh(y),templates:q}]:Ob.map(Z=>({category:Z,templates:q.filter(I=>I.category===Z)})).filter(Z=>Z.templates.length>0),[y,q]);d.useEffect(()=>{T(Z=>Math.min(Z,Math.max(0,q.length-1)))},[q.length]),d.useEffect(()=>{xf($h,b)},[b]),d.useEffect(()=>{xf(Bh,j)},[j]),d.useEffect(()=>{z.current?.focus();const Z=se=>{se.target instanceof Node&&!L.current?.contains(se.target)&&m()},I=se=>{se.key==="Escape"&&(se.preventDefault(),m())};return document.addEventListener("pointerdown",Z),document.addEventListener("keydown",I),()=>{document.removeEventListener("pointerdown",Z),document.removeEventListener("keydown",I)}},[m]);const K=Z=>{const I=G.get(Z.id);if(!I.available){N(I.reason||"This task is not available for the current targets and permission policy.");return}const se=[Z.id,...b.filter(W=>W!==Z.id)].slice(0,10);w(se),xf($h,se),u(Z.prompt),m()},O=Z=>{A(I=>{const se=I.includes(Z)?I.filter(W=>W!==Z):[Z,...I];return xf(Bh,se),se})},ve=Z=>{Z.key==="ArrowDown"?(Z.preventDefault(),T(I=>Math.min(I+1,Math.max(0,q.length-1)))):Z.key==="ArrowUp"?(Z.preventDefault(),T(I=>Math.max(I-1,0))):Z.key==="Enter"&&q[k]&&(Z.preventDefault(),K(q[k]))};let me=-1;return r.jsxs("section",{className:"agents-suggested-tasks",ref:L,"aria-label":"Suggested tasks",children:[r.jsxs("header",{className:"agents-suggested-header",children:[r.jsxs("div",{children:[r.jsxs("span",{className:"agents-suggested-title",children:[r.jsx(Il,{size:15})," Suggested tasks"]}),r.jsxs("small",{children:[_," available · ",H.length," total. Choose a task, edit it, then run it."]})]}),r.jsx("button",{className:"agents-suggested-close",type:"button","aria-label":"Close suggested tasks",onClick:m,children:r.jsx(Ra,{size:16})})]}),r.jsxs("label",{className:"agents-suggested-search",children:[r.jsx(z0,{size:15,"aria-hidden":"true"}),r.jsx("input",{ref:z,value:h,onChange:Z=>g(Z.target.value),onKeyDown:ve,placeholder:"Search tasks...","aria-label":"Search suggested tasks"})]}),r.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",...Ob].map(Z=>{const I=Z==="recent"?bx:Z==="favorites"?np:Z==="all"?Il:Z==="available"?ea:Z==="unavailable"?jx:Z==="read-only"||Z==="auto"||Z==="approval"||Z==="full-access"?Kn:EN[Z];return r.jsxs("button",{className:y===Z?"active":"",type:"button",title:Uh(Z),"aria-label":Uh(Z),"aria-pressed":y===Z,onClick:()=>{x(Z),T(0),N("")},children:[r.jsx(I,{size:12})," ",DN(Z)]},Z)})}),M&&r.jsx("div",{className:"agents-suggested-notice",role:"status",children:M}),r.jsxs("div",{className:"agents-suggested-list",role:"listbox","aria-label":"Suggested tasks",children:[U.map(Z=>r.jsxs("div",{className:"agents-suggested-group",children:[r.jsx("strong",{children:Z.category}),Z.templates.map(I=>{me+=1;const se=me===k,W=j.includes(I.id),F=G.get(I.id),oe=F.availableDeviceIds.length+F.unsupportedDeviceIds.length||Y,le=F.available?`Available on ${F.availableDeviceIds.length} of ${oe} target${oe===1?"":"s"}`:`Unavailable: ${F.reason||"not supported by the current targets"}`;return r.jsxs("div",{className:`agents-suggested-item ${se?"active":""} ${F.available?"":"unavailable"}`,children:[r.jsxs("button",{className:"agents-suggested-prompt",type:"button",role:"option","aria-selected":se,"aria-disabled":!F.available,onClick:()=>K(I),children:[r.jsx("span",{children:I.title}),r.jsx("small",{className:"agents-suggested-description",children:I.description}),r.jsxs("span",{className:"agents-suggested-meta",children:[r.jsx("em",{children:I.category}),r.jsx("em",{className:_N(F.state),children:F.label}),r.jsx("em",{className:`risk-${I.risk}`,children:IN(I.risk)}),r.jsx("em",{children:I.supportedPlatforms.map(zN).join(" · ")}),r.jsx("em",{className:F.available?"availability-ok":"availability-unavailable",children:le}),F.available&&F.unsupportedDeviceIds.length>0&&r.jsxs("em",{className:"availability-warning",children:["Unsupported on ",F.unsupportedDeviceIds.length]})]})]}),r.jsx("button",{className:`agents-suggested-favorite ${W?"favorite":""}`,type:"button","aria-label":W?`Remove ${I.title} from favorites`:`Add ${I.title} to favorites`,"aria-pressed":W,onClick:()=>O(I.id),children:r.jsx(np,{size:14,fill:W?"currentColor":"none"})})]},I.id)})]},Z.category)),q.length===0&&r.jsx("p",{className:"agents-suggested-empty",children:"No tasks match this search or current filter."})]})]})}function HN({devices:t,mode:a,selectedIds:i,onModeChange:l,onToggle:c,permissionMode:u,onPermissionModeChange:m}){const h=t.filter(qf),g=i.filter(y=>h.some(x=>x.deviceId===y)).length;return r.jsxs("section",{className:"agents-target-picker","aria-label":"Agent targets",children:[r.jsxs("div",{className:"agents-target-toolbar",children:[r.jsx("span",{className:"agents-section-label",children:"Targets"}),r.jsxs("div",{className:"agents-target-modes",children:[r.jsxs("button",{className:a==="all"?"active":"",onClick:()=>l("all"),type:"button",children:[r.jsx(Ku,{size:14})," All connected ",r.jsx("small",{children:h.length})]}),r.jsxs("button",{className:a==="selected"?"active":"",onClick:()=>l("selected"),type:"button",children:[r.jsx(Or,{size:14})," Selected ",g]}),r.jsxs("button",{className:a==="auto"?"active":"",onClick:()=>l("auto"),type:"button",children:[r.jsx(Il,{size:14})," Auto"]}),r.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[r.jsx(Ku,{size:14})," Group ",r.jsx("small",{children:"Soon"})]})]}),r.jsxs("label",{className:`agents-permission-picker permission-${u}`,children:[r.jsx(Wf,{size:14}),r.jsx("span",{children:"Permission"}),r.jsxs("select",{value:u,onChange:y=>m(y.target.value),"aria-label":"Agent permission mode",children:[r.jsx("option",{value:"ask",children:"Ask"}),r.jsx("option",{value:"safe-auto",children:"Safe Auto"}),r.jsx("option",{value:"full-access",children:"Full Access"}),r.jsx("option",{value:"custom",children:"Custom"})]}),r.jsx(kx,{size:13,"aria-hidden":"true"})]})]}),r.jsx("div",{className:"agents-target-list",children:t.length===0?r.jsx("span",{className:"agents-target-empty",children:"No Clients discovered."}):t.map(y=>{const x=qf(y),b=a==="all"||a==="auto"?x:i.includes(y.deviceId);return r.jsxs("label",{className:`agents-target-option ${b?"selected":""} ${x?"":"offline"}`,children:[r.jsx("input",{type:"checkbox",checked:b,disabled:!x||a!=="selected",onChange:()=>c(y.deviceId)}),r.jsx("span",{className:"agents-target-icon",children:r.jsx(Ea,{size:15})}),r.jsxs("span",{children:[r.jsx("strong",{children:Uf(y)}),r.jsx("small",{children:x?"Ready":y.connected?"Agent reconnecting":"Offline"})]}),b&&r.jsx(Or,{className:"agents-target-check",size:15,"aria-hidden":"true"})]},y.deviceId)})})]})}async function FN(t,a){return We("/api/settings/agent/plan",{method:"POST",body:JSON.stringify({instruction:a})},t)}async function PN(t,a){return We("/api/settings/agent/run",{method:"POST",body:JSON.stringify(a)},t)}async function $N(t,a){return We(`/api/settings/agent/runs/${encodeURIComponent(a)}`,void 0,t)}async function BN(t,a){return We(`/api/settings/agent/runs/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})},t)}async function UN(t){return We("/api/settings/agent/runs/cancel-all",{method:"POST",body:JSON.stringify({})},t)}async function qN(t,a,i,l){return We(`/api/settings/agent/runs/${encodeURIComponent(a)}/approvals/${encodeURIComponent(i)}/approve`,{method:"POST",body:JSON.stringify({scope:l})},t)}async function GN(t,a,i,l="User rejected this action."){return We(`/api/settings/agent/runs/${encodeURIComponent(a)}/approvals/${encodeURIComponent(i)}/reject`,{method:"POST",body:JSON.stringify({reason:l})},t)}async function VN(t,a,i){return We(`/api/settings/agent/policies/${encodeURIComponent(a)}`,{method:"PUT",body:JSON.stringify({categories:i})},t)}async function WN(t,a){return We("/api/settings/agent/summary",{method:"POST",body:JSON.stringify(a)},t)}async function KN(t,a){return We("/api/remote/tasks",{method:"POST",body:JSON.stringify({instruction:a.instruction,deviceIds:a.deviceIds,operation:a.operation,targetQuery:a.targetQuery,approvalLevel:"read-only"})},t)}async function YN(t,a){return We(`/api/remote/tasks/${encodeURIComponent(a)}`,void 0,t)}async function QN(t,a){return We(`/api/remote/tasks/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})},t)}async function XN(t,a){return We(`/api/remote/tasks/${encodeURIComponent(a)}/retry`,{method:"POST",body:JSON.stringify({failedOnly:!0})},t)}function po(t){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function wf(t,a){const i=new Map(a.map(l=>[l.deviceId,Uf(l)]));return t.results.map(l=>({deviceId:l.deviceId,deviceName:l.deviceName||i.get(l.deviceId)||l.deviceId,status:dN(l.status),stage:l.stage||(l.status==="running"?"Checking processes":void 0),result:l.result,data:l.data,error:l.error,sequence:Number.isSafeInteger(l.sequence)?l.sequence:0}))}function ZN(t,a){const i=new Map(a.map(l=>[l.deviceId,l]));return t.map(l=>{const c=i.get(l.deviceId);return!c||c.sequence<=l.sequence?l:c})}function JN(t,a){const i=a.filter(u=>u.status==="completed"),l=a.filter(u=>u.status==="failed");if(t.operation==="process.list"){const m=`${i.filter(h=>{const g=h.result||"";return!/not running|no process/i.test(g)&&/running|online|found/i.test(g)}).length}대에서 요청한 프로세스가 실행 중입니다.`;return l.length>0?`${m}
|
|
15
|
+
${l.map(h=>`${h.deviceName}는 ${h.error||"응답하지 않았습니다."}`).join(`
|
|
16
|
+
`)}`:m}return l.length>0?`${i.length}대 완료, ${l.length}대 실패했습니다.`:`${i.length}대 작업이 완료되었습니다.`}const eT={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 tT(t){return t==="safe-auto"?"Safe Auto":t==="full-access"?"Full Access":t==="custom"?"Custom":"Ask"}function nT(t){return t.replace(/([A-Z])/g," $1").replace(/^./,a=>a.toUpperCase())}function aT(t){const a=t instanceof Error?t.message:String(t);return/agent-ai-disabled/i.test(a)?"Enable AI Agent in Settings before running commands.":/agent-no-target-devices|agent-target-not-connected|device-not-connected/i.test(a)?"The selected Client is reconnecting. Wait until its Agent status is Ready and try again.":/codex-auth-required/i.test(a)?"Codex sign-in is required on the Hub. Open Settings > Agent and test the Codex connection.":a}function Pb({hubUrl:t,devices:a,launchRequest:i,variant:l="page",selectedDeviceIds:c=[]}){const u=l==="dock",[m,h]=d.useState(u?c.length>0?"selected":"auto":"all"),[g,y]=d.useState(c),[x,b]=d.useState("auto"),[w,j]=d.useState(""),[A,k]=d.useState([]),[T,M]=d.useState(""),[N,L]=d.useState(""),[z,H]=d.useState(""),[G,_]=d.useState("safe-auto"),[Y]=d.useState("custom-default"),[q,U]=d.useState(eT),[K,O]=d.useState([]),[ve,me]=d.useState(""),[Z,I]=d.useState(!1),[se,W]=d.useState(null),[F,oe]=d.useState(!1),[le,Q]=d.useState(""),[be,he]=d.useState(!1),[de,ee]=d.useState(null),Ce=d.useRef(null),Re=d.useRef(new Set),He=d.useRef(new Set),te=d.useRef(new Set),Ue=d.useMemo(()=>a.filter(qf).map(pe=>pe.deviceId),[a]),mt=d.useMemo(()=>RN(Pw,a,m,g,G,q),[q,a,G,g,m]);d.useEffect(()=>{u&&y(c)},[u,c]),d.useEffect(()=>{i?.deviceId&&(h("selected"),y([i.deviceId]),j(i.instruction),he(!1),window.requestAnimationFrame(()=>{Ce.current?.focus(),Ce.current?.setSelectionRange(i.instruction.length,i.instruction.length)}))},[i]);const ne=d.useCallback(pe=>{const De=wf(pe,a);if(k(Fe=>Fe.map(Ae=>Ae.type==="task"&&Ae.batchId===pe.batchId?{...Ae,states:ZN(Ae.states,De),status:pe.status}:Ae)),!["running","queued"].includes(pe.status)&&!Re.current.has(pe.batchId)){Re.current.add(pe.batchId);const Fe=po("agent-summary");k(Ae=>[...Ae,{type:"agent",id:Fe,text:JN(pe,De)}]),pe.operation&&WN(t,{instruction:pe.instructionPreview,operation:pe.operation,total:De.length,completed:De.filter(Ae=>Ae.status==="completed").length,failed:De.filter(Ae=>Ae.status==="failed").length,results:De.map(Ae=>({deviceName:Ae.deviceName,status:Ae.status,result:Ae.result,error:Ae.error}))}).then(Ae=>{!Ae.ok||!Ae.summary||k(ct=>ct.map(ht=>ht.type==="agent"&&ht.id===Fe?{...ht,text:Ae.summary}:ht))}).catch(()=>{}),M(Ae=>Ae===pe.batchId?"":Ae)}},[a,t]),xe=d.useCallback(async pe=>{const De=await YN(t,pe);return ne(De),De},[t,ne]),Oe=d.useCallback((pe,De)=>{te.current.has(pe.batchId)||(te.current.add(pe.batchId),k(Fe=>[...Fe,{type:"task",id:po("task"),batchId:pe.batchId,agentRunId:De,operation:pe.operation||"diagnostics.collect",instruction:pe.instructionPreview,states:wf(pe,a),status:pe.status}])),ne(pe)},[a,ne]),$e=d.useCallback(async pe=>{const De=await $N(t,pe);for(const Ae of De.taskBatches||[])Oe(Ae,pe);O(De.approvals||[]);const Fe=["running","queued","waiting-approval"].includes(De.status);if(ee(Fe?{runId:pe,stage:De.stage||De.status,message:De.progressMessage||(De.status==="waiting-approval"?"Review the requested action to continue.":"Codex is preparing the answer.")}:Ae=>Ae?.runId===pe?null:Ae),!Fe&&!He.current.has(pe)){He.current.add(pe);const Ae=[De.error,De.errorMessage].filter(Boolean).join(" — "),ct=De.finalResponse?.trim()||(De.status==="cancelled"?"Codex 작업을 취소했습니다.":Ae?`Codex 작업이 완료되지 않았습니다: ${Ae}`:"Codex 작업이 완료되었습니다.");k(ht=>[...ht,{type:De.status==="failed"?"error":"agent",id:po("agent-run-result"),text:ct}])}return De},[Oe,t]);d.useEffect(()=>{if(!T)return;let pe=!0;const De=async()=>{try{const Ae=await xe(T);pe&&!["running","queued"].includes(Ae.status)&&M("")}catch(Ae){pe&&Q(Ae instanceof Error?Ae.message:String(Ae))}};De();const Fe=window.setInterval(()=>{De()},800);return()=>{pe=!1,window.clearInterval(Fe)}},[T,xe]),d.useEffect(()=>{if(!N)return;let pe=!0;const De=async()=>{try{const Ae=await $e(N);pe&&!["running","queued","waiting-approval"].includes(Ae.status)&&(L(""),oe(!1))}catch(Ae){pe&&Q(Ae instanceof Error?Ae.message:String(Ae))}};De();const Fe=window.setInterval(()=>{De()},800);return()=>{pe=!1,window.clearInterval(Fe)}},[N,$e]);const ze=async(pe="",De,Fe=!1)=>{const Ae=(pe||w).trim();if(!Ae||T||N)return;let ct=null;const ht=De||(m==="all"||m==="auto"?Ue:g.filter(et=>Ue.includes(et)));if(ht.length===0){Q("Select at least one connected Client.");return}if(G==="full-access"&&!F&&!Fe){W({instruction:Ae,targetIds:ht});return}if(k(et=>[...et,{type:"user",id:po("user"),text:Ae}]),j(""),he(!1),Q(""),ht.length===0){k(et=>[...et,{type:"error",id:po("no-targets"),text:"연결된 대상 장비를 하나 이상 선택해 주세요."}]);return}const Dn=x==="ask"?`Read-only request. Inspect and answer without changing Client state.
|
|
17
|
+
|
|
18
|
+
${Ae}`:x==="plan"?`Plan only. Produce a safe execution plan, but do not change Client state.
|
|
19
|
+
|
|
20
|
+
${Ae}`:x==="execute"?`Execute this request within the configured LiveDesk approval policy.
|
|
21
|
+
|
|
22
|
+
${Ae}`:Ae,yn=m==="auto"?`Auto target selection is enabled. Inspect the allowed Clients and use only the most suitable target or targets for this request.
|
|
23
|
+
|
|
24
|
+
${Dn}`:Dn;if(!ct){try{if(G==="custom"){const xt=await VN(t,Y,q);if(!xt.ok)throw new Error(xt.error||"Custom Agent policy could not be saved.")}const et=await PN(t,{instruction:yn,deviceIds:ht,permissionMode:G,customPolicyId:Y});if(!et.ok||!et.runId)throw new Error(et.error||"Codex Agent run could not be started.");O(et.approvals||[]),ee({runId:et.runId,stage:et.stage||et.status||"queued",message:et.progressMessage||"Codex request queued on the Hub."}),L(et.runId);return}catch(et){try{const xt=await FN(t,yn);xt.ok&&xt.plan&&(ct={operation:xt.plan.operation,query:xt.plan.targetQuery})}catch{k(xt=>[...xt,{type:"error",id:po("unsupported"),text:aT(et)}])}}if(!ct)return}try{const et=await KN(t,{instruction:yn,deviceIds:ht,operation:ct.operation,targetQuery:ct.query});if(!et.ok||!et.batch||!et.batchId)throw new Error(et.error||"작업을 만들지 못했습니다.");const xt={type:"task",id:po("task"),batchId:et.batchId,operation:ct.operation,instruction:Ae,states:wf(et.batch,a),status:et.batch.status};te.current.add(et.batchId),k(kn=>[...kn,xt]),M(et.batchId)}catch(et){Q(et instanceof Error?et.message:String(et))}},Qe=async(pe,De)=>{me(pe.approvalId);try{const Fe=await qN(t,pe.runId,pe.approvalId,De);if(!Fe.ok)throw new Error(Fe.error||"Agent approval could not be applied.");await $e(pe.runId)}catch(Fe){Q(Fe instanceof Error?Fe.message:String(Fe))}finally{me("")}},qe=async pe=>{me(pe.approvalId);try{const De=await GN(t,pe.runId,pe.approvalId);if(!De.ok)throw new Error(De.error||"Agent approval could not be rejected.");await $e(pe.runId)}catch(De){Q(De instanceof Error?De.message:String(De))}finally{me("")}},Ye=async(pe,De)=>{H(pe);try{if(De){const Ae=await BN(t,De);for(const ct of Ae.taskBatches||[])ne(ct);L(ct=>ct===De?"":ct),ee(ct=>ct?.runId===De?null:ct);return}const Fe=await QN(t,pe);ne(Fe),M(Ae=>Ae===pe?"":Ae)}catch(Fe){Q(Fe instanceof Error?Fe.message:String(Fe))}finally{H("")}},ot=async()=>{if(!(Z||!T&&!N)){I(!0);try{const pe=await UN(t);if(!pe.ok)throw new Error(pe.error||"모든 Agent 작업을 취소하지 못했습니다.");M(""),L(""),ee(null),O([]),k(De=>De.map(Fe=>Fe.type==="task"&&["queued","running"].includes(Fe.status)?{...Fe,status:"cancelled",states:Fe.states.map(Ae=>["queued","running"].includes(Ae.status)?{...Ae,status:"cancelled",stage:"Cancelled",error:"Cancelled by user."}:Ae)}:Fe))}catch(pe){Q(pe instanceof Error?pe.message:String(pe))}finally{I(!1)}}},B=async pe=>{H(pe);try{const De=await XN(t,pe);if(!De.ok||!De.batch||!De.batchId)throw new Error(De.error||"재시도하지 못했습니다.");Re.current.delete(De.batchId),k(Fe=>Fe.map(Ae=>Ae.type==="task"&&Ae.batchId===pe?{...Ae,batchId:De.batchId,states:wf(De.batch,a),status:De.batch.status}:Ae)),M(De.batchId)}catch(De){Q(De instanceof Error?De.message:String(De))}finally{H("")}},ye=pe=>{j(pe),he(!1),window.requestAnimationFrame(()=>Ce.current?.focus())},je=d.useMemo(()=>a.filter(qf),[a]),Pe=d.useMemo(()=>je.filter(pe=>g.includes(pe.deviceId)),[je,g]),dt=m==="auto"?`Auto · ${je.length} available`:m==="all"?`All ${je.length} computers`:Pe.length===1?Uf(Pe[0]):`${Pe.length} selected`,nt=m==="auto"?"LiveDesk chooses the best computer for each task.":m==="all"?"The Agent may coordinate every connected computer.":Pe.length>0?Pe.map(Uf).join(" · "):"Select one or more computers on the Wall.",bt=m==="selected"&&Pe.length===1?["Diagnose this computer","Analyze recent errors","Summarize running applications","Check disk and GPU capacity"]:m==="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"],it=m==="selected"?Pe.length>0?"What should this computer do?":"Choose a computer or use Auto.":m==="all"?"Use all your computers together.":"What should LiveDesk handle?",Ct=m==="auto"?"LiveDesk can inspect the available computers and choose the best target.":"Describe the outcome. LiveDesk will plan, request approval when needed, and show progress per computer.";return r.jsxs("section",{className:`agents-page ${u?"agents-dock-console":""}`,children:[u&&r.jsxs("header",{className:"agent-console-header",children:[r.jsxs("div",{className:"agent-console-title",children:[r.jsx("span",{className:"agent-console-mark",children:r.jsx(Il,{size:16})}),r.jsxs("div",{children:[r.jsx("small",{children:"Live agent"}),r.jsx("strong",{children:"Agent Console"})]}),r.jsx("i",{children:"Ready"})]}),r.jsxs("section",{className:"agent-console-target","aria-label":"Agent target scope",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Target"}),r.jsx("strong",{children:dt}),r.jsx("small",{children:nt})]}),r.jsxs("div",{className:"agent-console-target-modes",children:[r.jsxs("button",{className:m==="selected"?"active":"",onClick:()=>h("selected"),type:"button",children:[r.jsx(Or,{size:12})," Selected"]}),r.jsxs("button",{className:m==="all"?"active":"",onClick:()=>h("all"),type:"button",children:[r.jsx(Ku,{size:12})," All"]}),r.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[r.jsx(Ku,{size:12})," Group"]}),r.jsxs("button",{className:m==="auto"?"active":"",onClick:()=>h("auto"),type:"button",children:[r.jsx(Il,{size:12})," Auto"]})]})]}),r.jsx("div",{className:"agent-console-interaction-modes","aria-label":"Agent interaction mode",children:["auto","ask","plan","execute"].map(pe=>r.jsxs("button",{className:x===pe?"active":"",onClick:()=>b(pe),type:"button",children:[pe==="auto"?r.jsx(Il,{size:12}):pe==="execute"?r.jsx(Ea,{size:12}):null,pe[0].toUpperCase()+pe.slice(1)]},pe))})]}),r.jsxs("div",{className:"agents-workspace",children:[(T||N)&&r.jsxs("div",{className:"agents-page-status",children:[r.jsxs("span",{children:[Ue.length," Clients · ",tT(G)]}),r.jsx("button",{type:"button",className:"agents-stop-all",onClick:()=>{ot()},disabled:Z,children:Z?"Stopping…":"Stop all"})]}),se&&r.jsx("div",{className:"agents-permission-modal-backdrop",role:"presentation",children:r.jsxs("section",{className:"agents-permission-modal",role:"dialog","aria-modal":"true","aria-labelledby":"full-access-title",children:[r.jsx("span",{className:"agents-permission-modal-icon",children:r.jsx(Wf,{size:20})}),r.jsx("h3",{id:"full-access-title",children:"Confirm Full Access"}),r.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."}),r.jsxs("div",{className:"agents-permission-modal-actions",children:[r.jsx("button",{type:"button",onClick:()=>W(null),children:"Cancel"}),r.jsx("button",{type:"button",className:"danger",onClick:()=>{const pe=se;W(null),oe(!0),ze(pe.instruction,pe.targetIds,!0)},children:"Run with Full Access"})]})]})}),le&&r.jsx("div",{className:"agents-error",role:"alert",children:le}),r.jsx(wN,{items:A,onCancel:Ye,onRetry:B,busyBatchId:z,approvals:K,onApprove:Qe,onReject:qe,busyApprovalId:ve,progress:de,emptyTitle:u?it:void 0,emptyBody:u?Ct:void 0}),u&&A.length===0&&!de&&r.jsx("div",{className:"agent-console-suggestions","aria-label":"Suggested Agent commands",children:bt.map(pe=>r.jsx("button",{type:"button",onClick:()=>ye(pe),children:pe},pe))}),r.jsxs("div",{className:"agents-composer-shell",children:[be&&r.jsx(ON,{devices:a,targetMode:m,selectedIds:g,permissionMode:G,customCategories:q,onSelectPrompt:ye,onClose:()=>he(!1)}),r.jsx(cN,{ref:Ce,value:w,onChange:j,onSubmit:()=>{ze()},onOpenSuggestedTasks:()=>he(pe=>!pe),suggestedOpen:be,suggestedTaskCount:mt,disabled:!!T||!!N,placeholder:u?"Tell LiveDesk what outcome you want...":void 0,compact:u})]})]}),!u&&r.jsxs("aside",{className:"agents-target-sidebar","aria-label":"Agent targets and permissions",children:[r.jsx(HN,{devices:a,mode:m,selectedIds:g,onModeChange:h,onToggle:pe=>y(De=>De.includes(pe)?De.filter(Fe=>Fe!==pe):[...De,pe]),permissionMode:G,onPermissionModeChange:pe=>{_(pe),pe!=="full-access"&&oe(!1)}}),G==="custom"&&r.jsxs("section",{className:"agents-custom-policy","aria-label":"Custom Agent permissions",children:[r.jsxs("div",{className:"agents-custom-policy-head",children:[r.jsxs("div",{children:[r.jsx("span",{className:"agents-section-label",children:"Custom policy"}),r.jsx("strong",{children:"Choose what Codex may do automatically."})]}),r.jsx("span",{children:"Denied actions never reach a device."})]}),r.jsx("div",{className:"agents-custom-policy-grid",children:uN.map(pe=>r.jsxs("label",{children:[r.jsx("span",{children:nT(pe)}),r.jsxs("select",{value:q[pe],onChange:De=>U(Fe=>({...Fe,[pe]:De.target.value})),children:[r.jsx("option",{value:"allow",children:"Allow automatically"}),r.jsx("option",{value:"ask",children:"Ask every time"}),r.jsx("option",{value:"deny",children:"Deny"})]})]},pe))})]})]})]})}function Bw(t){return{type:t.type,deviceIds:t.deviceIds,monitorIndex:t.monitorIndex,label:t.label}}async function Uw(t){try{return(await t.json()).error||`${t.status} ${t.statusText}`}catch{return`${t.status} ${t.statusText}`}}async function qw(t,a,i){const l=encodeURIComponent(JSON.stringify({kind:a.kind,fileName:a.fileName,mimeType:t.type||"application/octet-stream",durationMs:a.durationMs,target:Bw(a.target)})),c=await fetch(`${Hl(i)}/api/captures?metadata=${l}`,{method:"POST",headers:{"Content-Type":t.type||"application/octet-stream"},body:t,cache:"no-store"});if(!c.ok)throw new Error(await Uw(c));return await c.json()}async function sT(t,a){return await We("/api/capture-sessions",{method:"POST",body:JSON.stringify({...t,target:Bw(t.target)})},a)}async function rT(t,a,i,l){const c=await fetch(`${Hl(l)}/api/capture-sessions/${encodeURIComponent(t)}/chunks/${a}`,{method:"PUT",headers:{"Content-Type":i.type||"application/octet-stream"},body:i,cache:"no-store"});if(!c.ok)throw new Error(await Uw(c));return await c.json()}async function iT(t,a,i){return await We(`/api/capture-sessions/${encodeURIComponent(t)}/finalize`,{method:"POST",body:JSON.stringify({durationMs:a})},i)}async function $b(t,a){await We(`/api/capture-sessions/${encodeURIComponent(t)}`,{method:"DELETE"},a)}async function lT(t){return await We("/api/captures",void 0,t)}function Bb(t,a){return`${Hl(a)}/api/captures/${encodeURIComponent(t)}/content`}async function oT(t,a){return await We(`/api/captures/${encodeURIComponent(t)}`,{method:"DELETE"},a)}function cT({hubUrl:t,onToast:a}){const[i,l]=d.useState([]),[c,u]=d.useState(!0),m=d.useCallback(async()=>{u(!0);try{l((await lT(t)).captures||[])}catch(g){a(g instanceof Error?g.message:String(g))}finally{u(!1)}},[t,a]);d.useEffect(()=>{m()},[m]);const h=async g=>{const y=Bb(g.id,t);if(navigator.share)try{await navigator.share({title:g.fileName,url:y});return}catch{}window.open(y,"_blank","noopener,noreferrer")};return r.jsxs("section",{className:"capture-gallery",children:[r.jsxs("header",{children:[r.jsxs("div",{children:[r.jsx("span",{className:"settings-eyebrow",children:"Capture Gallery"}),r.jsx("h2",{children:"Saved captures"})]}),r.jsxs("button",{className:"text-button",onClick:()=>{m()},type:"button",children:[r.jsx(Mc,{size:15})," Refresh"]})]}),c?r.jsx("p",{className:"settings-help",children:"Loading captures..."}):i.length===0?r.jsx("p",{className:"settings-help",children:"No captures saved yet."}):r.jsx("div",{className:"capture-gallery-grid",children:i.map(g=>{const y=Bb(g.id,t);return r.jsxs("article",{className:"capture-gallery-card",children:[g.mimeType.startsWith("image/")?r.jsx("img",{src:y,alt:g.target.label}):r.jsx("video",{src:y,controls:!0,preload:"metadata"}),r.jsxs("div",{className:"capture-gallery-card-body",children:[r.jsx("strong",{children:g.fileName}),r.jsxs("small",{children:[g.target.label," · ",new Date(g.createdAt).toLocaleString()," · ",Math.ceil(g.sizeBytes/1024)," KB"]}),r.jsxs("div",{children:[r.jsx("button",{className:"icon-button",title:"Open","aria-label":"Open",onClick:()=>window.open(y,"_blank","noopener,noreferrer"),type:"button",children:r.jsx(P0,{size:15})}),r.jsx("a",{className:"icon-button",title:"Download","aria-label":"Download",href:`${y}?download=1`,download:g.fileName,children:r.jsx(Np,{size:15})}),r.jsx("button",{className:"icon-button",title:"Share","aria-label":"Share",onClick:()=>{h(g)},type:"button",children:r.jsx($0,{size:15})}),r.jsx("button",{className:"icon-button danger",title:"Delete","aria-label":"Delete",onClick:()=>{window.confirm(`Delete ${g.fileName}?`)&&oT(g.id,t).then(()=>m()).catch(x=>a(x instanceof Error?x.message:String(x)))},type:"button",children:r.jsx(Rp,{size:15})})]})]})]},g.id)})})]})}function Sf(t){if(!t)return"";const a=Math.max(0,Math.floor((Date.now()-t)/1e3)),i=Math.floor(a/3600),l=Math.floor(a%3600/60),c=a%60;return i>0?`${String(i).padStart(2,"0")}:${String(l).padStart(2,"0")}:${String(c).padStart(2,"0")}`:`${String(l).padStart(2,"0")}:${String(c).padStart(2,"0")}`}function Ub({controller:t,compact:a=!1,onFirstRollingUse:i,onError:l}){const{state:c,settings:u,videoSupported:m}=t,h=async b=>{try{await b()}catch(w){l?.(w instanceof Error?w.message:String(w))}},g=async()=>{if(u.rollingEnabled){t.setRollingEnabled(!1);return}(i?await i():window.confirm(`Keep the most recent 30 seconds in memory temporarily?
|
|
25
|
+
Nothing is saved until you press Save Last 30s.`))&&t.setRollingEnabled(!0)},y=c.recording?`Stop recording · ${Sf(c.recordingStartedAt)}`:`Start recording · ${c.targetLabel}`,x=c.timelapse?`Stop timelapse · ${Sf(c.timelapseStartedAt)}`:`Start timelapse · ${u.timelapseIntervalSeconds}s interval`;return r.jsxs("div",{className:`capture-toolbar ${a?"compact":""} ${c.recording?"recording-active":""}`,"aria-label":"Capture actions",children:[r.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:r.jsx(B0,{size:17})}),r.jsx("button",{className:`capture-action ${c.recording?"active":""}`,"aria-label":y,title:y,disabled:!m||c.busy||c.timelapse,onClick:()=>{h(c.recording?t.stopRecording:t.startRecording)},type:"button",children:c.recording?r.jsxs(r.Fragment,{children:[r.jsx(wy,{size:14,fill:"currentColor"}),r.jsx("span",{children:Sf(c.recordingStartedAt)})]}):r.jsx(Cx,{size:18})}),r.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:!m||c.recording||c.timelapse||c.busy||c.bufferEnabled&&c.bufferSeconds<1,onClick:()=>c.bufferEnabled?void h(t.saveLast30Seconds):void g(),type:"button",children:[r.jsx(U0,{size:17}),r.jsx("small",{children:"30s"})]}),r.jsx("button",{className:`capture-action ${c.timelapse?"timelapse-active":""}`,"aria-label":x,title:x,disabled:!m||c.busy||c.recording,onClick:()=>{h(c.timelapse?t.stopTimelapse:t.startTimelapse)},type:"button",children:c.timelapse?r.jsxs(r.Fragment,{children:[r.jsx(wy,{size:14,fill:"currentColor"}),r.jsx("span",{children:Sf(c.timelapseStartedAt)})]}):r.jsx(q0,{size:17})})]})}function Gw({state:t}){return t==="ok"?r.jsx(ea,{size:15,"aria-hidden":"true"}):r.jsx(jx,{size:15,"aria-hidden":"true"})}function qb({active:t,refreshing:a,onClick:i}){return r.jsx("button",{className:`remote-status-button ${t?"active":""}`,type:"button",title:"Check Remote Status","aria-label":"Check Remote Status","aria-pressed":t,"aria-busy":a,onClick:i,children:a?r.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):r.jsx(G0,{size:18,"aria-hidden":"true"})})}function Gb({active:t,refreshing:a,onClick:i}){return r.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":a,onClick:i,children:a?r.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):r.jsx(gx,{size:18,"aria-hidden":"true"})})}function Vb({active:t,refreshing:a,onClick:i}){return r.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":a,onClick:i,children:a?r.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):r.jsx(Hr,{size:18,"aria-hidden":"true"})})}function uT({items:t,mode:a="remote"}){return r.jsx("span",{className:`remote-status-lines mode-${a}`,role:"status","aria-label":a==="debug"?"Debug status":"Remote status",children:t.map(i=>r.jsxs("span",{className:`remote-status-line state-${i.state}`,title:i.detail,children:[r.jsx(Gw,{state:i.state}),r.jsxs("span",{children:[r.jsx("strong",{children:i.label}),r.jsx("small",{children:i.detail})]})]},i.id))})}function dT({items:t,collectedAt:a,onClose:i}){return r.jsxs("section",{className:"remote-status-dialog hub-status-dialog",role:"dialog","aria-modal":"false","aria-labelledby":"hub-status-dialog-title",children:[r.jsxs("header",{children:[r.jsx("span",{className:"remote-status-dialog-mark","aria-hidden":"true",children:r.jsx(Hr,{size:19})}),r.jsxs("span",{children:[r.jsx("small",{children:"Hub measurements"}),r.jsx("h2",{id:"hub-status-dialog-title",children:"Hub Status"})]}),r.jsx("button",{type:"button",onClick:i,title:"Close Hub status","aria-label":"Close Hub status",children:r.jsx(Ra,{size:17})})]}),r.jsx("p",{children:"LiveDesk collects these Hub and browser signals continuously. This check refreshed the latest snapshot instead of starting a one-time benchmark."}),r.jsx("div",{className:"remote-status-dialog-list",children:t.map(l=>r.jsxs("article",{className:`remote-status-dialog-row state-${l.state}`,children:[r.jsx(Gw,{state:l.state}),r.jsxs("span",{children:[r.jsx("strong",{children:l.label}),r.jsx("small",{children:l.detail})]})]},l.id))}),r.jsxs("footer",{children:["Checked ",new Date(a).toLocaleTimeString()]})]})}const fT=/(nvenc|videotoolbox|qsv|quick\s*sync|amf|vaapi|v4l2m2m|mediafoundation|h264_mf)/i,mT=/(libx264|openh264|software|cpu)/i,Tt=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,minimumClientStatusFreshMs:15e3,clientStatusFreshMultiplier:3,hubMinimumTotalMemoryBytes:8*1024**3,hubMinimumBrowserMemoryGb:4});function ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function tg(t,a){let i=t;for(const l of String(a).split(".")){if(!i||typeof i!="object")return;i=i[l]}return i}function Ta(t,...a){for(const i of a){const l=tg(t,i);if(l==null||l==="")continue;const c=Number(l);if(Number.isFinite(c))return c}}function Et(t,...a){for(const i of a){const l=tg(t,i);if(typeof l=="string"&&l.trim())return l.trim()}return""}function Vw(t,...a){for(const i of a){const l=tg(t,i);if(typeof l=="boolean")return l;if(l===1||l==="1"||String(l).toLowerCase()==="true")return!0;if(l===0||l==="0"||String(l).toLowerCase()==="false")return!1}}function wo(t,...a){const i=Ta(t,...a);if(i!==void 0)return Math.max(0,Math.min(1,i>1?i/100:i))}function Ze(t,a,i,l){return{id:t,state:a,label:i,detail:l}}function _f(t){const a=Date.parse(String(t||""));return Number.isFinite(a)&&a>0?a:void 0}function Wb(t){return`${(Math.max(0,Number(t||0))/1024**3).toFixed(1)} GB`}function hT(t){const a=String(t||"").replace(/^::ffff:/,"").trim().toLowerCase();if(!a||a==="::1"||a==="localhost"||a==="127.0.0.1"||/^10\./.test(a)||/^192\.168\./.test(a))return!0;const i=a.match(/^172\.(\d{1,3})\./);return!!i&&Number(i[1])>=16&&Number(i[1])<=31||a.startsWith("fe80:")||a.startsWith("fc")||a.startsWith("fd")}function Ww(t){const a=ln(t),i=Et(a,"controlTransport").toLowerCase();return i==="encrypted-rendezvous-relay"||/relay/.test(i)?"encrypted-rendezvous-relay":i==="direct-tcp"||/direct|tcp/.test(i)?"direct-tcp":""}function Kb(t){const a=String(t||"").trim();if(!a)return"";try{return new URL(a.includes("://")?a:`relay://${a}`).host}catch{return a.replace(/[?#].*$/,"").replace(/^[a-z][a-z0-9+.-]*:\/\//i,"").split("@").pop().split("/")[0].slice(0,256)}}function pT(t){const a=Ww(t);return a==="encrypted-rendezvous-relay"?Ze("control-transport","ok","Control connection: Encrypted rendezvous relay","Commands and remote input use the end-to-end encrypted rendezvous relay."):a==="direct-tcp"?Ze("control-transport","ok","Control connection: Direct TCP","Commands and remote input use the direct Hub connection."):Ze("control-transport","warning","Control connection is not identified","Waiting for Direct TCP or encrypted rendezvous relay status.")}function gT(t,a){const i=ln(t),l=ln(a),c=Ww(i);if(c==="encrypted-rendezvous-relay"){const u=Et(l,"state")||(l.connected===!0?"registered":"unknown"),m=Kb(Et(l,"endpoint"))||Kb(Et(i,"relayEndpoint")),h=i.connected!==!0||l.connected===!1||/(connecting|reconnect|failed|error|degraded|unavailable|disabled)/.test(u);return Ze("debug-control-transport",h?"warning":"ok",`Encrypted rendezvous relay control · ${u}`,[`endpoint ${m||"-"}`,`state ${u}`,`reconnect ${Math.max(0,Number(l.reconnectCount||0))}`,`handshake ${Math.max(0,Number(l.handshakeCount||0))}`,`peers ${Math.max(0,Number(l.peerCount||0))}`,Et(l,"lastError")].filter(Boolean).join(" · "))}if(c==="direct-tcp"){const u=Et(i,"remoteAddress"),m=Ta(i,"remotePort"),h=u?`${u}${m?`:${m}`:""}`:"-";return Ze("debug-control-transport",i.connected===!0?"ok":"warning","Direct TCP control",`peer ${h} · protocol ${Et(i,"protocol")||"-"} v${Ta(i,"protocolVersion")??"-"} · input ${ln(i.channels).input===!1?"shared control channel":"dedicated channel"}`)}return Ze("debug-control-transport","warning","Control transport is not identified","No Direct TCP or encrypted rendezvous relay metadata is available.")}function Kw(t,a){const i=Number(t?.browserReceivedEpochMs);return Number.isFinite(i)&&i>0?Math.max(0,a-i):Number.POSITIVE_INFINITY}function Yw(t,a,i){const l=ln(a?.frameTransport),c=Et(t,"frameTransportChangedAt"),u=Et(l,"changedAt"),m=_f(c),h=_f(u),g=h!==void 0&&(m===void 0||h>m),y=g?l:t,x=g?t:l,b=Et(t,"transport").toLowerCase(),w=Et(y,g?"active":"frameTransportActive")||Et(x,g?"frameTransportActive":"active"),j=Et(y,g?"protocol":"frameTransportProtocol")||Et(x,g?"frameTransportProtocol":"protocol"),k=(g?Et(l,"videoTransport","activeTransport")||[w,j].filter(Boolean).join("-")||Et(t,"videoTransport"):Et(t,"videoTransport")||Et(l,"videoTransport","activeTransport")||[w,j].filter(Boolean).join("-")).toLowerCase(),T=/(?:^|[-_])ws(?:$|[-_])|websocket/.test(k)||/(?:^|[-_])ws(?:$|[-_])|websocket/.test(b),M=/p2p|udp/.test(k)||b==="udp-p2p"?"p2p-udp":/direct|tcp|ws|websocket/.test(k)||b==="binary"||T?T?"direct-ws":"direct-tcp":"",N=(Et(y,g?"state":"frameTransportState")||Et(x,g?"frameTransportState":"state")||(M?"active":"")).toLowerCase(),L=Et(y,g?"reason":"frameTransportReason")||Et(x,g?"frameTransportReason":"reason"),z=g?u||c:c||u,H=_f(z),G=H===void 0?void 0:Math.max(0,i-H),_=G===void 0?"":G<1e3?"changed now":G<6e4?`changed ${Math.round(G/1e3)}s ago`:G<36e5?`changed ${Math.round(G/6e4)}m ago`:`changed ${z}`,Y=g?l.switchCount??t?.frameTransportSwitchCount:t?.frameTransportSwitchCount??l.switchCount,q=g?l.tcpFailureCount??t?.frameTransportTcpFailureCount:t?.frameTransportTcpFailureCount??l.tcpFailureCount,U=g?typeof l.p2pReady=="boolean"?l.p2pReady:t?.frameTransportP2pReady===!0:typeof t?.frameTransportP2pReady=="boolean"?t.frameTransportP2pReady:l.p2pReady===!0;return{rawTransport:b,videoTransport:M,state:N,reason:L,changedAt:z,changedLabel:_,switchCount:Math.max(0,Number(Y??0)||0),tcpFailureCount:Math.max(0,Number(q??0)||0),p2pReady:U}}function vT(t,a,i){const l=Yw(t,a,i),c=/(connecting|recovering|failed|error|degraded|unavailable)/.test(l.state);if(l.videoTransport==="p2p-udp")return Ze("transport",c?"warning":"ok",c?"P2P video connection needs attention":"P2P video connection",c?`Encrypted UDP P2P is ${l.state||"not ready"}; open Debug Status for the technical reason${l.changedLabel?` · ${l.changedLabel}`:""}.`:`Encrypted UDP P2P fallback is active${l.changedLabel?` · ${l.changedLabel}`:""}.`);if(l.videoTransport==="direct-tcp"||l.videoTransport==="direct-ws"){const u=l.videoTransport==="direct-ws"?"WebSocket":"TCP";return Ze("transport",c?"warning":"ok",c?"Direct video connection needs attention":"Direct video connection",c?`Direct ${u} to Hub is ${l.state||"not ready"}; open Debug Status for the technical reason${l.changedLabel?` · ${l.changedLabel}`:""}.`:`Direct ${u} to Hub is active${l.changedLabel?` · ${l.changedLabel}`:""}.`)}return Ze("transport","warning","Video transport is not identified",l.reason||"Waiting for Direct TCP or encrypted UDP P2P transport data.")}function yT(t){const a=String(t?.frameMode||t?.mode||t?.codec||"").toLowerCase(),i=[t?.hardwareEncoder,t?.platformProfile].filter(Boolean).join(" · "),l=Vw(t,"nativeEncoderHardwareAccelerated"),c=t?.nativeEncoderHardwareAccelerationKnown===!0||l!==void 0;return!t||!/h264/.test(a)?Ze("encoder","warning","Video encoder unavailable","Waiting for an H.264 frame."):c&&l===!1?Ze("encoder","warning","H.264 hardware acceleration is not active",`${i||"Native encoder"} is running without confirmed hardware acceleration.`):c&&l===!0?Ze("encoder","ok","Hardware H.264 encoding",`${i||"Native encoder"} · hardware acceleration confirmed`):fT.test(i)?Ze("encoder","ok","Hardware H.264 encoding",i):mT.test(i)?Ze("encoder","warning","Software H.264 encoding",`${i||"CPU encoder"} may limit frame rate.`):Ze("encoder","warning","H.264 encoder not identified",i||"The Client has not reported its active encoder profile.")}function bT({device:t,frame:a,receiveStat:i,paintStat:l,codec:c,selectedMonitorIndex:u=0,control:m=!1,controlInputReady:h=!1,controlBinding:g,hubRelay:y,capturePaused:x=!1,capturePauseConfirmed:b=!0,capturePauseError:w="",clientHeartbeatMs:j=5e3,now:A=Date.now()}={}){const k=ln(t),T=ln(k.status),M=ln(l?.lastInfo),N=[],L=Kw(a,A);N.push(pT(k)),N.push(x?b?Ze("connection","ok","Video capture is paused","Client screen capture and FFmpeg shutdown were confirmed by the Client."):Ze("connection","warning","Video stop needs attention",String(w||"The Hub is blocking video restart, but the Client did not confirm capture and FFmpeg shutdown.")):k.connected===!0&&L<=Tt.frameAgeWarningMs?Ze("connection","ok","Video connection is current",`${Math.round(L)}ms since the latest frame.`):Ze("connection","warning",k.connected===!0?"Video frame is stale":"Client is offline",k.connected===!0&&Number.isFinite(L)?`${Math.round(L)}ms since the latest frame.`:String(k.lastDisconnectReason||"No current Client session."))),N.push(vT(a,T,A)),N.push(yT(a));const z=Math.max(0,Number(a?.requestedFps||a?.effectiveFps||0)),H=Math.max(0,Number(i?.framesPerSecond||0));Math.max(0,Number(a?.sourceGapMs||0));const G=Math.max(0,Number(a?.nativeCaptureFps||0)),_=Math.max(0,Number(a?.nativeEncodedFps||0)),Y=Math.max(0,Number(a?.nativeCaptureSampleCount||0)),q=Math.max(0,Number(a?.nativeBackpressureSkippedFrameCount||0)),U=Math.max(0,Number(a?.nativeIdleSkippedFrameCount||0)),K=a?.nativeCaptureTelemetryAvailable===!0&&Y>0,O=Ta(a,"captureP95Ms","captureAverageMs","captureStageMs"),ve=Math.max(0,Number(O||0)),me=a?.captureTimingAvailable===!0&&z>0&&Number(i?.sampleMs||0)>0&&O!==void 0,Z=me||K,I=Math.max(Tt.minimumCaptureBudgetMs,z>0?1e3/z*Tt.captureBudgetMultiplier:0),se=z>0?1e3/z:100,W=z>0&&G>=z*Tt.receiveRatioWarning,F=_>0&&_<z*Tt.receiveRatioWarning,oe=K&&W&&F&&U>0&&q===0,le=K&&z>0&&(G<z*Tt.receiveRatioWarning||!oe&&_>0&&_<z*Tt.receiveRatioWarning),Q=K?le:me&&ve>I;N.push(Z?Q?Ze("capture","warning","Screen capture cannot keep target speed",K?`${G.toFixed(1)} native capture · ${_.toFixed(1)} encoded · ${z||"?"} requested fps`:`${ve?`capture p95 ${Math.round(ve)}ms`:"capture timing unavailable"} · ${H.toFixed(1)}/${z||"?"} fps`):Ze("capture","ok","Screen capture speed is healthy",K?`${G.toFixed(1)} native capture · ${_.toFixed(1)} encoded · ${z||"?"} requested fps${oe?" · idle optimized":""}`:`${ve?`capture p95 ${Math.round(ve)}ms`:"no slow capture reported"}${z?` · ${H.toFixed(1)}/${z} fps`:""}`):Ze("capture","warning","Screen capture data is still collecting","A current frame-rate and capture-time sample is required."));const be=Ta(a,"hubPacketTransitAgeMs"),he=Math.max(0,Number(be||0)),de=Math.max(0,Number(a?.agentSendGapMs||0)),ee=Math.max(0,Number(a?.agentSendDurationMs||0)),Ce=!hT(k.remoteAddress),Re=wo(T,"network.usageRatio"),He=Ta(T,"network.latencyMs"),te=(Re??0)>=Tt.networkUsageWarningRatio||(He??0)>=Tt.networkLatencyWarningMs,Ue=Math.max(0,Number(a?.hubClientQueueDepth||0)),mt=Math.max(0,Number(a?.hubClientQueueLimit||0)),ne=mt>0&&Ue>=mt,xe=be!==void 0&&Number(i?.sampleMs||0)>0,Oe=!oe&&z>0&&Number(i?.sampleMs||0)>0&&H<z*Tt.deliveryRatioWarning,$e=!oe&&de>Math.max(Tt.networkDelayWarningMs,se*3),ze=he>Tt.networkDelayWarningMs||$e||ee>Tt.networkDelayWarningMs||Oe||L>Tt.frameAgeWarningMs||te||ne;N.push(xe?ze||Ce?Ze("network","warning",Ce?"External network route may add delay":te?"Client network adapter needs attention":ne?"Hub browser video queue needs attention":"Video delivery is uneven",[he?`${Math.round(he)}ms Hub-to-browser`:"",de?`${Math.round(de)}ms Client send gap`:"",ee?`${Math.round(ee)}ms Client send time`:"",Oe?`${H.toFixed(1)} of ${z} requested fps`:"",He!==void 0?`${Math.round(He)}ms Client network latency`:"",Re!==void 0?`${Math.round(Re*100)}% Client link use`:"",mt>0?`Hub queue ${Ue}/${mt}`:"",Ce?String(k.remoteAddress||"external route"):""].filter(Boolean).join(" · ")||"Frame delivery is not current."):Ze("network","ok","Network delivery is healthy",`${Math.round(he)}ms Hub-to-browser · ${oe?`idle optimized at ${_.toFixed(1)} fps`:"the current video rate is on target."}`):Ze("network","warning","Network delivery data is still collecting","A calibrated Hub-to-browser transit sample is required."));const Qe=wo(T,"cpu.usageRatio","cpu.usedRatio","cpu.percent"),qe=wo(T,"memory.usedRatio","usedMemRatio"),Ye=wo(T,"gpu.usageRatio"),ot=wo(T,"gpu.memory.usedRatio"),B=Ta(T,"gpu.temperatureC","thermal.gpuC"),ye=Qe!==void 0&&qe!==void 0,je=_f(k.lastStatusAt),Pe=je===void 0?Number.POSITIVE_INFINITY:Math.max(0,A-je),dt=Math.max(Tt.minimumClientStatusFreshMs,Math.max(1e3,Number(j||0))*Tt.clientStatusFreshMultiplier),nt=Pe<=dt,bt=(Qe??0)>=Tt.cpuWarningRatio||(qe??0)>=Tt.memoryWarningRatio||(Ye??0)>=Tt.gpuWarningRatio||(ot??0)>=Tt.gpuMemoryWarningRatio||(B??0)>=Tt.gpuTemperatureWarningC;N.push(ye?nt?bt?Ze("computer","warning",(Ye??0)>=Tt.gpuWarningRatio||(ot??0)>=Tt.gpuMemoryWarningRatio||(B??0)>=Tt.gpuTemperatureWarningC?"Client GPU is under load":"Client computer is under load",[`CPU ${Math.round(Qe*100)}%`,`memory ${Math.round(qe*100)}%`,Ye!==void 0?`GPU ${Math.round(Ye*100)}%`:"",ot!==void 0?`GPU memory ${Math.round(ot*100)}%`:"",B!==void 0?`GPU ${Math.round(B)}C`:""].filter(Boolean).join(" · ")):Ze("computer","ok","Client computer has working capacity",[`CPU ${Math.round(Qe*100)}%`,`memory ${Math.round(qe*100)}%`,Ye!==void 0?`GPU ${Math.round(Ye*100)}%`:""].filter(Boolean).join(" · ")):Ze("computer","warning","Client performance snapshot is stale",Number.isFinite(Pe)?`The latest CPU and memory report is ${Math.round(Pe/1e3)} seconds old.`:"No current Client performance heartbeat has been received."):Ze("computer","warning","Client performance data is unavailable","CPU and memory telemetry have not been reported yet."));const it=Number(a?.monitorIndex),Ct=Number.isInteger(it)&&it===Number(u),pe=ln(k.channels),De=ln(k.capabilities),Fe=pe.input!==!1&&De.remoteInput!==!1&&De.accessibilityPermission!==!1,Ae=De.screenRecordingPermission!==!1,ct=ln(g),ht=!m||String(a?.sessionId||"")&&String(a?.sessionId||"")===String(ct.sessionId||"")&&String(a?.commandId||"")&&String(a?.commandId||"")===String(ct.commandId||"")&&Number(a?.captureGeneration||0)>0&&Number(a?.captureGeneration||0)===Number(ct.captureGeneration||0)&&Number(a?.monitorIndex)===Number(ct.monitorIndex),Le=!m||h&&ht;N.push(Ct&&Le&&Fe&&Ae?Ze("display","ok",m?"Display and remote input are bound":"Display and remote input are available",`Display ${Number(u)+1} · generation ${Number(a?.captureGeneration||0)||"current"}.`):Ze("display","warning",Ae?Fe?m?"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(it)?it+1:"not available"}.`));const Dn=ln(c),yn=Array.isArray(Dn.canvases)?ln(Dn.canvases[0]):{},et=Math.max(0,Number(l?.decoderInputFps||0)),xt=Math.max(0,Number(l?.decoderOutputFps||0)),kn=et>0&&Number(l?.sampleMs||i?.sampleMs||0)>0,_e=H>0&&Number(i?.sampleMs||0)>0&&Number(l?.sampleMs||0)>0&&et<H*Tt.decoderInputRatioWarning,tn=et>0?xt/et:0,on=Et(yn,"configuredAcceleration","requestedAcceleration")||Et(M,"h264DecodeAcceleration"),Da=Et(yn,"softwareFallbackReason"),nn=!!Da||on==="prefer-software";return N.push(_e?Ze("decoder","warning","Browser decoder input is dropping frames",`${H.toFixed(1)} received / ${et.toFixed(1)} decoder input / ${xt.toFixed(1)} output fps.`):kn?nn||tn<Tt.decoderOutputRatioWarning?Ze("decoder","warning",nn?"Browser is using software H.264 fallback":"Browser decoder output is slow",`${Da||String(M.decoderLabel||on||"decoder")} · ${et.toFixed(1)} in / ${xt.toFixed(1)} out fps.`):Ze("decoder","ok",on==="prefer-hardware"?"Browser requests hardware H.264":"Browser H.264 path is responsive",`${et.toFixed(1)} in / ${xt.toFixed(1)} out fps. Chrome does not expose definitive hardware acceptance.`):Ze("decoder","warning","Browser decoder data is still collecting","Decoder input and output samples are required before this path can be marked healthy.")),N}function Ir(t){const a=String(t||"").trim();return a?a.length<=14?a:`${a.slice(0,6)}…${a.slice(-5)}`:"-"}function gn(t,a=1){const i=Number(t);return Number.isFinite(i)?i.toFixed(a):"-"}function xT({device:t,frame:a,receiveStat:i,paintStat:l,codec:c,selectedMonitorIndex:u=0,control:m=!1,controlInputReady:h=!1,controlBinding:g,hubRelay:y,now:x=Date.now()}={}){const b=ln(t),w=ln(b.status),j=ln(g),A=ln(l?.lastInfo),k=ln(c),T=Array.isArray(k.canvases)?ln(k.canvases[0]):{},M=[],N=Number(u),L=Number(a?.monitorIndex),z=Number.isInteger(L)&&L===N,H=Number(a?.captureGeneration||0),G=Number(j.captureGeneration||0),_=!m||z&&String(a?.sessionId||"")===String(j.sessionId||"")&&String(a?.commandId||"")===String(j.commandId||"")&&H>0&&H===G,Y=Math.max(0,Number(a?.requestedFps||a?.effectiveFps||0)),q=Math.max(0,Number(i?.framesPerSecond||0)),U=Math.max(0,Number(l?.framesPerSecond||0)),K=Math.max(0,Number(l?.decoderInputFps||0)),O=Math.max(0,Number(l?.decoderOutputFps||0)),ve=Number(i?.sampleMs||0)>0&&Number(l?.sampleMs||0)>0,me=Y>0&&ve&&Math.min(q,U||q,O||q)<Y*Tt.deliveryRatioWarning,Z=Math.max(0,Number(a?.sourceGapMs||0)),I=Math.max(0,Number(a?.agentSendGapMs||0)),se=Math.max(0,Number(a?.agentSendDurationMs||0)),W=Math.max(0,Number(a?.agentSendDurationFrameSeq||0)),F=Math.max(0,Number(a?.agentQueueBeforePaceMs||0)),oe=Math.max(0,Number(a?.agentFrameAgeMs||0)),le=Ta(a,"hubPacketTransitAgeMs"),Q=Math.max(0,Number(a?.droppedByAgent||0)),be=Math.max(0,Number(a?.hubIngressDropped||0)),he=Math.max(0,Number(a?.hubClientDropped||0)),de=Math.max(0,Number(a?.hubClientQueueDepth||0)),ee=Math.max(0,Number(a?.hubClientQueueLimit||0)),Ce=Math.max(0,Number(a?.hubClientBufferedBytes||0)),Re=Math.max(0,Number(a?.udpIncompleteFrames||0)),He=Q+be+he,te=Kw(a,x),Ue=Et(T,"configuredAcceleration","requestedAcceleration")||Et(A,"h264DecodeAcceleration"),mt=Et(T,"softwareFallbackReason"),ne=ve&&q>0&&K<q*Tt.decoderInputRatioWarning,xe=Yw(a,w,x),Oe=Et(b,"deviceId")||Et(a,"deviceId"),$e=Et(a,"sessionId")||Et(b,"sessionId"),ze=Et(b,"productVersion")||Et(w,"productVersion","runtime.productVersion"),Qe=Et(b,"agentVersion")||Et(w,"agentVersion","runtime.agentVersion"),qe=Ta(b,"pid","runtimePid")??Ta(w,"pid","runtimePid","process.pid"),Ye=!!(Oe&&$e&&ze&&Qe&&(qe??0)>0),ot=a?.nativeCaptureTelemetryAvailable===!0,B=Vw(a,"nativeEncoderHardwareAccelerated"),ye=a?.nativeEncoderHardwareAccelerationKnown===!0||B!==void 0,je=Et(a,"nativeEncoderHardwareQueryStatus"),Pe=je==="0"?"confirmed":je,dt=Math.max(0,Number(a?.nativeCaptureFps||0)),nt=Math.max(0,Number(a?.nativeEncodedFps||0)),bt=Math.max(0,Number(a?.nativeCaptureSampleCount||0)),it=Math.max(0,Number(a?.nativeEncodableFrameCount||0)),Ct=Math.max(0,Number(a?.nativeSkippedFrameCount||0)),pe=Math.max(0,Number(a?.nativeEncodedFrameCount||0)),De=Math.max(0,Number(a?.nativeEncodeFramesInFlight||0)),Fe=Math.max(0,Number(a?.nativeBackpressureSkippedFrameCount||0)),Ae=Math.max(0,Number(a?.nativeIdleSkippedFrameCount||0)),ct=De>=2&&Fe>0,ht=`in-flight ${De}/2 · backpressure skipped ${Fe} · idle skipped ${Ae}`,Le=ot&&bt>0,Dn=Y>0?1e3/Y:100,yn=Y>0&&dt>=Y*Tt.receiveRatioWarning,et=nt>0&&nt<Y*Tt.receiveRatioWarning,xt=Le&&yn&&et&&Ae>0&&Fe===0,kn=me&&!xt,Pn=!xt&&I>Math.max(Tt.networkDelayWarningMs,Dn*3),_e=Le&&Y>0&&(dt<Y*Tt.receiveRatioWarning||!xt&&nt>0&&nt<Y*Tt.receiveRatioWarning);M.push(gT(b,y)),M.push(Ye?Ze("debug-runtime","ok",`LiveDesk ${ze} · Agent ${Qe}`,`pid ${qe} · session ${Ir($e)} · device ${Ir(Oe)}`):Ze("debug-runtime","warning","Runtime identity is incomplete",`LiveDesk ${ze||"-"} · Agent ${Qe||"-"} · pid ${qe??"-"} · session ${Ir($e)} · device ${Ir(Oe)}`)),M.push(a?Ze("debug-frame","ok",`Frame #${Number(a.frameSeq||0)} · ${String(a.streamPurpose||(m?"control":"wall"))}`,`stream ${Ir(a.streamId)} · ${a.width||0}x${a.height||0} · ${Math.round(Number(a.byteLength||0)/1024)} KB · age ${Number.isFinite(te)?Math.round(te):"-"}ms`):Ze("debug-frame","warning","No current frame",`Device ${Ir(b.deviceId)} has not produced a frame.`));const tn=/(connecting|recovering|failed|error|degraded|unavailable)/.test(xe.state);M.push(xe.videoTransport&&!tn?Ze("debug-transport","ok",`${xe.videoTransport==="p2p-udp"?"P2P UDP":xe.videoTransport==="direct-ws"?"Direct WebSocket":"Direct TCP"} · ${xe.state||"active"}`,[`raw ${xe.rawTransport||"-"}`,`P2P ${xe.p2pReady?"ready":"standby unavailable"}`,`switch ${xe.switchCount}`,`TCP failure ${xe.tcpFailureCount}`,xe.changedLabel,xe.reason].filter(Boolean).join(" · ")):Ze("debug-transport","warning",xe.videoTransport?`Video transport ${xe.state||"needs attention"}`:"Video transport is not identified",[xe.videoTransport||"no active path",`raw ${xe.rawTransport||"-"}`,`P2P ${xe.p2pReady?"ready":"not ready"}`,xe.changedLabel,xe.reason].filter(Boolean).join(" · "))),M.push(z?Ze("debug-monitor","ok",`Monitor selected ${N+1} · frame ${L+1}`,`reported ${Number(a?.monitorCount||0)||"?"} displays · generation ${H||"-"}`):Ze("debug-monitor","warning",`Monitor mismatch: selected ${N+1} · frame ${Number.isInteger(L)?L+1:"-"}`,`reported ${Number(a?.monitorCount||0)||"?"} displays · generation ${H||"-"}`)),M.push(_&&(!m||h)?Ze("debug-binding","ok",m?"Control generation is bound":"Wall capture generation is current",`session ${Ir(a?.sessionId)} · command ${Ir(a?.commandId)} · generation ${H||"-"}`):Ze("debug-binding","warning",m?"Control generation is not bound":"Wall capture generation is unavailable",`frame ${Ir(a?.commandId)}/${H||"-"} · expected ${Ir(j.commandId)}/${G||"-"} · input ${h?"ready":"waiting"}`)),M.push(ve&&!kn?Ze("debug-cadence","ok",`Cadence ${gn(q)} rx · ${gn(U)} paint · ${gn(O)} decode`,`requested ${gn(Y)} · decoder input ${gn(K)} fps · receive p95 ${gn(i?.p95IntervalMs)}ms${xt?" · idle optimized":""}`):Ze("debug-cadence","warning",ve?"Frame cadence is below request":"Frame cadence sample is collecting",`requested ${gn(Y)} · receive ${gn(q)} · paint ${gn(U)} · decode ${gn(O)} fps`)),M.push(Le&&!_e&&!ct&&B!==!1?Ze("debug-native-capture","ok",`Native capture ${gn(dt)} fps · encode ${gn(nt)} fps${xt?" · idle optimized":""}`,`telemetry yes · hardware ${ye?B?"yes":"no":"unknown"}${Pe?` (${Pe})`:""} · capture samples ${bt} · encodable ${it} · skipped ${Ct} · encoded ${pe} · ${ht} · encoded AU output gap ${Math.round(Z)}ms`):Ze("debug-native-capture","warning",Le?"Native capture or encoder needs attention":"Native capture telemetry is unavailable",`telemetry ${ot?"yes, waiting for samples":"no"} · hardware ${ye?B?"yes":"no":"unknown"}${Pe?` (${Pe})`:""} · capture ${gn(dt)} fps · encode ${gn(nt)} fps · capture samples ${bt} · encodable ${it} · skipped ${Ct} · encoded ${pe} · ${ht} · encoded AU output gap ${Math.round(Z)}ms`)),M.push(He===0&&Re===0&&(ee<=0||de<ee)&&!Pn&&se<=Tt.networkDelayWarningMs&&oe<=Tt.networkDelayWarningMs&&(le===void 0||le<=Tt.networkDelayWarningMs)?Ze("debug-delivery","ok","Delivery counters are clear",`encoded AU output gap ${Math.round(Z)}ms · Client send gap ${Math.round(I)}ms · Client send time ${Math.round(se)}ms (frame ${W||"-"}) · Agent queue ${Math.round(F)}ms · Agent age ${Math.round(oe)}ms · Agent drop ${Q} · Hub transit ${le===void 0?"-":Math.round(le)}ms · Hub ingress drop ${be} · browser queue drop ${he} (${de}/${ee||"-"}) · buffered ${Math.round(Ce/1024)} KB · UDP incomplete ${Re}${xt?" · idle optimized":""}`):Ze("debug-delivery","warning","Delivery counters show loss or delay",`encoded AU output gap ${Math.round(Z)}ms · Client send gap ${Math.round(I)}ms · Client send time ${Math.round(se)}ms (frame ${W||"-"}) · Agent queue ${Math.round(F)}ms · Agent age ${Math.round(oe)}ms · Agent drop ${Q} · Hub transit ${le===void 0?"-":Math.round(le)}ms · Hub ingress drop ${be} · browser queue drop ${he} (${de}/${ee||"-"}) · buffered ${Math.round(Ce/1024)} KB · UDP incomplete ${Re}`));const on=Ta(a,"captureP95Ms");return M.push(a?.captureTimingAvailable===!0&&on!==void 0?Ze("debug-capture","ok",`Capture p95 ${gn(on)}ms · avg ${gn(a?.captureAverageMs)}ms`,`stage ${gn(a?.captureStageMs)}ms · slow ${Number(a?.slowFrameCount||0)} · helper restart ${Number(a?.captureHelperRestarts||0)} · source skip ${Number(a?.captureSourceSkipped||0)}`):Ze("debug-capture","warning","Capture timing sample is unavailable",`stage ${gn(a?.captureStageMs)}ms · helper restart ${Number(a?.captureHelperRestarts||0)} · source serial ${Number(a?.captureSourceSerial||0)}`)),M.push(!mt&&Ue!=="prefer-software"&&!ne?Ze("debug-decoder","ok",`Decoder ${Ue||"acceleration unknown"}`,`${String(a?.frameMode||a?.codec||"-")} · ${String(a?.hardwareEncoder||"-")} · ${String(a?.platformProfile||"-")}`):Ze("debug-decoder","warning",ne?"Decoder input is losing received frames":"Decoder software fallback is active",ne?`${gn(q)} received / ${gn(K)} decoder input / ${gn(O)} output fps`:`${mt||Ue||"software"} · ${gn(K)} in / ${gn(O)} out fps`)),M}function wT({status:t,deviceDiagnostics:a=[],codec:i,browser:l,frameStats:c}={}){const u=ln(t),m=ln(u.diagnostics),h=ln(m.system),g=ln(m.network),y=ln(i),x=ln(l),b=Array.isArray(a)?a:[],w=b.reduce((ve,me)=>ve+(Array.isArray(me)&&me.some(Z=>Z?.state==="warning")?1:0),0),j=wo(h,"cpuUsageRatio","processCpuRatio"),A=wo(h,"memoryUsedRatio"),k=Ta(h,"totalMemoryBytes"),T=Ta(h,"cpuLogicalCores")??Ta(x,"hardwareConcurrency"),M=Ta(x,"deviceMemory"),N=(T??0)>0&&j!==void 0&&A!==void 0&&(k??0)>0,L=(k??0)>0&&k<Tt.hubMinimumTotalMemoryBytes,z=(M??0)>0&&M<Tt.hubMinimumBrowserMemoryGb,H=(T??0)>0&&T<4||(j??0)>=Tt.cpuWarningRatio||(A??0)>=Tt.memoryWarningRatio||L||z,G=Math.max(0,Number(y.activeSoftwareFallbackCount??y.softwareFallbackCount??0)),_=Math.max(0,Number(y.activeDecoderCount||0)),Y=Math.max(0,Number(c?.bytesPerSecond||0)*8/1e6),q=Ta(g,"externalDeviceCount"),U=Et(g,"route"),K=q!==void 0&&!!U,O=(q??0)>0||U==="external";return[u.started&&!u.lastError?Ze("hub-runtime","ok","Hub runtime is ready",`${u.connectedDeviceCount||0} Clients connected.`):Ze("hub-runtime","warning","Hub runtime needs attention",String(u.lastError||"Hub is not ready.")),N?H?Ze("hub-computer","warning",L?"Hub has limited system memory":z?"Browser reports limited memory capacity":"Hub computer may limit remote performance",[`${T||"?"} logical cores`,`${Wb(k)} RAM`,M!==void 0?`${M} GB browser memory class`:"",`CPU ${j===void 0?"?":Math.round(j*100)}%`,`memory ${A===void 0?"?":Math.round(A*100)}%`].filter(Boolean).join(" · ")):Ze("hub-computer","ok","Hub computer capacity is healthy",`${T||"?"} logical cores · ${Wb(k)} RAM · CPU ${j===void 0?"not reported":`${Math.round(j*100)}%`}.`):Ze("hub-computer","warning","Hub performance data is unavailable","Logical-core, CPU, used-memory, and total-memory telemetry are required."),_<=0?Ze("hub-codec","warning","No active browser H.264 decoder to check","Open Wall or Control and wait for a video frame."):G>0?Ze("hub-codec","warning","Some browser decoders use software fallback",`${_} active H.264 decoders · ${G} software fallbacks. Chrome does not expose definitive hardware acceptance.`):Ze("hub-codec","ok","All active streams request hardware H.264",`${_} active decoders. Chrome hardware acceptance is inferred from health, not directly exposed.`),w>0?Ze("hub-clients","warning",`${w} Clients need attention`,"Open the matching Wall slot lines for the exact cause."):Ze("hub-clients","ok","Connected Clients report healthy remote paths",`${b.length} Client reports checked.`),Ze("hub-network",!K||O||Y>120?"warning":"ok",K?O?`${q} Clients use an external network route`:Y>120?"Hub receive load is high":"Hub receive load is within range":"Hub network route data is unavailable",K?`${U.toUpperCase()} route · ${Y.toFixed(Y>=10?0:1)} Mbps received by this browser.`:"The Hub has not reported LAN/external route classification yet.")]}async function ST(t,a={}){const i=t.filter(b=>b.canvas&&b.canvas.width>0&&b.canvas.height>0),l=Math.max(320,a.maxWidth||1920),c=Math.max(180,a.maxHeight||1080),u=i.length<=1?1:i.length<=4?2:i.length<=9?3:4,m=Math.max(1,Math.ceil(Math.max(1,i.length)/u)),h=Math.floor(l/u),g=Math.floor(c/m),y=document.createElement("canvas");y.width=Math.max(320,h*u),y.height=Math.max(180,g*m);const x=y.getContext("2d",{alpha:!1});if(!x)return y;x.fillStyle="#0b1220",x.fillRect(0,0,y.width,y.height),x.font="600 14px system-ui, sans-serif",x.textBaseline="bottom";for(let b=0;b<i.length;b+=1){const w=i[b],j=b%u,A=Math.floor(b/u),k=j*h,T=A*g,M=w.canvas,N=Math.min(h/M.width,g/M.height),L=Math.max(1,Math.floor(M.width*N)),z=Math.max(1,Math.floor(M.height*N)),H=k+Math.floor((h-L)/2),G=T+Math.floor((g-z)/2);x.drawImage(M,H,G,L,z),a.includeLabels!==!1&&(x.fillStyle="rgba(4, 10, 20, .74)",x.fillRect(k,T+g-28,h,28),x.fillStyle="#f8fafc",x.fillText(w.label,k+9,T+g-9))}return y}function CT(t){return t?.signature||"none"}function kT(t){return t?.label||"No capture target"}function Yb(t){return{...t,deviceIds:[...t.deviceIds],sourceCanvas:t.sourceCanvas||null}}function jT(){const t=new Date,a=i=>String(i).padStart(2,"0");return`${t.getFullYear()}${a(t.getMonth()+1)}${a(t.getDate())}_${a(t.getHours())}${a(t.getMinutes())}${a(t.getSeconds())}`}function AT(t){return t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function MT(t){return`LiveDesk_${t.type==="wall"||t.type==="selection"?"Wall":`${AT(t.label)}_Monitor-${Number(t.monitorIndex||0)+1}`}_${jT()}.png`}async function NT(t,a,i){const l=await new Promise((u,m)=>t.toBlob(h=>h?u(h):m(new Error("Screenshot could not be encoded.")),"image/png")),c=await qw(l,{kind:"screenshot",fileName:MT(a),target:a},i);try{await navigator.clipboard.write([new ClipboardItem({"image/png":l})])}catch{}return c.capture}function Qw(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(a=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(a))||""}function TT(t,a){const i=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","_"),l=a.label.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,70)||"Wall";return t==="timelapse"?`LiveDesk_Timelapse_${l}_${i}.webm`:`LiveDesk_Recording_${l}_${i}.webm`}async function Xw(t){if(typeof MediaRecorder>"u"||typeof t.canvas.captureStream!="function")throw new Error("This browser does not support video recording.");const a=Qw();if(!a)throw new Error("This browser does not support WebM recording.");const i=t.kind||"recording",l=await sT({kind:i,fileName:TT(i,t.target),mimeType:a,target:t.target},t.hubUrl),c=t.canvas.captureStream(t.frameRequests?0:t.fps),u=new MediaRecorder(c,{mimeType:a,videoBitsPerSecond:i==="timelapse"?2e6:4e6}),m=performance.now();let h=0,g=!1,y=null,x=Promise.resolve();return u.ondataavailable=b=>{if(!b.data||b.data.size===0)return;const w=h++;x=x.then(()=>rT(l.sessionId,w,b.data,t.hubUrl).then(()=>{})).catch(j=>{y=y||(j instanceof Error?j:new Error(String(j))),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 x,y)throw await $b(l.sessionId,t.hubUrl).catch(()=>{}),y;await iT(l.sessionId,Math.max(0,performance.now()-m),t.hubUrl)}},cancel:async()=>{g||(g=!0,u.stop(),c.getTracks().forEach(b=>b.stop()),await $b(l.sessionId,t.hubUrl).catch(()=>{}))}}}class RT{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(a,i){if(this.recorder&&this.targetSignature===i.signature)return;if(this.stop(),typeof MediaRecorder>"u"||typeof a.captureStream!="function")throw new Error("This browser does not support Last 30s.");const l=Qw();if(!l)throw new Error("This browser does not support WebM recording.");this.targetSignature=i.signature,this.stream=a.captureStream(20),this.recorder=new MediaRecorder(this.stream,{mimeType:l,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 m=this.segments.shift();this.totalBytes-=m.blob.size}},this.recorder.start(1e3)}stop(){const a=this.recorder;this.recorder=null,a&&a.state!=="inactive"&&(a.ondataavailable=null,a.stop()),this.stream?.getTracks().forEach(i=>i.stop()),this.stream=null,this.segments=[],this.totalBytes=0,this.startedAt=0}async save(a,i){if(this.segments.length===0)throw new Error("The Last 30s buffer is not ready yet.");const l=new Blob(this.segments.map(m=>m.blob),{type:this.segments[0].blob.type||"video/webm"}),u=`LiveDesk_Last30s_${a.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 qw(l,{kind:"last-30s",fileName:u,target:a,durationMs:Math.min(3e4,this.segments.length*1e3)},i)}}async function ET(t,a,i,l,c){const u=await Xw({canvas:t,target:a,kind:"timelapse",fps:30,frameRequests:!0,hubUrl:l,onError:c});u.requestFrame?.();const m=window.setInterval(()=>u.requestFrame?.(),Math.max(5,i)*1e3);return{stop:async()=>{window.clearInterval(m),await u.stop()},cancel:async()=>{window.clearInterval(m),await u.cancel()}}}const Zw="livedesk.captureSettings";function DT(){const t={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const a=JSON.parse(localStorage.getItem(Zw)||"null");return{...t,...a&&typeof a=="object"?a:{}}}catch{return t}}function LT(t){const[a,i]=d.useState(DT),[l,c]=d.useState(0),[u,m]=d.useState(0),[h,g]=d.useState(0),[y,x]=d.useState(!1),b=d.useRef(void 0),w=d.useRef(!1),j=d.useRef(""),A=d.useRef(null),k=d.useRef(null),T=d.useRef(null),M=d.useRef(null),N=d.useRef(new RT),L=t.sourceRegistry.resolveCurrentTarget(),z=CT(L),H=kT(L),G=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;d.useEffect(()=>{if(localStorage.setItem(Zw,JSON.stringify(a)),!w.current)return;const W=JSON.stringify(a);W!==j.current&&(j.current=W,We("/api/settings",{method:"PATCH",body:JSON.stringify({revision:b.current,filesAudio:{rollingBufferEnabled:a.rollingEnabled,recordingQuality:a.recordingQuality,timelapseIntervalSeconds:a.timelapseIntervalSeconds,includeRemoteCursor:a.includeRemoteCursor}})},t.hubUrl).then(F=>{b.current=Number(F.revision||b.current||0)}).catch(()=>{}))},[t.hubUrl,a]),d.useEffect(()=>{let W=!0;return We("/api/settings",void 0,t.hubUrl).then(F=>{if(!W)return;const oe=F.settings?.filesAudio||{},le=typeof oe.rollingBufferEnabled=="boolean"?oe.rollingBufferEnabled:a.rollingEnabled,Q=oe.recordingQuality==="high"?"high":"standard",be=[5,10,30,60].includes(Number(oe.timelapseIntervalSeconds))?Number(oe.timelapseIntervalSeconds):a.timelapseIntervalSeconds,he=typeof oe.includeRemoteCursor=="boolean"?oe.includeRemoteCursor:a.includeRemoteCursor,de={rollingEnabled:le,recordingQuality:Q,timelapseIntervalSeconds:be,includeRemoteCursor:he};b.current=Number(F.revision||0),j.current=JSON.stringify(de),w.current=!0,i(de)}).catch(()=>{w.current=!0}),()=>{W=!1}},[t.hubUrl]);const _=d.useCallback(async W=>{if(W.sourceCanvas&&W.sourceCanvas.width>0&&W.sourceCanvas.height>0)return{target:Yb(W),canvas:W.sourceCanvas,cleanup:()=>{}};const F=await t.sourceRegistry.composeWall(W.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let oe=!1;const le=window.setInterval(async()=>{if(oe)return;const Q=await t.sourceRegistry.composeWall(W.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0}).catch(()=>null);!Q||oe||((F.width!==Q.width||F.height!==Q.height)&&(F.width=Q.width,F.height=Q.height),F.getContext("2d")?.drawImage(Q,0,0))},100);return{target:Yb(W),canvas:F,cleanup:()=>{oe=!0,window.clearInterval(le)}}},[t.sourceRegistry]);d.useEffect(()=>{const W=N.current;if(!a.rollingEnabled||!L||!G){W.stop(),g(0);return}let F=!1,oe=null;return(async()=>{try{if(oe=await _(L),F)return;await W.start(oe.canvas,oe.target);const Q=window.setInterval(()=>g(Math.round(W.seconds)),500),be=()=>{window.clearInterval(Q),oe?.cleanup()};W.__cleanup=be}catch(Q){F||t.onToast(Q instanceof Error?Q.message:String(Q))}})(),()=>{F=!0,W.stop(),W.__cleanup?.(),W.__cleanup=void 0,g(0)}},[_,t.onToast,a.rollingEnabled,z,G]);const Y=d.useCallback(W=>i(F=>({...F,rollingEnabled:W})),[]),q=d.useCallback(W=>i(F=>({...F,recordingQuality:W})),[]),U=d.useCallback(W=>i(F=>({...F,timelapseIntervalSeconds:W})),[]),K=d.useCallback(async()=>{const W=t.sourceRegistry.resolveCurrentTarget();if(!W)throw new Error("화면이 준비된 후 다시 시도하세요.");x(!0);let F=null;try{F=await _(W),await NT(F.canvas,F.target,t.hubUrl),t.onToast("Screenshot saved")}finally{F?.cleanup(),x(!1)}},[_,t.hubUrl,t.onToast,t.sourceRegistry]),O=d.useCallback(async()=>{if(T.current)throw new Error("Stop the timelapse before recording.");const W=t.sourceRegistry.resolveCurrentTarget();if(!W)throw new Error("화면이 준비된 후 다시 시도하세요.");const F=await _(W),oe=await Xw({canvas:F.canvas,target:F.target,fps:W.type==="control"?30:15,hubUrl:t.hubUrl,onError:le=>t.onToast(le.message)});k.current=F.cleanup,A.current=oe,c(Date.now()),t.onToast("Recording started")},[_,t.hubUrl,t.onToast,t.sourceRegistry]),ve=d.useCallback(async()=>{const W=A.current;if(W){x(!0);try{await W.stop(),t.onToast("Recording saved")}finally{A.current=null,k.current?.(),k.current=null,c(0),x(!1)}}},[t.onToast]),me=d.useCallback(async()=>{if(A.current||T.current)throw new Error("Last 30s is unavailable during a recording.");const W=t.sourceRegistry.resolveCurrentTarget();if(!W)throw new Error("화면이 준비된 후 다시 시도하세요.");x(!0);try{await N.current.save(W,t.hubUrl),t.onToast("Last 30 seconds saved")}finally{x(!1)}},[t.hubUrl,t.onToast,t.sourceRegistry]),Z=d.useCallback(async()=>{if(A.current)throw new Error("Stop the recording before starting a timelapse.");const W=t.sourceRegistry.resolveCurrentTarget();if(!W)throw new Error("화면이 준비된 후 다시 시도하세요.");const F=await _(W),oe=await ET(F.canvas,F.target,a.timelapseIntervalSeconds,t.hubUrl,le=>t.onToast(le.message));M.current=F.cleanup,T.current=oe,m(Date.now()),t.onToast("Timelapse started")},[_,t.hubUrl,t.onToast,t.sourceRegistry,a.timelapseIntervalSeconds]),I=d.useCallback(async()=>{const W=T.current;if(W){x(!0);try{await W.stop(),t.onToast("Timelapse saved")}finally{T.current=null,M.current?.(),M.current=null,m(0),x(!1)}}},[t.onToast]);return d.useEffect(()=>{const W=F=>{!A.current&&!T.current||(F.preventDefault(),F.returnValue="")};return window.addEventListener("beforeunload",W),()=>window.removeEventListener("beforeunload",W)},[]),d.useEffect(()=>()=>{N.current.stop(),A.current?.cancel(),T.current?.cancel(),k.current?.(),M.current?.()},[]),{state:d.useMemo(()=>({recording:!!A.current,recordingStartedAt:l,timelapse:!!T.current,timelapseStartedAt:u,bufferSeconds:h,bufferEnabled:a.rollingEnabled,busy:y,targetLabel:H}),[h,y,l,a.rollingEnabled,H,u]),settings:a,videoSupported:G,targetKey:z,setRollingEnabled:Y,setRecordingQuality:q,setTimelapseInterval:U,takeScreenshot:K,startRecording:O,stopRecording:ve,saveLast30Seconds:me,startTimelapse:Z,stopTimelapse:I}}const _T=120,IT=999,zu=5,Ou=30,zT=Number.POSITIVE_INFINITY,Jw="livedesk.remoteDirectory",Ap="livedesk.localHubAccessEnabled",OT="livedesk.streamSettings",HT=18,FT="livedesk.controlStreamSettings",PT=8,eS="livedesk.wallMonitorSelections",tS=2,qh=512*1024,Mp="".trim(),nS="".trim(),Qb="livedesk-adsense-script",Gh=!!Mp&&!!nS,$T=Object.freeze([{code:"ShiftLeft",label:"Shift"},{code:"ControlLeft",label:"Ctrl"},{code:"AltLeft",label:"Alt"},{code:"MetaLeft",label:"Win"}]),BT=1e3/60,Vh=1500,UT=650,qT=1800,GT=650,VT=2500,Xb=1500,Zb=15e3,WT=6e4,Jb=240,KT=1024,YT=640,QT=360,ex="Connected LiveDesk clients are updating in batches. Hub will restart after every target reconnects on the requested versions.",Cf="LiveDesk is replacing the Hub and verifying the requested version.",kf=5*6e4,XT=5e3,ZT=8e3;function go({label:t,tooltip:a,disabled:i=!1,active:l=!1,danger:c=!1,pressed:u,onClick:m,children:h}){return r.jsx("span",{className:`manual-action-tooltip ${i?"disabled":""}`.trim(),"data-tooltip":a,children:r.jsx("button",{className:`manual-action ${l?"active":""} ${c?"danger":""}`.trim(),onClick:m,disabled:i,"aria-label":t,"aria-pressed":u,type:"button",children:h})})}function JT(t,a){if(a.deviceId!==t.deviceId)return!1;const i=Number(a.browserReceivedEpochMs);if(!Number.isFinite(i)||i<t.startedAtEpochMs)return!1;const l=Number(a.monitorIndex);if(Number.isFinite(l)&&Math.floor(l)!==t.monitorIndex)return!1;const c=String(a.frameMode||a.mode||"").trim().toLowerCase();return!c||c===t.frameMode}const vo={free:{name:"Free",price:"$0",limit:zu,audience:"Personal trial",note:"5 devices with a standard ad banner."},ltd:{name:"Plus",price:"$79 LTD",ltd:"$79 LTD",limit:Ou,audience:"Creators and homelabs",note:"30 devices, no ads, personal use."},pro:{name:"Pro",price:"$199 LTD",ltd:"$199 LTD",limit:zT,audience:"Business and studios",note:"Commercial use and larger Client walls."}},eR={"mode3-h264-hw":30};function tx(t,a){const i=m=>{const g=String(m||"").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(x=>/^\d+$/.test(x)?x.length>1&&x.startsWith("0")?Number.NaN:Number(x):x):[];return y.some(x=>typeof x=="number"&&!Number.isFinite(x))?null:{core:[Number(g[1]),Number(g[2]),Number(g[3])],prerelease:y}},l=i(t),c=i(a);if(!l||!c)return!1;for(let m=0;m<3;m+=1){if(l.core[m]>c.core[m])return!0;if(l.core[m]<c.core[m])return!1}if(l.prerelease.length===0||c.prerelease.length===0)return l.prerelease.length===0;const u=Math.max(l.prerelease.length,c.prerelease.length);for(let m=0;m<u;m+=1){const h=l.prerelease[m],g=c.prerelease[m];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}function rs(t,a){return`${t}:${a}`}const tR={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:eR["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},nR={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:30,maxWidth:1920,maxHeight:1080,quality:75,showScreenStatus:!1};function Wh(t,a){if(t.length===0)return 0;const i=[...t].sort((c,u)=>c-u),l=Math.max(0,Math.min(i.length-1,Math.ceil(i.length*a)-1));return i[l]}function aS(t,a){t.push(a),t.length>Jb&&t.splice(0,t.length-Jb)}function nx(t,a){t.sampleFrames=0,t.sampleStartedAt=a,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 ax(t,a,i){if(t.lastAt!==void 0){const l=Math.max(0,a-t.lastAt);t.intervalCount+=1,t.intervalSumMs+=l,t.minIntervalMs=Math.min(t.minIntervalMs,l),t.maxIntervalMs=Math.max(t.maxIntervalMs,l),aS(t.intervalSamplesMs,l)}if(t.lastFrameSeq!==void 0){const l=i-t.lastFrameSeq;l!==1&&(t.seqGapCount+=1,t.maxSeqGap=Math.max(t.maxSeqGap,Math.abs(l)))}t.lastAt=a,t.lastFrameSeq=i}function sx(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 rx(t){return!t||t.seqGapCount<=0?"none":`${t.seqGapCount} gaps / max ${t.maxSeqGap}`}function aR(t){return Number.isFinite(t)?String(t):"30+"}const sS=[1,2,5,8,12,20,30],ix={large:{maxWidth:1280,maxHeight:720},medium:{maxWidth:960,maxHeight:540},list:{maxWidth:640,maxHeight:360}},Na={preserveConfiguredFpsDeviceCount:6,visibleRootMargin:"520px 0px 760px 0px",fallbackVisibleCounts:{large:12,medium:18,list:32},maxWallFramesPerSecond:xs.maxDirectFramesPerSecond,maxWallBytesPerSecond:80*1024*1024,maxFrameGapMs:280,lowLoadFrameRatio:.58,lowLoadByteRatio:.52,downshiftCooldownMs:1800,recoveryCooldownMs:14e3,minFps:5},lx=2200,sR=8e3,rR=3500,iR=7e3,lR=2,oR=7e3,cR=2600,uR=4200,dR=750,fR=2,ox=4200;function cx(t,a){return Math.min(3e4,t*2**Math.min(3,Math.max(0,a)))}function Vu(t,a){const i=t.capabilities?.[a];return typeof i=="boolean"?i:/^(1|true|yes|on)$/i.test(String(i||"").trim())}function va(t){return t.deviceName||t.hostname||t.deviceId}function mR(){return"npx -y --prefer-online livedesk@latest client"}function hR(){return"npx -y --prefer-online livedesk@latest"}function pR(){try{return localStorage.getItem(Jw)||""}catch{return""}}function gR(){try{return localStorage.getItem(Ap)==="1"}catch{return!1}}function xc(t){try{t?localStorage.setItem(Ap,"1"):localStorage.removeItem(Ap)}catch{}}function dr(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function El(t){const a=dr(t.status),i=dr(a.screens),l=dr(t.capabilities),c=dr(t.latestLiveFrame),u=dr(t.activeLiveStream),h=[a.monitorCount,a.screenCount,i.count,l.monitorCount,l.screenCount,c.monitorCount,u.monitorCount,Array.isArray(i.displays)?i.displays.length:0,Array.isArray(a.displays)?a.displays.length:0,Array.isArray(a.monitors)?a.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 _l(t){const a=Number(t);return Number.isFinite(a)&&a>0?Math.floor(a):0}function rS(t){const a=dr(t.status),l=[dr(a.screens).displays,a.displays,a.monitors];for(const c of l)if(!(!Array.isArray(c)||c.length===0))return c.map(u=>dr(u));return[]}function iS(t,a){const i=rS(t),l=i.find(g=>Number(g.index)===a)||i[a]||i[0]||{},c=_l(l.width),u=_l(l.height),m=[l.name,l.displayName,l.deviceName,l.id].find(g=>typeof g=="string"&&g.trim()),h=typeof m=="string"?m.trim():`Display ${a+1}`;return{index:a,name:h,width:c,height:u,primary:l.primary===!0||l.isPrimary===!0}}function vR(t){const a=El(t);return Array.from({length:a},(i,l)=>iS(t,l))}function yR(t){const a=rS(t);if(a.length===0)return"";const i=a.map((l,c)=>{const u=Number(l.index),m=[l.name,l.displayName,l.deviceName,l.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 m=="string"?m.trim().toLowerCase():"",h(l.left),h(l.top),h(l.width),h(l.height),l.primary===!0||l.isPrimary===!0]}).sort((l,c)=>l[0]-c[0]);return JSON.stringify(i)}function bR(t){const a=[t.name||`Display ${t.index+1}`];return t.width>0&&t.height>0&&a.push(`${t.width}x${t.height}`),t.primary&&a.push("Primary"),a.join(" - ")}function lS(t,a){const i=iS(t,a);if(i.width>0&&i.height>0)return{width:i.width,height:i.height};const l=dr(t.status),c=_l(l.screenWidth||l.width),u=_l(l.screenHeight||l.height);return c>0&&u>0?{width:c,height:u}:null}function oS(t){if(!t)return null;const a=_l(t.sourceWidth)||_l(t.width),i=_l(t.sourceHeight)||_l(t.height);return a>0&&i>0?{width:a,height:i}:null}function xR(t,a,i){const u=((typeof a?.monitorIndex=="number"?Hu(a.monitorIndex,Math.max(1,a.monitorCount||1)):i)===i?oS(a):null)||lS(t,i);return u?Math.max(.25,Math.min(4,u.width/u.height)):16/9}const jf=16/9;function Hu(t,a){const i=Math.max(1,Math.min(64,Math.floor(Number(a)||1))),l=Math.floor(Number(t));return Number.isFinite(l)?Math.max(0,Math.min(i-1,l)):0}function Hs(t,a){return xk(a,El(t),t.platform)}function wR(){try{const t=localStorage.getItem(eS);if(!t)return{selections:{},topologyFingerprints:{}};const a=JSON.parse(t),i=a&&typeof a=="object"&&!Array.isArray(a)?a.selections:void 0;if(Number(a?.version)!==tS||!i||typeof i!="object"||Array.isArray(i))return{selections:{},topologyFingerprints:{}};const l={},c={};for(const[u,m]of Object.entries(i)){const h=u.trim(),g=dr(m),y=g.monitorIndex,x=Math.floor(Number(y));if(!h||!Number.isFinite(x))continue;l[h]=Math.max(0,Math.min(63,x));const b=typeof g.topologyFingerprint=="string"?g.topologyFingerprint.trim():"";b&&(c[h]=b)}return{selections:l,topologyFingerprints:c}}catch{return{selections:{},topologyFingerprints:{}}}}function SR(t,a){try{const i=Object.fromEntries(Object.entries(t).map(([l,c])=>[l,{monitorIndex:c,topologyFingerprint:a[l]||""}]));localStorage.setItem(eS,JSON.stringify({version:tS,selections:i}))}catch{}}function CR(){return{...tR}}function kR(t){try{localStorage.setItem(OT,JSON.stringify({...t,version:HT}))}catch{}}function jR(){return{...nR}}function AR(t){try{localStorage.setItem(FT,JSON.stringify({...t,version:PT}))}catch{}}function Kh(t,a){return t.length!==a.length?!1:t.every((i,l)=>i===a[l])}function Yh(t){return[...new Set(t.filter(Boolean))].sort()}function MR(t){return Na.fallbackVisibleCounts[t]||Na.fallbackVisibleCounts.large}function NR(t,a,i){if(t.frameMode==="mode4-h264-atlas")return t.atlasTileSizeMode==="auto"?a==="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 l=ix[a]||ix.large;return{maxWidth:Math.min(t.maxWidth,l.maxWidth),maxHeight:Math.min(t.maxHeight,l.maxHeight)}}function TR(t,a=Na.minFps){const i=[...sS].sort((c,u)=>c-u),l=Math.max(a,Math.floor(t/2));return[...i].reverse().find(c=>c<t&&c>=a)||l}function RR(t,a){return[...sS].sort((l,c)=>l-c).find(l=>l>t&&l<=a)||a}function Fu(t){if(!Number.isFinite(t)||t<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let i=t,l=0;for(;i>=1024&&l<a.length-1;)i/=1024,l+=1;const c=l===0||i>=100?0:1;return`${i.toFixed(c)} ${a[l]}`}function ux(t){if(!Number.isFinite(t)||!t||t<=0)return"0GB";const a=1024**4,i=1024**3;return t>=a?`${Math.max(1,Math.round(t/a))}TB`:`${Math.max(1,Math.round(t/i))}GB`}function Qh(t,a){if(!Number.isFinite(t)||!t||t<=0)return"not reported";const i=Math.max(0,t-Math.max(0,Number(a||0)));return`${ux(i)} / ${ux(t)}`}function ER(t){const a=new Uint8Array(t),i=32768;let l="";for(let c=0;c<a.length;c+=i){const u=a.subarray(c,c+i);l+=String.fromCharCode(...u)}return btoa(l)}function dx(t){return Array.from(t).filter(a=>a.size>=0).map(a=>{const i=a.webkitRelativePath||a.name;return{file:a,relativePath:i,fingerprint:`${a.size}:${a.lastModified}`}})}function DR(t){return t===1?"middle":t===2?"right":"left"}function fx(t,...a){for(const i of a){const l=t?.[i];if(typeof l=="string"&&l.trim())return l.trim()}return""}function mx(t){const a=Number(t);return Number.isInteger(a)&&a>=1&&a<=IT?a:0}const LR={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function _R(t,a,i){if(t==="online")return"Online";if(t==="busy")return"Busy";if(t==="stale")return"Stale";if(t==="offline")return"Offline";if(i==="failed")return"Task failed";const l=t==="critical"?"critical":"warn",c=a.find(m=>m.state===l)||a.find(m=>m.state==="critical"||m.state==="warn");if(!c)return t==="critical"?"Issue":"Check";const u=LR[c.id]||c.label;return c.value&&c.value!=="-"?`${u} ${c.value}`:u}function nm(t,a){const i=a.split(".");let l=t;for(const c of i){if(l==null)return;if(Array.isArray(l)){const u=Number(c);l=Number.isInteger(u)?l[u]:void 0;continue}if(typeof l=="object"){l=l[c];continue}return}return l}function Cn(t,...a){for(const i of a){const l=nm(t,i),c=Number(l);if(Number.isFinite(c))return c}}function bs(t,...a){for(const i of a){const l=nm(t,i);if(typeof l=="string"&&l.trim())return l.trim();if(typeof l=="number"&&Number.isFinite(l))return String(l)}return""}function IR(t,...a){for(const i of a){const l=nm(t,i);if(typeof l=="boolean")return l;if(/^(1|true|yes|on|online|running|ready)$/i.test(String(l||"").trim()))return!0;if(/^(0|false|no|off|offline|stopped|missing)$/i.test(String(l||"").trim()))return!1}}function Ri(t){const a=Number(t);if(Number.isFinite(a))return Math.max(0,Math.min(1,a>1?a/100:a))}function Xh(t,a){if(!(typeof t!="number"||typeof a!="number"||!Number.isFinite(t)||!Number.isFinite(a)||t<=0))return Ri((t-Math.max(0,a))/t)}function wc(t){return t===void 0?"-":`${Math.round(t*100)}%`}function Zh(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 yo(t,a=.92,i=.78){return t===void 0?"unknown":t>=a?"critical":t>=i?"warn":"good"}function zR(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 Af(t,a,i){const l=nm(t,`tools.${a}`),c=bs(t,`tools.${a}.status`,`tooling.${a}.status`,`${a}.status`).toLowerCase(),u=IR(t,`tools.${a}.running`,`tooling.${a}.running`,`${a}.running`),m=bs(t,`tools.${a}.version`,`tooling.${a}.version`,`${a}.version`),h=bs(t,`tools.${a}.port`,`tooling.${a}.port`,`${a}.port`);let g="unknown";return c==="busy"?g="busy":["online","running","ready","active"].includes(c)||u===!0?g="online":(["offline","stopped","missing","not-found"].includes(c)||u===!1||l===!1)&&(g="offline"),{id:a,label:i,status:g,detail:g==="offline"?"offline":m||(h?`:${h}`:g==="unknown"?"not reported":g)}}function cS(t){const a=t.status||{},i=Cn(a,"cpu.cores","cpuCores","processorCount"),l=Cn(a,"loadavg.0","cpu.load1"),c=Ri(Cn(a,"cpu.usedRatio","cpu.usageRatio","cpu.ratio","cpu.usedPct","cpu.usagePct","cpu.percent")??(i&&l!==void 0?l/Math.max(1,i):void 0)),u=Cn(a,"memory.totalBytes","totalMem"),m=Cn(a,"memory.freeBytes","freeMem"),h=Ri(Cn(a,"memory.usedRatio","memory.usedPct","usedMemRatio"))??Xh(u,m),g=Cn(a,"disk.totalBytes","rootDisk.totalBytes","storage.totalBytes"),y=Cn(a,"disk.freeBytes","rootDisk.freeBytes","storage.freeBytes"),x=Ri(Cn(a,"disk.usedRatio","disk.usedPct","rootDisk.usedRatio","storage.usedRatio"))??Xh(g,y),b=Cn(a,"thermal.cpuC","temperatureC","cpu.temperatureC","gpu.temperatureC"),w=Ri(Cn(a,"gpu.usedRatio","gpu.usageRatio","gpu.usedPct","gpu.usagePct","gpu.percent","accelerators.gpu.usageRatio")),j=bs(a,"gpu.name","gpu.model","accelerators.gpu.name"),A=Cn(a,"gpu.memory.totalBytes","gpu.totalMemoryBytes","gpu.vramTotalBytes"),k=Cn(a,"gpu.memory.freeBytes","gpu.freeMemoryBytes","gpu.vramFreeBytes"),T=Ri(Cn(a,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??Xh(A,k),M=Cn(a,"gpu.temperatureC","thermal.gpuC"),N=Ri(Cn(a,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),L=bs(a,"npu.name","npu.model","accelerators.npu.name"),z=Cn(a,"npu.tops","npu.topsInt8","accelerators.npu.tops"),H=Cn(a,"network.rxMbps","network.receiveMbps","network.downMbps"),G=Cn(a,"network.txMbps","network.transmitMbps","network.upMbps"),_=Cn(a,"network.latencyMs","network.rttMs"),Y=Ri(Cn(a,"network.usedRatio","network.usageRatio","network.saturationRatio")),q=bs(a,"network.link","network.interface","network.name"),U=Math.max(b??Number.NEGATIVE_INFINITY,M??Number.NEGATIVE_INFINITY),K=Number.isFinite(U)?U:void 0,O=K===void 0?void 0:Ri((K-35)/60),ve=b!==void 0&&M!==void 0?`CPU ${Math.round(b)}° · GPU ${Math.round(M)}°`:b!==void 0?`CPU ${Math.round(b)}°`:M!==void 0?`GPU ${Math.round(M)}°`:"-",me=bs(a,"workload.role","role","lane")||(Vu(t,"aiAssist")?"Agent worker":Vu(t,"taskDispatch")?"Task worker":"Local machine"),Z=bs(t.latestTask,"status")||bs(a,"workload.status")||"idle",I=bs(t.latestTask,"title","instructionPreview")||bs(a,"workload.title"),se=bs(t.latestTask,"resultSummary","error","instructionPreview")||bs(a,"workload.summary"),W=[Af(a,"ollama","Ollama"),Af(a,"lmStudio","LM Studio"),Af(a,"comfyui","ComfyUI"),Af(a,"stableDiffusion","Stable Diffusion")],F=W.some(de=>de.status!=="unknown"),oe=Date.parse(t.lastSeenAt||t.connectedAt||""),le=Number.isFinite(oe)?Date.now()-oe:0;let Q="online";t.connected?le>5*6e4?Q="stale":(b??0)>=86||(M??0)>=88||(c??0)>=.94||(w??0)>=.96||(T??0)>=.96||(N??0)>=.96||(h??0)>=.94||(x??0)>=.94||(_??0)>=200||Z==="failed"?Q="critical":(b??0)>=78||(M??0)>=80||(c??0)>=.82||(w??0)>=.86||(T??0)>=.88||(N??0)>=.86||(h??0)>=.82||(x??0)>=.86||(_??0)>=80?Q="warn":(["queued","running","targeted"].includes(Z)||W.some(de=>de.status==="busy"))&&(Q="busy"):Q="offline";const be=W.filter(de=>de.status==="online"||de.status==="busy").length,he=[{id:"cpu",label:"CPU",value:wc(c),detail:i?`${i} cores`:l!==void 0?`load ${l.toFixed(1)}`:"not reported",ratio:c,state:yo(c,.92,.78)},{id:"memory",label:"RAM",value:wc(h),detail:Qh(u,m),ratio:h,state:yo(h,.92,.78)},{id:"disk",label:"DISK",value:wc(x),detail:Qh(g,y),ratio:x,state:yo(x,.92,.82)},{id:"gpu",label:"GPU",value:wc(w),detail:j||(A&&k!==void 0?`${Fu(k)} VRAM free`:M!==void 0?`${Math.round(M)}C`:"not reported"),ratio:w,state:M!==void 0&&M>=88?"critical":M!==void 0&&M>=80?"warn":yo(w,.96,.86)},{id:"vram",label:"VRAM",value:wc(T),detail:Qh(A,k),ratio:T,state:yo(T,.96,.88)},{id:"npu",label:"NPU",value:N!==void 0?wc(N):z!==void 0?`${Math.round(z)} TOPS`:"-",detail:L||(z!==void 0?"neural engine":"not reported"),ratio:N,state:yo(N,.96,.86)},{id:"temp",label:"TEMP",value:ve,detail:be>0?`${be} local tools`:`uptime ${zR(Cn(a,"uptimeSec"))}`,ratio:O,state:K===void 0?"unknown":K>=86?"critical":K>=78?"warn":"good"},{id:"network",label:"NET",value:Zh(H)||(_!==void 0?`${Math.round(_)}ms`:q||"-"),detail:Zh(G)?`${Zh(G)} up`:q||"not reported",ratio:Y,state:_!==void 0&&_>=200?"critical":_!==void 0&&_>=80?"warn":yo(Y,.9,.75)}];return{state:Q,label:_R(Q,he,Z),role:me,taskLabel:I||(Z==="idle"?"idle":Z),taskStatus:Z,taskSummary:se,tools:F?W:W.map(de=>({...de,detail:"not reported"})),metrics:he}}const OR=[{id:"list",label:"List"},{id:"medium",label:"Small"},{id:"large",label:"Large"}],HR=[{id:"sync-server",label:"Hub",icon:Hr,accent:"blue",tooltip:"hub"},{id:"wall",label:"Wall",icon:V0,accent:"blue",tooltip:"wall"},{id:"control",label:"Control",icon:ap,accent:"red",tooltip:"control"},{id:"share-files",label:"Share Files",icon:Mf,accent:"green",tooltip:"share-files"},{id:"agents",label:"Agents",icon:sp,accent:"violet",tooltip:"agents"}],FR=[{id:"doc",label:"Doc",icon:If,accent:"amber"},{id:"support",label:"Support",icon:Pu,accent:"violet"},{id:"pricing",label:"Pricing",icon:$u,accent:"green"}];function PR(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 vn(t){return PR(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 bo(t){return t.map(a=>vn(a))}function Aa(t){return{languageName:t.languageName,languageLabel:t.languageLabel,eyebrow:t.eyebrow,title:vn(t.title),intro:vn(t.intro),sections:[{title:vn(t.managerTitle),body:vn(t.managerBody),points:bo(t.managerPoints)},{title:vn(t.clientTitle),body:vn(t.clientBody),points:bo(t.clientPoints)},{title:vn(t.syncTitle),body:vn(t.syncBody),points:bo(t.syncPoints)},...t.agentTitle&&t.agentBody&&t.agentPoints?[{title:vn(t.agentTitle),body:vn(t.agentBody),points:bo(t.agentPoints)}]:[],{title:vn(t.platformTitle),body:vn(t.platformBody),points:bo(t.platformPoints)}],sync:{title:vn(t.syncTitle),body:vn(t.syncBody),points:bo(t.syncPoints)},firewall:{title:vn(t.firewallTitle),body:vn(t.firewallBody),points:bo(t.firewallPoints)},commands:{title:vn(t.commandsTitle),body:vn(t.commandsBody),manager:vn(t.managerCommandLabel),primary:vn(t.clientCommandLabel),slot:vn(t.slotCommandLabel),manual:vn(t.manualCommandLabel)}}}const Ac={ko:Aa({languageName:"한국어",languageLabel:"문서 언어",eyebrow:"LiveDesk Manual",title:"한 줄로 여는 로컬 Screen Wall",intro:"LiveDesk는 매니저 PC 한 대에서 여러 작업 PC, AI 박스, 맥미니, 개발 장비를 한 화면에 모니터링하고 필요한 제어를 실행하는 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에는 현재 72개의 읽기·운영 작업 템플릿이 있으며, 검색과 권한·플랫폼·capability 조건으로 실행 가능 항목을 안내합니다.","Ask, Safe Auto, Full Access, Custom 권한 모드를 선택할 수 있습니다. 위험한 변경 작업은 승인 카드와 장비 capability 검사를 거칩니다.","All connected 또는 Selected로 대상 장비를 제한하고, 결과는 장비별 상태 칩과 실제 RAM·디스크·GPU·프로세스 요약으로 확인합니다.","Agent 실행은 Hub의 격리된 runtime과 LiveDesk MCP 도구를 통해서만 장비에 전달되며, 모든 작업은 timeout·취소·tool limit·감사 로그 경계를 가집니다."],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:Aa({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 many Clients, AI boxes, Mac minis, and dev 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 currently contains 72 read-only and operational templates with search plus permission, platform, and capability availability 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.","Runs stay inside the Hub-isolated runtime and LiveDesk MCP tools, with timeout, cancellation, tool-call limits, and audit-log boundaries."],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:Aa({languageName:"日本語",languageLabel:"ドキュメント言語",eyebrow:"LiveDesk Manual",title:"1行でローカル Screen Wall を開く",intro:"LiveDesk は、複数の作業 PC、AI マシン、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":Aa({languageName:"简体中文",languageLabel:"文档语言",eyebrow:"LiveDesk Manual",title:"用一条命令打开本地 Screen Wall",intro:"LiveDesk 是 npm-first 的远程工作台,用一台 manager PC 监控多台工作站、AI 主机、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":Aa({languageName:"繁體中文",languageLabel:"文件語言",eyebrow:"LiveDesk Manual",title:"用一行指令開啟本機 Screen Wall",intro:"LiveDesk 是 npm-first 的遠端工作台,用一台 manager PC 監看多台工作站、AI 主機、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:Aa({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 muchas estaciones, cajas de IA, 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:Aa({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, machines IA, 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:Aa({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, AI-Boxen, 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":Aa({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, caixas de IA, 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:Aa({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, box AI, 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:Aa({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, AI box, 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:Aa({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, máy AI, 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:Aa({languageName:"ไทย",languageLabel:"ภาษาของเอกสาร",eyebrow:"LiveDesk Manual",title:"เปิด Screen Wall ภายในด้วยคำสั่งเดียว",intro:"LiveDesk คือ deck แบบ npm-first สำหรับดู Client, กล่อง AI, 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:Aa({languageName:"हिन्दी",languageLabel:"दस्तावेज़ भाषा",eyebrow:"LiveDesk Manual",title:"एक कमांड से local Screen Wall खोलें",intro:"LiveDesk एक npm-first remote work deck है जिससे एक manager PC से कई Client, AI box, 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:Aa({languageName:"العربية",languageLabel:"لغة المستند",eyebrow:"LiveDesk Manual",title:"افتح Screen Wall محلي بأمر واحد",intro:"LiveDesk هو deck بنمط npm-first لمراقبة عدة Clients وأجهزة AI و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:Aa({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, AI box, 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ı"})},$R=Object.entries(Ac).map(([t,a])=>({id:t,label:a.languageName}));function BR(){if(typeof navigator>"u")return"en";const t=navigator.languages?.length?navigator.languages:[navigator.language];for(const a of t){const i=a.toLowerCase();if(Ac[a])return a;if(i.startsWith("zh-tw")||i.startsWith("zh-hk"))return"zh-TW";if(i.startsWith("pt"))return"pt-BR";const l=i.split("-")[0];if(Ac[l])return l}return"en"}function hx({index:t}){const a=t+1;return r.jsx("article",{className:"device-tile placeholder-tile","aria-label":`Empty slot ${a}`,children:r.jsxs("div",{className:"tile-screen","aria-hidden":"true",children:[r.jsx("span",{className:"slot-grid","aria-hidden":"true"}),r.jsxs("span",{className:"empty-screen",children:[r.jsx(Ea,{size:24}),r.jsxs("strong",{children:["Slot ",String(a).padStart(3,"0")]})]})]})})}const UR=["cpu","gpu","memory","vram","network","disk","temp"];function qR({device:t,slotNumber:a,selected:i,updateIndicator:l,onSelect:c,onOpenControl:u}){const m=cS(t),h=new Map(m.metrics.map(y=>[y.id,y])),g=l?.label||m.label;return r.jsxs("div",{className:`wall-device-list-row state-${m.state} ${i?"selected":""}`,role:"row","aria-selected":i,tabIndex:0,onClick:c,onDoubleClick:y=>{y.preventDefault(),u()},onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),c())},children:[r.jsxs("span",{className:"wall-device-name",role:"gridcell",children:[r.jsx("span",{className:"wall-device-icon","aria-hidden":"true",children:r.jsx(Ea,{size:17})}),r.jsxs("span",{children:[r.jsx("strong",{children:va(t)}),r.jsxs("small",{children:["Slot ",String(a).padStart(3,"0"),t.platform?` · ${t.platform}`:"",t.arch?` · ${t.arch}`:""]})]}),i&&r.jsx(Or,{size:16,strokeWidth:3,"aria-label":"Selected"})]}),r.jsxs("span",{className:`wall-device-list-status state-${m.state} ${l?`update-${l.state}`:""}`,role:"gridcell",title:l?.error||g,children:[r.jsx("i",{"aria-hidden":"true"}),r.jsx("strong",{children:g})]}),UR.map(y=>{const x=h.get(y);return r.jsxs("span",{className:`wall-device-list-metric state-${x?.state||"unknown"}`,role:"gridcell",title:x?`${x.label}: ${x.value} · ${x.detail}`:"Not reported",children:[r.jsx("strong",{children:x?.value||"-"}),r.jsx("small",{children:x?.detail||"not reported"}),x?.ratio!==void 0&&r.jsx("i",{style:{width:`${Math.round(x.ratio*100)}%`},"aria-hidden":"true"})]},y)})]})}function GR(t){if(!t)return!1;const a=String(t.platform||"").trim().toLowerCase();return Ei(a)&&t.capabilities?.screenRecordingPermission===!1}function Ei(t){const a=String(t||"").trim().toLowerCase();return a==="macos"||a==="darwin"||a==="mac"||a==="macosx"}function VR(t){const a=String(t||"").trim().toLowerCase();return a==="linux"||a.startsWith("linux ")}function Jh({device:t,frame:a,selected:i,controlEnabled:l,showStatus:c,monitorIndex:u,monitorCount:m,onSelect:h,onFocusDevice:g,onOpenControl:y,onCycleMonitor:x,onCanvasReady:b,sendInput:w,remoteModifierState:j,updateIndicator:A,presentationReady:k,showPresentationSpinner:T=!1,remoteDiagnostics:M,diagnosticsMode:N="remote"}){const L=d.useRef(null),z=d.useRef(null),H=d.useRef(0),G=d.useRef(null),_=cS(t),Y=["cpu","gpu","memory","vram"].map(ee=>_.metrics.find(Ce=>Ce.id===ee)).filter(ee=>!!ee),q=Fp(u),U=m>1,K=k??!!a,O=GR(t)&&!K,ve=T&&t.connected&&!K&&!O,me=xR(t,a,q),Z=me>=jf?100:me/jf*100,I=me>=jf?jf/me*100:100,se={"--screen-aspect":me.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,Z)).toFixed(3)}%`,"--screen-content-height":`${Math.max(1,Math.min(100,I)).toFixed(3)}%`},W=d.useCallback(ee=>{L.current=ee,b(t.deviceId,ee)},[t.deviceId,b]),F=ee=>{const Ce=ee.currentTarget.getBoundingClientRect();return uk(ee.clientX,ee.clientY,Ce)},oe=ee=>hk(ee,j),le=d.useCallback(()=>{G.current!==null&&(window.cancelAnimationFrame(G.current),G.current=null)},[]),Q=d.useCallback(()=>{const ee=z.current;if(!ee)return;z.current=null;const Ce=Number(ee.input.normalizedX),Re=Number(ee.input.normalizedY);if(!Number.isFinite(Ce)||!Number.isFinite(Re))return;w(t.deviceId,{...ee.input,normalizedX:Ce,normalizedY:Re})&&(H.current=performance.now())},[t.deviceId,w]),be=d.useCallback(()=>{G.current===null&&(G.current=window.requestAnimationFrame(()=>{G.current=null,Q()}))},[Q]);d.useEffect(()=>()=>{le(),z.current=null},[le]);const he=(ee,Ce)=>{if(!l)return;const Re={type:Ce,monitorIndex:q,...F(ee),button:DR(ee.button),...oe(ee)};if(Ce==="pointermove"){const He=performance.now();z.current={input:Re},He-H.current>=BT&&(le(),Q()),be();return}z.current&&(le(),Q()),w(t.deviceId,Re)},de=d.useCallback(ee=>{const Ce=document.activeElement;Ce instanceof HTMLElement&&ee.contains(Ce)&&Ce.classList.contains("monitor-cycle-button")&&Ce.blur()},[]);return r.jsx("article",{className:`device-tile ${i?"selected":""} ${t.connected?"online":"offline"}`,"data-live-device-id":t.deviceId,style:se,children:r.jsxs("div",{className:`tile-screen ${K?"has-frame":"is-empty"}`,role:"button",tabIndex:l?-1:0,"aria-pressed":i,onClick:ee=>{ee.target instanceof Element&&ee.target.closest(".monitor-cycle")||l||h()},onKeyDown:ee=>{ee.target instanceof Element&&ee.target.closest(".monitor-cycle")||l||(ee.key==="Enter"||ee.key===" ")&&(ee.preventDefault(),h())},onDoubleClick:ee=>{ee.target instanceof Element&&ee.target.closest(".monitor-cycle")||(ee.preventDefault(),y())},onPointerLeave:ee=>de(ee.currentTarget),children:[r.jsx("span",{className:`screen-content ${K?"has-frame":"is-empty"}`,children:r.jsx("canvas",{ref:W,className:`remote-canvas ${K?"has-frame":"is-empty"}`,"data-monitor-index":q,tabIndex:l?0:-1,onPointerDown:ee=>{l&&(ee.preventDefault(),ee.stopPropagation(),g(),ee.currentTarget.focus(),ee.currentTarget.setPointerCapture(ee.pointerId),he(ee,"pointerdown"))},onPointerMove:ee=>{l&&ee.preventDefault(),he(ee,"pointermove")},onPointerLeave:ee=>{l&&(he(ee,"pointermove"),le(),Q())},onPointerUp:ee=>{l&&(ee.preventDefault(),ee.stopPropagation(),he(ee,"pointerup"),ee.currentTarget.hasPointerCapture(ee.pointerId)&&ee.currentTarget.releasePointerCapture(ee.pointerId))},onPointerCancel:ee=>{ee.currentTarget.hasPointerCapture(ee.pointerId)&&ee.currentTarget.releasePointerCapture(ee.pointerId)},onWheel:ee=>{l&&(ee.preventDefault(),w(t.deviceId,{type:"wheel",monitorIndex:q,...F(ee),deltaX:ee.deltaX,deltaY:ee.deltaY,...oe(ee)}))},onContextMenu:ee=>l&&ee.preventDefault()},`${t.deviceId}:monitor:${q}`)}),!K&&r.jsx("span",{className:"empty-screen",children:r.jsx(Ea,{size:26})}),r.jsx("span",{className:"wall-device-title",title:va(t),children:va(t)}),ve&&r.jsxs("span",{className:"wall-presentation-loading",role:"status","aria-live":"polite",children:[r.jsx("span",{className:"wall-presentation-spinner","aria-hidden":"true"}),r.jsx("strong",{children:"Preparing video"})]}),O&&r.jsxs("span",{className:"wall-presentation-loading permission-required",role:"status","aria-live":"polite",children:[r.jsx(Kn,{size:24,"aria-hidden":"true"}),r.jsx("strong",{children:"Screen Recording permission required"}),r.jsx("small",{children:"Allow the terminal app on this Mac, then restart LiveDesk."})]}),A&&r.jsxs("span",{className:`wall-update-status state-${A.state}`,role:"status","aria-live":"polite",title:A.error||A.label,children:[A.state==="updated"?r.jsx(ea,{size:20,"aria-hidden":"true"}):A.state==="failed"?r.jsx(Ra,{size:22,"aria-hidden":"true"}):A.state==="offline"?r.jsx(Vf,{size:22,"aria-hidden":"true"}):r.jsx("span",{className:"wall-update-spinner","aria-hidden":"true"}),r.jsx("strong",{children:A.label}),A.error?r.jsx("small",{children:A.error}):null]}),c&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:`tile-health-pill state-${_.state}`,children:_.label}),r.jsx("span",{className:"tile-metrics","aria-label":`${va(t)} status`,children:Y.map(ee=>r.jsxs("span",{className:`tile-metric state-${ee.state}`,children:[r.jsx("b",{children:ee.label}),r.jsx("em",{children:ee.value}),ee.ratio!==void 0&&r.jsx("i",{style:{width:`${Math.round(ee.ratio*100)}%`}})]},ee.id))})]}),M&&r.jsx(uT,{items:M,mode:N}),U&&r.jsxs("span",{className:"monitor-cycle","aria-label":`${va(t)} display ${q+1} of ${m}`,onPointerDown:ee=>ee.stopPropagation(),onClick:ee=>ee.stopPropagation(),onDoubleClick:ee=>ee.stopPropagation(),children:[r.jsx("button",{className:"monitor-cycle-button previous",onClick:ee=>{ee.preventDefault(),ee.stopPropagation(),x(-1),ee.currentTarget.blur()},title:"Previous display",type:"button",children:r.jsx(Ax,{size:18})}),r.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",q+1,"/",m]}),r.jsx("button",{className:"monitor-cycle-button next",onClick:ee=>{ee.preventDefault(),ee.stopPropagation(),x(1),ee.currentTarget.blur()},title:"Next display",type:"button",children:r.jsx(_p,{size:18})})]}),i&&r.jsx("span",{className:"device-selection-check","aria-hidden":"true",children:r.jsx(Or,{size:23,strokeWidth:3.5})})]})})}function WR({visible:t}){return d.useEffect(()=>{if(!t||!Gh)return;if(!document.getElementById(Qb)){const i=document.createElement("script");i.id=Qb,i.async=!0,i.crossOrigin="anonymous",i.src=`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${encodeURIComponent(Mp)}`,document.head.appendChild(i)}const a=window.setTimeout(()=>{try{window.adsbygoogle=window.adsbygoogle||[],window.adsbygoogle.push({})}catch{}},120);return()=>window.clearTimeout(a)},[t]),t?r.jsxs("aside",{className:`free-ad-banner ${Gh?"adsense-ready":"house-ad"}`,"aria-label":"Advertisement",children:[r.jsx("span",{className:"ad-label",children:"Advertisement"}),Gh?r.jsx("ins",{className:"adsbygoogle livedesk-ad-unit",style:{display:"block"},"data-ad-client":Mp,"data-ad-slot":nS,"data-ad-format":"auto","data-full-width-responsive":"true"}):r.jsxs("div",{className:"house-ad-copy",children:[r.jsx("strong",{children:"Sponsored placement"}),r.jsx("span",{children:"Local AI gear, mini PCs, GPUs, NAS, and developer tools."})]})]}):null}function KR(){const{session:t,loading:a}=$1(),{target:i,error:l,refresh:c}=U1(t),u=d.useMemo(()=>{if(!i?.active)return null;const v=i.expires_at?Date.parse(i.expires_at):Number.POSITIVE_INFINITY;return Number.isFinite(v)&&v<=Date.now()?null:i},[i]),m=d.useMemo(()=>Iy(u),[u]),h=d.useMemo(()=>m.length>0?[...new Set([...m,En])]:[En],[m]),[g,y]=d.useState(gR),x=d.useMemo(()=>h.some(v=>!!Uu(v)),[h]),b=!x||g,{status:w,devices:j,error:A,refresh:k,hubBaseUrl:T}=B1(h,b),{entitlement:M,licensed:N,loading:L,error:z,refresh:H}=q1(t),[G,_]=d.useState([]),[Y,q]=d.useState(""),[U,K]=d.useState(""),[O,ve]=d.useState(""),[me,Z]=d.useState(""),[I,se]=d.useState(""),[W,F]=d.useState("idle"),[oe,le]=d.useState(!1),[Q,be]=d.useState(null),he=d.useRef(null),[de,ee]=d.useState(""),Ce=d.useRef("");Ce.current=me;const[Re,He]=d.useState(!1),[te,Ue]=d.useState([]),mt=d.useRef(null),[ne,xe]=d.useState(!1),Oe=d.useRef(""),$e=d.useRef(new Map),ze=d.useRef(0),[Qe,qe]=d.useState({}),Ye=d.useRef({}),ot=d.useRef(new Map),B=d.useRef(new Map),[ye,je]=d.useState({}),Pe=d.useMemo(()=>new Set(Object.keys(Qe)),[Qe]),dt=d.useCallback((v,C)=>{if(!v)return;const E={...Ye.current};C?E[v]=C:delete E[v],Ye.current=E,qe(E)},[]),nt=d.useCallback((v,C)=>{v&&je(E=>{if(!!E[v]===C)return E;const P={...E};return C?P[v]=!0:delete P[v],P})},[]),bt=d.useCallback((v,C)=>{v&&B.current.set(v,{paused:C,expiresAt:Date.now()+ZT})},[]),[it,Ct]=d.useState(""),[pe,De]=d.useState(""),[Fe,Ae]=d.useState(!1),ct=d.useRef(null),ht=d.useRef(null);d.useEffect(()=>{it==="auth"&&t?.access_token&&Ct("")},[it,t?.access_token]);const[Le,Dn]=d.useState(""),[yn,et]=d.useState(null),xt=d.useRef(null),kn=d.useRef(0),Pn=d.useCallback((v,C,E)=>{const P=String(v||"").trim();if(Dn(P),xt.current!==null&&(window.clearTimeout(xt.current),xt.current=null),!P){et(null);return}const D=++kn.current;if(et({id:D,message:P,tone:C}),!E)return;const J=window.setTimeout(()=>{et(ie=>ie?.id===D?null:ie),xt.current===J&&(xt.current=null)},5e3);xt.current=J},[]),_e=d.useCallback((v,C="info")=>{Pn(v,C,!0)},[Pn]),tn=d.useCallback(v=>{Pn(v,"progress",!1)},[Pn]);d.useEffect(()=>()=>{xt.current!==null&&window.clearTimeout(xt.current)},[]);const[on,Da]=d.useState(()=>typeof window<"u"&&window.location.pathname.startsWith("/support")?"support":"wall");d.useEffect(()=>{const v=()=>{Da(window.location.pathname.startsWith("/support")?"support":C=>C==="support"?"wall":C)};return window.addEventListener("popstate",v),()=>window.removeEventListener("popstate",v)},[]);const[nn,$s]=d.useState("large"),[Yn,Bs]=d.useState(!1),[$,Xe]=d.useState(!1),[ft,mn]=d.useState(!1),[Ba,Ii]=d.useState(!1),[Ss,re]=d.useState(Date.now),Ee=d.useRef(null);d.useEffect(()=>()=>{Ee.current!==null&&window.clearTimeout(Ee.current)},[]);const[Ge,vt]=d.useState(BR),[Bt,Vt]=d.useState(!1),[at,Rt]=d.useState(!1),[ra,$n]=d.useState(!1),[bn,en]=d.useState(pR),[Ke]=d.useState(CR),[At]=d.useState(jR),[Us]=d.useState(wR),[Ht,jn]=d.useState(Us.selections),Ln=d.useRef({...Us.topologyFingerprints}),$r=d.useRef({}),Br=d.useRef({...Us.selections}),[Dt,Cs]=d.useState(null),[zi,Ur]=d.useState([]),[cn,ia]=d.useState(Ke.fps),[Oi,am]=d.useState(""),[Dc,nd]=d.useState(0),[No,ad]=d.useState(0),[Ua,Lc]=d.useState(0),[_c,qr]=d.useState(()=>new Set),xn=d.useRef(new Map),qs=d.useRef(new Map),Gs=d.useRef(new Map),ls=d.useRef(new Map),ya=d.useRef(new Map),Hi=d.useRef(new Map),Vs=d.useRef(new Set),Fi=d.useRef(new Map),Fl=d.useRef(""),os=d.useRef(null),Pl=d.useRef(Promise.resolve()),qa=d.useRef(0),Ws=d.useRef(null),ks=d.useRef(new Map),Ks=d.useRef(null),mr=d.useRef(0),$l=d.useRef(new Map),[Pi,Ic]=d.useState({}),hr=d.useRef(new Map),[Ga,To]=d.useState({}),[$i,wn]=d.useState(!1),Bl=d.useRef(null),La=d.useRef(null),Ul=d.useRef(!1),ba=d.useRef(0),Bn=d.useRef(""),zc=d.useRef(Promise.resolve()),la=d.useRef(""),wt=d.useRef(null),oa=d.useRef(""),cs=d.useRef(null),Bi=d.useRef(0),Gr=d.useRef(""),js=d.useRef(new Map),us=d.useRef(new Map),Vr=d.useRef(performance.now()),Wr=d.useRef(new Map),Kr=d.useRef(new Map),Yr=d.useRef(new Map),Ui=d.useRef(new Map),qi=d.useRef(new Map),ql=d.useRef(0),Ro=d.useRef(0),Eo=d.useRef(0),Do=d.useRef(0),Oc=d.useRef(0),Hc=d.useRef(new Map),Ys=d.useRef(new Map),Va=d.useCallback((v,C)=>{const E=rs(v,C),P=performance.now();js.current.delete(E),us.current.delete(E),Wr.current.delete(E),qi.current.delete(E),Ys.current.delete(E),hr.current.delete(E),$l.current.delete(E),To(D=>{if(!Object.prototype.hasOwnProperty.call(D,E))return D;const J={...D};return delete J[E],J}),Ic(D=>{if(!Object.prototype.hasOwnProperty.call(D,E))return D;const J={...D};return delete J[E],J}),v==="control"?(Kr.current.delete(E),Yr.current.set(E,P)):Ui.current.set(E,P)},[]),[Qr,pr]=d.useState(null),[Fc,Pc]=d.useState(!1),[ng,sm]=d.useState([]),[Xr,rm]=d.useState("all"),[Gi,$c]=d.useState([]),[ag,sg]=d.useState(!1),[rg,im]=d.useState(!0),sd=d.useRef(null),rd=d.useRef(null),Bc=d.useRef(null),Gl=d.useRef(null),lm=d.useRef(!1),Lo=d.useRef(!1),_o=d.useRef(!1),Vi=d.useRef(0),Qs=d.useRef(0),Vl=on==="settings",Zr=on==="pricing",id=on==="doc",ld=on==="support",Wl=on==="share-files",Io=on==="agents",Wi=!Vl&&!Zr&&!id&&!ld&&!Wl&&!Io,pt=on==="control",Xs=on==="wall",Ki=pt||Xs;d.useEffect(()=>{Wi||(Bs(!1),Xe(!1),mn(!1))},[Wi]);const Mt=Ke.frameMode==="mode4-h264-atlas",xa=I||At.frameMode,Yi=xa!=="mode3-h264-hw"?Math.min(30,At.fps):At.fps,Uc=j.find(v=>v.deviceId===U)?.platform,zo=VR(Uc)?{maxWidth:1280,maxHeight:720}:{maxWidth:3840,maxHeight:2160},Jr={maxWidth:Math.min(xa!=="mode3-h264-hw"?1920:3840,zo.maxWidth,At.maxWidth),maxHeight:Math.min(xa!=="mode3-h264-hw"?1080:2160,zo.maxHeight,At.maxHeight)};d.useEffect(()=>{if(w?.started){if(!t?.access_token){We("/api/remote/license",{method:"DELETE"},T).catch(()=>{});return}We("/api/remote/license/sync",{method:"POST",headers:{Authorization:`Bearer ${t.access_token}`}},T).catch(v=>{console.warn("[LiveDesk] Hub license sync failed",v)})}},[M?.updated_at,T,t?.access_token,w?.started]),d.useEffect(()=>{!t?.access_token||!w?.started||w.runtimeRole!=="hub"||!w.deviceId||(async()=>{try{const{data:v,error:C}=await St.rpc("register_livedesk_device",{p_device_id:w.deviceId,p_device_name:w.deviceName||w.deviceId,p_role:"hub",p_assigned_hub_id:null,p_platform:navigator.platform||navigator.userAgent,p_os_version:navigator.userAgent,p_app_version:w.managerVersion||w.managerPackage||""}),E=Array.isArray(v)?v[0]:v;(C||E?.ok===!1)&&console.warn("[LiveDesk] Hub device role registration failed",C||E?.reason||"unknown-error")}catch(v){console.warn("[LiveDesk] Hub device role registration failed",v)}})()},[t?.access_token,w?.deviceId,w?.deviceName,w?.managerPackage,w?.managerVersion,w?.runtimeRole,w?.started]),d.useEffect(()=>{!t?.access_token||!t.refresh_token||!w?.started||w.runtimeRole!=="hub"||_o.current||(_o.current=!0,We("/api/auth/session",{method:"POST",body:JSON.stringify({accessToken:t.access_token,refreshToken:t.refresh_token,expiresAt:t.expires_at,user:{id:t.user.id,email:t.user.email}})},T||En).then(v=>{v.hostTarget?.ok===!1&&console.warn("[LiveDesk] Hub host target publish is waiting for a valid Hub role:",v.hostTarget.error||"unknown-error"),k()}).catch(v=>{console.warn("[LiveDesk] Hub session sync failed:",v)}).finally(()=>{_o.current=!1}))},[T,k,t?.access_token,t?.expires_at,t?.refresh_token,t?.user?.email,t?.user?.id,w?.runtimeRole,w?.started]);const rt=d.useMemo(()=>j.filter(v=>v.connected),[j]);d.useEffect(()=>{const v={...Ye.current},C=Date.now();let E=!1;je(P=>{const D={...P};let J=!1;for(const ie of j){const Ne=String(ie.liveCapturePause?.token||"").trim(),Te=B.current.get(ie.deviceId);if(Te)if((Te.paused?!!Ne:!Ne)||Te.expiresAt<=C)B.current.delete(ie.deviceId);else continue;const Be=!!Ne&&(ie.liveCapturePause?.captureStopConfirmed!==!0||ie.liveCapturePause?.phase==="stop-unconfirmed");!!D[ie.deviceId]!==Be&&(J=!0,Be?D[ie.deviceId]=!0:delete D[ie.deviceId])}return J?D:P});for(const P of j){const D=String(P.liveCapturePause?.token||"").trim(),J=String(v[P.deviceId]||""),ie=B.current.get(P.deviceId);if(ie)if((ie.paused?!!D:!D)||ie.expiresAt<=C)B.current.delete(P.deviceId);else continue;D&&D!==J?(v[P.deviceId]=D,E=!0):!D&&J&&(delete v[P.deviceId],ot.current.delete(P.deviceId),E=!0)}E&&(Ye.current=v,qe(v))},[j]);const qc=Xr==="all"?rt.length:Gi.filter(v=>rt.some(C=>C.deviceId===v)).length,om=d.useMemo(()=>rt.reduce((v,C)=>Math.max(v,mx(C.slotNumber)),0),[rt]),Gc=Math.max(_T,rt.length,om),ei=d.useMemo(()=>{const v=Array(Gc).fill(null),C=[];for(const E of rt){const P=mx(E.slotNumber);P>0&&P<=Gc&&!v[P-1]?v[P-1]=E:C.push(E)}for(const E of C){const P=v.findIndex(D=>!D);P<0?v.push(E):v[P]=E}return v},[rt]),od=d.useMemo(()=>ei.flatMap((v,C)=>v?[{device:v,slotNumber:C+1}]:[]),[ei]),Vc=d.useMemo(()=>rt.map(v=>v.deviceId),[rt]),An=d.useMemo(()=>new Set(G),[G]),Un=d.useMemo(()=>rt.filter(v=>An.has(v.deviceId)),[rt,An]),ti=d.useMemo(()=>j.find(v=>v.deviceId===Y)||Un[0]||null,[j,Y,Un]),Qn=d.useMemo(()=>j.find(v=>v.deviceId===U)||null,[U,j]),_a=Qn?Hs(Qn,Ht[Qn.deviceId]):0,Ie=pt?Qn:ti,Oo=d.useMemo(()=>new Set(Gi),[Gi]),cm=d.useMemo(()=>Xr==="all"?rt.map(v=>v.deviceId):rt.filter(v=>Oo.has(v.deviceId)).map(v=>v.deviceId),[rt,Oo,Xr]),Qi=Ie?Vu(Ie,"control"):!1,Kl=Ei(Ie?.platform)&&(Ie?.capabilities?.controlPermission===!1||Ie?.capabilities?.accessibilityPermission===!1),Zs=Ie?Vu(Ie,"audio")||Vu(Ie,"remoteAudio"):!1,Wc=(Array.isArray(Ie?.capabilities?.agentTools)?Ie.capabilities.agentTools.map(String):[]).includes("system.power"),Wt=N?M?.plan==="pro"?"pro":"ltd":"free",ni=vo[Wt],Xi=ni.limit,ai=d.useMemo(()=>{if(!Number.isFinite(Xi))return new Set(rt.map(C=>C.deviceId));const v=Ie?[Ie,...rt.filter(C=>C.deviceId!==Ie.deviceId)]:rt;return new Set(v.slice(0,Xi).map(C=>C.deviceId))},[Xi,rt,Ie]),si=!Ie||ai.has(Ie.deviceId),ud=Wt==="free",Xt=si,ri=Wt==="ltd"?`Plus includes up to ${Ou} Clients. Upgrade to Pro for commercial use and larger walls.`:`Free includes up to ${zu} Clients. Upgrade to Plus for ${Ou} devices and no ads.`,um=Wt==="free",Js=Xt&&!!Ie&&Qi,dd=Xt&&!!Ie&&Zs,Zi=!!Ie&&Pe.has(Ie.deviceId),Ho=!!Ie&&ye[Ie.deviceId]===!0,Ji=d.useMemo(()=>ei.filter(v=>!!v?.connected).slice(0,MR(nn)).map(v=>v.deviceId),[ei,nn]),wa=d.useMemo(()=>!Xs||nn==="list"?[]:Mt?Vc:Ke.visibleOnlyLive?zi.length>0?zi:Ji:Vc,[Ji,Mt,zi,Ke.visibleOnlyLive,Vc,Xs,nn]),Sa=d.useMemo(()=>Yh(wa.filter(v=>ai.has(v))),[ai,wa]),Mn=d.useMemo(()=>Sa.filter(v=>v!==Oi&&!Pe.has(v)),[Pe,Sa,Oi]),er=d.useMemo(()=>new Map(rt.map(v=>[v.deviceId,v.platform])),[rt]),Wa=wk(Mt,Sa.length),qn=d.useMemo(()=>Mt?Mn.filter(v=>Lu({mode4Enabled:Mt,directMode4WallEnabled:Wa,isMac:Ei(er.get(v))})==="atlas"):[],[Wa,Mt,er,Mn]),Xn=d.useMemo(()=>Mn.filter(v=>Lu({mode4Enabled:Mt,directMode4WallEnabled:Wa,isMac:Ei(er.get(v))})==="direct"),[Wa,Mt,er,Mn]);d.useEffect(()=>{const v=new Set(Sa);qr(C=>{let E=!1;const P=new Set;for(const D of C)v.has(D)?P.add(D):E=!0;return E?P:C})},[Sa]);const Kc=d.useMemo(()=>{const v=D=>rt.find(J=>J.deviceId===D)||null,C=D=>{const J=v(D);return J?Hs(J,Ht[D]):0},E=(D,J=C(D))=>D===O&&(W==="connecting"||W==="active"||W==="warm")?ya.current.get(D)||qs.current.get(D)||null:Mt?ks.current.get(D)||xn.current.get(D)||null:xn.current.get(D)||null,P=(D,J=C(D))=>{const ie=v(D);return`${ie?va(ie):D} · Monitor ${J+1}`};return{resolveCurrentTarget(){if(pt&&Qn){const Te=_a;return{type:"control",deviceIds:[Qn.deviceId],monitorIndex:Te,label:`${va(Qn)} · Monitor ${Te+1}`,sourceCanvas:E(Qn.deviceId,Te),signature:`control:${Qn.deviceId}:${Te}:${At.frameMode}`}}const D=Un.map(Te=>Te.deviceId).filter(Te=>Mn.includes(Te)),J=ti&&Mn.includes(ti.deviceId)?ti.deviceId:"",ie=D.length>0?D:J?[J]:Mn,Ne=D.length===0&&!J;if(ie.length===0)return null;if(ie.length===1){const Te=ie[0],Be=C(Te);return{type:Ne?"wall":D.length>1?"selection":"device",deviceIds:ie,monitorIndex:Be,label:Ne?"Wall":P(Te,Be),sourceCanvas:Ne?null:E(Te,Be),signature:`${Ne?"wall":"device"}:${Te}:${Be}:${Mt?"atlas":"direct"}`}}return{type:D.length>1?"selection":"wall",deviceIds:ie,label:D.length>1?`${ie.length} selected Clients`:"Wall",sourceCanvas:null,signature:`${D.length>1?"selection":"wall"}:${ie.join(",")}:${nn}`}},getDeviceCanvas:E,composeWall(D,J={}){return ST(D.map(ie=>{const Ne=C(ie);return{deviceId:ie,label:P(ie,Ne),canvas:E(ie,Ne)}}),J)}}},[rt,Qn,O,W,At.frameMode,xn,Mt,Ht,_a,Un,pt,Mn,ti,nn]),gr=LT({hubUrl:T,sourceRegistry:Kc,onToast:_e}),ii=d.useMemo(()=>Ki&&Xt&&O&&ai.has(O)&&(W==="connecting"||W==="active"||W==="warm")?[O]:[],[Ki,O,W,Xt,ai]),Fo=d.useMemo(()=>Yh([...Sa,...ii]),[ii,Sa]),Zn=d.useMemo(()=>NR(Ke,nn),[Ke,nn]),li=Sk({mode4Enabled:Mt,directMode4WallEnabled:Wa,adaptiveFps:cn,directDeviceCount:Xn.length,adaptive:Ke.adaptiveLoadShedding}),ca=Ck({deviceCount:qn.length,targetFps:cn,adaptive:Ke.adaptiveLoadShedding});Mt&&qn.length>0;const Gn=d.useCallback((v,C,E)=>{if(v.width<=0||v.height<=0)return!1;const P=E?Math.min(1,E.maxWidth/v.width,E.maxHeight/v.height):1,D=Math.max(1,Math.round(v.width*P)),J=Math.max(1,Math.round(v.height*P));(C.width!==D||C.height!==J)&&(C.width=D,C.height=J);const ie=C.getContext("2d",{alpha:!1});return ie?(ie.imageSmoothingEnabled=!0,ie.imageSmoothingQuality="high",ie.drawImage(v,0,0,v.width,v.height,0,0,C.width,C.height),!0):!1},[]),_n=d.useCallback(v=>{v&&qr(C=>{if(C.has(v))return C;const E=new Set(C);return E.add(v),E})},[]),Yl=d.useCallback(v=>{v&&qr(C=>{if(!C.has(v))return C;const E=new Set(C);return E.delete(v),E})},[]),tr=d.useCallback((v,C)=>{if(!C||C.width<=0||C.height<=0)return!1;const E=document.createElement("canvas");return E.width=C.width,E.height=C.height,Gn(C,E)?(Gs.current.set(v,E),_n(v),!0):!1},[_n,Gn]),Ca=d.useCallback(v=>{const C=ls.current.get(v);C!==void 0&&(window.cancelAnimationFrame(C),ls.current.delete(v))},[]),vr=d.useCallback(v=>{Ca(v),Gs.current.delete(v)},[Ca]),Ql=d.useCallback((v,C)=>{Ca(v);const E=()=>{const P=Gs.current.get(v),D=xn.current.get(v)===C||ks.current.get(v)===C;if(!P||!D){ls.current.delete(v);return}Gn(P,C),ls.current.set(v,window.requestAnimationFrame(E))};E()},[Gn,Ca]);d.useEffect(()=>()=>{for(const v of ls.current.values())window.cancelAnimationFrame(v);ls.current.clear()},[]);const ds=d.useCallback((v,C=!1)=>{if(!Vs.current.has(v))return!1;const E=performance.now(),P=Fi.current.get(v)||0,D=Math.max(1,Math.min(xs.controlWallReuseMaxFps,Yi)),J=Yi>D?Math.max(0,1e3/D-2):0;if(!C&&E-P<J)return!1;const ie=ya.current.get(v)||qs.current.get(v),Ne=xn.current.get(v)||ks.current.get(v);return!ie||!Ne||!Gn(ie,Ne,Zn)?!1:(Fi.current.set(v,E),_n(v),vr(v),!0)},[Yi,Zn,_n,Gn,vr]);d.useEffect(()=>{Fl.current=Oi},[Oi]);const Yc=d.useCallback((v,C)=>{const E=xn.current.get(v);if(E&&E!==C&&(Ca(v),tr(v,E),vc(E)),C){xn.current.set(v,C);const P=Gs.current.get(v);P&&Gn(P,C)&&(_n(v),Ql(v,C)),ds(v,!0);return}xn.current.delete(v),Gs.current.has(v)||Yl(v)},[Yl,Ql,_n,Gn,ds,tr,Ca]),Ka=d.useCallback((v,C)=>{const E=qs.current.get(v);if(E&&E!==C&&vc(E),C){qs.current.set(v,C);const P=O===v&&oe?ya.current.get(v):null;P&&Gn(P,C)&&v===U&&wn(!0);return}qs.current.delete(v)},[U,O,oe,Gn]),nr=d.useCallback((v,C,E)=>{const P=performance.now(),D=rs(v,E.deviceId);let J=E;if(v==="control"&&E.visualChanged){const Ne=Q1(E.deviceId),Te=Hc.current.get(E.deviceId)||0,Be=Ne?P-Ne.sentAt:Number.POSITIVE_INFINITY;Ne&&Ne.inputSeq>Te&&Be<=Xb&&(J={...E,inputFeedbackSeq:Ne.inputSeq,inputFeedbackMs:Math.max(0,Be),inputFeedbackAt:P},Hc.current.set(E.deviceId,Ne.inputSeq))}us.current.set(D,P);const ie=$l.current.get(D)||{totalFrames:0,totalChangedFrames:0,sampleFrames:0,sampleChangedFrames:0,sampleStartedAt:P,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleDecoderInputBase:0,sampleDecoderOutputBase:0};v==="control"&&J.inputFeedbackMs===void 0&&ie.lastInfo?.inputFeedbackMs!==void 0&&ie.lastInfo.inputFeedbackAt!==void 0&&P-ie.lastInfo.inputFeedbackAt<=Xb&&(J={...J,inputFeedbackSeq:ie.lastInfo.inputFeedbackSeq,inputFeedbackMs:ie.lastInfo.inputFeedbackMs,inputFeedbackAt:ie.lastInfo.inputFeedbackAt}),ie.totalFrames+=1,ie.sampleFrames+=1,ax(ie,P,J.frameSeq),J.visualChanged&&(ie.totalChangedFrames+=1,ie.sampleChangedFrames+=1),ie.lastInfo=J,$l.current.set(D,ie)},[]),ar=d.useCallback((v,C)=>{nr("wall",v,C),v.kind==="live"&&(_n(v.deviceId),vr(v.deviceId));const E=oe&&O===v.deviceId;Fl.current!==v.deviceId&&!E&&(Vs.current.delete(v.deviceId),Fi.current.delete(v.deviceId))},[O,oe,_n,nr,vr]),Xl=d.useCallback((v,C)=>{if(Ye.current[v.deviceId]||!nb(v,wt.current))return;nr("control",v,C),ee(J=>J&&"");const E=ya.current.get(v.deviceId),P=qs.current.get(v.deviceId);E&&E.width>0&&E.height>0&&(P&&Gn(E,P),Hi.current.set(v.deviceId,{...v,payload:new Uint8Array(0),byteLength:0}),Vs.current.add(v.deviceId),v.deviceId===O&&(le(!0),F(J=>J==="connecting"?"active":J)),ds(v.deviceId));const D=Bl.current;!D||!JT(D,v)||wn(!0)},[O,Gn,ds,nr]);d.useEffect(()=>{const v=window.setInterval(()=>{const C=performance.now(),E={};for(const[P,D]of $l.current.entries()){const J=Math.max(1,C-D.sampleStartedAt);E[P]={totalFrames:D.totalFrames,totalChangedFrames:D.totalChangedFrames,framesPerSecond:D.sampleFrames*1e3/J,changedFramesPerSecond:D.sampleChangedFrames*1e3/J,averageIntervalMs:D.intervalCount>0?D.intervalSumMs/D.intervalCount:0,minIntervalMs:Number.isFinite(D.minIntervalMs)?D.minIntervalMs:0,maxIntervalMs:D.maxIntervalMs,p95IntervalMs:Wh(D.intervalSamplesMs,.95),intervalCount:D.intervalCount,seqGapCount:D.seqGapCount,maxSeqGap:D.maxSeqGap,decoderInputFps:Math.max(0,(Number(D.lastInfo?.decoderInputCount||0)-D.sampleDecoderInputBase)*1e3/J),decoderOutputFps:Math.max(0,(Number(D.lastInfo?.decoderOutputCount||0)-D.sampleDecoderOutputBase)*1e3/J),sampleMs:J,lastInfo:D.lastInfo},D.sampleDecoderInputBase=Number(D.lastInfo?.decoderInputCount||0),D.sampleDecoderOutputBase=Number(D.lastInfo?.decoderOutputCount||0),D.sampleChangedFrames=0,nx(D,C)}Ic(E)},1e3);return()=>window.clearInterval(v)},[]);const As=d.useCallback((v,C)=>{const E=performance.now(),P=rs(v,C.deviceId);js.current.set(P,E),Ys.current.delete(P),v==="control"?Kr.current.delete(P):Ui.current.delete(P);const D=hr.current.get(P)||{totalFrames:0,sampleFrames:0,sampleStartedAt:E,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleBytes:0,sampleH264Frames:0,sampleTinyFrames:0,sampleRepeatedFrames:0,sourceSendIntervalsMs:[]};if(D.totalFrames+=1,D.sampleFrames+=1,D.sampleBytes+=Math.max(0,Number(C.byteLength||0)),String(C.frameMode||C.mode||C.codec||C.mimeType||"").toLowerCase().includes("h264")){D.sampleH264Frames+=1,Number(C.byteLength||0)<=KT&&(D.sampleTinyFrames+=1);const Te=String(C.contentHash||"");Te&&D.lastContentHash===Te&&(D.sampleRepeatedFrames+=1),D.lastContentHash=Te}const Ne=Number(C.agentSendGapMs||0);Ne>0&&Ne<1e3&&aS(D.sourceSendIntervalsMs,Ne),D.lastFrame=C,ax(D,E,C.frameSeq),hr.current.set(P,D)},[]);d.useEffect(()=>{const v=window.setInterval(()=>{const C=performance.now(),E={};for(const[P,D]of hr.current.entries()){const J=Math.max(1,C-D.sampleStartedAt);E[P]={totalFrames:D.totalFrames,framesPerSecond:D.sampleFrames*1e3/J,averageIntervalMs:D.intervalCount>0?D.intervalSumMs/D.intervalCount:0,minIntervalMs:Number.isFinite(D.minIntervalMs)?D.minIntervalMs:0,maxIntervalMs:D.maxIntervalMs,p95IntervalMs:Wh(D.intervalSamplesMs,.95),intervalCount:D.intervalCount,seqGapCount:D.seqGapCount,maxSeqGap:D.maxSeqGap,averageFrameBytes:D.sampleFrames>0?D.sampleBytes/D.sampleFrames:0,tinyFrameRatio:D.sampleH264Frames>0?D.sampleTinyFrames/D.sampleH264Frames:0,repeatedFrameRatio:D.sampleH264Frames>0?D.sampleRepeatedFrames/D.sampleH264Frames:0,sourceSendAverageMs:D.sourceSendIntervalsMs.length>0?D.sourceSendIntervalsMs.reduce((ie,Ne)=>ie+Ne,0)/D.sourceSendIntervalsMs.length:0,sourceSendP95Ms:Wh(D.sourceSendIntervalsMs,.95),sourceSendSampleCount:D.sourceSendIntervalsMs.length,sampleMs:J,lastFrame:D.lastFrame},D.sampleBytes=0,D.sampleH264Frames=0,D.sampleTinyFrames=0,D.sampleRepeatedFrames=0,D.sourceSendIntervalsMs.length=0,nx(D,C)}To(E)},1e3);return()=>window.clearInterval(v)},[]);const Ia=d.useCallback(v=>{if(Fl.current===v.deviceId)return;As("wall",v);const C=xn.current.get(v.deviceId);if(!C)return;const E=kk(Mt,Ke.h264DecodeAcceleration);Eh(C,v,()=>xn.current.get(v.deviceId)!==C,ar,E.acceleration,E.latencyMode).catch(()=>{})},[ar,Mt,As,Ke.h264DecodeAcceleration]),za=d.useCallback(v=>{if(Ye.current[v.deviceId]||!nb(v,wt.current))return;As("control",v);let C=ya.current.get(v.deviceId);C||(C=document.createElement("canvas"),C.setAttribute("aria-hidden","true"),ya.current.set(v.deviceId,C));const E=C,P=Ce.current;Eh(E,v,()=>ya.current.get(v.deviceId)!==E,Xl,At.h264DecodeAcceleration,"interactive").catch(D=>{Ce.current!==P||ya.current.get(v.deviceId)!==E||O!==v.deviceId||ee(D instanceof Error?D.message:String(D||"Control H.264 decode failed"))})},[O,At.h264DecodeAcceleration,Xl,As]),yr=d.useCallback(v=>{const C=Ws.current;C&&C!==v&&vc(C),Ws.current=v,ql.current=0,Ro.current=0,Eo.current=0,Do.current=0,Oc.current=0,mr.current=0},[]),ua=d.useCallback(()=>{const v=new Set,C=Ws.current,E=Ks.current;if(!C||!E||C.width<=0||C.height<=0||mr.current!==E.layoutVersion)return v;for(const P of E.tiles){const D=ks.current.get(P.deviceId);if(!D||P.width<=0||P.height<=0)continue;const J=Math.max(1,Math.round(P.width)),ie=Math.max(1,Math.round(P.height)),Ne=YT,Te=QT;(D.width!==Ne||D.height!==Te)&&(D.width=Ne,D.height=Te);const Be=D.getContext("2d",{alpha:!1});if(Be){Be.imageSmoothingEnabled=!0,Be.imageSmoothingQuality="high";try{Be.drawImage(C,Math.round(P.x),Math.round(P.y),J,ie,0,0,Ne,Te),v.add(P.deviceId)}catch{}}}return v},[]),Ms=d.useCallback((v,C)=>{if(C){ks.current.set(v,C);const P=Gs.current.get(v);P&&Gn(P,C)&&(_n(v),Ql(v,C)),window.requestAnimationFrame(()=>{ua().has(v)&&vr(v)}),window.requestAnimationFrame(()=>ds(v,!0));return}const E=ks.current.get(v);Ca(v),tr(v,E),ks.current.delete(v),Gs.current.has(v)||Yl(v)},[Yl,Ql,_n,ua,Gn,ds,tr,vr,Ca]),Ns=d.useCallback((v,C)=>{Eo.current=performance.now(),mr.current=Number(v.layoutVersion||0),ua();const E=Ks.current?.tiles||[],P=E.length>0?Math.round(v.byteLength/E.length):v.byteLength;for(const D of E){const J={...v,deviceId:D.deviceId,width:D.width,height:D.height,sourceWidth:D.width,sourceHeight:D.height,byteLength:P};ar(J,{...C,deviceId:D.deviceId,width:D.width,height:D.height,byteLength:P}),Fl.current===D.deviceId&&ds(D.deviceId,!0)}},[ar,ua,ds]),fd=d.useCallback(v=>{const C=performance.now();ql.current<=0&&(ql.current=C),Ro.current=C;const E=Ws.current;if(!E)return;const P=Ks.current?.tiles||[],D=P.length>0?Math.round(v.byteLength/P.length):v.byteLength;for(const J of P)As("wall",{...v,deviceId:J.deviceId,width:J.width,height:J.height,sourceWidth:J.width,sourceHeight:J.height,byteLength:D});Eh(E,v,()=>Ws.current!==E,Ns).catch(()=>{})},[Ns,As]),Qc=d.useMemo(()=>({fps:li,maxWidth:Zn.maxWidth,maxHeight:Zn.maxHeight,quality:Ke.quality,mode:Mt?"mode3-h264-hw":Ke.frameMode,frameMode:Mt?"mode3-h264-hw":Ke.frameMode,streamPurpose:"wall",monitorSelections:Ht,onFrame:Ia}),[li,Ia,Zn,Mt,Ht,Ke]),Po=d.useCallback(v=>{const C=wt.current;if(Ye.current[v.deviceId]||!C||C.deviceId!==v.deviceId||v.deviceId!==O||v.streamPurpose!=="control"||v.monitorIndex!==_a)return;const E=rt.find(P=>P.deviceId===v.deviceId);!E?.sessionId||E.sessionId!==v.sessionId||(wt.current=cf(C.deviceId,C.transitionGeneration,v),he.current=v,be(v),F(P=>P==="connecting"?"active":P))},[rt,O,_a]);d.useEffect(()=>{he.current=null;const v=wt.current;v&&v.deviceId===O&&(wt.current=cf(v.deviceId,v.transitionGeneration,{sessionId:v.sessionId,monitorIndex:_a})),be(null)},[O,me,xa,_a]);const Zl=me?`${me}-monitor-${_a}`:"",Vn=d.useMemo(()=>({fps:Yi,maxWidth:Jr.maxWidth,maxHeight:Jr.maxHeight,quality:At.quality,mode:xa,frameMode:xa,streamPurpose:"control",forceRestart:Zl!=="",forceRestartToken:Zl,restartReason:Zl?"control-session-or-monitor-change":"",monitorSelections:Ht,onFrame:za,onStreamReady:Po}),[Zl,At.quality,za,Yi,xa,Jr.maxHeight,Jr.maxWidth,Po,Ht]),{frames:Kt,state:kt,error:sr,stats:Nn,restartLive:el}=Ky(Xn,Ke.autoStartLive&&Xn.length>0,T,Qc),{frame:Oa,layout:br,state:$o,stats:tl,refreshInputs:xr}=Z1(qn,Mt&&Ke.autoStartLive&&qn.length>0,T,{fps:xs.atlasOutputFps,inputFps:ca,width:1920,height:1080,tileWidth:Zn.maxWidth,tileHeight:Zn.maxHeight,captureDeviceIds:qn,monitorSelections:Ht,onFrame:fd});d.useEffect(()=>{Ks.current=br,br&&window.requestAnimationFrame(ua)},[br,ua]),d.useEffect(()=>{if(!Mt||$o!=="open"){ql.current=0,Ro.current=0,Eo.current=0;return}const v=window.setInterval(()=>{const C=Ws.current,E=performance.now();if(!C||document.visibilityState!=="visible"||E-Vr.current<Vh)return;const P=Ro.current,D=ql.current;if(P<=0||D<=0||E-P>500)return;const J=Eo.current||D,ie=E-J;if(ie>=qT&&E-Oc.current>=VT){Eu(C)&&(Oc.current=E,Do.current=E);return}ie>=UT&&E-Do.current>=GT&&I1(C)&&(Do.current=E)},250);return()=>window.clearInterval(v)},[$o,Mt]);const{frames:nl,state:oi,error:ci,stats:ui,restartLive:Ya,reconnectLive:rr}=Ky(ii,ii.length>0,T,Vn);d.useEffect(()=>{const v=Br.current,C=new Set([...Object.keys(v),...Object.keys(Ht)]);for(const E of C){const P=Math.max(0,Math.floor(Number(v[E])||0)),D=Math.max(0,Math.floor(Number(Ht[E])||0));P!==D&&(Va("wall",E),Va("control",E),Eu(xn.current.get(E)||null),Eu(ya.current.get(E)||null))}Br.current={...Ht}},[Ht,Va]);const Ha=d.useMemo(()=>{const v=(E,P)=>{const D=rt.find(ie=>ie.deviceId===E),J=D?Hs(D,Ht[E]):0;return!Number.isFinite(Number(P.monitorIndex))||Number(P.monitorIndex)===J},C=new Map;for(const[E,P]of Kt.entries())v(E,P)&&C.set(E,P);if(Mt&&Oa&&qn.length>0){const E=new Map((br?.tiles||[]).map(D=>[D.deviceId,D])),P=Math.max(1,E.size);for(const D of qn){const J=E.get(D);J&&C.set(D,{...Oa,deviceId:D,width:J.width,height:J.height,sourceWidth:J.width,sourceHeight:J.height,byteLength:Math.round(Oa.byteLength/P)})}}for(const[E,P]of nl.entries())v(E,P)&&C.set(E,P);for(const E of wa){if(!Vs.current.has(E)||C.has(E))continue;const P=Hi.current.get(E);P&&v(E,P)&&C.set(E,P)}return C},[Oa,br,rt,nl,qn,Mt,Ht,Kt,wa,Ua]),Jl=pt&&ii.length>0?oi:qn.length>0?$o:kt,al=pt&&ii.length>0?ui:qn.length>0?tl:Nn;d.useCallback((v,C="browser-stale")=>{const E=el(v,C),P=Ya(v,C);return E||P},[Ya,el]),d.useEffect(()=>{Mt&&qn.length>0&&!pt&&xr()},[qn.length,Mt,xr,pt]);const ir=d.useCallback((v,C,E)=>{const P=C==="control"?ya.current.get(v)||null:xn.current.get(v)||null;if(!P||!Eu(P))return!1;const D=performance.now();return qi.current.set(rs(C,v),D),!0},[]),di=d.useCallback(v=>{if(xa!=="mode3-h264-hw"||!O||I)return!1;const C=rt.find(Ne=>Ne.deviceId===O)||Qn,E=String(C?.platform||"").toLowerCase();if(!["win32","windows","win32nt"].includes(E))return!1;const P="mode5-lzo-delta",D=rs("control",O),J=performance.now();Yr.current.set(D,J),js.current.delete(D),us.current.delete(D),Wr.current.delete(D),Kr.current.delete(D),Ys.current.delete(D),Eu(ya.current.get(O)||null),rr([O],"control-decode-fallback"),se(P),Z(`control-${P}-fallback-${O}-${Date.now()}`),le(!1),wn(!1);const ie=v==="no first frame"||v==="control-first-frame-timeout";return ee(Ne=>Ne||(ie?`Control frame transport timeout; retrying Control with Mode 5 (${v})`:`H.264 decode failed; retrying Control with Mode 5 (${v})`)),F("connecting"),!0},[rt,Qn,O,I,xa,rr]);d.useEffect(()=>{const v=pt?Qn:null;if(v){Bl.current={deviceId:v.deviceId,monitorIndex:_a,frameMode:xa,startedAtEpochMs:Date.now()},wn(O===v.deviceId&&oe);return}Bl.current=null,wn(!1)},[Qn?.sessionId,U,O,oe,xa,_a,pt]);const Fa=d.useCallback(async v=>{if(Ye.current[v])throw new Error("LIVE_CAPTURE_PAUSED");if(!Xs)return{ok:!0,skipped:!0,reason:"wall-presentation-hidden"};const C=j.find(J=>J.deviceId===v);Lu({mode4Enabled:Mt,directMode4WallEnabled:Wa,isMac:Ei(C?.platform)});const E=C?Hs(C,Ht[v]):0,P={fps:Mt?li:cn,maxWidth:Zn.maxWidth,maxHeight:Zn.maxHeight,quality:Ke.quality,mode:Mt?"mode3-h264-hw":Ke.frameMode,frameMode:Mt?"mode3-h264-hw":Ke.frameMode,streamPurpose:"wall",monitorIndex:E},D=await We(`/api/remote/devices/${encodeURIComponent(v)}/live/start`,{method:"POST",body:JSON.stringify(P)},T);if(D?.ok===!1)throw new Error(D.error||"wall-stream-start-failed");return D},[cn,ca,j,Wa,li,Zn.maxHeight,Zn.maxWidth,T,Mt,Ht,Ke.frameMode,Ke.quality,Xs]),In=d.useCallback(async v=>{const C=j.find(P=>P.deviceId===v);Lu({mode4Enabled:Mt,directMode4WallEnabled:Wa,isMac:Ei(C?.platform)});const E=await We(`/api/remote/devices/${encodeURIComponent(v)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"wall",reason:"control-active"})},T);if(E?.ok===!1)throw new Error(E.error||"wall-stream-stop-failed");return E},[j,Wa,T,Mt]),eo=d.useCallback(async(v,C="control-session-stop")=>{const E=await We(`/api/remote/devices/${encodeURIComponent(v)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"control",reason:C})},T);if(E?.ok===!1)throw new Error(E.error||"control-stream-stop-failed");return E},[T]),fi=d.useCallback(v=>{const C=ya.current.get(v);C&&(Gs.current.has(v)||xn.current.has(v)||ks.current.has(v)||tr(v,C),vc(C),ya.current.delete(v));const E=qs.current.get(v);E&&vc(E),Hi.current.delete(v),Vs.current.delete(v),Fi.current.delete(v)},[tr]),sl=d.useCallback(v=>{const C=tb(Pl.current,v);return Pl.current=C.tail,C.result},[]),wr=d.useCallback(v=>{const C=tb(zc.current,v);return zc.current=C.tail,C.result},[]),Ts=d.useCallback(v=>{os.current=v,qa.current=0;const C=v?.deviceId||"";Fl.current=C,am(C),C&&Vs.current.add(C)},[]),Zt=d.useCallback(v=>sl(async()=>{if(Ye.current[v.deviceId])return!1;const C=os.current;return!vs(C,v)||!uf(v.deviceId,v,wt.current)?!1:(await Fa(v.deviceId),vs(os.current,v)&&Ts(null),!0)}),[Ts,sl,Fa]),Bo=d.useCallback((v,C,E)=>sl(async()=>{const P=os.current;if(vs(P,v))return E.stoppedWallDeviceId=v.deviceId,!0;if(P)if(Ye.current[P.deviceId])vs(os.current,P)&&Ts(null);else{if(!uf(P.deviceId,P,wt.current))return!1;await Fa(P.deviceId),vs(os.current,P)&&Ts(null)}if(!C())return!1;if(await In(v.deviceId),E.stoppedWallDeviceId=v.deviceId,!C()){if(uf(E.stoppedWallDeviceId,v,wt.current))try{await Fa(E.stoppedWallDeviceId)}catch(D){throw Ts(v),D}finally{E.stoppedWallDeviceId=""}return!1}return vc(xn.current.get(v.deviceId)||null),Ts(v),!0}),[Ts,sl,Fa,In]),Sr=d.useCallback(async(v,C)=>{if(C.stoppedWallDeviceId){if(vs(os.current,v)){try{await Zt(v)}catch(E){_e(E instanceof Error?E.message:String(E))}finally{C.stoppedWallDeviceId=""}return}await sl(async()=>{if(!C.stoppedWallDeviceId||!uf(C.stoppedWallDeviceId,v,wt.current))return;const E=C.stoppedWallDeviceId;try{await Fa(E)}catch(P){Ts(v),_e(P instanceof Error?P.message:String(P))}finally{C.stoppedWallDeviceId=""}})}},[Ts,sl,Zt,_e,Fa]),Qa=d.useCallback(async(v,C,E=!1)=>{try{await eo(v.deviceId,C)}catch(P){if(!E)throw P}if(!vs(wt.current,v))return!1;wt.current=null,he.current=null,be(null),fi(v.deviceId),le(!1),Z(""),se(""),ee(""),ve(P=>P===v.deviceId?"":P);try{await Zt(v)}catch(P){_e(P instanceof Error?P.message:String(P))}return!0},[fi,Zt,_e,eo]),mi=(pt&&Xt&&U&&!Pe.has(U)&&rt.find(v=>v.deviceId===U)||null)?.deviceId||"";d.useEffect(()=>{la.current=mi},[mi]),d.useEffect(()=>{const v=U&&rt.find(J=>J.deviceId===U)||null;if(!pt||!Xt||!v){Bn.current&&(++ba.current,Bn.current="");return}if(Ye.current[v.deviceId]){Bn.current&&(++ba.current,Bn.current=""),O===v.deviceId&&F("paused");return}if(oa.current){if(oa.current===v.deviceId)return;oa.current=""}if(O===v.deviceId&&(W==="active"||W==="warm"||W==="connecting")){F(J=>J==="warm"?"active":J);return}if(Bn.current===v.deviceId)return;const C=++ba.current,E=cf(v.deviceId,C,{sessionId:v.sessionId,monitorIndex:_a});Bn.current=v.deviceId;const P={stoppedWallDeviceId:""},D=()=>C===ba.current&&la.current===E.deviceId;wr(async()=>{if(!D())return;const J=wt.current;if(J){F("stopping");try{await Qa(J,"control-session-switch")}catch(Te){D()&&(F("error"),_e(Te instanceof Error?Te.message:String(Te)));return}if(!D()){wt.current||F("idle");return}}try{if(!await Bo(E,D,P)||!D()){await Sr(E,P),wt.current||F("idle");return}}catch(Te){await Sr(E,P),D()&&(F("error"),_e(Te instanceof Error?Te.message:String(Te)));return}if(!D()){await Sr(E,P);return}wt.current=E,oa.current="",cs.current=null,Bi.current=0,Gr.current="",P.stoppedWallDeviceId="";const ie=rs("control",E.deviceId),Ne=`control-session-${C}-${E.deviceId}`;Yr.current.set(ie,performance.now()),js.current.delete(ie),us.current.delete(ie),Ys.current.delete(ie),Kr.current.delete(ie),se(""),ee(""),Z(Ne),ve(E.deviceId),le(!1),F("connecting")}).catch(J=>{D()&&(F("error"),_e(J instanceof Error?J.message:String(J)))}).finally(()=>{ba.current===C&&Bn.current===E.deviceId&&(Bn.current="")})},[rt,U,O,W,wr,Xt,Bo,Sr,_a,_e,pt,Qa,Qe]),d.useEffect(()=>{if(!O||rt.some(E=>E.deviceId===O))return;const v=O;++ba.current,Bn.current="";const C=wt.current;F("stopping"),wr(async()=>{C&&C.deviceId===v?await Qa(C,"control-device-disconnected",!0):(fi(v),ve(E=>E===v?"":E)),wt.current||F("idle")})},[rt,O,wr,fi,Qa]),d.useEffect(()=>{if(La.current!==null&&(window.clearTimeout(La.current),La.current=null),!O||W==="idle"||W==="paused"||W==="stopping"||W==="error"||Ki){O&&Ki&&W==="connecting"&&(Ul.current=!1),O&&Ki&&Ul.current&&(W==="warm"||W==="active")&&(Ul.current=!1,he.current=null,be(null),le(!1),wn(!1),Va("control",O),Z(`control-presentation-resume-${Date.now()}-${O}`),F("connecting"));return}he.current=null,Ul.current=!0,be(null),le(!1),wn(!1),F(C=>C==="idle"||C==="stopping"?C:"warm");const v=O;return La.current=window.setTimeout(()=>{La.current=null,++ba.current,Bn.current="";const C=wt.current;F("stopping"),wr(async()=>{if(C&&C.deviceId===v)try{await Qa(C,"control-session-warm-timeout")}catch(E){F("error"),_e(E instanceof Error?E.message:String(E));return}else fi(v),ve(E=>E===v?"":E);wt.current||F("idle")})},WT),()=>{La.current!==null&&(window.clearTimeout(La.current),La.current=null)}},[Ki,O,W,wr,fi,Va,_e,Qa]),d.useEffect(()=>()=>{La.current!==null&&window.clearTimeout(La.current)},[]),d.useEffect(()=>{const v=os.current,C=wt.current;if(!v||Ye.current[v.deviceId]||C&&C.deviceId===v.deviceId){qa.current=0;return}const E=qa.current,P=Math.min(5e3,500*2**Math.min(E,4)),D=window.setTimeout(()=>{const J=os.current;!J||Ye.current[J.deviceId]||!vs(J,v)||(qa.current=E+1,Zt(J).catch(ie=>{_e(ie instanceof Error?ie.message:String(ie)),vs(os.current,J)&&!wt.current&&nd(Ne=>Ne+1)}))},P);return()=>window.clearTimeout(D)},[W,Zt,_e,Dc,Oi]);const Rs=O&&rt.find(v=>v.deviceId===O)||null,Uo=!!(pt&&Re&&W==="active"&&oe&&Rs?.sessionId&&Q?.deviceId===Rs.deviceId&&Q.sessionId===Rs.sessionId&&Q.streamPurpose==="control"&&Q.commandId&&Q.captureGeneration>0&&Q.monitorIndex===_a),{state:qo,sendInput:hd,stats:fs,error:Cr}=J1(Js&&Uo,T),to=Rs?.deviceId||"",rl=Rs?.sessionId||"",Go=Q?.commandId||"",kr=Number(Q?.captureGeneration||0),Vo=Number(Q?.monitorIndex||0),jr=d.useCallback((v,C)=>!Uo||!to||!rl||!Go||kr<=0||v!==to?!1:hd(v,{...C,monitorIndex:Vo,controlSessionId:rl,controlCommandId:Go,captureGeneration:kr}),[Uo,kr,Go,to,Vo,rl,hd]),Xa=Uo&&qo==="open",Wo={shiftKey:te.includes("ShiftLeft"),ctrlKey:te.includes("ControlLeft"),altKey:te.includes("AltLeft"),metaKey:te.includes("MetaLeft")},{state:pd,lastFrame:Ar,stats:hn,error:Xc}=ok(Ie?.deviceId||"",dd&&ne,T),no=d.useRef(new Map);d.useEffect(()=>{const v=[["hub",A],["registry",l],["license",z],["wall-stream",sr],["control-stream",ci],["control-decode",de],["remote-input",Cr],["remote-audio",Xc]];for(const[C,E]of v){const P=String(E||"").trim();if(C==="hub"&&Dt?.requiresHubRestart&&Dt.stage==="updating"){no.current.delete(C);continue}if(!P){no.current.delete(C);continue}no.current.get(C)!==P&&(no.current.set(C,P),_e(P))}},[Xc,de,ci,A,Cr,z,l,_e,sr,Dt]);const lr=Ie?.deviceId||"",il=Ie?Hs(Ie,Ht[lr]):0;d.useEffect(()=>{if(!Re||!Js||!Xa||!lr)return;const v=gk(),C=lr,E=il,P=ut=>ut?jr(C,{...ut,monitorIndex:E}):!1,D=(ut,pn)=>{const ma=ut.target,Pa=ma?.tagName?.toLowerCase(),Is=ma?.isContentEditable||Pa==="input"||Pa==="textarea"||Pa==="select",xi=v.isPressed(ut);if(Is&&(pn==="keydown"||!xi))return;const co=v.event(ut,pn);co&&(ut.preventDefault(),ut.stopPropagation(),P(co))},J=ut=>D(ut,"keydown"),ie=ut=>D(ut,"keyup"),Ne=(ut,pn=!1)=>{const ma=v.reset(ut,pn);ma&&(P(ma),Ue([]))};mt.current=ut=>{const pn=v.snapshot().latchedCodes.includes(ut),ma=v.modifier(ut,!pn);ma&&(P(ma),Ue(Pa=>pn?Pa.filter(Is=>Is!==ut):[...Pa.filter(Is=>Is!==ut),ut]))};const Te=()=>Ne("browser-window-blur"),Be=()=>Ne("browser-page-hidden"),Lt=()=>{document.visibilityState==="hidden"&&Ne("browser-document-hidden")};return window.addEventListener("keydown",J),window.addEventListener("keyup",ie),window.addEventListener("blur",Te),window.addEventListener("pagehide",Be),document.addEventListener("visibilitychange",Lt),()=>{window.removeEventListener("keydown",J),window.removeEventListener("keyup",ie),window.removeEventListener("blur",Te),window.removeEventListener("pagehide",Be),document.removeEventListener("visibilitychange",Lt),mt.current=null,Ne("control-keyboard-owner-changed",!0)}},[Js,Xa,lr,il,Re,jr]),d.useEffect(()=>{const v=()=>{document.visibilityState==="visible"&&(Vr.current=performance.now())};return document.addEventListener("visibilitychange",v),window.addEventListener("pageshow",v),()=>{document.removeEventListener("visibilitychange",v),window.removeEventListener("pageshow",v)}},[]),d.useEffect(()=>{if(!O||W!=="connecting"&&W!=="active"&&W!=="warm"||oi!=="open")return;const v=O,C=rs("control",v),E=window.setInterval(()=>{const P=performance.now();if(document.visibilityState!=="visible"||P-Vr.current<Vh)return;const D=js.current.get(C)||0,J=us.current.get(C)||0,ie=Wr.current.get(C)||0,Ne=Yr.current.get(C)||P;Yr.current.has(C)||Yr.current.set(C,Ne);const Te=D<=0,Be=Te?P-Ne>sR:P-D>lx,Lt=D>0&&(J<=0||P-J>lx);if(!Be&&Lt){const Pa=qi.current.get(C)||0;P-Pa>=ox&&ir(v,"control","decoder-paint-stale");return}if(!Be)return;const ut=Kr.current.get(C)||0;if(ut>0){if(P-ut<iR)return;Kr.current.delete(C)}const pn=Ys.current.get(C)||0;if(pn>=lR){if(di(Te?"no first frame":"stale stream"))return;le(!1),wn(!1),oa.current=v,F("error");return}if(P-ie<cx(rR,pn))return;Ya([v],Te?"control-first-frame-timeout":"control-receive-stale")&&(Wr.current.set(C,P),Kr.current.set(C,P),Yr.current.set(C,P),Ys.current.set(C,pn+1))},650);return()=>window.clearInterval(E)},[oi,O,W,di,ir,Ya]),d.useEffect(()=>{!de||O&&Ye.current[O]||xa!=="mode3-h264-hw"||di(de)||(le(!1),wn(!1),oa.current=wt.current?.deviceId||"",F("error"))},[de,O,xa,di]),d.useEffect(()=>{!pt||!O||Ye.current[O]||!ci||(oa.current=O,F(v=>v==="error"?v:"error"))},[ci,O,pt]),d.useEffect(()=>{if(W!=="error")return;const v=wt.current;if(!v)return;oa.current=v.deviceId,vs(cs.current,v)||(cs.current=v,Bi.current=0);const C=Bi.current,E=C===0?0:Math.min(5e3,500*2**Math.min(C-1,4)),P=window.setTimeout(()=>{vs(wt.current,v)&&(++ba.current,Bn.current="",F("stopping"),wr(async()=>{if(vs(wt.current,v))try{if(!await Qa(v,"control-session-terminal-error"))return;cs.current=null,Bi.current=0,Gr.current===v.deviceId?(Gr.current="",oa.current="",F("idle")):F("error")}catch(D){if(!vs(wt.current,v))return;Bi.current+=1,_e(D instanceof Error?D.message:String(D)),F("error"),ad(J=>J+1)}}))},E);return()=>window.clearTimeout(P)},[W,No,wr,_e,Qa]);const Mr=d.useCallback(v=>{if(!v||oa.current!==v)return!1;const C=wt.current;return++ba.current,Bn.current="",Bi.current=0,C&&C.deviceId===v?(Gr.current=v,cs.current=null,F("error"),ad(E=>E+1),!0):(Gr.current="",oa.current="",cs.current=null,F("idle"),!0)},[]);d.useEffect(()=>{if(kt!=="open"||!Ke.autoStartLive||Xn.length===0)return;const v=window.setInterval(()=>{const C=performance.now();if(document.visibilityState!=="visible"||C-Vr.current<Vh)return;const E=1e3/Math.max(1,li||Ke.fps||1),P=Math.max(cR,Math.ceil(E*4)),D=[];for(const J of Xn){if(D.length>=fR)break;const ie=rs("wall",J),Ne=js.current.get(ie)||0,Te=Ne<=0,Be=Ui.current.get(ie)||C;if(Ui.current.has(ie)||Ui.current.set(ie,Be),Te&&C-Be<=oR)continue;const Lt=Wr.current.get(ie)||0,ut=us.current.get(ie)||0,pn=Te||C-Ne>P,ma=!Te&&(ut<=0||C-ut>P);if(!pn&&ma){const Is=qi.current.get(ie)||0;C-Is>=ox&&ir(J,"wall","decoder-paint-stale");continue}if(!pn)continue;const Pa=Ys.current.get(ie)||0;C-Lt>=cx(uR,Pa)&&D.push(J)}if(D.length>0&&el(D,D.some(J=>(js.current.get(rs("wall",J))||0)<=0)?"wall-first-frame-timeout":"wall-frame-stale"))for(const J of D){const ie=rs("wall",J);Wr.current.set(ie,C),Ui.current.set(ie,C),js.current.delete(ie),us.current.delete(ie),Ys.current.set(ie,(Ys.current.get(ie)||0)+1)}},dR);return()=>window.clearInterval(v)},[li,Xn,ir,el,Ke.autoStartLive,Ke.fps,kt]),d.useEffect(()=>{ia(Ke.fps),Vi.current=Date.now(),Qs.current=0},[Ke.fps,Ke.frameMode,Ke.adaptiveLoadShedding]),d.useEffect(()=>{j1({h264DecodeAcceleration:Ke.h264DecodeAcceleration})},[Ke.h264DecodeAcceleration]),d.useEffect(()=>{if(!Xt||pt||nn==="list"||!Ke.visibleOnlyLive){Ur([]);return}const v=sd.current;if(!v||typeof IntersectionObserver>"u"){Ur(Ji);return}const C=Array.from(v.querySelectorAll("[data-live-device-id]"));if(C.length===0){Ur([]);return}const E=new Map,P=()=>{const J=Yh(C.map(ie=>String(ie.dataset.liveDeviceId||"")).filter(ie=>(E.get(ie)||0)>0));Ur(ie=>Kh(ie,J)?ie:J)},D=new IntersectionObserver(J=>{for(const ie of J){const Ne=String(ie.target.dataset.liveDeviceId||"");Ne&&E.set(Ne,ie.isIntersecting?ie.intersectionRatio||.01:0)}P()},{root:null,rootMargin:Na.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return C.forEach(J=>D.observe(J)),P(),()=>D.disconnect()},[Ji,Xt,pt,ei,Ke.visibleOnlyLive,nn]),d.useEffect(()=>{if(!Ke.adaptiveLoadShedding||!Ke.autoStartLive||Xn.length===0)return;const v=Ke.fps;if(Xn.length<=Na.preserveConfiguredFpsDeviceCount){cn!==v&&(ia(v),Vi.current=Date.now(),Qs.current=0);return}if(kt!=="open"||Nn.sampleMs<500)return;const C=Date.now(),E=Xn.length*cn,P=Nn.framesPerSecond,D=Nn.bytesPerSecond,J=Math.max(0,...Xn.map(Lt=>Ga[rs("wall",Lt)]?.maxIntervalMs||0)),ie=Math.max(0,...Xn.map(Lt=>Pi[rs("wall",Lt)]?.maxIntervalMs||0)),Ne=E>8&&P>0&&P<E*.72;if(P>Na.maxWallFramesPerSecond||D>Na.maxWallBytesPerSecond||J>Na.maxFrameGapMs||ie>Na.maxFrameGapMs||Ne){Qs.current=0;const Lt=Na.minFps;if(C-Vi.current>=Na.downshiftCooldownMs&&cn>Lt){const ut=Math.max(Lt,TR(cn,Lt));ut<cn&&(ia(ut),Vi.current=C)}return}const Be=P<Na.maxWallFramesPerSecond*Na.lowLoadFrameRatio&&D<Na.maxWallBytesPerSecond*Na.lowLoadByteRatio;if(!Be||cn>=v){Be||(Qs.current=0);return}if(!Qs.current){Qs.current=C;return}if(C-Qs.current>=Na.recoveryCooldownMs){const Lt=Math.min(v,RR(cn,v));Lt>cn&&(ia(Lt),Vi.current=C,Qs.current=0)}},[cn,Xn.length,Xn,Pi,Ga,kt,Nn.bytesPerSecond,Nn.framesPerSecond,Nn.lastUpdatedAt,Nn.sampleMs,Ke.adaptiveLoadShedding,Ke.autoStartLive,Ke.frameMode,Ke.fps]),d.useEffect(()=>{const v=new URLSearchParams(window.location.search).get("checkout");if(v==="success"){_e("Checkout returned. Waiting for Dodo confirmation."),H();const C=window.setInterval(()=>{H()},4e3),E=window.setTimeout(()=>{window.clearInterval(C)},45e3);return()=>{window.clearInterval(C),window.clearTimeout(E)}}v==="cancelled"&&_e("Checkout cancelled.")},[H]),d.useEffect(()=>{!Xt&&Re&&He(!1),!Xt&&ne&&xe(!1)},[ne,Re,Xt]),d.useEffect(()=>{const v=Ie?.deviceId||"",C=Oe.current;if(Oe.current=v,!C||C===v)return;const E=++ze.current,P=v?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";v&&ne&&$e.current.set(v,P);let D=!0;return(async()=>{try{const ie=$e.current.get(C);if($e.current.delete(C),await We(`/api/remote/devices/${encodeURIComponent(C)}/audio/stop`,{method:"POST",body:JSON.stringify(ie?{streamId:ie}:{})},T),!D||E!==ze.current||!ne||!v||!Xt||!Zs)return;const Ne=await We(`/api/remote/devices/${encodeURIComponent(v)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:P,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},T);if(Ne.ok===!1)throw new Error(Ne.error||"Remote audio start failed.")}catch(ie){D&&($e.current.delete(v),xe(!1),_e(ie instanceof Error?ie.message:String(ie)))}})(),()=>{D=!1}},[ne,Xt,T,Zs,Ie?.deviceId]),d.useEffect(()=>{const v=rt.map(D=>D.deviceId),C=new Set(v),E=new Map(rt.map(D=>[D.deviceId,D])),P=new Map;for(const D of rt){const J=yR(D);if(!J)continue;const ie=dr(D.status),Ne=[D.lastStatusAt,ie.capturedAt,ie.collectedAt,ie.timestamp,ie.updatedAt].find(Be=>typeof Be=="string"&&Be.trim()),Te=yk($r.current[D.deviceId],J,Ne);Te&&($r.current[D.deviceId]=Te,P.set(D.deviceId,Te),sw({platform:D.platform,topologyFingerprint:J,consecutiveTopologySamples:Te.consecutiveSamples})&&(Ln.current[D.deviceId]=J))}for(const D of Object.keys($r.current))C.has(D)||delete $r.current[D];_(D=>{const J=D.filter(ie=>C.has(ie));return Kh(D,J)?D:J}),q(D=>D&&C.has(D)?D:""),K(D=>D&&C.has(D)?D:""),jn(D=>{let J=!1;const ie={};for(const[Ne,Te]of Object.entries(D)){const Be=E.get(Ne);if(!Be){ie[Ne]=Te;continue}const Lt=P.get(Ne)||$r.current[Ne],ut=bk({requestedIndex:Te,monitorCount:El(Be),platform:Be.platform,topologyFingerprint:Lt?.fingerprint||"",consecutiveTopologySamples:Lt?.consecutiveSamples||0});ie[Ne]=ut,ut!==Te&&(J=!0)}return J?ie:D}),$c(D=>{const J=D.filter(ie=>C.has(ie));return Kh(D,J)?D:J})},[rt,Gc]),d.useEffect(()=>{sm([]),im(!1)},[ds]),d.useEffect(()=>{!Wl||Xr!=="selected"||Gi.length>0||Un.length===0||$c(Un.map(v=>v.deviceId))},[Un,Gi.length,Xr,Wl]),d.useEffect(()=>{try{localStorage.setItem(Jw,bn)}catch{}},[bn]),d.useEffect(()=>{kR(Ke)},[Ke]),d.useEffect(()=>{AR(At)},[At]),d.useEffect(()=>{SR(Ht,Ln.current)},[rt,Ht]);const hi=d.useCallback(async()=>{const v=new Set(h);v.add(En);try{const J=await We("/api/remote/status",void 0,En);Iy({endpoint:J.agentEndpoint,endpoint_candidates:[...J.agentEndpointCandidates||[],...J.hostTargetEndpointCandidates||[]]}).forEach(ie=>v.add(ie))}catch{}const C=[...v].sort((J,ie)=>{const Ne=Te=>{const Be=Uu(Te);return Be==="local"?0:Be==="loopback"?1:2};return Ne(J)-Ne(ie)||J.localeCompare(ie)});let E=!1,P="",D=!1;try{for(const J of C){const ie=Uu(J);try{if(await We("/api/health",void 0,J),ie==="local")return y(!0),xc(!0),J;ie==="loopback"&&(E=!0,P=J)}catch{ie==="local"&&(D=!0)}}return E?(D&&_e("LiveDesk Hub is reachable on this PC, but not through the LAN address yet. Restart LiveDesk Hub to bind 5179 on the network."),y(!0),xc(!0),P||En):(y(!1),xc(!1),"")}catch{return y(!1),xc(!1),""}},[h]),Nr=async()=>{if(Ct("auth"),Rt(!1),await hi(),window.liveDesk?.auth?.signInWithGoogle){const E=await window.liveDesk.auth.signInWithGoogle();E?.ok===!1&&(_e(E.error||"LiveDesk could not open the system browser for Google sign-in."),Ct(""));return}const{data:v,error:C}=await St.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}/callback`}});C&&(_e(C.message),Ct(""))},gd=async()=>{Ct("auth"),Rt(!1),await St.auth.signOut(),(await window.liveDesk?.auth?.persistSession?.(null))?.runtimeCleared===!1?_e("Signed out locally. The LiveDesk runtime could not be reached to clear its session."):window.liveDesk?.auth?.persistSession||await We("/api/auth/session",{method:"DELETE"},En).catch(()=>{}),Ct("")};d.useEffect(()=>{if(!at)return;const v=E=>{E.target instanceof Element&&(E.target.closest(".account-popover, .rail-account")||Rt(!1))},C=E=>{E.key==="Escape"&&Rt(!1)};return window.addEventListener("pointerdown",v),window.addEventListener("keydown",C),()=>{window.removeEventListener("pointerdown",v),window.removeEventListener("keydown",C)}},[at]);const Tr=d.useCallback(async(v={})=>{const C=v.silent===!0,E=v.takeover===!0,P=v.requestLocalAccess===!0;if(!t?.user){C||_e("Sign in before publishing this host.","error");return}if(!Lo.current){Lo.current=!0,C||(Ct("host"),tn("Hub · 1/4 · Checking the local runtime…"));try{const J=(P?await hi():"")||T||En;if(!(w||await We("/api/remote/status",void 0,J)).started)throw new Error("Start LiveDesk on this computer before syncing the server.");C||tn("Hub · 2/4 · Sending the signed-in session to the Hub…");const Ne=await We("/api/auth/session",{method:"POST",body:JSON.stringify({accessToken:t.access_token,refreshToken:t.refresh_token,expiresAt:t.expires_at,user:{id:t.user.id,email:t.user.email}})},J);if(!Ne.ok||!Ne.authenticated)throw new Error(Ne.error||"hub-session-sync-failed");C||tn("Hub · 3/4 · Claiming the Hub role and publishing its endpoint…");const Te=await We("/api/hub/sync",{method:"POST",body:JSON.stringify({takeover:E})},J);if(!Te.ok)throw new Error(Te.error||"host-target-failed");if(!C){tn("Hub · 4/4 · Verifying the endpoint and lease renewal…");const Be=await We("/api/hub/status",void 0,J);if(!Be.hostTargetActive)throw new Error(Be.hostTargetLease?.lastError||"host-target-not-active-after-sync");const Lt=Be.hostTargetEndpoint||Be.agentEndpoint||"endpoint ready",ut=Number(Be.connectedDeviceCount||0),pn=ut>0?`${ut} client${ut===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";_e(`Hub ready · ${Lt} · lease auto-renewal active. ${pn}`,"success"),(P||x)&&(y(!0),xc(!0)),k()}c()}catch(D){if(!C){const J=D instanceof Error?D.message:String(D);J.includes("local network access")&&(y(!1),xc(!1)),_e(`Hub setup failed · ${J}`,"error")}}finally{Lo.current=!1,C||Ct("")}}},[T,x,k,c,hi,t,_e,tn,w]),ll=d.useCallback((v=!0)=>{it!=="host"&&(Ae(!1),v&&window.requestAnimationFrame(()=>ht.current?.focus()))},[it]),Rr=d.useCallback(()=>{it!=="host"&&(ht.current=document.activeElement instanceof HTMLElement?document.activeElement:null,Rt(!1),Ae(!0))},[it]),Zc=d.useCallback(()=>{Ae(!1),Tr({takeover:!0,requestLocalAccess:!0})},[Tr]);d.useEffect(()=>{if(!Fe)return;const v=window.requestAnimationFrame(()=>ct.current?.focus()),C=P=>{P.target instanceof Element&&P.target.closest(".client-hub-switch-popover, .hub-sync-trigger")||ll(!1)},E=P=>{P.key==="Escape"&&ll()};return window.addEventListener("pointerdown",C),window.addEventListener("keydown",E),()=>{window.cancelAnimationFrame(v),window.removeEventListener("pointerdown",C),window.removeEventListener("keydown",E)}},[ll,Fe]);const Jc=d.useCallback(async()=>{if(!(!w?.update?.canApply||it==="update")){Ct("update");try{const v=await We("/api/update/apply",{method:"POST",body:JSON.stringify({})},T||En);if(!v.ok)throw new Error(v.error||"LiveDesk update could not be started.");const C=[...new Set((v.targets||[]).map(D=>String(D.deviceId||"").trim()).filter(Boolean))],E=!!(v.managerUpdateAvailable||v.clientPackageUpdateAvailable),P=v.state==="hub-restart-requested"?Date.now():void 0;(C.length>0||E)&&Cs({operationId:String(v.operationId||`wall-update-${Date.now()}`),targetIds:C,stage:v.state==="clients-updated"?"updated":"updating",requiresHubRestart:E,initialHostInstanceId:String(w.hostInstanceId||""),targetManagerVersion:String(v.latestVersion||w.update?.latestVersion||""),targetClientVersion:String(v.latestClientVersion||w.update?.latestClientVersion||""),restartRequestedAt:P,restartDeadlineAt:P?P+kf:void 0}),tn(v.state==="hub-restart-requested"?Cf:ex),k()}catch(v){_e(v instanceof Error?v.message:String(v),"error")}finally{Ct("")}}},[it,T,k,_e,tn,w]);d.useEffect(()=>{const v=Dt,C=w?.update;if(!v||v.stage!=="updating"||!C)return;const E=C.restartResult?.operationId===v.operationId?C.restartResult:null;if(E?.outcome==="restored"){const Te=E.error||`The requested Hub ${E.targetVersion||v.targetManagerVersion||"version"} failed verification.`;Cs(Be=>Be?.operationId===v.operationId?{...Be,stage:"restored",error:Te}:Be),_e(`LiveDesk update did not complete. Hub ${E.fallbackVersion||E.appVersion||"the previous version"} was restored. ${Te}`,"error");return}if(E?.outcome==="failed"){const Te=E.error||"No verified LiveDesk Hub replacement could be started.";Cs(Be=>Be?.operationId===v.operationId?{...Be,stage:"failed",error:Te}:Be),_e(`LiveDesk Hub update failed. ${Te}`,"error");return}if(C.operationId===v.operationId&&C.state==="failed"){const Te=C.error||"LiveDesk update failed before the Hub replacement completed.";Cs(Be=>Be?.operationId===v.operationId?{...Be,stage:"failed",error:Te}:Be),_e(Te,"error");return}if(C.operationId===v.operationId){if(C.state==="hub-restart-requested"&&!v.restartDeadlineAt){const Te=Date.now();Cs(Be=>Be?.operationId===v.operationId?{...Be,restartRequestedAt:Te,restartDeadlineAt:Te+kf}:Be),tn(Cf)}!v.requiresHubRestart&&C.state==="clients-updated"&&(Cs(Te=>Te?.operationId===v.operationId?{...Te,stage:"updated"}:Te),_e("LiveDesk clients updated and reconnected successfully.","success"));return}if(!v.requiresHubRestart)return;const P=w.started===!0&&(!v.initialHostInstanceId||w.hostInstanceId&&w.hostInstanceId!==v.initialHostInstanceId),D=!!C.checkedAt,J=tx(C.currentVersion,v.targetManagerVersion),ie=!v.targetClientVersion||tx(C.currentClientVersion,v.targetClientVersion),Ne=D&&C.state==="idle"&&C.updateAvailable===!1&&J&&ie;P&&Ne&&(Cs(Te=>Te?.operationId===v.operationId?{...Te,stage:"updated"}:Te),_e(`LiveDesk Hub ${C.currentVersion||E?.appVersion||v.targetManagerVersion} restarted and passed version verification.`,"success"))},[_e,tn,w,Dt]),d.useEffect(()=>{const v=Dt;if(!v||v.stage!=="updating"||!v.requiresHubRestart||v.restartDeadlineAt)return;const C=()=>{const P=Date.now();Cs(D=>D?.operationId===v.operationId&&D.stage==="updating"&&!D.restartDeadlineAt?{...D,restartRequestedAt:P,restartDeadlineAt:P+kf}:D),tn(Cf)};if(w?.update?.state==="hub-restart-requested"){C();return}if(!A)return;const E=window.setTimeout(C,XT);return()=>window.clearTimeout(E)},[A,tn,w?.update?.state,Dt]),d.useEffect(()=>{const v=Dt;if(!v||v.stage!=="updating"||!v.requiresHubRestart||!v.restartDeadlineAt)return;const C=Math.max(0,v.restartDeadlineAt-Date.now()),E=v.operationId,P=window.setTimeout(()=>{const D=`LiveDesk Hub did not return and verify ${v.targetManagerVersion||"the requested version"} within ${Math.round(kf/6e4)} minutes. Check the Hub terminal or restart log, then run livedesk@latest manually if the Hub is still offline.`;Cs(J=>J?.operationId===E&&J.stage==="updating"?{...J,stage:"failed",error:D}:J),_e(D,"error")},C);return()=>window.clearTimeout(P)},[_e,Dt]),d.useEffect(()=>{if(!Dt||Dt.stage!=="updated")return;const v=Dt.operationId,C=window.setTimeout(()=>{Cs(E=>E?.operationId===v?null:E)},8e3);return()=>window.clearTimeout(C)},[Dt]),d.useEffect(()=>{if(Le!==ex&&Le!==Cf)return;const v=w?.update;if(String(v?.state||"")==="failed"){_e(v?.error||"LiveDesk update failed.","error");return}Dt?.stage==="updated"&&_e("")},[Le,_e,w?.update?.error,w?.update?.state,Dt?.stage]);const Er=d.useCallback(async()=>{if(!it){Ct("pin");try{const C=await We("/api/remote/pairing-pin",{method:"POST"},T||En);if(!C.ok)throw new Error(C.error||"pin-rotation-failed");await k(),_e("New PIN published.")}catch(v){_e(v instanceof Error?v.message:String(v))}finally{Ct("")}}},[it,T,k]),Es=d.useCallback(v=>{v&&(q(v),_(C=>C.includes(v)?C:[...C,v]))},[]),pi=d.useCallback(v=>{if(!v)return;const C=An.has(v);q(E=>C?E===v?"":E:v),_(E=>C?E.filter(P=>P!==v):E.includes(v)?E:[...E,v])},[An]),gi=d.useCallback(()=>{_([]),q("")},[Gn]),Ko=d.useCallback(()=>{_(rt.map(v=>v.deviceId)),q("")},[rt]),vi=d.useCallback((v,C)=>{const E=rt.find(D=>D.deviceId===v);if(!E)return;const P=El(E);if(!(P<=1)&&(jn(D=>{const J=Hu(D[v],P),ie=(J+C+P)%P;return ie===J?D:{...D,[v]:ie}}),Va("wall",v),Va("control",v),qr(D=>{if(!D.has(v))return D;const J=new Set(D);return J.delete(v),J}),Hi.current.delete(v),Vs.current.delete(v),pt)){const D=Mr(v);le(!1),D||F("connecting"),wn(!1),K(v)}},[rt,Va,Mr,pt]);d.useEffect(()=>{const v=C=>{if(Re&&Js&&Xa)return;const E=C.target,P=E?.tagName?.toLowerCase();E?.isContentEditable||P==="input"||P==="textarea"||P==="select"||((C.ctrlKey||C.metaKey)&&C.key.toLowerCase()==="a"&&(C.preventDefault(),Ko()),C.key==="Escape"&&gi())};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[Js,gi,Xa,Re,Ko]);const ao=(v,C)=>{const E=rt.find(ie=>ie.deviceId===v),P=E?El(E):1,D=Hu(Ht[v],P),J=Hu(C,P);if(D!==J&&(jn(ie=>({...ie,[v]:J})),qr(ie=>{if(!ie.has(v))return ie;const Ne=new Set(ie);return Ne.delete(v),Ne}),Hi.current.delete(v),Vs.current.delete(v),Va("wall",v),Va("control",v)),pt){const ie=Mr(v);D!==J&&(le(!1),ie||F("connecting")),wn(!1),K(v)}else Es(v)},ol=async v=>{if(Mr(v),wn(!1),K(v),Da("control"),!ai.has(v)){He(!1),_e(ri);return}const C=rt.find(P=>P.deviceId===v);if(Ei(C?.platform)&&(C?.capabilities?.controlPermission===!1||C?.capabilities?.accessibilityPermission===!1)){He(!1),_e("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts LiveDesk, then restart the Mac client.","error");return}He(!0),_e(`Opening remote control${C?` for ${va(C)}`:""}.`,"success")},vd=async()=>{if(!Ie){_e("Select a Client before playing audio.");return}if(!Xt){_e(ri);return}if(!Zs){_e("Selected Client does not report remote audio support yet.");return}if(pe)return;const v=!ne,C=v?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:$e.current.get(Ie.deviceId);v&&C?$e.current.set(Ie.deviceId,C):v||$e.current.delete(Ie.deviceId),De("audio"),xe(v);try{await We(`/api/remote/devices/${encodeURIComponent(Ie.deviceId)}/audio/${v?"start":"stop"}`,{method:"POST",body:JSON.stringify({...C?{streamId:C}:{},mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},T),_e(`${v?"Audio started":"Audio stopped"} for ${va(Ie)}.`,"success")}catch(E){v&&$e.current.delete(Ie.deviceId),xe(!1),_e(E instanceof Error?E.message:String(E),"error")}finally{De("")}},cl=async()=>{if(!Ie){_e("Select a Client before pausing video.");return}if(!Xt){_e(ri);return}if(pe)return;const v=Ie,C=v.deviceId,E=String(Ye.current[C]||""),P=!!E&&ye[C]===!0,D=!E||P;if(De("video"),D){const J=E||`pending:${Date.now()}:${C}`,ie=wt.current?.deviceId===C?wt.current:null,Ne=ot.current.get(C);ot.current.set(C,{deviceId:C,monitorIndex:Hs(v,Ht[C]??Ne?.monitorIndex),previousControlOwner:ie||Ne?.previousControlOwner||null}),bt(C,!0),nt(C,!1),dt(C,J),(ie||O===C)&&(++ba.current,Bn.current="",F("paused"));try{const Te=await We(`/api/remote/devices/${encodeURIComponent(C)}/live/pause`,{method:"POST",body:JSON.stringify({reason:"user-video-pause"})},T);if(!Te?.pauseToken){B.current.delete(C),dt(C,""),nt(C,!1),ot.current.delete(C),(ie||O===C)&&(he.current=null,be(null),le(!1),Z(`control-pause-rollback-${Date.now()}-${C}`),F("connecting")),_e(Te?.error||"video-capture-pause-failed","error");return}const Be=wt.current?.deviceId===C?wt.current:ie,Lt=ot.current.get(C);Lt&&(Lt.previousControlOwner=Be),wt.current?.deviceId===C&&(wt.current=null),he.current=null,be(null),dt(C,Te.pauseToken),(Be||O===C)&&F("paused"),Te.ok===!1||Te.captureStopConfirmed!==!0?(nt(C,!0),_e(`Video restart is blocked for ${va(v)}, but Client capture shutdown was not confirmed: ${Te.stopError||Te.error||"unknown stop error"}. Press Retry pause to check again.`,"error")):(nt(C,!1),_e(`Video paused for ${va(v)}. Client capture and FFmpeg shutdown were confirmed.`,"success")),k()}catch(Te){nt(C,!0),k(),_e(`Video pause could not be confirmed: ${Te instanceof Error?Te.message:String(Te)}. LiveDesk will reconcile Hub status before allowing restart.`,"error")}finally{De("")}return}if(E.startsWith("pending:")){De("");return}try{bt(C,!1);const J=await We(`/api/remote/devices/${encodeURIComponent(C)}/live/resume`,{method:"POST",body:JSON.stringify({pauseToken:E})},T);if(J?.ok===!1)throw new Error(J.error||"video-capture-resume-failed");const ie=ot.current.get(C),Ne=ie?.previousControlOwner||null,Te=O===C&&(Ne!==null||os.current?.deviceId===C||W==="paused");if(dt(C,""),nt(C,!1),ot.current.delete(C),Te){const Be=++ba.current;Bn.current="";const Lt=cf(C,Be,{sessionId:v.sessionId||Ne?.sessionId,monitorIndex:Hs(v,Ht[C]??ie?.monitorIndex)});wt.current=Lt,Ts(Lt),oa.current="",cs.current=null,he.current=null,be(null),se(""),ee(""),le(!1),Va("control",C);const ut=`control-video-resume-${Be}-${C}`;Z(ut),ve(C),F("connecting")}else Va("wall",C);k(),_e(`Video resumed for ${va(v)}.`,"success")}catch(J){B.current.delete(C),k(),_e(J instanceof Error?J.message:String(J),"error")}finally{De("")}},Yo=v=>{const C=v instanceof Error?v.message:String(v);return/remote-actions-disabled|allowAgent-blocked-by-settings/i.test(C)?"Remote actions are off. Turn on Settings > Agent > Enable AI Agent first.":/power-actions-disabled/i.test(C)?"Power actions are off. Turn on Settings > Agent > Allow power actions first.":/agent-tool-capability-unavailable|unsupported-agent-operation/i.test(C)?"This Client needs a newer LiveDesk Client for power actions.":/device-not-connected|404 device-not-found/i.test(C)?"The Client disconnected before the action could be sent.":C},Qo=async v=>{if(!Ie||pe)return;const C=Ie,P={sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[v];if(window.confirm(`${P} ${va(C)}? Unsaved work on that computer may be lost.`)){De(v),_e(`Sending ${P.toLowerCase()} request to ${va(C)}...`);try{const D=await We(`/api/remote/devices/${encodeURIComponent(C.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:v})},T);if(!D.ok)throw new Error(D.error||"The remote action could not be sent.");_e(`${P} request sent to ${va(C)}.`,"success"),k()}catch(D){_e(Yo(D),"error")}finally{De("")}}},Xo=async(v,C,E="files")=>{const P=v.filter(Ne=>Ne.file.size>=0);if(P.length===0)return{files:0,bytes:0};if(!Xt)throw new Error(ri);if(C.length===0)throw new Error("Select at least one connected Client.");const D=crypto.randomUUID(),J=P.reduce((Ne,Te)=>Ne+Te.file.size,0);let ie=0;pr({id:D,status:"reading",progress:1,message:`Preparing ${P.length} ${E}`});try{for(let Ne=0;Ne<P.length;Ne+=1){const Te=P[Ne],Be=Te.file,Lt=Math.max(1,Math.ceil(Be.size/qh));for(let ut=0;ut<Lt;ut+=1){const pn=ut*qh,ma=Math.min(Be.size,pn+qh),Pa=Be.size===0?new ArrayBuffer(0):await Be.slice(pn,ma).arrayBuffer(),Is=ut===Lt-1;pr({id:D,status:"sending",progress:Math.max(2,Math.min(98,Math.round(ie/Math.max(1,J)*96))),message:`${Ne+1}/${P.length} ${Te.relativePath}`});const xi=await We("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:D,deviceIds:C,remoteDirectory:bn.trim(),name:Be.name,relativePath:Te.relativePath,size:Be.size,type:Be.type,lastModified:Be.lastModified,offset:pn,totalBytes:Be.size,final:Is,dataBase64:ER(Pa)})},T);if(!xi.ok||xi.queued!==C.length)throw new Error(xi.error||`file-chunk-not-queued-${xi.queued}/${C.length}`);ie+=Pa.byteLength,await new Promise(co=>window.setTimeout(co,0))}}return pr({id:D,status:"queued",progress:100,message:`Sent ${P.length} file${P.length===1?"":"s"} to ${C.length} Client${C.length===1?"":"s"}`}),window.setTimeout(()=>{pr(Ne=>Ne?.id===D&&Ne.status==="queued"?null:Ne)},4500),{files:P.length,bytes:J}}catch(Ne){throw pr({id:D,status:"failed",progress:100,message:Ne instanceof Error?Ne.message:String(Ne)}),Ne}},Zo=async v=>{const C=Un.length>0?Un.map(E=>E.deviceId):Ie?[Ie.deviceId]:[];try{await Xo(dx(v),C)}catch(E){_e(E instanceof Error?E.message:String(E))}},ka=async v=>{try{await Xo(dx(v),cm)}catch(C){_e(C instanceof Error?C.message:String(C))}};d.useEffect(()=>{lm.current=!1},[]);const Za=v=>{v.preventDefault(),v.stopPropagation(),Pc(!1),Zo(v.dataTransfer.files)},Ds=async(v="ltd")=>{if(!t){_e("Sign in with Google before checkout.");return}if(N&&v===Wt){_e("LiveDesk license is already active.");return}if(N&&Wt==="pro"){_e("LiveDesk Pro is already active.");return}Ct("checkout");try{const{data:C,error:E}=await St.functions.invoke("dodo-checkout",{body:{plan:v}});if(E)throw E;if(!C?.checkout_url)throw new Error("Checkout function did not return a checkout URL.");window.location.assign(C.checkout_url)}catch(C){_e(C instanceof Error?C.message:String(C)),Ct("")}},ul=mR(),eu=hR(),Ls=Fo.filter(v=>Ha.has(v)).length,da=Jl==="open"&&al.sampleMs>0?`${al.framesPerSecond.toFixed(1)} fps`:Jl,Me=Ie?pt?nl.get(Ie.deviceId):Ha.get(Ie.deviceId):void 0,yi=Ie?Hs(Ie,Ht[Ie.deviceId]):0,_s=Ie?vR(Ie):[],yt=typeof Me?.monitorIndex=="number"?Hu(Me.monitorIndex,Math.max(1,Me.monitorCount||1)):yi,un=(Me&&yt===yi?oS(Me):null)||(Ie?lS(Ie,yi):null);un&&`${un.width}${un.height}`;const bi=Ie?rs(pt?"control":"wall",Ie.deviceId):"",dn=bi?Ga[bi]:void 0,Tn=bi?Pi[bi]:void 0,Nt=Tn?.lastInfo,so=dn&&dn.sampleMs>0?`${dn.framesPerSecond.toFixed(1)} fps`:"waiting";dn&&`${dn.totalFrames}${so}`,Tn&&Tn.sampleMs>0&&`${Tn.framesPerSecond.toFixed(1)}`,Tn&&Tn.sampleMs>0&&`${Tn.changedFramesPerSecond.toFixed(1)}`,Nt&&(`${Nt.frameSeq}${Nt.decoderLabel}${Nt.queueSize}${Nt.renderQueueSize}${Nt.droppedForLatency}${Nt.decoderFlushCount}${Nt.decoderTimestampFallbacks}${Nt.decoderInputCount}${Nt.decoderOutputCount}`,Nt.visualChanged),Nt&&`${Math.round(Nt.queuedForMs)}${Math.round(Nt.decodedForMs)}${Math.round(Nt.scheduledForMs)}${Nt.drawMs.toFixed(1)}`,Nt?.targetPaintIntervalMs&&`${Nt.targetPaintIntervalMs.toFixed(1)}${(1e3/Nt.targetPaintIntervalMs).toFixed(1)}`,Tn&&`${Tn.decoderInputFps.toFixed(1)}${Tn.decoderOutputFps.toFixed(1)}`,Nt?.canvasPresentation,Nt&&`${Nt.interactiveBufferWaitCount}${Math.round(Nt.interactiveBufferWaitMs)}${Nt.interactiveQueueDrainCount}`,dn&&(Me?.frameMode==="mode5-lzo-delta"?`${Fu(dn.averageFrameBytes)}${Me.deltaVisualTileCount||0}${Me.deltaRefreshTileCount||0}${Me.deltaTotalTiles||0}`:`${Fu(dn.averageFrameBytes)}${Math.round(dn.tinyFrameRatio*100)}${Math.round(dn.repeatedFrameRatio*100)}`),dn&&dn.sourceSendSampleCount>0&&`${dn.sourceSendAverageMs.toFixed(1)}${dn.sourceSendP95Ms.toFixed(1)}`,sx(dn),sx(Tn),dn&&Tn&&`${rx(dn)}${rx(Tn)}`,Me?Me.frameMode||Me.mode||Me.codec||Me.mimeType:pt?At.frameMode:Ke.frameMode,pt?At.frameMode:Ke.frameMode,Me?`${Me.width}${Me.height}${Fu(Me.byteLength)}`:pt?`${Jr.maxWidth}${Jr.maxHeight}`:`${Ke.maxWidth}${Ke.maxHeight}`,Me&&`${Me.isKeyFrame?"key":String(Me.chunkType||"delta")}`,Me&&Me.monitorCount&&((Me.monitorIndex??0)+1,`${Me.monitorCount}`),Me&&[`src ${Math.round(Me.sourceGapMs||0)}ms`,`gap ${Math.round(Me.agentSendGapMs||0)}ms`,`tx ${Math.round(Me.agentSendDurationMs||0)}ms`,`pace ${Math.round(Me.agentPaceMs||0)}ms`,`queue ${Math.round(Me.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(Me.agentFrameAgeMs||0)}ms`,Me.hubPacketTransitAgeMs!==void 0?`sock ${Math.max(0,Math.round(Me.hubPacketTransitAgeMs))}ms`:"",Me.droppedByAgent?`drop ${Me.droppedByAgent}`:"",Me.hubIngressDropped?`ingress-drop ${Me.hubIngressDropped}`:"",Me.hubClientDropped?`ws-drop ${Me.hubClientDropped}`:"",Me.captureStageMs?`capture ${Math.round(Me.captureStageMs)}ms`:"",Me.requestedFps?`req ${Math.round(Me.requestedFps)}fps`:"",Me.effectiveFps?`eff ${Math.round(Me.effectiveFps)}fps`:"",Me.captureAverageMs?`avg ${Math.round(Me.captureAverageMs)}ms`:"",Me.captureP95Ms?`p95 ${Math.round(Me.captureP95Ms)}ms`:"",Me.slowFrameCount?`slow ${Math.round(Me.slowFrameCount)}`:"",Me.captureHelperRestarts?`helper ${Math.round(Me.captureHelperRestarts)}`:"",Me.convertMs?`rgb565 ${Math.round(Me.convertMs)}ms`:"",Me.compressMs?`lzo ${Math.round(Me.compressMs)}ms`:"",Me.captureSourceSerial?`cap #${Me.captureSourceSerial}`:"",Me.captureSourceSkipped?`cap skip ${Me.captureSourceSkipped}`:"",Me.frameMode==="mode5-lzo-delta"?`tiles ${Me.deltaVisualTileCount||0}+${Me.deltaRefreshTileCount||0}/${Me.deltaTotalTiles||0}@${Me.deltaTileSize||0}`:"",Me.platformProfile||Me.hardwareEncoder||"-",Me.atlasComposeMs?`atlas ${Me.atlasComposeMs.toFixed(1)}ms`:"",Me.atlasPoolStarved?`pool ${Me.atlasPoolStarved}`:"",Me.atlasTileCount?`tiles ${Me.atlasReadyTiles||0}/${Me.atlasTileCount}`:"",Me.atlasInputRevision?`input #${Me.atlasInputRevision}`:"",Me.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(Me.atlasSourceMaxAgeMs)}ms`:"",Nt?.inputFeedbackMs!==void 0&&Nt.inputFeedbackAt!==void 0&&performance.now()-Nt.inputFeedbackAt<=Zb?`feedback ${Math.round(Nt.inputFeedbackMs)}ms`:"",Me.contentHash?`enc ${Me.contentHash.slice(0,6)}`:"",Nt?.visualHash?`pix ${Nt.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "),qo==="open"&&[`${fs.sentPerSecond.toFixed(1)} hz`,fs.lastInputSeq>0?`rtt ${Math.round(fs.lastRoundTripMs)}ms`:"",fs.lastInputSeq>0?`apply ${fs.lastAgentApplyMs.toFixed(1)}ms`:"",fs.droppedPerSecond>0?`drop ${fs.droppedPerSecond.toFixed(1)}/s`:"",fs.bufferedAmount>0?`buf ${Fu(fs.bufferedAmount)}`:"",fs.lastInputType||"ready"].filter(Boolean).join(" / "),Nt?.inputFeedbackMs!==void 0&&Nt.inputFeedbackAt!==void 0&&performance.now()-Nt.inputFeedbackAt<=Zb&&`${Math.round(Nt.inputFeedbackMs)}${Nt.inputFeedbackSeq||0}`,ne&&[pd,`context ${hn.audioContextState}`,`queue ${Math.round(hn.queuedMs)}ms`,`last ${Math.round(hn.lastPacketAgeMs)}ms`,`accepted ${Math.round(hn.lastAcceptedAgeMs)}ms`,`process ${Math.round(hn.localProcessingAgeMs)}ms`,`remote ${Math.round(hn.browserAgeMs)}/${Math.round(hn.captureAgeMs)}ms`,`heartbeat ${Math.round(hn.captureStatusAgeMs)}ms`,`capture ${hn.captureAlive&&hn.helperAlive?"alive":"down"}`,`drop ${hn.drops}`,`resync ${hn.resyncs}`,`restart ${hn.automaticRestarts}`,hn.pendingDecodes>0?`decode ${hn.pendingDecodes}`:"",Ar?`#${Ar.frameSeq}`:"waiting"].filter(Boolean).join(" / "),Me&&`${Me.frameSeq}${Ex(Me.receivedAt||Me.capturedAt)}`;const ms=Math.max(0,al.bytesPerSecond*8/1e6),dl=d.useCallback(()=>{Ii(!0),re(Date.now()),k(),Ee.current!==null&&window.clearTimeout(Ee.current),Ee.current=window.setTimeout(()=>{Ee.current=null,re(Date.now()),Ii(!1)},650)},[k]),an=d.useCallback(()=>{if(Yn){Bs(!1);return}Xe(!1),Bs(!0),dl()},[dl,Yn]),Jo=d.useCallback(()=>{if($){Xe(!1);return}Bs(!1),Xe(!0),dl()},[$,dl]),ec=d.useCallback(()=>{if(ft){mn(!1);return}mn(!0),dl()},[ft,dl]),fl=new Map,ro=new Map;if(Yn||$||ft)for(const v of rt){const C=v.deviceId,E=pt&&O===C,D=rs(E?"control":"wall",C),J=E?nl.get(C):Ha.get(C),ie=E?ya.current.get(C)||qs.current.get(C)||null:xn.current.get(C)||(Mt?Ws.current:null),Ne={device:v,frame:J,receiveStat:Ga[D],paintStat:Pi[D],codec:ie?qy(ie):{},selectedMonitorIndex:Hs(v,Ht[C]),control:E,controlInputReady:E&&Xa,controlBinding:E&&Q?.deviceId===C?Q:void 0,hubRelay:w?.relay,capturePaused:Pe.has(C),capturePauseConfirmed:v.liveCapturePause?.captureStopConfirmed===!0,capturePauseError:v.liveCapturePause?.stopError||"",clientHeartbeatMs:Number(w?.heartbeatMs||5e3),now:Date.now()};(Yn||ft)&&fl.set(C,bT(Ne)),$&&ro.set(C,xT(Ne))}const dm=ft?wT({status:w||{},deviceDiagnostics:[...fl.values()],codec:qy(),browser:{hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:Number(navigator.deviceMemory||0)},frameStats:al}):[],tc=Oa?.atlasReadyTiles??Ls,io=Oa?.atlasTileCount??Ls,tu=tc===io?`${io} tiles`:`${tc}/${io} tiles`,fa=qn.length>0;pt?`${da}${ms.toFixed(ms>=10?0:1)}`:fa?`${tu}${da}${ms.toFixed(ms>=10?0:1)}`:`${Ls}${da}${ms.toFixed(ms>=10?0:1)}`;const sn=Un.length,nc=pt?Ie?va(Ie):"No Client":sn===0?"No Client":sn>1?`${sn} selected`:Ie?va(Ie):"No Client",lo=pt?[Ie?.deviceId].filter(v=>!!v):Un.map(v=>v.deviceId),zn=Ac[Ge]||Ac.en,ml=zn.sync||Ac.en.sync,or=a||L?"checking":N?Wt==="pro"?"Pro LTD active":`Plus LTD ${rt.length}/${Ou}`:ud?`Free ${rt.length}/${zu}`:`Upgrade ${rt.length}/${zu}`,au=N?Wt==="pro"?"Pro active":"Upgrade to Pro LTD":t?it==="checkout"?"Opening checkout":Wt==="ltd"?"Buy Pro LTD":"Buy Plus LTD":it==="auth"?"Opening Google":"Sign in to buy",su=Wt==="pro"||it==="checkout"||it==="auth"||a||L,ru=t?.user?.user_metadata,oo=fx(ru,"avatar_url","picture"),hl=fx(ru,"full_name","name")||t?.user?.email||"Google",iu=hl.slice(0,1).toUpperCase(),yd=w?.started?"Local app ready":"Start LiveDesk",bd=i?.active?"Published":t?"Not published":"Sign in required",lu=/^\d{6}$/.test(w?.pairingPin||"")?w?.pairingPin:"------",ac=v=>{if(typeof window<"u"&&(v==="support"?window.history.pushState({},"","/support"):on==="support"&&window.history.pushState({},"","/")),v==="control"){const C=Qn||ti;if(C&&(Mr(C.deviceId),wn(!1),K(C.deviceId)),Da(v),!Xt){He(!1),_e(ri);return}He(!0);return}v==="wall"&&Lc(C=>C+1),Da(v),He(!1)},pl=it==="update"||Dt?.stage==="updating"||["dispatching","waiting-for-clients","hub-restart-requested"].includes(w?.update?.state||""),xd=!!(w?.update?.updateAvailable&&w.update.canApply||pl||Dt?.error||!w&&Dt),Dr=QC(Ge),sc=d.useCallback(v=>{if(!Dt?.targetIds.includes(v))return;const C=w?.update?.operationId===Dt.operationId?w.update.targets?.find(E=>E.deviceId===v):void 0;switch(C?.state){case"completed":return{state:"updated",label:"Updated"};case"failed":return{state:"failed",label:"Update failed",error:C.error};case"pending-offline":return{state:"offline",label:"Waiting for reconnect"};case"queued":return Dt.stage==="updating"?{state:"queued",label:"Queued"}:void 0;case"waiting":return Dt.stage==="updating"?C.candidateSince?{state:"updating",label:"Verifying restart..."}:{state:"updating",label:"Restarting..."}:void 0;default:return Dt.stage==="updated"?{state:"updated",label:"Updated"}:Dt.stage==="updating"?{state:"updating",label:"Verifying..."}:void 0}},[w?.update,Dt]);return r.jsxs("main",{className:"app-shell",children:[r.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk tools",children:[r.jsx("div",{className:"rail-brand",title:"LiveDesk",children:r.jsx(Dx,{size:25})}),r.jsx("nav",{className:"rail-tools",children:HR.map(v=>{const C=v.icon,E=zf(v.tooltip,Ge);return r.jsxs("button",{className:`rail-tool ${v.id==="sync-server"?"sync-server hub-sync-trigger":""} ${on===v.id?"active":""} accent-${v.accent}`,onClick:()=>v.id==="sync-server"?Rr():ac(v.id),"data-tooltip":v.id==="sync-server"&&Fe?void 0:lp(v.label,v.tooltip,Ge),"aria-label":`${v.label}. ${E}`,type:"button",disabled:v.id==="sync-server"&&it==="host","aria-busy":v.id==="sync-server"&&it==="host","aria-expanded":v.id==="sync-server"?Fe:void 0,"aria-haspopup":v.id==="sync-server"?"dialog":void 0,"aria-controls":v.id==="sync-server"&&Fe?"hub-sync-popover":void 0,children:[v.id==="sync-server"&&it==="host"?r.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):r.jsx(C,{size:19}),r.jsx("span",{children:v.id==="sync-server"&&it==="host"?"Syncing…":v.label})]},v.id)})}),r.jsxs("div",{className:"rail-footer",children:[FR.map(v=>{const C=v.icon;return r.jsxs("button",{className:`rail-tool compact ${on===v.id?"active":""} accent-${v.accent}`,onClick:()=>ac(v.id),title:v.label,type:"button",children:[r.jsx(C,{size:18}),r.jsx("span",{children:v.label})]},v.id)}),r.jsxs("button",{className:`rail-tool compact local-settings ${Vl?"active":""}`,onClick:()=>{Da("settings"),typeof window<"u"&&window.history.pushState({},"","/"),Rt(!1),He(!1),Vt(!1)},title:"Settings",type:"button",children:[r.jsx(Tp,{size:18}),r.jsx("span",{children:"Settings"})]}),r.jsxs("button",{className:`rail-account ${t?"signed-in":""}`,onClick:()=>{Rt(v=>!v)},disabled:a||it==="auth","aria-expanded":at,title:t?`Account: ${t.user?.email||hl}`:"Sign in with Google",type:"button",children:[t?oo?r.jsx("img",{src:oo,alt:hl,referrerPolicy:"no-referrer"}):r.jsx("span",{className:"avatar-fallback",children:iu}):r.jsx(jo,{size:18}),r.jsx("span",{children:t?"Account":"Google"})]}),at&&r.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[r.jsxs("div",{className:"account-popover-head",children:[r.jsx("div",{className:"account-popover-avatar",children:t&&oo?r.jsx("img",{src:oo,alt:hl,referrerPolicy:"no-referrer"}):t?r.jsx("span",{children:iu}):r.jsx(jo,{size:18})}),r.jsxs("div",{children:[r.jsx("strong",{children:t?hl:"Account"}),r.jsx("p",{children:t?.user?.email||"Not signed in"})]})]}),r.jsxs("dl",{className:"account-popover-facts",children:[r.jsx("dt",{children:"User"}),r.jsx("dd",{children:t?.user?.email||"Not signed in"}),r.jsx("dt",{children:"Network"}),r.jsx("dd",{children:yd}),r.jsx("dt",{children:"Access"}),r.jsx("dd",{children:bd}),r.jsx("dt",{children:"Plan"}),r.jsx("dd",{children:or}),r.jsx("dt",{children:"Ads"}),r.jsx("dd",{children:Wt==="free"?"Standard banner":"Removed"})]}),t?r.jsxs("button",{className:"account-popover-action",onClick:gd,disabled:it==="auth",type:"button",children:[r.jsx(vx,{size:16}),"Logout"]}):r.jsxs("button",{className:"account-popover-action primary",onClick:Nr,disabled:it==="auth",type:"button",children:[r.jsx(jo,{size:16}),"Sign in with Google"]})]})]})]}),Fe&&r.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:[r.jsxs("header",{className:"client-hub-switch-head",children:[r.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:r.jsx(Hr,{size:19})}),r.jsx("span",{className:"client-hub-switch-eyebrow",children:Dr.eyebrow}),r.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>ll(),"aria-label":Dr.closeLabel,children:r.jsx(Ra,{size:17})})]}),r.jsx("h2",{id:"hub-sync-title",children:Dr.title}),r.jsx("p",{id:"hub-sync-description",children:Dr.description}),r.jsxs("p",{id:"hub-sync-notice",className:"client-hub-switch-notice",children:[r.jsx(Kn,{size:16,"aria-hidden":"true"}),r.jsx("span",{children:Dr.restartNotice})]}),r.jsxs("div",{className:"client-hub-switch-actions",children:[r.jsx("button",{type:"button",onClick:()=>ll(),children:Dr.cancel}),r.jsxs("button",{ref:ct,className:"primary",type:"button",onClick:Zc,disabled:it==="host",children:[r.jsx(Hr,{size:16}),Dr.confirm]})]})]}),r.jsxs("section",{className:`desk-stage ${Wi&&!Bt?"dock-open":""} ${pt?"control-stage":""} ${Io?"agents-stage":""}`,children:[r.jsxs("header",{className:"topbar",children:[r.jsxs("div",{className:"brand",children:[r.jsx("span",{className:"brand-mark",children:r.jsx(Ao,{size:18})}),r.jsxs("div",{className:"brand-copy",children:[r.jsx("h1",{children:"LiveDesk"}),r.jsx("p",{children:"Control wall for local machines"})]}),xd?r.jsxs("button",{className:"topbar-update-button",onClick:()=>{Jc()},title:Dt?.error?`LiveDesk Hub update failed: ${Dt.error}`:`Update LiveDesk to ${w?.update?.latestVersion||Dt?.targetManagerVersion||"latest"}`,"aria-label":Dt?.error?`LiveDesk Hub update failed: ${Dt.error}`:pl?"LiveDesk update in progress":`Update LiveDesk to ${w?.update?.latestVersion||Dt?.targetManagerVersion||"latest"}`,type:"button",disabled:pl||!w?.update?.canApply,"aria-busy":pl,children:[pl?r.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):r.jsx(Np,{size:19,"aria-hidden":"true"}),pl&&w?.update?.targetCount?r.jsxs("span",{className:"topbar-update-count","aria-hidden":"true",children:[w.update.completedCount||0,"/",w.update.targetCount]}):null]}):null]}),r.jsxs("div",{className:"topbar-tray",children:[Wl&&!pt&&r.jsxs("div",{className:"file-share-top-route","aria-label":"File distribution route",children:[r.jsxs("div",{children:[r.jsx(So,{size:17}),r.jsxs("span",{children:[r.jsx("small",{children:"Source"}),r.jsx("strong",{children:"LiveDesk Hub"})]})]}),r.jsx(Lp,{size:15}),r.jsx(W0,{size:16}),r.jsxs("div",{children:[r.jsx("span",{className:"file-share-top-route-laptops",children:"▣ ▣ ▣"}),r.jsxs("span",{children:[r.jsx("small",{children:"Destination"}),r.jsxs("strong",{children:[qc," Client",qc===1?"":"s"]}),r.jsx("em",{children:bn.trim()||"Desktop/LiveDeskFiles"})]})]})]}),Wi&&!pt&&r.jsxs("div",{className:"top-actions",children:[r.jsx(Vb,{active:ft,refreshing:ft&&Ba,onClick:ec}),r.jsx(qb,{active:Yn,refreshing:Yn&&Ba,onClick:an}),r.jsx(Gb,{active:$,refreshing:$&&Ba,onClick:Jo}),r.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),r.jsx(Ub,{controller:gr,onError:_e}),r.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),r.jsx("div",{className:"segmented-control","aria-label":"Wall view",children:OR.map(v=>r.jsx("button",{className:nn===v.id?"active":"",onClick:()=>$s(v.id),type:"button",children:v.label},v.id))})]}),pt&&r.jsxs("div",{className:"top-actions",children:[r.jsx(Vb,{active:ft,refreshing:ft&&Ba,onClick:ec}),r.jsx(qb,{active:Yn,refreshing:Yn&&Ba,onClick:an}),r.jsx(Gb,{active:$,refreshing:$&&Ba,onClick:Jo}),r.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),r.jsx(Ub,{controller:gr,onError:_e})]})]})]}),ft&&Wi&&r.jsx(dT,{items:dm,collectedAt:Ss,onClose:()=>mn(!1)}),id?r.jsxs("section",{className:"doc-page",lang:Ge,dir:Ge==="ar"?"rtl":"ltr",children:[r.jsxs("section",{className:"doc-hero",children:[r.jsxs("div",{className:"doc-hero-copy",children:[r.jsxs("span",{className:"pricing-eyebrow",children:[r.jsx(If,{size:16}),zn.eyebrow]}),r.jsx("h2",{children:zn.title}),r.jsx("p",{children:zn.intro})]}),r.jsxs("label",{className:"doc-language-picker",children:[r.jsxs("span",{children:[r.jsx(K0,{size:17}),zn.languageLabel]}),r.jsx("select",{value:Ge,onChange:v=>vt(v.target.value),children:$R.map(v=>r.jsx("option",{value:v.id,children:v.label},v.id))})]})]}),r.jsx("section",{className:"doc-grid",children:zn.sections.map((v,C)=>{const P=[Hr,sp,Sy,Kn,Vf][C]||If;return r.jsxs("article",{className:"doc-card",children:[r.jsx("div",{className:"doc-card-icon",children:r.jsx(P,{size:19})}),r.jsxs("div",{children:[r.jsx("h3",{children:v.title}),r.jsx("p",{children:v.body}),r.jsx("ul",{children:v.points.map(D=>r.jsx("li",{children:D},D))})]})]},v.title)})}),ml&&r.jsxs("section",{className:"doc-sync",children:[r.jsxs("div",{className:"doc-sync-head",children:[r.jsx(Sy,{size:20}),r.jsxs("div",{children:[r.jsx("h3",{children:ml.title}),r.jsx("p",{children:ml.body})]})]}),r.jsx("ul",{children:ml.points.map(v=>r.jsx("li",{children:v},v))})]}),r.jsxs("section",{className:"doc-firewall",children:[r.jsxs("div",{className:"doc-firewall-head",children:[r.jsx(Kn,{size:20}),r.jsxs("div",{children:[r.jsx("h3",{children:zn.firewall.title}),r.jsx("p",{children:zn.firewall.body})]})]}),r.jsx("ul",{children:zn.firewall.points.map(v=>r.jsx("li",{children:v},v))})]}),r.jsxs("section",{className:"doc-command-panel",children:[r.jsxs("div",{className:"doc-command-head",children:[r.jsx(sp,{size:20}),r.jsxs("div",{children:[r.jsx("h3",{children:zn.commands.title}),r.jsx("p",{children:zn.commands.body})]})]}),r.jsxs("div",{className:"doc-command-list",children:[zn.commands.manager&&r.jsxs("div",{className:"doc-command-row",children:[r.jsx("span",{children:zn.commands.manager}),r.jsx("code",{children:eu}),r.jsx("button",{className:"icon-button",onClick:()=>Nf(eu),title:"Copy command",type:"button",children:r.jsx(bh,{size:16})})]}),r.jsxs("div",{className:"doc-command-row",children:[r.jsx("span",{children:zn.commands.primary}),r.jsx("code",{children:ul}),r.jsx("button",{className:"icon-button",onClick:()=>Nf(ul),title:"Copy command",type:"button",children:r.jsx(bh,{size:16})})]}),r.jsxs("div",{className:"doc-command-row",children:[r.jsx("span",{children:zn.commands.slot}),r.jsx("code",{children:`${ul} 3`}),r.jsx("button",{className:"icon-button",onClick:()=>Nf(`${ul} 3`),title:"Copy command",type:"button",children:r.jsx(bh,{size:16})})]})]})]})]}):Io?r.jsx(Pb,{hubUrl:T,devices:j}):Wl?r.jsx(oN,{hubUrl:T,devices:rt,localFeatureAccess:Xt,upgradeNotice:ri,remoteDirectory:bn,onRemoteDirectoryChange:en,targetMode:Xr,selectedTargetIds:Gi,onTargetModeChange:rm,onTargetToggle:v=>$c(C=>C.includes(v)?C.filter(E=>E!==v):[...C,v]),filePickerRef:Bc,folderPickerRef:Gl,onBrowserFileImport:v=>{ka(v)},onBrowserFolderImport:v=>{ka(v)},onNotice:_e,onTransferChange:v=>{if(!v){pr(null);return}const C=v.state==="failed"||v.state==="partially-failed"||v.state==="cancelled"?"failed":v.state==="completed"?"queued":v.state==="sending"?"sending":"reading";pr({id:v.id,status:C,progress:v.progress,message:v.message}),["completed","partially-failed","failed","cancelled"].includes(v.state)&&window.setTimeout(()=>pr(E=>E?.id===v.id?null:E),4500)}}):ld?r.jsx(Nx,{session:t,currentProductKey:"livedesk",appVersion:"",onSignIn:Nr}):Vl?r.jsx(Ak,{hubUrl:T,runtimeRole:w?.runtimeRole||"hub",runtimeDeviceId:w?.deviceId||"",sessionAccessToken:t?.access_token||"",pin:r.jsxs(Mk,{children:[r.jsx("div",{className:"settings-section-grid",children:r.jsxs("section",{className:"settings-section-card settings-pairing-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Pair a Client"}),r.jsx("h3",{children:"Connect another local PC"})]}),r.jsx(Ea,{size:20})]}),r.jsxs("div",{className:"settings-pin-display",children:[r.jsx("span",{children:"Hub PIN"}),r.jsx("strong",{children:lu}),r.jsxs("button",{className:"text-button ghost compact",onClick:Er,disabled:!w?.started||it==="pin",type:"button",children:[r.jsx(Di,{size:15}),it==="pin"?"Creating":"New PIN"]})]})]})}),r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"File transfer"}),r.jsx("h3",{children:"Client destination folder"})]}),r.jsx(Sc,{size:20})]}),r.jsxs("label",{className:"settings-field",children:[r.jsx("span",{children:"Remote folder"}),r.jsx("input",{value:bn,onChange:v=>en(v.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),r.jsx("p",{className:"settings-help",children:"Blank uses Desktop/LiveDeskFiles on each Client."})]})]}),agent:r.jsx(Tk,{hubUrl:T}),captureGallery:r.jsx(cT,{hubUrl:T,onToast:_e})}):Zr?r.jsxs("section",{className:"pricing-page",children:[r.jsxs("header",{className:"pricing-header",children:[r.jsxs("div",{children:[r.jsxs("span",{className:"pricing-eyebrow",children:[r.jsx(np,{size:15})," LiveDesk plans"]}),r.jsx("h2",{children:"Choose the plan that fits your wall"}),r.jsx("p",{children:"Start free with a local screen wall. Upgrade when you need ad-free monitoring, more Clients, or commercial controls."})]}),r.jsx("button",{className:"pricing-close",onClick:()=>ac("wall"),title:"Close pricing",type:"button",children:r.jsx(Ra,{size:18})})]}),r.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[r.jsx("span",{children:"Current plan"}),r.jsx("strong",{children:ni.name}),r.jsxs("small",{children:[rt.length,"/",aR(Xi)," connected devices"]})]}),r.jsxs("div",{className:"pricing-cards","aria-label":"LiveDesk plans",children:[r.jsxs("article",{className:`pricing-plan-card ${Wt==="free"?"current":""}`,children:[r.jsxs("div",{className:"pricing-plan-topline",children:[r.jsx("span",{className:"pricing-plan-badge free",children:"Free"}),r.jsx("strong",{children:"$0"})]}),r.jsx("p",{className:"pricing-plan-audience",children:vo.free.audience}),r.jsx("h3",{children:"Monitor your local wall"}),r.jsx("p",{children:vo.free.note}),r.jsxs("ul",{children:[r.jsxs("li",{children:[r.jsx(ea,{size:16})," Up to ",zu," devices"]}),r.jsxs("li",{children:[r.jsx(ea,{size:16})," Live view and local control"]}),r.jsxs("li",{children:[r.jsx(ea,{size:16})," Standard ad-supported banner"]})]}),r.jsx("span",{className:"pricing-current-label",children:Wt==="free"?"Current plan":"Included for everyone"})]}),r.jsxs("article",{className:`pricing-plan-card featured ${Wt==="ltd"?"current":""}`,children:[r.jsxs("div",{className:"pricing-plan-topline",children:[r.jsxs("span",{className:"pricing-plan-badge plus",children:[r.jsx(Y0,{size:14})," Plus"]}),r.jsx("strong",{children:"$5"})]}),r.jsx("p",{className:"pricing-plan-audience",children:vo.ltd.audience}),r.jsx("h3",{children:"Ad-free monitoring"}),r.jsx("p",{children:"More room for personal AI Clients without the standard banner."}),r.jsxs("ul",{children:[r.jsxs("li",{children:[r.jsx(ea,{size:16})," Up to ",Ou," devices"]}),r.jsxs("li",{children:[r.jsx(ea,{size:16})," No standard ad banner"]}),r.jsxs("li",{children:[r.jsx(ea,{size:16})," ",vo.ltd.ltd]})]}),r.jsxs("button",{className:"pricing-plan-button",onClick:t?()=>Ds("ltd"):Nr,disabled:Wt!=="free"||it==="checkout"||it==="auth"||a||L,type:"button",children:[r.jsx($u,{size:16}),Wt==="free"?t?"Choose Plus":"Sign in for Plus":"Plus active"]})]}),r.jsxs("article",{className:`pricing-plan-card pro ${Wt==="pro"?"current":""}`,children:[r.jsxs("div",{className:"pricing-plan-topline",children:[r.jsxs("span",{className:"pricing-plan-badge pro",children:[r.jsx(Kn,{size:14})," Pro"]}),r.jsx("strong",{children:"$15"})]}),r.jsx("p",{className:"pricing-plan-audience",children:vo.pro.audience}),r.jsx("h3",{children:"For serious operations"}),r.jsx("p",{children:"Commercial-ready monitoring for larger AI labs, studios, and teams."}),r.jsxs("ul",{children:[r.jsxs("li",{children:[r.jsx(ea,{size:16})," 30+ Client walls"]}),r.jsxs("li",{children:[r.jsx(ea,{size:16})," Commercial use included"]}),r.jsxs("li",{children:[r.jsx(ea,{size:16})," ",vo.pro.ltd]})]}),r.jsxs("button",{className:"pricing-plan-button",onClick:t?()=>Ds("pro"):Nr,disabled:Wt==="pro"||it==="checkout"||it==="auth"||a||L,type:"button",children:[r.jsx($u,{size:16}),Wt==="pro"?"Pro active":t?"Choose Pro":"Sign in for Pro"]})]})]}),r.jsxs("section",{className:"pricing-includes",children:[r.jsxs("div",{children:[r.jsx(Ea,{size:17}),r.jsx("span",{children:"Screen wall"}),r.jsx("strong",{children:"120+ slots"})]}),r.jsxs("div",{children:[r.jsx(ap,{size:17}),r.jsx("span",{children:"Focused control"}),r.jsx("strong",{children:"Local-first"})]}),r.jsxs("div",{children:[r.jsx(Cy,{size:17}),r.jsx("span",{children:"Remote audio"}),r.jsx("strong",{children:"Available"})]}),r.jsxs("div",{children:[r.jsx(Sc,{size:17}),r.jsx("span",{children:"File transfer"}),r.jsx("strong",{children:"Included"})]})]}),r.jsxs("p",{className:"pricing-note",children:[r.jsx(ea,{size:15})," Commercial use requires Pro. Plus LTD is for personal, creator, and homelab use."]}),r.jsxs("button",{className:"pricing-primary-cta",onClick:t?()=>Ds(Wt==="ltd"?"pro":"ltd"):Nr,disabled:su,type:"button",children:[r.jsx($u,{size:18}),au]})]}):r.jsx(r.Fragment,{children:r.jsxs("section",{className:`monitor-layout ${Bt?"dock-collapsed":""}`,children:[r.jsxs("section",{ref:sd,className:`screen-wall-panel ${Fc?"drop-active":""}`,onClick:v=>{v.currentTarget===v.target&&gi()},onDragEnter:v=>{v.preventDefault(),Pc(!0)},onDragOver:v=>{v.preventDefault(),v.dataTransfer.dropEffect="copy"},onDragLeave:v=>{v.currentTarget===v.target&&Pc(!1)},onDrop:Za,children:[qn.length>0&&r.jsx("canvas",{ref:yr,className:"atlas-source-canvas",width:br?.width||1920,height:br?.height||1080,"aria-hidden":"true"}),pt?r.jsx("section",{className:"control-focus",children:r.jsxs("div",{className:"control-wall",children:[Ie&&_s.length>1&&r.jsx("div",{className:"control-monitor-tabs","aria-label":"Select monitor",children:_s.map(v=>r.jsxs("button",{className:v.index===yi?"active":"",onClick:()=>ao(Ie.deviceId,v.index),title:bR(v),type:"button",children:[r.jsx("span",{children:v.name||`Display ${v.index+1}`}),v.width>0&&v.height>0&&r.jsxs("small",{children:[v.width,"x",v.height]})]},v.index))}),Ie&&Xa&&r.jsx("div",{className:"control-modifier-bar","aria-label":"Hold remote modifier keys",children:$T.map(v=>{const C=v.code==="MetaLeft"&&Ei(Ie.platform)?"Cmd":v.label,E=te.includes(v.code);return r.jsx("button",{className:E?"active":"",type:"button","aria-pressed":E,title:`Hold ${C} on the remote computer`,onClick:()=>mt.current?.(v.code),children:C},v.code)})}),Ie?r.jsx(Jh,{device:Ie,frame:Me,selected:!1,controlEnabled:Js&&Re&&Xa,showStatus:At.showScreenStatus,monitorIndex:Hs(Ie,Ht[Ie.deviceId]),monitorCount:El(Ie),onSelect:()=>{},onFocusDevice:()=>K(Ie.deviceId),onOpenControl:()=>ol(Ie.deviceId),onCycleMonitor:v=>vi(Ie.deviceId,v),onCanvasReady:Ka,sendInput:jr,remoteModifierState:Wo,presentationReady:$i,remoteDiagnostics:$?ro.get(Ie.deviceId):Yn?fl.get(Ie.deviceId):void 0,diagnosticsMode:$?"debug":"remote"},Ie.deviceId):r.jsxs("div",{className:"control-empty",children:[r.jsx(Ea,{size:30}),r.jsx("strong",{children:"No Client"}),r.jsx("span",{children:"Open a Client from the Wall."})]}),Ie&&Kl&&r.jsxs("div",{className:"control-connection-overlay",role:"alert",children:[r.jsx(Kn,{size:22,"aria-hidden":"true"}),r.jsx("strong",{children:"Accessibility permission required"}),r.jsx("small",{children:"On the Mac, allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client."})]}),Ie&&!Kl&&!$i&&r.jsxs("div",{className:"control-connection-overlay",role:"status","aria-live":"polite",children:[W!=="error"&&r.jsx("span",{className:"control-connection-spinner","aria-hidden":"true"}),r.jsx("strong",{children:W==="error"?"Connection failed":"Connecting"}),r.jsx("small",{children:W==="error"?"See the notification for details. Reopen Control to retry.":ci||de?"Control stream is recovering. See the notification for details.":Jl==="open"?"Preparing the first control frame":"Opening the Control stream"})]})]})}):nn==="list"?r.jsxs("div",{className:"wall-device-list",role:"grid","aria-label":"Computer status list",children:[r.jsxs("div",{className:"wall-device-list-head",role:"row",children:[r.jsx("span",{role:"columnheader",children:"Computer"}),r.jsx("span",{role:"columnheader",children:"Status"}),r.jsx("span",{role:"columnheader",children:"CPU"}),r.jsx("span",{role:"columnheader",children:"GPU"}),r.jsx("span",{role:"columnheader",children:"RAM"}),r.jsx("span",{role:"columnheader",children:"VRAM"}),r.jsx("span",{role:"columnheader",children:"Network"}),r.jsx("span",{role:"columnheader",children:"HDD"}),r.jsx("span",{role:"columnheader",children:"Temp"})]}),od.length>0?od.map(({device:v,slotNumber:C})=>r.jsx(qR,{device:v,slotNumber:C,selected:An.has(v.deviceId),updateIndicator:sc(v.deviceId),onSelect:()=>pi(v.deviceId),onOpenControl:()=>ol(v.deviceId)},v.deviceId)):r.jsxs("div",{className:"wall-device-list-empty",children:[r.jsx(Ea,{size:24,"aria-hidden":"true"}),r.jsx("strong",{children:"No connected computers"})]})]}):Mt?r.jsx("div",{className:`screen-wall atlas-slot-wall size-${nn}`,onClick:v=>{v.currentTarget===v.target&&gi()},children:ei.map((v,C)=>v?r.jsx(Jh,{device:v,frame:Ha.get(v.deviceId),selected:An.has(v.deviceId),controlEnabled:!1,showStatus:Ke.showScreenStatus,monitorIndex:Hs(v,Ht[v.deviceId]),monitorCount:El(v),onSelect:()=>pi(v.deviceId),onFocusDevice:()=>Es(v.deviceId),onOpenControl:()=>ol(v.deviceId),onCycleMonitor:E=>vi(v.deviceId,E),onCanvasReady:Lu({mode4Enabled:Mt,directMode4WallEnabled:Wa,isMac:Ei(v.platform)})==="direct"?Yc:Ms,sendInput:jr,remoteModifierState:Wo,updateIndicator:sc(v.deviceId),presentationReady:Ke.autoStartLive&&Sa.includes(v.deviceId)?_c.has(v.deviceId):void 0,showPresentationSpinner:Ke.autoStartLive&&Sa.includes(v.deviceId),remoteDiagnostics:$?ro.get(v.deviceId):Yn?fl.get(v.deviceId):void 0,diagnosticsMode:$?"debug":"remote"},v.deviceId):r.jsx(hx,{index:C},`slot-${C}`))}):r.jsx("div",{className:`screen-wall size-${nn}`,onClick:v=>{v.currentTarget===v.target&&gi()},children:ei.map((v,C)=>v?r.jsx(Jh,{device:v,frame:Ha.get(v.deviceId),selected:An.has(v.deviceId),controlEnabled:Js&&Re&&Xa&&Ie?.deviceId===v.deviceId,showStatus:Ke.showScreenStatus,monitorIndex:Hs(v,Ht[v.deviceId]),monitorCount:El(v),onSelect:()=>pi(v.deviceId),onFocusDevice:()=>Es(v.deviceId),onOpenControl:()=>ol(v.deviceId),onCycleMonitor:E=>vi(v.deviceId,E),onCanvasReady:Yc,sendInput:jr,remoteModifierState:Wo,updateIndicator:sc(v.deviceId),presentationReady:Ke.autoStartLive&&Sa.includes(v.deviceId)?_c.has(v.deviceId):void 0,showPresentationSpinner:Ke.autoStartLive&&Sa.includes(v.deviceId),remoteDiagnostics:$?ro.get(v.deviceId):Yn?fl.get(v.deviceId):void 0,diagnosticsMode:$?"debug":"remote"},v.deviceId):r.jsx(hx,{index:C},`slot-${C}`))}),r.jsx(WR,{visible:um&&!pt})]}),!Vl&&r.jsxs("aside",{className:`right-dock actions-mode ${Bt?"collapsed":""}`,"aria-label":"LiveDesk tools",children:[r.jsx("button",{className:"dock-toggle",onClick:()=>Vt(v=>!v),"aria-label":Bt?"Show control panel":"Hide control panel",title:Bt?"Show control panel":"Hide control panel",type:"button",children:Bt?r.jsx(Ax,{size:18}):r.jsx(_p,{size:18})}),!Bt&&r.jsxs(r.Fragment,{children:[r.jsxs("section",{className:"action-dock",children:[r.jsx("input",{ref:rd,className:"hidden-file-input",type:"file",multiple:!0,onChange:v=>{v.currentTarget.files&&Zo(v.currentTarget.files),v.currentTarget.value=""}}),r.jsxs("div",{className:"manual-action-bar",role:"toolbar","aria-label":"Manual Client controls",children:[r.jsx(go,{label:"Control",tooltip:Ie?Kl?"Allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client.":Js?Xa?"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(pt&&Re){He(!1),_e("Remote control paused. Screen viewing stays on.");return}ol(Ie.deviceId)}},disabled:!Js||!!pe,active:Re,pressed:pt&&Re,children:r.jsx(ap,{size:17})}),r.jsx(go,{label:"Audio",tooltip:Ie?Zs?ne?"Stop hearing this Client":"Hear this Client":"Audio is not available on this Client":"Select a Client to use Audio",onClick:()=>{vd()},disabled:!dd||!!pe,active:ne,pressed:ne,children:pe==="audio"?r.jsx(zr,{className:"spin",size:17}):r.jsx(Cy,{size:17})}),r.jsx(go,{label:Ho?"Retry pause":Zi?"Resume video":"Pause video",tooltip:Ie?Ho?"Retry stopping Client screen capture and wait for FFmpeg shutdown confirmation":Zi?"Resume Client screen capture and video encoding":"Pause Client screen capture and stop FFmpeg encoding":"Select a Client to pause video",onClick:()=>{cl()},disabled:!Ie||!Xt||!!pe,active:Zi,pressed:Zi,children:pe==="video"?r.jsx(zr,{className:"spin",size:17}):Zi&&!Ho?r.jsx(Q0,{size:17}):r.jsx(X0,{size:17})}),r.jsx(go,{label:"Send files",tooltip:Un.length===0&&!pt?"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:()=>{_e(`Choose files to send to ${nc}.`),rd.current?.click()},disabled:!!pe||!Xt||(pt?!Ie:Un.length===0),children:r.jsx(Sc,{size:17})}),r.jsx(go,{label:"Restart",tooltip:Ie?Wc?"Restart Client":"Restart is not available on this Client":"Select a Client to restart",onClick:()=>{Qo("restart")},disabled:!Ie||!Xt||!!pe||!Wc,children:pe==="restart"?r.jsx(zr,{className:"spin",size:17}):r.jsx(Ep,{size:17})}),r.jsx(go,{label:"Sleep",tooltip:Ie?"Put Client to sleep":"Select a Client to put to sleep",onClick:()=>{Qo("sleep")},disabled:!Ie||!Xt||!!pe,children:pe==="sleep"?r.jsx(zr,{className:"spin",size:17}):r.jsx(Z0,{size:17})}),r.jsx(go,{label:"Shut down",tooltip:Ie?"Shut down Client":"Select a Client to shut down",onClick:()=>{Qo("shutdown")},disabled:!Ie||!Xt||!!pe,danger:!0,children:pe==="shutdown"?r.jsx(zr,{className:"spin",size:17}):r.jsx(J0,{size:17})})]})]}),r.jsx(Pb,{hubUrl:T,devices:j,variant:"dock",selectedDeviceIds:lo})]})]})]})})]}),Qr&&r.jsxs("aside",{className:`transfer-bar state-${Qr.status}`,"aria-live":"polite",children:[r.jsx("span",{className:"transfer-bar-icon","aria-hidden":"true",children:Qr.status==="queued"?r.jsx(ea,{size:18}):Qr.status==="failed"?r.jsx(Ra,{size:18}):r.jsx(Sx,{size:18})}),r.jsxs("div",{className:"transfer-bar-copy",children:[r.jsx("p",{children:Qr.message}),r.jsx("div",{className:"transfer-bar-track",children:r.jsx("span",{style:{width:`${Math.max(0,Math.min(100,Qr.progress))}%`}})})]}),r.jsxs("strong",{children:[Math.max(0,Math.min(100,Qr.progress)),"%"]})]}),yn&&r.jsxs("aside",{className:`livedesk-toast tone-${yn.tone}`,role:yn.tone==="error"?"alert":"status","aria-live":yn.tone==="error"?"assertive":"polite","aria-busy":yn.tone==="progress",children:[yn.tone==="progress"&&r.jsx("span",{className:"livedesk-toast-spinner","aria-hidden":"true"}),r.jsx("span",{children:yn.message}),r.jsx("button",{className:"livedesk-toast-close",onClick:()=>_e(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:r.jsx(Ra,{size:15})})]})]})}function YR(){if(typeof window>"u")return[];const t=window.location.origin;return window.location.port==="5179"?[t]:["http://127.0.0.1:5179"]}function QR(){const[a,i]=d.useState(null);return d.useEffect(()=>{let l=!1,c=!1;const u=async()=>{for(const g of YR())try{const y=await fetch(`${g}/api/runtime`,{cache:"no-store"});if(!y.ok)continue;const b=(await y.json()).role==="hub"?"hub":"client";c=!0,l||i(b);return}catch{}};u();const m=window.setInterval(()=>{u()},1e3),h=window.setTimeout(()=>{!l&&!c&&i("client")},2500);return()=>{l=!0,window.clearInterval(m),window.clearTimeout(h)}},[null]),a?a==="client"?r.jsx(i1,{}):r.jsx(KR,{}):r.jsxs("main",{className:"runtime-role-boot","aria-busy":"true","aria-label":"Starting LiveDesk",children:[r.jsx("span",{className:"runtime-role-boot-mark","aria-hidden":"true"}),r.jsx("strong",{children:"Starting LiveDesk"}),r.jsx("p",{children:"Loading this computer's assigned role..."})]})}lC.createRoot(document.getElementById("root")).render(r.jsx(d.StrictMode,{children:r.jsx(QR,{})}));
|