livedesk 0.1.376 → 0.1.378

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.
@@ -0,0 +1,16 @@
1
+ import{r as NS,a as u,M as qc,S as zt,R as Ro,B as MS,P as Bm,X as Ds,b as Do,C as Pr,F as Qv,L as Rs,A as Fy,c as TS,d as Xv,E as Zv,T as ES,D as Gh,e as Ln,f as RS,g as DS,h as _S,i as LS,j as Zt,k as Wd,l as Co,m as Py,n as Al,o as Hy,p as an,q as $y,s as Uy,t as zS,u as IS,v as Kd,H as Cl,W as ko,w as OS,x as BS,y as Ao,K as No,z as qy,G as Gy,I as Qd,J as FS,N as Xc,O as Nl,Q as jo,U as Jv,V as PS,Y as HS,Z as Vh,_ as Gc,$ as Yh,a0 as $S,a1 as Wh,a2 as Vy,a3 as US,a4 as Hr,a5 as ex,a6 as Kh,a7 as lf,a8 as Yy,a9 as Fd,aa as qS,ab as Wy,ac as GS,ad as Ky,ae as VS,af as YS,ag as bh,ah as WS,ai as KS,aj as QS,ak as XS,al as ZS,am as JS,an as e0,ao as tx,ap as t0,aq as n0,ar as Pd,as as Pc,at as Hd,au as a0,av as s0,aw as gl,ax as i0,ay as nx,az as Qy,aA as ax,aB as sx,aC as r0}from"./icons-MsRY-S-W.js";import{r as Xy}from"./react-C3IPw5cG.js";import{c as l0}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 d of c)if(d.type==="childList")for(const m of d.addedNodes)m.tagName==="LINK"&&m.rel==="modulepreload"&&l(m)}).observe(document,{childList:!0,subtree:!0});function r(c){const d={};return c.integrity&&(d.integrity=c.integrity),c.referrerPolicy&&(d.referrerPolicy=c.referrerPolicy),c.crossOrigin==="use-credentials"?d.credentials="include":c.crossOrigin==="anonymous"?d.credentials="omit":d.credentials="same-origin",d}function l(c){if(c.ep)return;c.ep=!0;const d=r(c);fetch(c.href,d)}})();var Fm={exports:{}},Lc={};var ix;function o0(){if(ix)return Lc;ix=1;var n=Symbol.for("react.transitional.element"),a=Symbol.for("react.fragment");function r(l,c,d){var m=null;if(d!==void 0&&(m=""+d),c.key!==void 0&&(m=""+c.key),"key"in c){d={};for(var p in c)p!=="key"&&(d[p]=c[p])}else d=c;return c=d.ref,{$$typeof:n,type:l,key:m,ref:c!==void 0?c:null,props:d}}return Lc.Fragment=a,Lc.jsx=r,Lc.jsxs=r,Lc}var rx;function c0(){return rx||(rx=1,Fm.exports=o0()),Fm.exports}var s=c0(),Pm={exports:{}},zc={},Hm={exports:{}},$m={};var lx;function u0(){return lx||(lx=1,(function(n){function a(O,Z){var X=O.length;O.push(Z);e:for(;0<X;){var D=X-1>>>1,K=O[D];if(0<c(K,Z))O[D]=Z,O[X]=K,X=D;else break e}}function r(O){return O.length===0?null:O[0]}function l(O){if(O.length===0)return null;var Z=O[0],X=O.pop();if(X!==Z){O[0]=X;e:for(var D=0,K=O.length,ce=K>>>1;D<ce;){var W=2*(D+1)-1,P=O[W],me=W+1,pe=O[me];if(0>c(P,X))me<K&&0>c(pe,P)?(O[D]=pe,O[me]=X,D=me):(O[D]=P,O[W]=X,D=W);else if(me<K&&0>c(pe,X))O[D]=pe,O[me]=X,D=me;else break e}}return Z}function c(O,Z){var X=O.sortIndex-Z.sortIndex;return X!==0?X:O.id-Z.id}if(n.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var d=performance;n.unstable_now=function(){return d.now()}}else{var m=Date,p=m.now();n.unstable_now=function(){return m.now()-p}}var v=[],g=[],w=1,y=null,b=3,j=!1,C=!1,N=!1,T=!1,k=typeof setTimeout=="function"?setTimeout:null,E=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function $(O){for(var Z=r(g);Z!==null;){if(Z.callback===null)l(g);else if(Z.startTime<=O)l(g),Z.sortIndex=Z.expirationTime,a(v,Z);else break;Z=r(g)}}function F(O){if(N=!1,$(O),!C)if(r(v)!==null)C=!0,q||(q=!0,Q());else{var Z=r(g);Z!==null&&Y(F,Z.startTime-O)}}var q=!1,z=-1,L=5,ie=-1;function V(){return T?!0:!(n.unstable_now()-ie<L)}function ne(){if(T=!1,q){var O=n.unstable_now();ie=O;var Z=!0;try{e:{C=!1,N&&(N=!1,E(z),z=-1),j=!0;var X=b;try{t:{for($(O),y=r(v);y!==null&&!(y.expirationTime>O&&V());){var D=y.callback;if(typeof D=="function"){y.callback=null,b=y.priorityLevel;var K=D(y.expirationTime<=O);if(O=n.unstable_now(),typeof K=="function"){y.callback=K,$(O),Z=!0;break t}y===r(v)&&l(v),$(O)}else l(v);y=r(v)}if(y!==null)Z=!0;else{var ce=r(g);ce!==null&&Y(F,ce.startTime-O),Z=!1}}break e}finally{y=null,b=X,j=!1}Z=void 0}}finally{Z?Q():q=!1}}}var Q;if(typeof R=="function")Q=function(){R(ne)};else if(typeof MessageChannel<"u"){var J=new MessageChannel,le=J.port2;J.port1.onmessage=ne,Q=function(){le.postMessage(null)}}else Q=function(){k(ne,0)};function Y(O,Z){z=k(function(){O(n.unstable_now())},Z)}n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(O){O.callback=null},n.unstable_forceFrameRate=function(O){0>O||125<O?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):L=0<O?Math.floor(1e3/O):5},n.unstable_getCurrentPriorityLevel=function(){return b},n.unstable_next=function(O){switch(b){case 1:case 2:case 3:var Z=3;break;default:Z=b}var X=b;b=Z;try{return O()}finally{b=X}},n.unstable_requestPaint=function(){T=!0},n.unstable_runWithPriority=function(O,Z){switch(O){case 1:case 2:case 3:case 4:case 5:break;default:O=3}var X=b;b=O;try{return Z()}finally{b=X}},n.unstable_scheduleCallback=function(O,Z,X){var D=n.unstable_now();switch(typeof X=="object"&&X!==null?(X=X.delay,X=typeof X=="number"&&0<X?D+X:D):X=D,O){case 1:var K=-1;break;case 2:K=250;break;case 5:K=1073741823;break;case 4:K=1e4;break;default:K=5e3}return K=X+K,O={id:w++,callback:Z,priorityLevel:O,startTime:X,expirationTime:K,sortIndex:-1},X>D?(O.sortIndex=X,a(g,O),r(v)===null&&O===r(g)&&(N?(E(z),z=-1):N=!0,Y(F,X-D))):(O.sortIndex=K,a(v,O),C||j||(C=!0,q||(q=!0,Q()))),O},n.unstable_shouldYield=V,n.unstable_wrapCallback=function(O){var Z=b;return function(){var X=b;b=Z;try{return O.apply(this,arguments)}finally{b=X}}}})($m)),$m}var ox;function d0(){return ox||(ox=1,Hm.exports=u0()),Hm.exports}var cx;function f0(){if(cx)return zc;cx=1;var n=d0(),a=NS(),r=Xy();function l(e){var t="https://react.dev/errors/"+e;if(1<arguments.length){t+="?args[]="+encodeURIComponent(arguments[1]);for(var i=2;i<arguments.length;i++)t+="&args[]="+encodeURIComponent(arguments[i])}return"Minified React error #"+e+"; visit "+t+" 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 d(e){var t=e,i=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,(t.flags&4098)!==0&&(i=t.return),e=t.return;while(e)}return t.tag===3?i:null}function m(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function p(e){if(e.tag===31){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function v(e){if(d(e)!==e)throw Error(l(188))}function g(e){var t=e.alternate;if(!t){if(t=d(e),t===null)throw Error(l(188));return t!==e?null:e}for(var i=e,o=t;;){var f=i.return;if(f===null)break;var h=f.alternate;if(h===null){if(o=f.return,o!==null){i=o;continue}break}if(f.child===h.child){for(h=f.child;h;){if(h===i)return v(f),e;if(h===o)return v(f),t;h=h.sibling}throw Error(l(188))}if(i.return!==o.return)i=f,o=h;else{for(var S=!1,M=f.child;M;){if(M===i){S=!0,i=f,o=h;break}if(M===o){S=!0,o=f,i=h;break}M=M.sibling}if(!S){for(M=h.child;M;){if(M===i){S=!0,i=h,o=f;break}if(M===o){S=!0,o=h,i=f;break}M=M.sibling}if(!S)throw Error(l(189))}}if(i.alternate!==o)throw Error(l(190))}if(i.tag!==3)throw Error(l(188));return i.stateNode.current===i?e:t}function w(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e;for(e=e.child;e!==null;){if(t=w(e),t!==null)return t;e=e.sibling}return null}var y=Object.assign,b=Symbol.for("react.element"),j=Symbol.for("react.transitional.element"),C=Symbol.for("react.portal"),N=Symbol.for("react.fragment"),T=Symbol.for("react.strict_mode"),k=Symbol.for("react.profiler"),E=Symbol.for("react.consumer"),R=Symbol.for("react.context"),$=Symbol.for("react.forward_ref"),F=Symbol.for("react.suspense"),q=Symbol.for("react.suspense_list"),z=Symbol.for("react.memo"),L=Symbol.for("react.lazy"),ie=Symbol.for("react.activity"),V=Symbol.for("react.memo_cache_sentinel"),ne=Symbol.iterator;function Q(e){return e===null||typeof e!="object"?null:(e=ne&&e[ne]||e["@@iterator"],typeof e=="function"?e:null)}var J=Symbol.for("react.client.reference");function le(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===J?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case N:return"Fragment";case k:return"Profiler";case T:return"StrictMode";case F:return"Suspense";case q:return"SuspenseList";case ie:return"Activity"}if(typeof e=="object")switch(e.$$typeof){case C:return"Portal";case R:return e.displayName||"Context";case E:return(e._context.displayName||"Context")+".Consumer";case $:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case z:return t=e.displayName||null,t!==null?t:le(e.type)||"Memo";case L:t=e._payload,e=e._init;try{return le(e(t))}catch{}}return null}var Y=Array.isArray,O=a.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Z=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,X={pending:!1,data:null,method:null,action:null},D=[],K=-1;function ce(e){return{current:e}}function W(e){0>K||(e.current=D[K],D[K]=null,K--)}function P(e,t){K++,D[K]=e.current,e.current=t}var me=ce(null),pe=ce(null),ve=ce(null),ke=ce(null);function _e(e,t){switch(P(ve,t),P(pe,e),P(me,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?yv(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=yv(t),e=wv(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}W(me),P(me,e)}function Le(){W(me),W(pe),W(ve)}function ue(e){e.memoizedState!==null&&P(ke,e);var t=me.current,i=wv(t,e.type);t!==i&&(P(pe,e),P(me,i))}function Ve(e){pe.current===e&&(W(me),W(pe)),ke.current===e&&(W(ke),Ec._currentValue=X)}var Ye,oe;function Ne(e){if(Ye===void 0)try{throw Error()}catch(i){var t=i.stack.trim().match(/\n( *(at )?)/);Ye=t&&t[1]||"",oe=-1<i.stack.indexOf(`
2
+ at`)?" (<anonymous>)":-1<i.stack.indexOf("@")?"@unknown:0:0":""}return`
3
+ `+Ye+e+oe}var je=!1;function Ee(e,t){if(!e||je)return"";je=!0;var i=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var o={DetermineComponentFrameRoot:function(){try{if(t){var Se=function(){throw Error()};if(Object.defineProperty(Se.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Se,[])}catch(fe){var re=fe}Reflect.construct(e,[],Se)}else{try{Se.call()}catch(fe){re=fe}e.call(Se.prototype)}}else{try{throw Error()}catch(fe){re=fe}(Se=e())&&typeof Se.catch=="function"&&Se.catch(function(){})}}catch(fe){if(fe&&re&&typeof fe.stack=="string")return[fe.stack,re.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 h=o.DetermineComponentFrameRoot(),S=h[0],M=h[1];if(S&&M){var H=S.split(`
4
+ `),se=M.split(`
5
+ `);for(f=o=0;o<H.length&&!H[o].includes("DetermineComponentFrameRoot");)o++;for(;f<se.length&&!se[f].includes("DetermineComponentFrameRoot");)f++;if(o===H.length||f===se.length)for(o=H.length-1,f=se.length-1;1<=o&&0<=f&&H[o]!==se[f];)f--;for(;1<=o&&0<=f;o--,f--)if(H[o]!==se[f]){if(o!==1||f!==1)do if(o--,f--,0>f||H[o]!==se[f]){var xe=`
6
+ `+H[o].replace(" at new "," at ");return e.displayName&&xe.includes("<anonymous>")&&(xe=xe.replace("<anonymous>",e.displayName)),xe}while(1<=o&&0<=f);break}}}finally{je=!1,Error.prepareStackTrace=i}return(i=e?e.displayName||e.name:"")?Ne(i):""}function Re(e,t){switch(e.tag){case 26:case 27:case 5:return Ne(e.type);case 16:return Ne("Lazy");case 13:return e.child!==t&&t!==null?Ne("Suspense Fallback"):Ne("Suspense");case 19:return Ne("SuspenseList");case 0:case 15:return Ee(e.type,!1);case 11:return Ee(e.type.render,!1);case 1:return Ee(e.type,!0);case 31:return Ne("Activity");default:return""}}function Fe(e){try{var t="",i=null;do t+=Re(e,i),i=e,e=e.return;while(e);return t}catch(o){return`
7
+ Error generating stack: `+o.message+`
8
+ `+o.stack}}var he=Object.prototype.hasOwnProperty,Ae=n.unstable_scheduleCallback,de=n.unstable_cancelCallback,ye=n.unstable_shouldYield,qe=n.unstable_requestPaint,tt=n.unstable_now,pn=n.unstable_getCurrentPriorityLevel,Ke=n.unstable_ImmediatePriority,ht=n.unstable_UserBlockingPriority,St=n.unstable_NormalPriority,An=n.unstable_LowPriority,Oe=n.unstable_IdlePriority,It=n.log,Ut=n.unstable_setDisableYieldValue,pt=null,st=null;function Jt(e){if(typeof It=="function"&&Ut(e),st&&typeof st.setStrictMode=="function")try{st.setStrictMode(pt,e)}catch{}}var Nt=Math.clz32?Math.clz32:Vi,De=Math.log,Nn=Math.LN2;function Vi(e){return e>>>=0,e===0?32:31-(De(e)/Nn|0)|0}var un=256,Bn=262144,ga=4194304;function Ka(e){var t=e&42;if(t!==0)return t;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 Mn(e,t,i){var o=e.pendingLanes;if(o===0)return 0;var f=0,h=e.suspendedLanes,S=e.pingedLanes;e=e.warmLanes;var M=o&134217727;return M!==0?(o=M&~h,o!==0?f=Ka(o):(S&=M,S!==0?f=Ka(S):i||(i=M&~e,i!==0&&(f=Ka(i))))):(M=o&~h,M!==0?f=Ka(M):S!==0?f=Ka(S):i||(i=o&~e,i!==0&&(f=Ka(i)))),f===0?0:t!==0&&t!==f&&(t&h)===0&&(h=f&-f,i=t&-t,h>=i||h===32&&(i&4194048)!==0)?t:f}function Qa(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function Ie(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+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 t+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 ri(){var e=ga;return ga<<=1,(ga&62914560)===0&&(ga=4194304),e}function ut(e){for(var t=[],i=0;31>i;i++)t.push(e);return t}function Xa(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function qt(e,t,i,o,f,h){var S=e.pendingLanes;e.pendingLanes=i,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=i,e.entangledLanes&=i,e.errorRecoveryDisabledLanes&=i,e.shellSuspendCounter=0;var M=e.entanglements,H=e.expirationTimes,se=e.hiddenUpdates;for(i=S&~i;0<i;){var xe=31-Nt(i),Se=1<<xe;M[xe]=0,H[xe]=-1;var re=se[xe];if(re!==null)for(se[xe]=null,xe=0;xe<re.length;xe++){var fe=re[xe];fe!==null&&(fe.lane&=-536870913)}i&=~Se}o!==0&&zs(e,o,0),h!==0&&f===0&&e.tag!==0&&(e.suspendedLanes|=h&~(S&~t))}function zs(e,t,i){e.pendingLanes|=t,e.suspendedLanes&=~t;var o=31-Nt(t);e.entangledLanes|=t,e.entanglements[o]=e.entanglements[o]|1073741824|i&261930}function B(e,t){var i=e.entangledLanes|=t;for(e=e.entanglements;i;){var o=31-Nt(i),f=1<<o;f&t|e[o]&t&&(e[o]|=t),i&=~f}}function He(e,t){var i=t&-t;return i=(i&42)!==0?1:dt(i),(i&(e.suspendedLanes|t))!==0?0:i}function dt(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 en(e){return e&=-e,2<e?8<e?(e&134217727)!==0?32:268435456:8:2}function sn(){var e=Z.p;return e!==0?e:(e=window.event,e===void 0?32:Uv(e.type))}function Is(e,t){var i=Z.p;try{return Z.p=e,t()}finally{Z.p=i}}var na=Math.random().toString(36).slice(2),te="__reactFiber$"+na,Me="__reactProps$"+na,Pe="__reactContainer$"+na,at="__reactEvents$"+na,Wt="__reactListeners$"+na,Mt="__reactHandles$"+na,Qe="__reactResources$"+na,rt="__reactMarker$"+na;function Kt(e){delete e[te],delete e[Me],delete e[at],delete e[Wt],delete e[Mt]}function Pt(e){var t=e[te];if(t)return t;for(var i=e.parentNode;i;){if(t=i[Pe]||i[te]){if(i=t.alternate,t.child!==null||i!==null&&i.child!==null)for(e=Nv(e);e!==null;){if(i=e[te])return i;e=Nv(e)}return t}e=i,i=e.parentNode}return null}function Rt(e){if(e=e[te]||e[Pe]){var t=e.tag;if(t===5||t===6||t===13||t===31||t===26||t===27||t===3)return e}return null}function Ot(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e.stateNode;throw Error(l(33))}function Ht(e){var t=e[Qe];return t||(t=e[Qe]={hoistableStyles:new Map,hoistableScripts:new Map}),t}function Dt(e){e[rt]=!0}var Tn=new Set,Za={};function rn(e,t){Qt(e,t),Qt(e+"Capture",t)}function Qt(e,t){for(Za[e]=t,e=0;e<t.length;e++)Tn.add(t[e])}var gs=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]*$"),vs={},li={};function zo(e){return he.call(li,e)?!0:he.call(vs,e)?!1:gs.test(e)?li[e]=!0:(vs[e]=!0,!1)}function Yi(e,t,i){if(zo(t))if(i===null)e.removeAttribute(t);else{switch(typeof i){case"undefined":case"function":case"symbol":e.removeAttribute(t);return;case"boolean":var o=t.toLowerCase().slice(0,5);if(o!=="data-"&&o!=="aria-"){e.removeAttribute(t);return}}e.setAttribute(t,""+i)}}function Rl(e,t,i){if(i===null)e.removeAttribute(t);else{switch(typeof i){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(t);return}e.setAttribute(t,""+i)}}function La(e,t,i,o){if(o===null)e.removeAttribute(i);else{switch(typeof o){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(i);return}e.setAttributeNS(t,i,""+o)}}function Yn(e){switch(typeof e){case"bigint":case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function su(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function iu(e,t,i){var o=Object.getOwnPropertyDescriptor(e.constructor.prototype,t);if(!e.hasOwnProperty(t)&&typeof o<"u"&&typeof o.get=="function"&&typeof o.set=="function"){var f=o.get,h=o.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return f.call(this)},set:function(S){i=""+S,h.call(this,S)}}),Object.defineProperty(e,t,{enumerable:o.enumerable}),{getValue:function(){return i},setValue:function(S){i=""+S},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Wn(e){if(!e._valueTracker){var t=su(e)?"checked":"value";e._valueTracker=iu(e,t,""+e[t])}}function Dl(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var i=t.getValue(),o="";return e&&(o=su(e)?e.checked?"true":"false":e.value),e=o,e!==i?(t.setValue(e),!0):!1}function aa(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 za=/[\n"\\]/g;function gn(e){return e.replace(za,function(t){return"\\"+t.charCodeAt(0).toString(16)+" "})}function oi(e,t,i,o,f,h,S,M){e.name="",S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"?e.type=S:e.removeAttribute("type"),t!=null?S==="number"?(t===0&&e.value===""||e.value!=t)&&(e.value=""+Yn(t)):e.value!==""+Yn(t)&&(e.value=""+Yn(t)):S!=="submit"&&S!=="reset"||e.removeAttribute("value"),t!=null?Ki(e,S,Yn(t)):i!=null?Ki(e,S,Yn(i)):o!=null&&e.removeAttribute("value"),f==null&&h!=null&&(e.defaultChecked=!!h),f!=null&&(e.checked=f&&typeof f!="function"&&typeof f!="symbol"),M!=null&&typeof M!="function"&&typeof M!="symbol"&&typeof M!="boolean"?e.name=""+Yn(M):e.removeAttribute("name")}function Wi(e,t,i,o,f,h,S,M){if(h!=null&&typeof h!="function"&&typeof h!="symbol"&&typeof h!="boolean"&&(e.type=h),t!=null||i!=null){if(!(h!=="submit"&&h!=="reset"||t!=null)){Wn(e);return}i=i!=null?""+Yn(i):"",t=t!=null?""+Yn(t):i,M||t===e.value||(e.value=t),e.defaultValue=t}o=o??f,o=typeof o!="function"&&typeof o!="symbol"&&!!o,e.checked=M?e.checked:!!o,e.defaultChecked=!!o,S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"&&(e.name=S),Wn(e)}function Ki(e,t,i){t==="number"&&aa(e.ownerDocument)===e||e.defaultValue===""+i||(e.defaultValue=""+i)}function Ja(e,t,i,o){if(e=e.options,t){t={};for(var f=0;f<i.length;f++)t["$"+i[f]]=!0;for(i=0;i<e.length;i++)f=t.hasOwnProperty("$"+e[i].value),e[i].selected!==f&&(e[i].selected=f),f&&o&&(e[i].defaultSelected=!0)}else{for(i=""+Yn(i),t=null,f=0;f<e.length;f++){if(e[f].value===i){e[f].selected=!0,o&&(e[f].defaultSelected=!0);return}t!==null||e[f].disabled||(t=e[f])}t!==null&&(t.selected=!0)}}function ci(e,t,i){if(t!=null&&(t=""+Yn(t),t!==e.value&&(e.value=t),i==null)){e.defaultValue!==t&&(e.defaultValue=t);return}e.defaultValue=i!=null?""+Yn(i):""}function ui(e,t,i,o){if(t==null){if(o!=null){if(i!=null)throw Error(l(92));if(Y(o)){if(1<o.length)throw Error(l(93));o=o[0]}i=o}i==null&&(i=""),t=i}i=Yn(t),e.defaultValue=i,o=e.textContent,o===i&&o!==""&&o!==null&&(e.value=o),Wn(e)}function Os(e,t){if(t){var i=e.firstChild;if(i&&i===e.lastChild&&i.nodeType===3){i.nodeValue=t;return}}e.textContent=t}var Gr=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 Vr(e,t,i){var o=t.indexOf("--")===0;i==null||typeof i=="boolean"||i===""?o?e.setProperty(t,""):t==="float"?e.cssFloat="":e[t]="":o?e.setProperty(t,i):typeof i!="number"||i===0||Gr.has(t)?t==="float"?e.cssFloat=i:e[t]=(""+i).trim():e[t]=i+"px"}function Yr(e,t,i){if(t!=null&&typeof t!="object")throw Error(l(62));if(e=e.style,i!=null){for(var o in i)!i.hasOwnProperty(o)||t!=null&&t.hasOwnProperty(o)||(o.indexOf("--")===0?e.setProperty(o,""):o==="float"?e.cssFloat="":e[o]="");for(var f in t)o=t[f],t.hasOwnProperty(f)&&i[f]!==o&&Vr(e,f,o)}else for(var h in t)t.hasOwnProperty(h)&&Vr(e,h,t[h])}function Qi(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 Io=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"]]),ru=/^[\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 Ia(e){return ru.test(""+e)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":e}function Fn(){}var es=null;function Oo(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Bs=null,Wr=null;function lu(e){var t=Rt(e);if(t&&(e=t.stateNode)){var i=e[Me]||null;e:switch(e=t.stateNode,t.type){case"input":if(oi(e,i.value,i.defaultValue,i.defaultValue,i.checked,i.defaultChecked,i.type,i.name),t=i.name,i.type==="radio"&&t!=null){for(i=e;i.parentNode;)i=i.parentNode;for(i=i.querySelectorAll('input[name="'+gn(""+t)+'"][type="radio"]'),t=0;t<i.length;t++){var o=i[t];if(o!==e&&o.form===e.form){var f=o[Me]||null;if(!f)throw Error(l(90));oi(o,f.value,f.defaultValue,f.defaultValue,f.checked,f.defaultChecked,f.type,f.name)}}for(t=0;t<i.length;t++)o=i[t],o.form===e.form&&Dl(o)}break e;case"textarea":ci(e,i.value,i.defaultValue);break e;case"select":t=i.value,t!=null&&Ja(e,!!i.multiple,t,!1)}}}var Fs=!1;function ou(e,t,i){if(Fs)return e(t,i);Fs=!0;try{var o=e(t);return o}finally{if(Fs=!1,(Bs!==null||Wr!==null)&&(Qu(),Bs&&(t=Bs,e=Wr,Wr=Bs=null,lu(t),e)))for(t=0;t<e.length;t++)lu(e[t])}}function ts(e,t){var i=e.stateNode;if(i===null)return null;var o=i[Me]||null;if(o===null)return null;i=o[t];e:switch(t){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(i&&typeof i!="function")throw Error(l(231,t,typeof i));return i}var Oa=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),cu=!1;if(Oa)try{var _l={};Object.defineProperty(_l,"passive",{get:function(){cu=!0}}),window.addEventListener("test",_l,_l),window.removeEventListener("test",_l,_l)}catch{cu=!1}var di=null,Bo=null,Kr=null;function Fo(){if(Kr)return Kr;var e,t=Bo,i=t.length,o,f="value"in di?di.value:di.textContent,h=f.length;for(e=0;e<i&&t[e]===f[e];e++);var S=i-e;for(o=1;o<=S&&t[i-o]===f[h-o];o++);return Kr=f.slice(e,1<o?1-o:void 0)}function Ll(e){var t=e.keyCode;return"charCode"in e?(e=e.charCode,e===0&&t===13&&(e=13)):e=t,e===10&&(e=13),32<=e||e===13?e:0}function zl(){return!0}function uu(){return!1}function En(e){function t(i,o,f,h,S){this._reactName=i,this._targetInst=f,this.type=o,this.nativeEvent=h,this.target=S,this.currentTarget=null;for(var M in e)e.hasOwnProperty(M)&&(i=e[M],this[M]=i?i(h):h[M]);return this.isDefaultPrevented=(h.defaultPrevented!=null?h.defaultPrevented:h.returnValue===!1)?zl:uu,this.isPropagationStopped=uu,this}return y(t.prototype,{preventDefault:function(){this.defaultPrevented=!0;var i=this.nativeEvent;i&&(i.preventDefault?i.preventDefault():typeof i.returnValue!="unknown"&&(i.returnValue=!1),this.isDefaultPrevented=zl)},stopPropagation:function(){var i=this.nativeEvent;i&&(i.stopPropagation?i.stopPropagation():typeof i.cancelBubble!="unknown"&&(i.cancelBubble=!0),this.isPropagationStopped=zl)},persist:function(){},isPersistent:zl}),t}var xs={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Ps=En(xs),va=y({},xs,{view:0,detail:0}),Il=En(va),Ol,Bl,Xi,Hs=y({},va,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Us,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!==Xi&&(Xi&&e.type==="mousemove"?(Ol=e.screenX-Xi.screenX,Bl=e.screenY-Xi.screenY):Bl=Ol=0,Xi=e),Ol)},movementY:function(e){return"movementY"in e?e.movementY:Bl}}),Fl=En(Hs),du=y({},Hs,{dataTransfer:0}),et=En(du),gt=y({},va,{relatedTarget:0}),Kn=En(gt),Po=y({},xs,{animationName:0,elapsedTime:0,pseudoElement:0}),$s=En(Po),Je=y({},xs,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),fu=En(Je),gf=y({},xs,{data:0}),Qr=En(gf),Xr={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Ho={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"},Zi={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Ba(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):(e=Zi[e])?!!t[e]:!1}function Us(){return Ba}var Pn=y({},va,{key:function(e){if(e.key){var t=Xr[e.key]||e.key;if(t!=="Unidentified")return t}return e.type==="keypress"?(e=Ll(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?Ho[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Us,charCode:function(e){return e.type==="keypress"?Ll(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?Ll(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),qs=En(Pn),Te=y({},Hs,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),$o=En(Te),vf=y({},va,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Us}),ns=En(vf),xf=y({},xs,{propertyName:0,elapsedTime:0,pseudoElement:0}),Uo=En(xf),Zr=y({},Hs,{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}),mu=En(Zr),Pl=y({},xs,{newState:0,oldState:0}),hu=En(Pl),$t=[9,13,27,32],Hl=Oa&&"CompositionEvent"in window,Gs=null;Oa&&"documentMode"in document&&(Gs=document.documentMode);var fi=Oa&&"TextEvent"in window&&!Gs,pu=Oa&&(!Hl||Gs&&8<Gs&&11>=Gs),gu=" ",Gt=!1;function mi(e,t){switch(e){case"keyup":return $t.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function vu(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var hi=!1;function ys(e,t){switch(e){case"compositionend":return vu(t);case"keypress":return t.which!==32?null:(Gt=!0,gu);case"textInput":return e=t.data,e===gu&&Gt?null:e;default:return null}}function xu(e,t){if(hi)return e==="compositionend"||!Hl&&mi(e,t)?(e=Fo(),Kr=Bo=di=null,hi=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1<t.char.length)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case"compositionend":return pu&&t.locale!=="ko"?null:t.data;default:return null}}var $l={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 Jr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t==="input"?!!$l[e.type]:t==="textarea"}function Fa(e,t,i,o){Bs?Wr?Wr.push(o):Wr=[o]:Bs=o,t=ad(t,"onChange"),0<t.length&&(i=new Ps("onChange","change",null,i,o),e.push({event:i,listeners:t}))}var sa=null,as=null;function ss(e){mv(e,0)}function Hn(e){var t=Ot(e);if(Dl(t))return e}function yu(e,t){if(e==="change")return t}var qo=!1;if(Oa){var Vs;if(Oa){var Go="oninput"in document;if(!Go){var Qn=document.createElement("div");Qn.setAttribute("oninput","return;"),Go=typeof Qn.oninput=="function"}Vs=Go}else Vs=!1;qo=Vs&&(!document.documentMode||9<document.documentMode)}function pi(){sa&&(sa.detachEvent("onpropertychange",is),as=sa=null)}function is(e){if(e.propertyName==="value"&&Hn(as)){var t=[];Fa(t,as,e,Oo(e)),ou(ss,t)}}function Ji(e,t,i){e==="focusin"?(pi(),sa=t,as=i,sa.attachEvent("onpropertychange",is)):e==="focusout"&&pi()}function Ul(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return Hn(as)}function ql(e,t){if(e==="click")return Hn(t)}function ws(e,t){if(e==="input"||e==="change")return Hn(t)}function wu(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var ia=typeof Object.is=="function"?Object.is:wu;function Ys(e,t){if(ia(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;var i=Object.keys(e),o=Object.keys(t);if(i.length!==o.length)return!1;for(o=0;o<i.length;o++){var f=i[o];if(!he.call(t,f)||!ia(e[f],t[f]))return!1}return!0}function el(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function Vo(e,t){var i=el(e);e=0;for(var o;i;){if(i.nodeType===3){if(o=e+i.textContent.length,e<=t&&o>=t)return{node:i,offset:t-e};e=o}e:{for(;i;){if(i.nextSibling){i=i.nextSibling;break e}i=i.parentNode}i=void 0}i=el(i)}}function gi(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?gi(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Yo(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=aa(e.document);t instanceof e.HTMLIFrameElement;){try{var i=typeof t.contentWindow.location.href=="string"}catch{i=!1}if(i)e=t.contentWindow;else break;t=aa(e.document)}return t}function Gl(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}var yf=Oa&&"documentMode"in document&&11>=document.documentMode,Pa=null,Wo=null,er=null,Ko=!1;function bu(e,t,i){var o=i.window===i?i.document:i.nodeType===9?i:i.ownerDocument;Ko||Pa==null||Pa!==aa(o)||(o=Pa,"selectionStart"in o&&Gl(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}),er&&Ys(er,o)||(er=o,o=ad(Wo,"onSelect"),0<o.length&&(t=new Ps("onSelect","select",null,t,i),e.push({event:t,listeners:o}),t.target=Pa)))}function Ws(e,t){var i={};return i[e.toLowerCase()]=t.toLowerCase(),i["Webkit"+e]="webkit"+t,i["Moz"+e]="moz"+t,i}var tr={animationend:Ws("Animation","AnimationEnd"),animationiteration:Ws("Animation","AnimationIteration"),animationstart:Ws("Animation","AnimationStart"),transitionrun:Ws("Transition","TransitionRun"),transitionstart:Ws("Transition","TransitionStart"),transitioncancel:Ws("Transition","TransitionCancel"),transitionend:Ws("Transition","TransitionEnd")},Vl={},nr={};Oa&&(nr=document.createElement("div").style,"AnimationEvent"in window||(delete tr.animationend.animation,delete tr.animationiteration.animation,delete tr.animationstart.animation),"TransitionEvent"in window||delete tr.transitionend.transition);function Ks(e){if(Vl[e])return Vl[e];if(!tr[e])return e;var t=tr[e],i;for(i in t)if(t.hasOwnProperty(i)&&i in nr)return Vl[e]=t[i];return e}var bs=Ks("animationend"),tl=Ks("animationiteration"),vi=Ks("animationstart"),xi=Ks("transitionrun"),Qo=Ks("transitionstart"),wf=Ks("transitioncancel"),Xo=Ks("transitionend"),Yl=new Map,nl="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(" ");nl.push("scrollEnd");function $n(e,t){Yl.set(e,t),rn(t,[e])}var Wl=typeof reportError=="function"?reportError:function(e){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var t=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(t))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",e);return}console.error(e)},Un=[],yi=0,ar=0;function sr(){for(var e=yi,t=ar=yi=0;t<e;){var i=Un[t];Un[t++]=null;var o=Un[t];Un[t++]=null;var f=Un[t];Un[t++]=null;var h=Un[t];if(Un[t++]=null,o!==null&&f!==null){var S=o.pending;S===null?f.next=f:(f.next=S.next,S.next=f),o.pending=f}h!==0&&al(i,f,h)}}function ir(e,t,i,o){Un[yi++]=e,Un[yi++]=t,Un[yi++]=i,Un[yi++]=o,ar|=o,e.lanes|=o,e=e.alternate,e!==null&&(e.lanes|=o)}function rr(e,t,i,o){return ir(e,t,i,o),wi(e)}function rs(e,t){return ir(e,null,null,t),wi(e)}function al(e,t,i){e.lanes|=i;var o=e.alternate;o!==null&&(o.lanes|=i);for(var f=!1,h=e.return;h!==null;)h.childLanes|=i,o=h.alternate,o!==null&&(o.childLanes|=i),h.tag===22&&(e=h.stateNode,e===null||e._visibility&1||(f=!0)),e=h,h=h.return;return e.tag===3?(h=e.stateNode,f&&t!==null&&(f=31-Nt(i),e=h.hiddenUpdates,o=e[f],o===null?e[f]=[t]:o.push(t),t.lane=i|536870912),h):null}function wi(e){if(50<jc)throw jc=0,om=null,Error(l(185));for(var t=e.return;t!==null;)e=t,t=e.return;return e.tag===3?e.stateNode:null}var Ha={};function lr(e,t,i,o){this.tag=e,this.key=i,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=t,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 Xn(e,t,i,o){return new lr(e,t,i,o)}function Ss(e){return e=e.prototype,!(!e||!e.isReactComponent)}function xa(e,t){var i=e.alternate;return i===null?(i=Xn(e.tag,t,e.key,e.mode),i.elementType=e.elementType,i.type=e.type,i.stateNode=e.stateNode,i.alternate=e,e.alternate=i):(i.pendingProps=t,i.type=e.type,i.flags=0,i.subtreeFlags=0,i.deletions=null),i.flags=e.flags&65011712,i.childLanes=e.childLanes,i.lanes=e.lanes,i.child=e.child,i.memoizedProps=e.memoizedProps,i.memoizedState=e.memoizedState,i.updateQueue=e.updateQueue,t=e.dependencies,i.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},i.sibling=e.sibling,i.index=e.index,i.ref=e.ref,i.refCleanup=e.refCleanup,i}function sl(e,t){e.flags&=65011714;var i=e.alternate;return i===null?(e.childLanes=0,e.lanes=t,e.child=null,e.subtreeFlags=0,e.memoizedProps=null,e.memoizedState=null,e.updateQueue=null,e.dependencies=null,e.stateNode=null):(e.childLanes=i.childLanes,e.lanes=i.lanes,e.child=i.child,e.subtreeFlags=0,e.deletions=null,e.memoizedProps=i.memoizedProps,e.memoizedState=i.memoizedState,e.updateQueue=i.updateQueue,e.type=i.type,t=i.dependencies,e.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext}),e}function il(e,t,i,o,f,h){var S=0;if(o=e,typeof e=="function")Ss(e)&&(S=1);else if(typeof e=="string")S=pS(e,i,me.current)?26:e==="html"||e==="head"||e==="body"?27:5;else e:switch(e){case ie:return e=Xn(31,i,t,f),e.elementType=ie,e.lanes=h,e;case N:return Rn(i.children,f,h,t);case T:S=8,f|=24;break;case k:return e=Xn(12,i,t,f|2),e.elementType=k,e.lanes=h,e;case F:return e=Xn(13,i,t,f),e.elementType=F,e.lanes=h,e;case q:return e=Xn(19,i,t,f),e.elementType=q,e.lanes=h,e;default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case R:S=10;break e;case E:S=9;break e;case $:S=11;break e;case z:S=14;break e;case L:S=16,o=null;break e}S=29,i=Error(l(130,e===null?"null":typeof e,"")),o=null}return t=Xn(S,i,t,f),t.elementType=e,t.type=o,t.lanes=h,t}function Rn(e,t,i,o){return e=Xn(7,e,o,t),e.lanes=i,e}function Kl(e,t,i){return e=Xn(6,e,null,t),e.lanes=i,e}function or(e){var t=Xn(18,null,null,0);return t.stateNode=e,t}function bi(e,t,i){return t=Xn(4,e.children!==null?e.children:[],e.key,t),t.lanes=i,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}var Su=new WeakMap;function ra(e,t){if(typeof e=="object"&&e!==null){var i=Su.get(e);return i!==void 0?i:(t={value:e,source:t,stack:Fe(t)},Su.set(e,t),t)}return{value:e,source:t,stack:Fe(t)}}var ln=[],Si=0,cr=null,ji=0,Dn=[],ya=0,js=null,ls=1,os="";function $a(e,t){ln[Si++]=ji,ln[Si++]=cr,cr=e,ji=t}function Zo(e,t,i){Dn[ya++]=ls,Dn[ya++]=os,Dn[ya++]=js,js=e;var o=ls;e=os;var f=32-Nt(o)-1;o&=~(1<<f),i+=1;var h=32-Nt(t)+f;if(30<h){var S=f-f%5;h=(o&(1<<S)-1).toString(32),o>>=S,f-=S,ls=1<<32-Nt(t)+f|i<<f|o,os=h+e}else ls=1<<h|i<<f|o,os=e}function Ci(e){e.return!==null&&($a(e,1),Zo(e,1,0))}function Ql(e){for(;e===cr;)cr=ln[--Si],ln[Si]=null,ji=ln[--Si],ln[Si]=null;for(;e===js;)js=Dn[--ya],Dn[ya]=null,os=Dn[--ya],Dn[ya]=null,ls=Dn[--ya],Dn[ya]=null}function Xl(e,t){Dn[ya++]=ls,Dn[ya++]=os,Dn[ya++]=js,ls=t.id,os=t.overflow,js=e}var vn=null,Bt=null,ft=!1,Qs=null,wa=!1,ur=Error(l(519));function Xs(e){var t=Error(l(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw ba(ra(t,e)),ur}function Jo(e){var t=e.stateNode,i=e.type,o=e.memoizedProps;switch(t[te]=e,t[Me]=o,i){case"dialog":yt("cancel",t),yt("close",t);break;case"iframe":case"object":case"embed":yt("load",t);break;case"video":case"audio":for(i=0;i<kc.length;i++)yt(kc[i],t);break;case"source":yt("error",t);break;case"img":case"image":case"link":yt("error",t),yt("load",t);break;case"details":yt("toggle",t);break;case"input":yt("invalid",t),Wi(t,o.value,o.defaultValue,o.checked,o.defaultChecked,o.type,o.name,!0);break;case"select":yt("invalid",t);break;case"textarea":yt("invalid",t),ui(t,o.value,o.defaultValue,o.children)}i=o.children,typeof i!="string"&&typeof i!="number"&&typeof i!="bigint"||t.textContent===""+i||o.suppressHydrationWarning===!0||vv(t.textContent,i)?(o.popover!=null&&(yt("beforetoggle",t),yt("toggle",t)),o.onScroll!=null&&yt("scroll",t),o.onScrollEnd!=null&&yt("scrollend",t),o.onClick!=null&&(t.onclick=Fn),t=!0):t=!1,t||Xs(e,!0)}function ec(e){for(vn=e.return;vn;)switch(vn.tag){case 5:case 31:case 13:wa=!1;return;case 27:case 3:wa=!0;return;default:vn=vn.return}}function ki(e){if(e!==vn)return!1;if(!ft)return ec(e),ft=!0,!1;var t=e.tag,i;if((i=t!==3&&t!==27)&&((i=t===5)&&(i=e.type,i=!(i!=="form"&&i!=="button")||jm(e.type,e.memoizedProps)),i=!i),i&&Bt&&Xs(e),ec(e),t===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(l(317));Bt=Av(e)}else if(t===31){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(l(317));Bt=Av(e)}else t===27?(t=Bt,Er(e.type)?(e=Mm,Mm=null,Bt=e):Bt=t):Bt=vn?fs(e.stateNode.nextSibling):null;return!0}function Ai(){Bt=vn=null,ft=!1}function dr(){var e=Qs;return e!==null&&(Aa===null?Aa=e:Aa.push.apply(Aa,e),Qs=null),e}function ba(e){Qs===null?Qs=[e]:Qs.push(e)}var fr=ce(null),Ni=null,Ua=null;function cs(e,t,i){P(fr,t._currentValue),t._currentValue=i}function Ce(e){e._currentValue=fr.current,W(fr)}function mr(e,t,i){for(;e!==null;){var o=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,o!==null&&(o.childLanes|=t)):o!==null&&(o.childLanes&t)!==t&&(o.childLanes|=t),e===i)break;e=e.return}}function Zl(e,t,i,o){var f=e.child;for(f!==null&&(f.return=e);f!==null;){var h=f.dependencies;if(h!==null){var S=f.child;h=h.firstContext;e:for(;h!==null;){var M=h;h=f;for(var H=0;H<t.length;H++)if(M.context===t[H]){h.lanes|=i,M=h.alternate,M!==null&&(M.lanes|=i),mr(h.return,i,e),o||(S=null);break e}h=M.next}}else if(f.tag===18){if(S=f.return,S===null)throw Error(l(341));S.lanes|=i,h=S.alternate,h!==null&&(h.lanes|=i),mr(S,i,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 hr(e,t,i,o){e=null;for(var f=t,h=!1;f!==null;){if(!h){if((f.flags&524288)!==0)h=!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 M=f.type;ia(f.pendingProps.value,S.value)||(e!==null?e.push(M):e=[M])}}else if(f===ke.current){if(S=f.alternate,S===null)throw Error(l(387));S.memoizedState.memoizedState!==f.memoizedState.memoizedState&&(e!==null?e.push(Ec):e=[Ec])}f=f.return}e!==null&&Zl(t,e,i,o),t.flags|=262144}function tc(e){for(e=e.firstContext;e!==null;){if(!ia(e.context._currentValue,e.memoizedValue))return!0;e=e.next}return!1}function Cs(e){Ni=e,Ua=null,e=e.dependencies,e!==null&&(e.firstContext=null)}function jn(e){return xn(Ni,e)}function Mi(e,t){return Ni===null&&Cs(e),xn(e,t)}function xn(e,t){var i=t._currentValue;if(t={context:t,memoizedValue:i,next:null},Ua===null){if(e===null)throw Error(l(308));Ua=t,e.dependencies={lanes:0,firstContext:t},e.flags|=524288}else Ua=Ua.next=t;return i}var la=typeof AbortController<"u"?AbortController:function(){var e=[],t=this.signal={aborted:!1,addEventListener:function(i,o){e.push(o)}};this.abort=function(){t.aborted=!0,e.forEach(function(i){return i()})}},vt=n.unstable_scheduleCallback,bf=n.unstable_NormalPriority,on={$$typeof:R,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function nc(){return{controller:new la,data:new Map,refCount:0}}function rl(e){e.refCount--,e.refCount===0&&vt(bf,function(){e.controller.abort()})}var ll=null,ac=0,pr=0,gr=null;function Sf(e,t){if(ll===null){var i=ll=[];ac=0,pr=hm(),gr={status:"pending",value:void 0,then:function(o){i.push(o)}}}return ac++,t.then(ju,ju),t}function ju(){if(--ac===0&&ll!==null){gr!==null&&(gr.status="fulfilled");var e=ll;ll=null,pr=0,gr=null;for(var t=0;t<e.length;t++)(0,e[t])()}}function jf(e,t){var i=[],o={status:"pending",value:null,reason:null,then:function(f){i.push(f)}};return e.then(function(){o.status="fulfilled",o.value=t;for(var f=0;f<i.length;f++)(0,i[f])(t)},function(f){for(o.status="rejected",o.reason=f,f=0;f<i.length;f++)(0,i[f])(void 0)}),o}var Cu=O.S;O.S=function(e,t){Hg=tt(),typeof t=="object"&&t!==null&&typeof t.then=="function"&&Sf(e,t),Cu!==null&&Cu(e,t)};var Ti=ce(null);function sc(){var e=Ti.current;return e!==null?e:Ft.pooledCache}function Jl(e,t){t===null?P(Ti,Ti.current):P(Ti,t.pool)}function ku(){var e=sc();return e===null?null:{parent:on._currentValue,pool:e}}var Zs=Error(l(460)),ol=Error(l(474)),eo=Error(l(542)),to={then:function(){}};function Au(e){return e=e.status,e==="fulfilled"||e==="rejected"}function Nu(e,t,i){switch(i=e[i],i===void 0?e.push(t):i!==t&&(t.then(Fn,Fn),t=i),t.status){case"fulfilled":return t.value;case"rejected":throw e=t.reason,Tu(e),e;default:if(typeof t.status=="string")t.then(Fn,Fn);else{if(e=Ft,e!==null&&100<e.shellSuspendCounter)throw Error(l(482));e=t,e.status="pending",e.then(function(o){if(t.status==="pending"){var f=t;f.status="fulfilled",f.value=o}},function(o){if(t.status==="pending"){var f=t;f.status="rejected",f.reason=o}})}switch(t.status){case"fulfilled":return t.value;case"rejected":throw e=t.reason,Tu(e),e}throw Ri=t,Zs}}function Ei(e){try{var t=e._init;return t(e._payload)}catch(i){throw i!==null&&typeof i=="object"&&typeof i.then=="function"?(Ri=i,Zs):i}}var Ri=null;function Mu(){if(Ri===null)throw Error(l(459));var e=Ri;return Ri=null,e}function Tu(e){if(e===Zs||e===eo)throw Error(l(483))}var vr=null,us=0;function cl(e){var t=us;return us+=1,vr===null&&(vr=[]),Nu(vr,e,t)}function Di(e,t){t=t.props.ref,e.ref=t!==void 0?t:null}function no(e,t){throw t.$$typeof===b?Error(l(525)):(e=Object.prototype.toString.call(t),Error(l(31,e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)))}function Eu(e){function t(ee,G){if(e){var ae=ee.deletions;ae===null?(ee.deletions=[G],ee.flags|=16):ae.push(G)}}function i(ee,G){if(!e)return null;for(;G!==null;)t(ee,G),G=G.sibling;return null}function o(ee){for(var G=new Map;ee!==null;)ee.key!==null?G.set(ee.key,ee):G.set(ee.index,ee),ee=ee.sibling;return G}function f(ee,G){return ee=xa(ee,G),ee.index=0,ee.sibling=null,ee}function h(ee,G,ae){return ee.index=ae,e?(ae=ee.alternate,ae!==null?(ae=ae.index,ae<G?(ee.flags|=67108866,G):ae):(ee.flags|=67108866,G)):(ee.flags|=1048576,G)}function S(ee){return e&&ee.alternate===null&&(ee.flags|=67108866),ee}function M(ee,G,ae,be){return G===null||G.tag!==6?(G=Kl(ae,ee.mode,be),G.return=ee,G):(G=f(G,ae),G.return=ee,G)}function H(ee,G,ae,be){var We=ae.type;return We===N?xe(ee,G,ae.props.children,be,ae.key):G!==null&&(G.elementType===We||typeof We=="object"&&We!==null&&We.$$typeof===L&&Ei(We)===G.type)?(G=f(G,ae.props),Di(G,ae),G.return=ee,G):(G=il(ae.type,ae.key,ae.props,null,ee.mode,be),Di(G,ae),G.return=ee,G)}function se(ee,G,ae,be){return G===null||G.tag!==4||G.stateNode.containerInfo!==ae.containerInfo||G.stateNode.implementation!==ae.implementation?(G=bi(ae,ee.mode,be),G.return=ee,G):(G=f(G,ae.children||[]),G.return=ee,G)}function xe(ee,G,ae,be,We){return G===null||G.tag!==7?(G=Rn(ae,ee.mode,be,We),G.return=ee,G):(G=f(G,ae),G.return=ee,G)}function Se(ee,G,ae){if(typeof G=="string"&&G!==""||typeof G=="number"||typeof G=="bigint")return G=Kl(""+G,ee.mode,ae),G.return=ee,G;if(typeof G=="object"&&G!==null){switch(G.$$typeof){case j:return ae=il(G.type,G.key,G.props,null,ee.mode,ae),Di(ae,G),ae.return=ee,ae;case C:return G=bi(G,ee.mode,ae),G.return=ee,G;case L:return G=Ei(G),Se(ee,G,ae)}if(Y(G)||Q(G))return G=Rn(G,ee.mode,ae,null),G.return=ee,G;if(typeof G.then=="function")return Se(ee,cl(G),ae);if(G.$$typeof===R)return Se(ee,Mi(ee,G),ae);no(ee,G)}return null}function re(ee,G,ae,be){var We=G!==null?G.key:null;if(typeof ae=="string"&&ae!==""||typeof ae=="number"||typeof ae=="bigint")return We!==null?null:M(ee,G,""+ae,be);if(typeof ae=="object"&&ae!==null){switch(ae.$$typeof){case j:return ae.key===We?H(ee,G,ae,be):null;case C:return ae.key===We?se(ee,G,ae,be):null;case L:return ae=Ei(ae),re(ee,G,ae,be)}if(Y(ae)||Q(ae))return We!==null?null:xe(ee,G,ae,be,null);if(typeof ae.then=="function")return re(ee,G,cl(ae),be);if(ae.$$typeof===R)return re(ee,G,Mi(ee,ae),be);no(ee,ae)}return null}function fe(ee,G,ae,be,We){if(typeof be=="string"&&be!==""||typeof be=="number"||typeof be=="bigint")return ee=ee.get(ae)||null,M(G,ee,""+be,We);if(typeof be=="object"&&be!==null){switch(be.$$typeof){case j:return ee=ee.get(be.key===null?ae:be.key)||null,H(G,ee,be,We);case C:return ee=ee.get(be.key===null?ae:be.key)||null,se(G,ee,be,We);case L:return be=Ei(be),fe(ee,G,ae,be,We)}if(Y(be)||Q(be))return ee=ee.get(ae)||null,xe(G,ee,be,We,null);if(typeof be.then=="function")return fe(ee,G,ae,cl(be),We);if(be.$$typeof===R)return fe(ee,G,ae,Mi(G,be),We);no(G,be)}return null}function Ue(ee,G,ae,be){for(var We=null,Ct=null,Ge=G,ct=G=0,bt=null;Ge!==null&&ct<ae.length;ct++){Ge.index>ct?(bt=Ge,Ge=null):bt=Ge.sibling;var kt=re(ee,Ge,ae[ct],be);if(kt===null){Ge===null&&(Ge=bt);break}e&&Ge&&kt.alternate===null&&t(ee,Ge),G=h(kt,G,ct),Ct===null?We=kt:Ct.sibling=kt,Ct=kt,Ge=bt}if(ct===ae.length)return i(ee,Ge),ft&&$a(ee,ct),We;if(Ge===null){for(;ct<ae.length;ct++)Ge=Se(ee,ae[ct],be),Ge!==null&&(G=h(Ge,G,ct),Ct===null?We=Ge:Ct.sibling=Ge,Ct=Ge);return ft&&$a(ee,ct),We}for(Ge=o(Ge);ct<ae.length;ct++)bt=fe(Ge,ee,ct,ae[ct],be),bt!==null&&(e&&bt.alternate!==null&&Ge.delete(bt.key===null?ct:bt.key),G=h(bt,G,ct),Ct===null?We=bt:Ct.sibling=bt,Ct=bt);return e&&Ge.forEach(function(zr){return t(ee,zr)}),ft&&$a(ee,ct),We}function Ze(ee,G,ae,be){if(ae==null)throw Error(l(151));for(var We=null,Ct=null,Ge=G,ct=G=0,bt=null,kt=ae.next();Ge!==null&&!kt.done;ct++,kt=ae.next()){Ge.index>ct?(bt=Ge,Ge=null):bt=Ge.sibling;var zr=re(ee,Ge,kt.value,be);if(zr===null){Ge===null&&(Ge=bt);break}e&&Ge&&zr.alternate===null&&t(ee,Ge),G=h(zr,G,ct),Ct===null?We=zr:Ct.sibling=zr,Ct=zr,Ge=bt}if(kt.done)return i(ee,Ge),ft&&$a(ee,ct),We;if(Ge===null){for(;!kt.done;ct++,kt=ae.next())kt=Se(ee,kt.value,be),kt!==null&&(G=h(kt,G,ct),Ct===null?We=kt:Ct.sibling=kt,Ct=kt);return ft&&$a(ee,ct),We}for(Ge=o(Ge);!kt.done;ct++,kt=ae.next())kt=fe(Ge,ee,ct,kt.value,be),kt!==null&&(e&&kt.alternate!==null&&Ge.delete(kt.key===null?ct:kt.key),G=h(kt,G,ct),Ct===null?We=kt:Ct.sibling=kt,Ct=kt);return e&&Ge.forEach(function(AS){return t(ee,AS)}),ft&&$a(ee,ct),We}function Lt(ee,G,ae,be){if(typeof ae=="object"&&ae!==null&&ae.type===N&&ae.key===null&&(ae=ae.props.children),typeof ae=="object"&&ae!==null){switch(ae.$$typeof){case j:e:{for(var We=ae.key;G!==null;){if(G.key===We){if(We=ae.type,We===N){if(G.tag===7){i(ee,G.sibling),be=f(G,ae.props.children),be.return=ee,ee=be;break e}}else if(G.elementType===We||typeof We=="object"&&We!==null&&We.$$typeof===L&&Ei(We)===G.type){i(ee,G.sibling),be=f(G,ae.props),Di(be,ae),be.return=ee,ee=be;break e}i(ee,G);break}else t(ee,G);G=G.sibling}ae.type===N?(be=Rn(ae.props.children,ee.mode,be,ae.key),be.return=ee,ee=be):(be=il(ae.type,ae.key,ae.props,null,ee.mode,be),Di(be,ae),be.return=ee,ee=be)}return S(ee);case C:e:{for(We=ae.key;G!==null;){if(G.key===We)if(G.tag===4&&G.stateNode.containerInfo===ae.containerInfo&&G.stateNode.implementation===ae.implementation){i(ee,G.sibling),be=f(G,ae.children||[]),be.return=ee,ee=be;break e}else{i(ee,G);break}else t(ee,G);G=G.sibling}be=bi(ae,ee.mode,be),be.return=ee,ee=be}return S(ee);case L:return ae=Ei(ae),Lt(ee,G,ae,be)}if(Y(ae))return Ue(ee,G,ae,be);if(Q(ae)){if(We=Q(ae),typeof We!="function")throw Error(l(150));return ae=We.call(ae),Ze(ee,G,ae,be)}if(typeof ae.then=="function")return Lt(ee,G,cl(ae),be);if(ae.$$typeof===R)return Lt(ee,G,Mi(ee,ae),be);no(ee,ae)}return typeof ae=="string"&&ae!==""||typeof ae=="number"||typeof ae=="bigint"?(ae=""+ae,G!==null&&G.tag===6?(i(ee,G.sibling),be=f(G,ae),be.return=ee,ee=be):(i(ee,G),be=Kl(ae,ee.mode,be),be.return=ee,ee=be),S(ee)):i(ee,G)}return function(ee,G,ae,be){try{us=0;var We=Lt(ee,G,ae,be);return vr=null,We}catch(Ge){if(Ge===Zs||Ge===eo)throw Ge;var Ct=Xn(29,Ge,null,ee.mode);return Ct.lanes=be,Ct.return=ee,Ct}}}var Js=Eu(!0),ul=Eu(!1),ks=!1;function Cn(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function xr(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function As(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function ei(e,t,i){var o=e.updateQueue;if(o===null)return null;if(o=o.shared,(At&2)!==0){var f=o.pending;return f===null?t.next=t:(t.next=f.next,f.next=t),o.pending=t,t=wi(e),al(e,null,i),t}return ir(e,o,t,i),wi(e)}function ao(e,t,i){if(t=t.updateQueue,t!==null&&(t=t.shared,(i&4194048)!==0)){var o=t.lanes;o&=e.pendingLanes,i|=o,t.lanes=i,B(e,i)}}function ic(e,t){var i=e.updateQueue,o=e.alternate;if(o!==null&&(o=o.updateQueue,i===o)){var f=null,h=null;if(i=i.firstBaseUpdate,i!==null){do{var S={lane:i.lane,tag:i.tag,payload:i.payload,callback:null,next:null};h===null?f=h=S:h=h.next=S,i=i.next}while(i!==null);h===null?f=h=t:h=h.next=t}else f=h=t;i={baseState:o.baseState,firstBaseUpdate:f,lastBaseUpdate:h,shared:o.shared,callbacks:o.callbacks},e.updateQueue=i;return}e=i.lastBaseUpdate,e===null?i.firstBaseUpdate=t:e.next=t,i.lastBaseUpdate=t}var rc=!1;function yr(){if(rc){var e=gr;if(e!==null)throw e}}function ti(e,t,i,o){rc=!1;var f=e.updateQueue;ks=!1;var h=f.firstBaseUpdate,S=f.lastBaseUpdate,M=f.shared.pending;if(M!==null){f.shared.pending=null;var H=M,se=H.next;H.next=null,S===null?h=se:S.next=se,S=H;var xe=e.alternate;xe!==null&&(xe=xe.updateQueue,M=xe.lastBaseUpdate,M!==S&&(M===null?xe.firstBaseUpdate=se:M.next=se,xe.lastBaseUpdate=H))}if(h!==null){var Se=f.baseState;S=0,xe=se=H=null,M=h;do{var re=M.lane&-536870913,fe=re!==M.lane;if(fe?(wt&re)===re:(o&re)===re){re!==0&&re===pr&&(rc=!0),xe!==null&&(xe=xe.next={lane:0,tag:M.tag,payload:M.payload,callback:null,next:null});e:{var Ue=e,Ze=M;re=t;var Lt=i;switch(Ze.tag){case 1:if(Ue=Ze.payload,typeof Ue=="function"){Se=Ue.call(Lt,Se,re);break e}Se=Ue;break e;case 3:Ue.flags=Ue.flags&-65537|128;case 0:if(Ue=Ze.payload,re=typeof Ue=="function"?Ue.call(Lt,Se,re):Ue,re==null)break e;Se=y({},Se,re);break e;case 2:ks=!0}}re=M.callback,re!==null&&(e.flags|=64,fe&&(e.flags|=8192),fe=f.callbacks,fe===null?f.callbacks=[re]:fe.push(re))}else fe={lane:re,tag:M.tag,payload:M.payload,callback:M.callback,next:null},xe===null?(se=xe=fe,H=Se):xe=xe.next=fe,S|=re;if(M=M.next,M===null){if(M=f.shared.pending,M===null)break;fe=M,M=fe.next,fe.next=null,f.lastBaseUpdate=fe,f.shared.pending=null}}while(!0);xe===null&&(H=Se),f.baseState=H,f.firstBaseUpdate=se,f.lastBaseUpdate=xe,h===null&&(f.shared.lanes=0),kr|=S,e.lanes=S,e.memoizedState=Se}}function wr(e,t){if(typeof e!="function")throw Error(l(191,e));e.call(t)}function lc(e,t){var i=e.callbacks;if(i!==null)for(e.callbacks=null,e=0;e<i.length;e++)wr(i[e],t)}var br=ce(null),so=ce(0);function Ru(e,t){e=Pi,P(so,e),P(br,t),Pi=e|t.baseLanes}function oc(){P(so,Pi),P(br,br.current)}function cc(){Pi=so.current,W(br),W(so)}var oa=ce(null),Sa=null;function dn(e){var t=e.alternate;P(Vt,Vt.current&1),P(oa,e),Sa===null&&(t===null||br.current!==null||t.memoizedState!==null)&&(Sa=e)}function uc(e){P(Vt,Vt.current),P(oa,e),Sa===null&&(Sa=e)}function Du(e){e.tag===22?(P(Vt,Vt.current),P(oa,e),Sa===null&&(Sa=e)):ca()}function ca(){P(Vt,Vt.current),P(oa,oa.current)}function ua(e){W(oa),Sa===e&&(Sa=null),W(Vt)}var Vt=ce(0);function io(e){for(var t=e;t!==null;){if(t.tag===13){var i=t.memoizedState;if(i!==null&&(i=i.dehydrated,i===null||Am(i)||Nm(i)))return t}else if(t.tag===19&&(t.memoizedProps.revealOrder==="forwards"||t.memoizedProps.revealOrder==="backwards"||t.memoizedProps.revealOrder==="unstable_legacy-backwards"||t.memoizedProps.revealOrder==="together")){if((t.flags&128)!==0)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var ds=0,x=null,A=null,_=null,U=!1,I=!1,ge=!1,we=0,ze=0,Xe=null,mt=0;function it(){throw Error(l(321))}function yn(e,t){if(t===null)return!1;for(var i=0;i<t.length&&i<e.length;i++)if(!ia(e[i],t[i]))return!1;return!0}function da(e,t,i,o,f,h){return ds=h,x=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,O.H=e===null||e.memoizedState===null?Zp:Of,ge=!1,h=i(o,f),ge=!1,I&&(h=fl(t,i,o,f)),dl(e),h}function dl(e){O.H=hc;var t=A!==null&&A.next!==null;if(ds=0,_=A=x=null,U=!1,ze=0,Xe=null,t)throw Error(l(300));e===null||wn||(e=e.dependencies,e!==null&&tc(e)&&(wn=!0))}function fl(e,t,i,o){x=e;var f=0;do{if(I&&(Xe=null),ze=0,I=!1,25<=f)throw Error(l(301));if(f+=1,_=A=null,e.updateQueue!=null){var h=e.updateQueue;h.lastEffect=null,h.events=null,h.stores=null,h.memoCache!=null&&(h.memoCache.index=0)}O.H=Jp,h=t(i,o)}while(I);return h}function Cf(){var e=O.H,t=e.useState()[0];return t=typeof t.then=="function"?fc(t):t,e=e.useState()[0],(A!==null?A.memoizedState:null)!==e&&(x.flags|=1024),t}function Sr(){var e=we!==0;return we=0,e}function dc(e,t,i){t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i}function kf(e){if(U){for(e=e.memoizedState;e!==null;){var t=e.queue;t!==null&&(t.pending=null),e=e.next}U=!1}ds=0,_=A=x=null,I=!1,ze=we=0,Xe=null}function fa(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return _===null?x.memoizedState=_=e:_=_.next=e,_}function fn(){if(A===null){var e=x.alternate;e=e!==null?e.memoizedState:null}else e=A.next;var t=_===null?x.memoizedState:_.next;if(t!==null)_=t,A=e;else{if(e===null)throw x.alternate===null?Error(l(467)):Error(l(310));A=e,e={memoizedState:A.memoizedState,baseState:A.baseState,baseQueue:A.baseQueue,queue:A.queue,next:null},_===null?x.memoizedState=_=e:_=_.next=e}return _}function _u(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function fc(e){var t=ze;return ze+=1,Xe===null&&(Xe=[]),e=Nu(Xe,e,t),t=x,(_===null?t.memoizedState:_.next)===null&&(t=t.alternate,O.H=t===null||t.memoizedState===null?Zp:Of),e}function Lu(e){if(e!==null&&typeof e=="object"){if(typeof e.then=="function")return fc(e);if(e.$$typeof===R)return jn(e)}throw Error(l(438,String(e)))}function Af(e){var t=null,i=x.updateQueue;if(i!==null&&(t=i.memoCache),t==null){var o=x.alternate;o!==null&&(o=o.updateQueue,o!==null&&(o=o.memoCache,o!=null&&(t={data:o.data.map(function(f){return f.slice()}),index:0})))}if(t==null&&(t={data:[],index:0}),i===null&&(i=_u(),x.updateQueue=i),i.memoCache=t,i=t.data[t.index],i===void 0)for(i=t.data[t.index]=Array(e),o=0;o<e;o++)i[o]=V;return t.index++,i}function _i(e,t){return typeof t=="function"?t(e):t}function zu(e){var t=fn();return Nf(t,A,e)}function Nf(e,t,i){var o=e.queue;if(o===null)throw Error(l(311));o.lastRenderedReducer=i;var f=e.baseQueue,h=o.pending;if(h!==null){if(f!==null){var S=f.next;f.next=h.next,h.next=S}t.baseQueue=f=h,o.pending=null}if(h=e.baseState,f===null)e.memoizedState=h;else{t=f.next;var M=S=null,H=null,se=t,xe=!1;do{var Se=se.lane&-536870913;if(Se!==se.lane?(wt&Se)===Se:(ds&Se)===Se){var re=se.revertLane;if(re===0)H!==null&&(H=H.next={lane:0,revertLane:0,gesture:null,action:se.action,hasEagerState:se.hasEagerState,eagerState:se.eagerState,next:null}),Se===pr&&(xe=!0);else if((ds&re)===re){se=se.next,re===pr&&(xe=!0);continue}else Se={lane:0,revertLane:se.revertLane,gesture:null,action:se.action,hasEagerState:se.hasEagerState,eagerState:se.eagerState,next:null},H===null?(M=H=Se,S=h):H=H.next=Se,x.lanes|=re,kr|=re;Se=se.action,ge&&i(h,Se),h=se.hasEagerState?se.eagerState:i(h,Se)}else re={lane:Se,revertLane:se.revertLane,gesture:se.gesture,action:se.action,hasEagerState:se.hasEagerState,eagerState:se.eagerState,next:null},H===null?(M=H=re,S=h):H=H.next=re,x.lanes|=Se,kr|=Se;se=se.next}while(se!==null&&se!==t);if(H===null?S=h:H.next=M,!ia(h,e.memoizedState)&&(wn=!0,xe&&(i=gr,i!==null)))throw i;e.memoizedState=h,e.baseState=S,e.baseQueue=H,o.lastRenderedState=h}return f===null&&(o.lanes=0),[e.memoizedState,o.dispatch]}function Mf(e){var t=fn(),i=t.queue;if(i===null)throw Error(l(311));i.lastRenderedReducer=e;var o=i.dispatch,f=i.pending,h=t.memoizedState;if(f!==null){i.pending=null;var S=f=f.next;do h=e(h,S.action),S=S.next;while(S!==f);ia(h,t.memoizedState)||(wn=!0),t.memoizedState=h,t.baseQueue===null&&(t.baseState=h),i.lastRenderedState=h}return[h,o]}function xp(e,t,i){var o=x,f=fn(),h=ft;if(h){if(i===void 0)throw Error(l(407));i=i()}else i=t();var S=!ia((A||f).memoizedState,i);if(S&&(f.memoizedState=i,wn=!0),f=f.queue,Rf(bp.bind(null,o,f,e),[e]),f.getSnapshot!==t||S||_!==null&&_.memoizedState.tag&1){if(o.flags|=2048,ro(9,{destroy:void 0},wp.bind(null,o,f,i,t),null),Ft===null)throw Error(l(349));h||(ds&127)!==0||yp(o,t,i)}return i}function yp(e,t,i){e.flags|=16384,e={getSnapshot:t,value:i},t=x.updateQueue,t===null?(t=_u(),x.updateQueue=t,t.stores=[e]):(i=t.stores,i===null?t.stores=[e]:i.push(e))}function wp(e,t,i,o){t.value=i,t.getSnapshot=o,Sp(t)&&jp(e)}function bp(e,t,i){return i(function(){Sp(t)&&jp(e)})}function Sp(e){var t=e.getSnapshot;e=e.value;try{var i=t();return!ia(e,i)}catch{return!0}}function jp(e){var t=rs(e,2);t!==null&&Na(t,e,2)}function Tf(e){var t=fa();if(typeof e=="function"){var i=e;if(e=i(),ge){Jt(!0);try{i()}finally{Jt(!1)}}}return t.memoizedState=t.baseState=e,t.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:_i,lastRenderedState:e},t}function Cp(e,t,i,o){return e.baseState=i,Nf(e,A,typeof o=="function"?o:_i)}function xb(e,t,i,o,f){if(Bu(e))throw Error(l(485));if(e=t.action,e!==null){var h={payload:f,action:e,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(S){h.listeners.push(S)}};O.T!==null?i(!0):h.isTransition=!1,o(h),i=t.pending,i===null?(h.next=t.pending=h,kp(t,h)):(h.next=i.next,t.pending=i.next=h)}}function kp(e,t){var i=t.action,o=t.payload,f=e.state;if(t.isTransition){var h=O.T,S={};O.T=S;try{var M=i(f,o),H=O.S;H!==null&&H(S,M),Ap(e,t,M)}catch(se){Ef(e,t,se)}finally{h!==null&&S.types!==null&&(h.types=S.types),O.T=h}}else try{h=i(f,o),Ap(e,t,h)}catch(se){Ef(e,t,se)}}function Ap(e,t,i){i!==null&&typeof i=="object"&&typeof i.then=="function"?i.then(function(o){Np(e,t,o)},function(o){return Ef(e,t,o)}):Np(e,t,i)}function Np(e,t,i){t.status="fulfilled",t.value=i,Mp(t),e.state=i,t=e.pending,t!==null&&(i=t.next,i===t?e.pending=null:(i=i.next,t.next=i,kp(e,i)))}function Ef(e,t,i){var o=e.pending;if(e.pending=null,o!==null){o=o.next;do t.status="rejected",t.reason=i,Mp(t),t=t.next;while(t!==o)}e.action=null}function Mp(e){e=e.listeners;for(var t=0;t<e.length;t++)(0,e[t])()}function Tp(e,t){return t}function Ep(e,t){if(ft){var i=Ft.formState;if(i!==null){e:{var o=x;if(ft){if(Bt){t:{for(var f=Bt,h=wa;f.nodeType!==8;){if(!h){f=null;break t}if(f=fs(f.nextSibling),f===null){f=null;break t}}h=f.data,f=h==="F!"||h==="F"?f:null}if(f){Bt=fs(f.nextSibling),o=f.data==="F!";break e}}Xs(o)}o=!1}o&&(t=i[0])}}return i=fa(),i.memoizedState=i.baseState=t,o={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Tp,lastRenderedState:t},i.queue=o,i=Kp.bind(null,x,o),o.dispatch=i,o=Tf(!1),h=If.bind(null,x,!1,o.queue),o=fa(),f={state:t,dispatch:null,action:e,pending:null},o.queue=f,i=xb.bind(null,x,f,h,i),f.dispatch=i,o.memoizedState=e,[t,i,!1]}function Rp(e){var t=fn();return Dp(t,A,e)}function Dp(e,t,i){if(t=Nf(e,t,Tp)[0],e=zu(_i)[0],typeof t=="object"&&t!==null&&typeof t.then=="function")try{var o=fc(t)}catch(S){throw S===Zs?eo:S}else o=t;t=fn();var f=t.queue,h=f.dispatch;return i!==t.memoizedState&&(x.flags|=2048,ro(9,{destroy:void 0},yb.bind(null,f,i),null)),[o,h,e]}function yb(e,t){e.action=t}function _p(e){var t=fn(),i=A;if(i!==null)return Dp(t,i,e);fn(),t=t.memoizedState,i=fn();var o=i.queue.dispatch;return i.memoizedState=e,[t,o,!1]}function ro(e,t,i,o){return e={tag:e,create:i,deps:o,inst:t,next:null},t=x.updateQueue,t===null&&(t=_u(),x.updateQueue=t),i=t.lastEffect,i===null?t.lastEffect=e.next=e:(o=i.next,i.next=e,e.next=o,t.lastEffect=e),e}function Lp(){return fn().memoizedState}function Iu(e,t,i,o){var f=fa();x.flags|=e,f.memoizedState=ro(1|t,{destroy:void 0},i,o===void 0?null:o)}function Ou(e,t,i,o){var f=fn();o=o===void 0?null:o;var h=f.memoizedState.inst;A!==null&&o!==null&&yn(o,A.memoizedState.deps)?f.memoizedState=ro(t,h,i,o):(x.flags|=e,f.memoizedState=ro(1|t,h,i,o))}function zp(e,t){Iu(8390656,8,e,t)}function Rf(e,t){Ou(2048,8,e,t)}function wb(e){x.flags|=4;var t=x.updateQueue;if(t===null)t=_u(),x.updateQueue=t,t.events=[e];else{var i=t.events;i===null?t.events=[e]:i.push(e)}}function Ip(e){var t=fn().memoizedState;return wb({ref:t,nextImpl:e}),function(){if((At&2)!==0)throw Error(l(440));return t.impl.apply(void 0,arguments)}}function Op(e,t){return Ou(4,2,e,t)}function Bp(e,t){return Ou(4,4,e,t)}function Fp(e,t){if(typeof t=="function"){e=e();var i=t(e);return function(){typeof i=="function"?i():t(null)}}if(t!=null)return e=e(),t.current=e,function(){t.current=null}}function Pp(e,t,i){i=i!=null?i.concat([e]):null,Ou(4,4,Fp.bind(null,t,e),i)}function Df(){}function Hp(e,t){var i=fn();t=t===void 0?null:t;var o=i.memoizedState;return t!==null&&yn(t,o[1])?o[0]:(i.memoizedState=[e,t],e)}function $p(e,t){var i=fn();t=t===void 0?null:t;var o=i.memoizedState;if(t!==null&&yn(t,o[1]))return o[0];if(o=e(),ge){Jt(!0);try{e()}finally{Jt(!1)}}return i.memoizedState=[o,t],o}function _f(e,t,i){return i===void 0||(ds&1073741824)!==0&&(wt&261930)===0?e.memoizedState=t:(e.memoizedState=i,e=Ug(),x.lanes|=e,kr|=e,i)}function Up(e,t,i,o){return ia(i,t)?i:br.current!==null?(e=_f(e,i,o),ia(e,t)||(wn=!0),e):(ds&42)===0||(ds&1073741824)!==0&&(wt&261930)===0?(wn=!0,e.memoizedState=i):(e=Ug(),x.lanes|=e,kr|=e,t)}function qp(e,t,i,o,f){var h=Z.p;Z.p=h!==0&&8>h?h:8;var S=O.T,M={};O.T=M,If(e,!1,t,i);try{var H=f(),se=O.S;if(se!==null&&se(M,H),H!==null&&typeof H=="object"&&typeof H.then=="function"){var xe=jf(H,o);mc(e,t,xe,Va(e))}else mc(e,t,o,Va(e))}catch(Se){mc(e,t,{then:function(){},status:"rejected",reason:Se},Va())}finally{Z.p=h,S!==null&&M.types!==null&&(S.types=M.types),O.T=S}}function bb(){}function Lf(e,t,i,o){if(e.tag!==5)throw Error(l(476));var f=Gp(e).queue;qp(e,f,t,X,i===null?bb:function(){return Vp(e),i(o)})}function Gp(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:X,baseState:X,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_i,lastRenderedState:X},next:null};var i={};return t.next={memoizedState:i,baseState:i,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_i,lastRenderedState:i},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Vp(e){var t=Gp(e);t.next===null&&(t=e.alternate.memoizedState),mc(e,t.next.queue,{},Va())}function zf(){return jn(Ec)}function Yp(){return fn().memoizedState}function Wp(){return fn().memoizedState}function Sb(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var i=Va();e=As(i);var o=ei(t,e,i);o!==null&&(Na(o,t,i),ao(o,t,i)),t={cache:nc()},e.payload=t;return}t=t.return}}function jb(e,t,i){var o=Va();i={lane:o,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null},Bu(e)?Qp(t,i):(i=rr(e,t,i,o),i!==null&&(Na(i,e,o),Xp(i,t,o)))}function Kp(e,t,i){var o=Va();mc(e,t,i,o)}function mc(e,t,i,o){var f={lane:o,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null};if(Bu(e))Qp(t,f);else{var h=e.alternate;if(e.lanes===0&&(h===null||h.lanes===0)&&(h=t.lastRenderedReducer,h!==null))try{var S=t.lastRenderedState,M=h(S,i);if(f.hasEagerState=!0,f.eagerState=M,ia(M,S))return ir(e,t,f,0),Ft===null&&sr(),!1}catch{}if(i=rr(e,t,f,o),i!==null)return Na(i,e,o),Xp(i,t,o),!0}return!1}function If(e,t,i,o){if(o={lane:2,revertLane:hm(),gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null},Bu(e)){if(t)throw Error(l(479))}else t=rr(e,i,o,2),t!==null&&Na(t,e,2)}function Bu(e){var t=e.alternate;return e===x||t!==null&&t===x}function Qp(e,t){I=U=!0;var i=e.pending;i===null?t.next=t:(t.next=i.next,i.next=t),e.pending=t}function Xp(e,t,i){if((i&4194048)!==0){var o=t.lanes;o&=e.pendingLanes,i|=o,t.lanes=i,B(e,i)}}var hc={readContext:jn,use:Lu,useCallback:it,useContext:it,useEffect:it,useImperativeHandle:it,useLayoutEffect:it,useInsertionEffect:it,useMemo:it,useReducer:it,useRef:it,useState:it,useDebugValue:it,useDeferredValue:it,useTransition:it,useSyncExternalStore:it,useId:it,useHostTransitionStatus:it,useFormState:it,useActionState:it,useOptimistic:it,useMemoCache:it,useCacheRefresh:it};hc.useEffectEvent=it;var Zp={readContext:jn,use:Lu,useCallback:function(e,t){return fa().memoizedState=[e,t===void 0?null:t],e},useContext:jn,useEffect:zp,useImperativeHandle:function(e,t,i){i=i!=null?i.concat([e]):null,Iu(4194308,4,Fp.bind(null,t,e),i)},useLayoutEffect:function(e,t){return Iu(4194308,4,e,t)},useInsertionEffect:function(e,t){Iu(4,2,e,t)},useMemo:function(e,t){var i=fa();t=t===void 0?null:t;var o=e();if(ge){Jt(!0);try{e()}finally{Jt(!1)}}return i.memoizedState=[o,t],o},useReducer:function(e,t,i){var o=fa();if(i!==void 0){var f=i(t);if(ge){Jt(!0);try{i(t)}finally{Jt(!1)}}}else f=t;return o.memoizedState=o.baseState=f,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:f},o.queue=e,e=e.dispatch=jb.bind(null,x,e),[o.memoizedState,e]},useRef:function(e){var t=fa();return e={current:e},t.memoizedState=e},useState:function(e){e=Tf(e);var t=e.queue,i=Kp.bind(null,x,t);return t.dispatch=i,[e.memoizedState,i]},useDebugValue:Df,useDeferredValue:function(e,t){var i=fa();return _f(i,e,t)},useTransition:function(){var e=Tf(!1);return e=qp.bind(null,x,e.queue,!0,!1),fa().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,i){var o=x,f=fa();if(ft){if(i===void 0)throw Error(l(407));i=i()}else{if(i=t(),Ft===null)throw Error(l(349));(wt&127)!==0||yp(o,t,i)}f.memoizedState=i;var h={value:i,getSnapshot:t};return f.queue=h,zp(bp.bind(null,o,h,e),[e]),o.flags|=2048,ro(9,{destroy:void 0},wp.bind(null,o,h,i,t),null),i},useId:function(){var e=fa(),t=Ft.identifierPrefix;if(ft){var i=os,o=ls;i=(o&~(1<<32-Nt(o)-1)).toString(32)+i,t="_"+t+"R_"+i,i=we++,0<i&&(t+="H"+i.toString(32)),t+="_"}else i=mt++,t="_"+t+"r_"+i.toString(32)+"_";return e.memoizedState=t},useHostTransitionStatus:zf,useFormState:Ep,useActionState:Ep,useOptimistic:function(e){var t=fa();t.memoizedState=t.baseState=e;var i={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return t.queue=i,t=If.bind(null,x,!0,i),i.dispatch=t,[e,t]},useMemoCache:Af,useCacheRefresh:function(){return fa().memoizedState=Sb.bind(null,x)},useEffectEvent:function(e){var t=fa(),i={impl:e};return t.memoizedState=i,function(){if((At&2)!==0)throw Error(l(440));return i.impl.apply(void 0,arguments)}}},Of={readContext:jn,use:Lu,useCallback:Hp,useContext:jn,useEffect:Rf,useImperativeHandle:Pp,useInsertionEffect:Op,useLayoutEffect:Bp,useMemo:$p,useReducer:zu,useRef:Lp,useState:function(){return zu(_i)},useDebugValue:Df,useDeferredValue:function(e,t){var i=fn();return Up(i,A.memoizedState,e,t)},useTransition:function(){var e=zu(_i)[0],t=fn().memoizedState;return[typeof e=="boolean"?e:fc(e),t]},useSyncExternalStore:xp,useId:Yp,useHostTransitionStatus:zf,useFormState:Rp,useActionState:Rp,useOptimistic:function(e,t){var i=fn();return Cp(i,A,e,t)},useMemoCache:Af,useCacheRefresh:Wp};Of.useEffectEvent=Ip;var Jp={readContext:jn,use:Lu,useCallback:Hp,useContext:jn,useEffect:Rf,useImperativeHandle:Pp,useInsertionEffect:Op,useLayoutEffect:Bp,useMemo:$p,useReducer:Mf,useRef:Lp,useState:function(){return Mf(_i)},useDebugValue:Df,useDeferredValue:function(e,t){var i=fn();return A===null?_f(i,e,t):Up(i,A.memoizedState,e,t)},useTransition:function(){var e=Mf(_i)[0],t=fn().memoizedState;return[typeof e=="boolean"?e:fc(e),t]},useSyncExternalStore:xp,useId:Yp,useHostTransitionStatus:zf,useFormState:_p,useActionState:_p,useOptimistic:function(e,t){var i=fn();return A!==null?Cp(i,A,e,t):(i.baseState=e,[e,i.queue.dispatch])},useMemoCache:Af,useCacheRefresh:Wp};Jp.useEffectEvent=Ip;function Bf(e,t,i,o){t=e.memoizedState,i=i(o,t),i=i==null?t:y({},t,i),e.memoizedState=i,e.lanes===0&&(e.updateQueue.baseState=i)}var Ff={enqueueSetState:function(e,t,i){e=e._reactInternals;var o=Va(),f=As(o);f.payload=t,i!=null&&(f.callback=i),t=ei(e,f,o),t!==null&&(Na(t,e,o),ao(t,e,o))},enqueueReplaceState:function(e,t,i){e=e._reactInternals;var o=Va(),f=As(o);f.tag=1,f.payload=t,i!=null&&(f.callback=i),t=ei(e,f,o),t!==null&&(Na(t,e,o),ao(t,e,o))},enqueueForceUpdate:function(e,t){e=e._reactInternals;var i=Va(),o=As(i);o.tag=2,t!=null&&(o.callback=t),t=ei(e,o,i),t!==null&&(Na(t,e,i),ao(t,e,i))}};function eg(e,t,i,o,f,h,S){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(o,h,S):t.prototype&&t.prototype.isPureReactComponent?!Ys(i,o)||!Ys(f,h):!0}function tg(e,t,i,o){e=t.state,typeof t.componentWillReceiveProps=="function"&&t.componentWillReceiveProps(i,o),typeof t.UNSAFE_componentWillReceiveProps=="function"&&t.UNSAFE_componentWillReceiveProps(i,o),t.state!==e&&Ff.enqueueReplaceState(t,t.state,null)}function ml(e,t){var i=t;if("ref"in t){i={};for(var o in t)o!=="ref"&&(i[o]=t[o])}if(e=e.defaultProps){i===t&&(i=y({},i));for(var f in e)i[f]===void 0&&(i[f]=e[f])}return i}function ng(e){Wl(e)}function ag(e){console.error(e)}function sg(e){Wl(e)}function Fu(e,t){try{var i=e.onUncaughtError;i(t.value,{componentStack:t.stack})}catch(o){setTimeout(function(){throw o})}}function ig(e,t,i){try{var o=e.onCaughtError;o(i.value,{componentStack:i.stack,errorBoundary:t.tag===1?t.stateNode:null})}catch(f){setTimeout(function(){throw f})}}function Pf(e,t,i){return i=As(i),i.tag=3,i.payload={element:null},i.callback=function(){Fu(e,t)},i}function rg(e){return e=As(e),e.tag=3,e}function lg(e,t,i,o){var f=i.type.getDerivedStateFromError;if(typeof f=="function"){var h=o.value;e.payload=function(){return f(h)},e.callback=function(){ig(t,i,o)}}var S=i.stateNode;S!==null&&typeof S.componentDidCatch=="function"&&(e.callback=function(){ig(t,i,o),typeof f!="function"&&(Ar===null?Ar=new Set([this]):Ar.add(this));var M=o.stack;this.componentDidCatch(o.value,{componentStack:M!==null?M:""})})}function Cb(e,t,i,o,f){if(i.flags|=32768,o!==null&&typeof o=="object"&&typeof o.then=="function"){if(t=i.alternate,t!==null&&hr(t,i,f,!0),i=oa.current,i!==null){switch(i.tag){case 31:case 13:return Sa===null?Xu():i.alternate===null&&cn===0&&(cn=3),i.flags&=-257,i.flags|=65536,i.lanes=f,o===to?i.flags|=16384:(t=i.updateQueue,t===null?i.updateQueue=new Set([o]):t.add(o),dm(e,o,f)),!1;case 22:return i.flags|=65536,o===to?i.flags|=16384:(t=i.updateQueue,t===null?(t={transitions:null,markerInstances:null,retryQueue:new Set([o])},i.updateQueue=t):(i=t.retryQueue,i===null?t.retryQueue=new Set([o]):i.add(o)),dm(e,o,f)),!1}throw Error(l(435,i.tag))}return dm(e,o,f),Xu(),!1}if(ft)return t=oa.current,t!==null?((t.flags&65536)===0&&(t.flags|=256),t.flags|=65536,t.lanes=f,o!==ur&&(e=Error(l(422),{cause:o}),ba(ra(e,i)))):(o!==ur&&(t=Error(l(423),{cause:o}),ba(ra(t,i))),e=e.current.alternate,e.flags|=65536,f&=-f,e.lanes|=f,o=ra(o,i),f=Pf(e.stateNode,o,f),ic(e,f),cn!==4&&(cn=2)),!1;var h=Error(l(520),{cause:o});if(h=ra(h,i),Sc===null?Sc=[h]:Sc.push(h),cn!==4&&(cn=2),t===null)return!0;o=ra(o,i),i=t;do{switch(i.tag){case 3:return i.flags|=65536,e=f&-f,i.lanes|=e,e=Pf(i.stateNode,o,e),ic(i,e),!1;case 1:if(t=i.type,h=i.stateNode,(i.flags&128)===0&&(typeof t.getDerivedStateFromError=="function"||h!==null&&typeof h.componentDidCatch=="function"&&(Ar===null||!Ar.has(h))))return i.flags|=65536,f&=-f,i.lanes|=f,f=rg(f),lg(f,e,i,o),ic(i,f),!1}i=i.return}while(i!==null);return!1}var Hf=Error(l(461)),wn=!1;function qn(e,t,i,o){t.child=e===null?ul(t,null,i,o):Js(t,e.child,i,o)}function og(e,t,i,o,f){i=i.render;var h=t.ref;if("ref"in o){var S={};for(var M in o)M!=="ref"&&(S[M]=o[M])}else S=o;return Cs(t),o=da(e,t,i,S,h,f),M=Sr(),e!==null&&!wn?(dc(e,t,f),Li(e,t,f)):(ft&&M&&Ci(t),t.flags|=1,qn(e,t,o,f),t.child)}function cg(e,t,i,o,f){if(e===null){var h=i.type;return typeof h=="function"&&!Ss(h)&&h.defaultProps===void 0&&i.compare===null?(t.tag=15,t.type=h,ug(e,t,h,o,f)):(e=il(i.type,null,o,t,t.mode,f),e.ref=t.ref,e.return=t,t.child=e)}if(h=e.child,!Kf(e,f)){var S=h.memoizedProps;if(i=i.compare,i=i!==null?i:Ys,i(S,o)&&e.ref===t.ref)return Li(e,t,f)}return t.flags|=1,e=xa(h,o),e.ref=t.ref,e.return=t,t.child=e}function ug(e,t,i,o,f){if(e!==null){var h=e.memoizedProps;if(Ys(h,o)&&e.ref===t.ref)if(wn=!1,t.pendingProps=o=h,Kf(e,f))(e.flags&131072)!==0&&(wn=!0);else return t.lanes=e.lanes,Li(e,t,f)}return $f(e,t,i,o,f)}function dg(e,t,i,o){var f=o.children,h=e!==null?e.memoizedState:null;if(e===null&&t.stateNode===null&&(t.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),o.mode==="hidden"){if((t.flags&128)!==0){if(h=h!==null?h.baseLanes|i:i,e!==null){for(o=t.child=e.child,f=0;o!==null;)f=f|o.lanes|o.childLanes,o=o.sibling;o=f&~h}else o=0,t.child=null;return fg(e,t,h,i,o)}if((i&536870912)!==0)t.memoizedState={baseLanes:0,cachePool:null},e!==null&&Jl(t,h!==null?h.cachePool:null),h!==null?Ru(t,h):oc(),Du(t);else return o=t.lanes=536870912,fg(e,t,h!==null?h.baseLanes|i:i,i,o)}else h!==null?(Jl(t,h.cachePool),Ru(t,h),ca(),t.memoizedState=null):(e!==null&&Jl(t,null),oc(),ca());return qn(e,t,f,i),t.child}function pc(e,t){return e!==null&&e.tag===22||t.stateNode!==null||(t.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),t.sibling}function fg(e,t,i,o,f){var h=sc();return h=h===null?null:{parent:on._currentValue,pool:h},t.memoizedState={baseLanes:i,cachePool:h},e!==null&&Jl(t,null),oc(),Du(t),e!==null&&hr(e,t,o,!0),t.childLanes=f,null}function Pu(e,t){return t=$u({mode:t.mode,children:t.children},e.mode),t.ref=e.ref,e.child=t,t.return=e,t}function mg(e,t,i){return Js(t,e.child,null,i),e=Pu(t,t.pendingProps),e.flags|=2,ua(t),t.memoizedState=null,e}function kb(e,t,i){var o=t.pendingProps,f=(t.flags&128)!==0;if(t.flags&=-129,e===null){if(ft){if(o.mode==="hidden")return e=Pu(t,o),t.lanes=536870912,pc(null,e);if(uc(t),(e=Bt)?(e=kv(e,wa),e=e!==null&&e.data==="&"?e:null,e!==null&&(t.memoizedState={dehydrated:e,treeContext:js!==null?{id:ls,overflow:os}:null,retryLane:536870912,hydrationErrors:null},i=or(e),i.return=t,t.child=i,vn=t,Bt=null)):e=null,e===null)throw Xs(t);return t.lanes=536870912,null}return Pu(t,o)}var h=e.memoizedState;if(h!==null){var S=h.dehydrated;if(uc(t),f)if(t.flags&256)t.flags&=-257,t=mg(e,t,i);else if(t.memoizedState!==null)t.child=e.child,t.flags|=128,t=null;else throw Error(l(558));else if(wn||hr(e,t,i,!1),f=(i&e.childLanes)!==0,wn||f){if(o=Ft,o!==null&&(S=He(o,i),S!==0&&S!==h.retryLane))throw h.retryLane=S,rs(e,S),Na(o,e,S),Hf;Xu(),t=mg(e,t,i)}else e=h.treeContext,Bt=fs(S.nextSibling),vn=t,ft=!0,Qs=null,wa=!1,e!==null&&Xl(t,e),t=Pu(t,o),t.flags|=4096;return t}return e=xa(e.child,{mode:o.mode,children:o.children}),e.ref=t.ref,t.child=e,e.return=t,e}function Hu(e,t){var i=t.ref;if(i===null)e!==null&&e.ref!==null&&(t.flags|=4194816);else{if(typeof i!="function"&&typeof i!="object")throw Error(l(284));(e===null||e.ref!==i)&&(t.flags|=4194816)}}function $f(e,t,i,o,f){return Cs(t),i=da(e,t,i,o,void 0,f),o=Sr(),e!==null&&!wn?(dc(e,t,f),Li(e,t,f)):(ft&&o&&Ci(t),t.flags|=1,qn(e,t,i,f),t.child)}function hg(e,t,i,o,f,h){return Cs(t),t.updateQueue=null,i=fl(t,o,i,f),dl(e),o=Sr(),e!==null&&!wn?(dc(e,t,h),Li(e,t,h)):(ft&&o&&Ci(t),t.flags|=1,qn(e,t,i,h),t.child)}function pg(e,t,i,o,f){if(Cs(t),t.stateNode===null){var h=Ha,S=i.contextType;typeof S=="object"&&S!==null&&(h=jn(S)),h=new i(o,h),t.memoizedState=h.state!==null&&h.state!==void 0?h.state:null,h.updater=Ff,t.stateNode=h,h._reactInternals=t,h=t.stateNode,h.props=o,h.state=t.memoizedState,h.refs={},Cn(t),S=i.contextType,h.context=typeof S=="object"&&S!==null?jn(S):Ha,h.state=t.memoizedState,S=i.getDerivedStateFromProps,typeof S=="function"&&(Bf(t,i,S,o),h.state=t.memoizedState),typeof i.getDerivedStateFromProps=="function"||typeof h.getSnapshotBeforeUpdate=="function"||typeof h.UNSAFE_componentWillMount!="function"&&typeof h.componentWillMount!="function"||(S=h.state,typeof h.componentWillMount=="function"&&h.componentWillMount(),typeof h.UNSAFE_componentWillMount=="function"&&h.UNSAFE_componentWillMount(),S!==h.state&&Ff.enqueueReplaceState(h,h.state,null),ti(t,o,h,f),yr(),h.state=t.memoizedState),typeof h.componentDidMount=="function"&&(t.flags|=4194308),o=!0}else if(e===null){h=t.stateNode;var M=t.memoizedProps,H=ml(i,M);h.props=H;var se=h.context,xe=i.contextType;S=Ha,typeof xe=="object"&&xe!==null&&(S=jn(xe));var Se=i.getDerivedStateFromProps;xe=typeof Se=="function"||typeof h.getSnapshotBeforeUpdate=="function",M=t.pendingProps!==M,xe||typeof h.UNSAFE_componentWillReceiveProps!="function"&&typeof h.componentWillReceiveProps!="function"||(M||se!==S)&&tg(t,h,o,S),ks=!1;var re=t.memoizedState;h.state=re,ti(t,o,h,f),yr(),se=t.memoizedState,M||re!==se||ks?(typeof Se=="function"&&(Bf(t,i,Se,o),se=t.memoizedState),(H=ks||eg(t,i,H,o,re,se,S))?(xe||typeof h.UNSAFE_componentWillMount!="function"&&typeof h.componentWillMount!="function"||(typeof h.componentWillMount=="function"&&h.componentWillMount(),typeof h.UNSAFE_componentWillMount=="function"&&h.UNSAFE_componentWillMount()),typeof h.componentDidMount=="function"&&(t.flags|=4194308)):(typeof h.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=o,t.memoizedState=se),h.props=o,h.state=se,h.context=S,o=H):(typeof h.componentDidMount=="function"&&(t.flags|=4194308),o=!1)}else{h=t.stateNode,xr(e,t),S=t.memoizedProps,xe=ml(i,S),h.props=xe,Se=t.pendingProps,re=h.context,se=i.contextType,H=Ha,typeof se=="object"&&se!==null&&(H=jn(se)),M=i.getDerivedStateFromProps,(se=typeof M=="function"||typeof h.getSnapshotBeforeUpdate=="function")||typeof h.UNSAFE_componentWillReceiveProps!="function"&&typeof h.componentWillReceiveProps!="function"||(S!==Se||re!==H)&&tg(t,h,o,H),ks=!1,re=t.memoizedState,h.state=re,ti(t,o,h,f),yr();var fe=t.memoizedState;S!==Se||re!==fe||ks||e!==null&&e.dependencies!==null&&tc(e.dependencies)?(typeof M=="function"&&(Bf(t,i,M,o),fe=t.memoizedState),(xe=ks||eg(t,i,xe,o,re,fe,H)||e!==null&&e.dependencies!==null&&tc(e.dependencies))?(se||typeof h.UNSAFE_componentWillUpdate!="function"&&typeof h.componentWillUpdate!="function"||(typeof h.componentWillUpdate=="function"&&h.componentWillUpdate(o,fe,H),typeof h.UNSAFE_componentWillUpdate=="function"&&h.UNSAFE_componentWillUpdate(o,fe,H)),typeof h.componentDidUpdate=="function"&&(t.flags|=4),typeof h.getSnapshotBeforeUpdate=="function"&&(t.flags|=1024)):(typeof h.componentDidUpdate!="function"||S===e.memoizedProps&&re===e.memoizedState||(t.flags|=4),typeof h.getSnapshotBeforeUpdate!="function"||S===e.memoizedProps&&re===e.memoizedState||(t.flags|=1024),t.memoizedProps=o,t.memoizedState=fe),h.props=o,h.state=fe,h.context=H,o=xe):(typeof h.componentDidUpdate!="function"||S===e.memoizedProps&&re===e.memoizedState||(t.flags|=4),typeof h.getSnapshotBeforeUpdate!="function"||S===e.memoizedProps&&re===e.memoizedState||(t.flags|=1024),o=!1)}return h=o,Hu(e,t),o=(t.flags&128)!==0,h||o?(h=t.stateNode,i=o&&typeof i.getDerivedStateFromError!="function"?null:h.render(),t.flags|=1,e!==null&&o?(t.child=Js(t,e.child,null,f),t.child=Js(t,null,i,f)):qn(e,t,i,f),t.memoizedState=h.state,e=t.child):e=Li(e,t,f),e}function gg(e,t,i,o){return Ai(),t.flags|=256,qn(e,t,i,o),t.child}var Uf={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function qf(e){return{baseLanes:e,cachePool:ku()}}function Gf(e,t,i){return e=e!==null?e.childLanes&~i:0,t&&(e|=Ga),e}function vg(e,t,i){var o=t.pendingProps,f=!1,h=(t.flags&128)!==0,S;if((S=h)||(S=e!==null&&e.memoizedState===null?!1:(Vt.current&2)!==0),S&&(f=!0,t.flags&=-129),S=(t.flags&32)!==0,t.flags&=-33,e===null){if(ft){if(f?dn(t):ca(),(e=Bt)?(e=kv(e,wa),e=e!==null&&e.data!=="&"?e:null,e!==null&&(t.memoizedState={dehydrated:e,treeContext:js!==null?{id:ls,overflow:os}:null,retryLane:536870912,hydrationErrors:null},i=or(e),i.return=t,t.child=i,vn=t,Bt=null)):e=null,e===null)throw Xs(t);return Nm(e)?t.lanes=32:t.lanes=536870912,null}var M=o.children;return o=o.fallback,f?(ca(),f=t.mode,M=$u({mode:"hidden",children:M},f),o=Rn(o,f,i,null),M.return=t,o.return=t,M.sibling=o,t.child=M,o=t.child,o.memoizedState=qf(i),o.childLanes=Gf(e,S,i),t.memoizedState=Uf,pc(null,o)):(dn(t),Vf(t,M))}var H=e.memoizedState;if(H!==null&&(M=H.dehydrated,M!==null)){if(h)t.flags&256?(dn(t),t.flags&=-257,t=Yf(e,t,i)):t.memoizedState!==null?(ca(),t.child=e.child,t.flags|=128,t=null):(ca(),M=o.fallback,f=t.mode,o=$u({mode:"visible",children:o.children},f),M=Rn(M,f,i,null),M.flags|=2,o.return=t,M.return=t,o.sibling=M,t.child=o,Js(t,e.child,null,i),o=t.child,o.memoizedState=qf(i),o.childLanes=Gf(e,S,i),t.memoizedState=Uf,t=pc(null,o));else if(dn(t),Nm(M)){if(S=M.nextSibling&&M.nextSibling.dataset,S)var se=S.dgst;S=se,o=Error(l(419)),o.stack="",o.digest=S,ba({value:o,source:null,stack:null}),t=Yf(e,t,i)}else if(wn||hr(e,t,i,!1),S=(i&e.childLanes)!==0,wn||S){if(S=Ft,S!==null&&(o=He(S,i),o!==0&&o!==H.retryLane))throw H.retryLane=o,rs(e,o),Na(S,e,o),Hf;Am(M)||Xu(),t=Yf(e,t,i)}else Am(M)?(t.flags|=192,t.child=e.child,t=null):(e=H.treeContext,Bt=fs(M.nextSibling),vn=t,ft=!0,Qs=null,wa=!1,e!==null&&Xl(t,e),t=Vf(t,o.children),t.flags|=4096);return t}return f?(ca(),M=o.fallback,f=t.mode,H=e.child,se=H.sibling,o=xa(H,{mode:"hidden",children:o.children}),o.subtreeFlags=H.subtreeFlags&65011712,se!==null?M=xa(se,M):(M=Rn(M,f,i,null),M.flags|=2),M.return=t,o.return=t,o.sibling=M,t.child=o,pc(null,o),o=t.child,M=e.child.memoizedState,M===null?M=qf(i):(f=M.cachePool,f!==null?(H=on._currentValue,f=f.parent!==H?{parent:H,pool:H}:f):f=ku(),M={baseLanes:M.baseLanes|i,cachePool:f}),o.memoizedState=M,o.childLanes=Gf(e,S,i),t.memoizedState=Uf,pc(e.child,o)):(dn(t),i=e.child,e=i.sibling,i=xa(i,{mode:"visible",children:o.children}),i.return=t,i.sibling=null,e!==null&&(S=t.deletions,S===null?(t.deletions=[e],t.flags|=16):S.push(e)),t.child=i,t.memoizedState=null,i)}function Vf(e,t){return t=$u({mode:"visible",children:t},e.mode),t.return=e,e.child=t}function $u(e,t){return e=Xn(22,e,null,t),e.lanes=0,e}function Yf(e,t,i){return Js(t,e.child,null,i),e=Vf(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function xg(e,t,i){e.lanes|=t;var o=e.alternate;o!==null&&(o.lanes|=t),mr(e.return,t,i)}function Wf(e,t,i,o,f,h){var S=e.memoizedState;S===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:o,tail:i,tailMode:f,treeForkCount:h}:(S.isBackwards=t,S.rendering=null,S.renderingStartTime=0,S.last=o,S.tail=i,S.tailMode=f,S.treeForkCount=h)}function yg(e,t,i){var o=t.pendingProps,f=o.revealOrder,h=o.tail;o=o.children;var S=Vt.current,M=(S&2)!==0;if(M?(S=S&1|2,t.flags|=128):S&=1,P(Vt,S),qn(e,t,o,i),o=ft?ji:0,!M&&e!==null&&(e.flags&128)!==0)e:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&xg(e,i,t);else if(e.tag===19)xg(e,i,t);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;e.sibling===null;){if(e.return===null||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}switch(f){case"forwards":for(i=t.child,f=null;i!==null;)e=i.alternate,e!==null&&io(e)===null&&(f=i),i=i.sibling;i=f,i===null?(f=t.child,t.child=null):(f=i.sibling,i.sibling=null),Wf(t,!1,f,i,h,o);break;case"backwards":case"unstable_legacy-backwards":for(i=null,f=t.child,t.child=null;f!==null;){if(e=f.alternate,e!==null&&io(e)===null){t.child=f;break}e=f.sibling,f.sibling=i,i=f,f=e}Wf(t,!0,i,null,h,o);break;case"together":Wf(t,!1,null,null,void 0,o);break;default:t.memoizedState=null}return t.child}function Li(e,t,i){if(e!==null&&(t.dependencies=e.dependencies),kr|=t.lanes,(i&t.childLanes)===0)if(e!==null){if(hr(e,t,i,!1),(i&t.childLanes)===0)return null}else return null;if(e!==null&&t.child!==e.child)throw Error(l(153));if(t.child!==null){for(e=t.child,i=xa(e,e.pendingProps),t.child=i,i.return=t;e.sibling!==null;)e=e.sibling,i=i.sibling=xa(e,e.pendingProps),i.return=t;i.sibling=null}return t.child}function Kf(e,t){return(e.lanes&t)!==0?!0:(e=e.dependencies,!!(e!==null&&tc(e)))}function Ab(e,t,i){switch(t.tag){case 3:_e(t,t.stateNode.containerInfo),cs(t,on,e.memoizedState.cache),Ai();break;case 27:case 5:ue(t);break;case 4:_e(t,t.stateNode.containerInfo);break;case 10:cs(t,t.type,t.memoizedProps.value);break;case 31:if(t.memoizedState!==null)return t.flags|=128,uc(t),null;break;case 13:var o=t.memoizedState;if(o!==null)return o.dehydrated!==null?(dn(t),t.flags|=128,null):(i&t.child.childLanes)!==0?vg(e,t,i):(dn(t),e=Li(e,t,i),e!==null?e.sibling:null);dn(t);break;case 19:var f=(e.flags&128)!==0;if(o=(i&t.childLanes)!==0,o||(hr(e,t,i,!1),o=(i&t.childLanes)!==0),f){if(o)return yg(e,t,i);t.flags|=128}if(f=t.memoizedState,f!==null&&(f.rendering=null,f.tail=null,f.lastEffect=null),P(Vt,Vt.current),o)break;return null;case 22:return t.lanes=0,dg(e,t,i,t.pendingProps);case 24:cs(t,on,e.memoizedState.cache)}return Li(e,t,i)}function wg(e,t,i){if(e!==null)if(e.memoizedProps!==t.pendingProps)wn=!0;else{if(!Kf(e,i)&&(t.flags&128)===0)return wn=!1,Ab(e,t,i);wn=(e.flags&131072)!==0}else wn=!1,ft&&(t.flags&1048576)!==0&&Zo(t,ji,t.index);switch(t.lanes=0,t.tag){case 16:e:{var o=t.pendingProps;if(e=Ei(t.elementType),t.type=e,typeof e=="function")Ss(e)?(o=ml(e,o),t.tag=1,t=pg(null,t,e,o,i)):(t.tag=0,t=$f(null,t,e,o,i));else{if(e!=null){var f=e.$$typeof;if(f===$){t.tag=11,t=og(null,t,e,o,i);break e}else if(f===z){t.tag=14,t=cg(null,t,e,o,i);break e}}throw t=le(e)||e,Error(l(306,t,""))}}return t;case 0:return $f(e,t,t.type,t.pendingProps,i);case 1:return o=t.type,f=ml(o,t.pendingProps),pg(e,t,o,f,i);case 3:e:{if(_e(t,t.stateNode.containerInfo),e===null)throw Error(l(387));o=t.pendingProps;var h=t.memoizedState;f=h.element,xr(e,t),ti(t,o,null,i);var S=t.memoizedState;if(o=S.cache,cs(t,on,o),o!==h.cache&&Zl(t,[on],i,!0),yr(),o=S.element,h.isDehydrated)if(h={element:o,isDehydrated:!1,cache:S.cache},t.updateQueue.baseState=h,t.memoizedState=h,t.flags&256){t=gg(e,t,o,i);break e}else if(o!==f){f=ra(Error(l(424)),t),ba(f),t=gg(e,t,o,i);break e}else for(e=t.stateNode.containerInfo,e.nodeType===9?e=e.body:e=e.nodeName==="HTML"?e.ownerDocument.body:e,Bt=fs(e.firstChild),vn=t,ft=!0,Qs=null,wa=!0,i=ul(t,null,o,i),t.child=i;i;)i.flags=i.flags&-3|4096,i=i.sibling;else{if(Ai(),o===f){t=Li(e,t,i);break e}qn(e,t,o,i)}t=t.child}return t;case 26:return Hu(e,t),e===null?(i=Rv(t.type,null,t.pendingProps,null))?t.memoizedState=i:ft||(i=t.type,e=t.pendingProps,o=sd(ve.current).createElement(i),o[te]=t,o[Me]=e,Gn(o,i,e),Dt(o),t.stateNode=o):t.memoizedState=Rv(t.type,e.memoizedProps,t.pendingProps,e.memoizedState),null;case 27:return ue(t),e===null&&ft&&(o=t.stateNode=Mv(t.type,t.pendingProps,ve.current),vn=t,wa=!0,f=Bt,Er(t.type)?(Mm=f,Bt=fs(o.firstChild)):Bt=f),qn(e,t,t.pendingProps.children,i),Hu(e,t),e===null&&(t.flags|=4194304),t.child;case 5:return e===null&&ft&&((f=o=Bt)&&(o=nS(o,t.type,t.pendingProps,wa),o!==null?(t.stateNode=o,vn=t,Bt=fs(o.firstChild),wa=!1,f=!0):f=!1),f||Xs(t)),ue(t),f=t.type,h=t.pendingProps,S=e!==null?e.memoizedProps:null,o=h.children,jm(f,h)?o=null:S!==null&&jm(f,S)&&(t.flags|=32),t.memoizedState!==null&&(f=da(e,t,Cf,null,null,i),Ec._currentValue=f),Hu(e,t),qn(e,t,o,i),t.child;case 6:return e===null&&ft&&((e=i=Bt)&&(i=aS(i,t.pendingProps,wa),i!==null?(t.stateNode=i,vn=t,Bt=null,e=!0):e=!1),e||Xs(t)),null;case 13:return vg(e,t,i);case 4:return _e(t,t.stateNode.containerInfo),o=t.pendingProps,e===null?t.child=Js(t,null,o,i):qn(e,t,o,i),t.child;case 11:return og(e,t,t.type,t.pendingProps,i);case 7:return qn(e,t,t.pendingProps,i),t.child;case 8:return qn(e,t,t.pendingProps.children,i),t.child;case 12:return qn(e,t,t.pendingProps.children,i),t.child;case 10:return o=t.pendingProps,cs(t,t.type,o.value),qn(e,t,o.children,i),t.child;case 9:return f=t.type._context,o=t.pendingProps.children,Cs(t),f=jn(f),o=o(f),t.flags|=1,qn(e,t,o,i),t.child;case 14:return cg(e,t,t.type,t.pendingProps,i);case 15:return ug(e,t,t.type,t.pendingProps,i);case 19:return yg(e,t,i);case 31:return kb(e,t,i);case 22:return dg(e,t,i,t.pendingProps);case 24:return Cs(t),o=jn(on),e===null?(f=sc(),f===null&&(f=Ft,h=nc(),f.pooledCache=h,h.refCount++,h!==null&&(f.pooledCacheLanes|=i),f=h),t.memoizedState={parent:o,cache:f},Cn(t),cs(t,on,f)):((e.lanes&i)!==0&&(xr(e,t),ti(t,null,null,i),yr()),f=e.memoizedState,h=t.memoizedState,f.parent!==o?(f={parent:o,cache:o},t.memoizedState=f,t.lanes===0&&(t.memoizedState=t.updateQueue.baseState=f),cs(t,on,o)):(o=h.cache,cs(t,on,o),o!==f.cache&&Zl(t,[on],i,!0))),qn(e,t,t.pendingProps.children,i),t.child;case 29:throw t.pendingProps}throw Error(l(156,t.tag))}function zi(e){e.flags|=4}function Qf(e,t,i,o,f){if((t=(e.mode&32)!==0)&&(t=!1),t){if(e.flags|=16777216,(f&335544128)===f)if(e.stateNode.complete)e.flags|=8192;else if(Yg())e.flags|=8192;else throw Ri=to,ol}else e.flags&=-16777217}function bg(e,t){if(t.type!=="stylesheet"||(t.state.loading&4)!==0)e.flags&=-16777217;else if(e.flags|=16777216,!Iv(t))if(Yg())e.flags|=8192;else throw Ri=to,ol}function Uu(e,t){t!==null&&(e.flags|=4),e.flags&16384&&(t=e.tag!==22?ri():536870912,e.lanes|=t,uo|=t)}function gc(e,t){if(!ft)switch(e.tailMode){case"hidden":t=e.tail;for(var i=null;t!==null;)t.alternate!==null&&(i=t),t=t.sibling;i===null?e.tail=null:i.sibling=null;break;case"collapsed":i=e.tail;for(var o=null;i!==null;)i.alternate!==null&&(o=i),i=i.sibling;o===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:o.sibling=null}}function Yt(e){var t=e.alternate!==null&&e.alternate.child===e.child,i=0,o=0;if(t)for(var f=e.child;f!==null;)i|=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;)i|=f.lanes|f.childLanes,o|=f.subtreeFlags,o|=f.flags,f.return=e,f=f.sibling;return e.subtreeFlags|=o,e.childLanes=i,t}function Nb(e,t,i){var o=t.pendingProps;switch(Ql(t),t.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Yt(t),null;case 1:return Yt(t),null;case 3:return i=t.stateNode,o=null,e!==null&&(o=e.memoizedState.cache),t.memoizedState.cache!==o&&(t.flags|=2048),Ce(on),Le(),i.pendingContext&&(i.context=i.pendingContext,i.pendingContext=null),(e===null||e.child===null)&&(ki(t)?zi(t):e===null||e.memoizedState.isDehydrated&&(t.flags&256)===0||(t.flags|=1024,dr())),Yt(t),null;case 26:var f=t.type,h=t.memoizedState;return e===null?(zi(t),h!==null?(Yt(t),bg(t,h)):(Yt(t),Qf(t,f,null,o,i))):h?h!==e.memoizedState?(zi(t),Yt(t),bg(t,h)):(Yt(t),t.flags&=-16777217):(e=e.memoizedProps,e!==o&&zi(t),Yt(t),Qf(t,f,e,o,i)),null;case 27:if(Ve(t),i=ve.current,f=t.type,e!==null&&t.stateNode!=null)e.memoizedProps!==o&&zi(t);else{if(!o){if(t.stateNode===null)throw Error(l(166));return Yt(t),null}e=me.current,ki(t)?Jo(t):(e=Mv(f,o,i),t.stateNode=e,zi(t))}return Yt(t),null;case 5:if(Ve(t),f=t.type,e!==null&&t.stateNode!=null)e.memoizedProps!==o&&zi(t);else{if(!o){if(t.stateNode===null)throw Error(l(166));return Yt(t),null}if(h=me.current,ki(t))Jo(t);else{var S=sd(ve.current);switch(h){case 1:h=S.createElementNS("http://www.w3.org/2000/svg",f);break;case 2:h=S.createElementNS("http://www.w3.org/1998/Math/MathML",f);break;default:switch(f){case"svg":h=S.createElementNS("http://www.w3.org/2000/svg",f);break;case"math":h=S.createElementNS("http://www.w3.org/1998/Math/MathML",f);break;case"script":h=S.createElement("div"),h.innerHTML="<script><\/script>",h=h.removeChild(h.firstChild);break;case"select":h=typeof o.is=="string"?S.createElement("select",{is:o.is}):S.createElement("select"),o.multiple?h.multiple=!0:o.size&&(h.size=o.size);break;default:h=typeof o.is=="string"?S.createElement(f,{is:o.is}):S.createElement(f)}}h[te]=t,h[Me]=o;e:for(S=t.child;S!==null;){if(S.tag===5||S.tag===6)h.appendChild(S.stateNode);else if(S.tag!==4&&S.tag!==27&&S.child!==null){S.child.return=S,S=S.child;continue}if(S===t)break e;for(;S.sibling===null;){if(S.return===null||S.return===t)break e;S=S.return}S.sibling.return=S.return,S=S.sibling}t.stateNode=h;e:switch(Gn(h,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&&zi(t)}}return Yt(t),Qf(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,i),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==o&&zi(t);else{if(typeof o!="string"&&t.stateNode===null)throw Error(l(166));if(e=ve.current,ki(t)){if(e=t.stateNode,i=t.memoizedProps,o=null,f=vn,f!==null)switch(f.tag){case 27:case 5:o=f.memoizedProps}e[te]=t,e=!!(e.nodeValue===i||o!==null&&o.suppressHydrationWarning===!0||vv(e.nodeValue,i)),e||Xs(t,!0)}else e=sd(e).createTextNode(o),e[te]=t,t.stateNode=e}return Yt(t),null;case 31:if(i=t.memoizedState,e===null||e.memoizedState!==null){if(o=ki(t),i!==null){if(e===null){if(!o)throw Error(l(318));if(e=t.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(l(557));e[te]=t}else Ai(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;Yt(t),e=!1}else i=dr(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=i),e=!0;if(!e)return t.flags&256?(ua(t),t):(ua(t),null);if((t.flags&128)!==0)throw Error(l(558))}return Yt(t),null;case 13:if(o=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(f=ki(t),o!==null&&o.dehydrated!==null){if(e===null){if(!f)throw Error(l(318));if(f=t.memoizedState,f=f!==null?f.dehydrated:null,!f)throw Error(l(317));f[te]=t}else Ai(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;Yt(t),f=!1}else f=dr(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=f),f=!0;if(!f)return t.flags&256?(ua(t),t):(ua(t),null)}return ua(t),(t.flags&128)!==0?(t.lanes=i,t):(i=o!==null,e=e!==null&&e.memoizedState!==null,i&&(o=t.child,f=null,o.alternate!==null&&o.alternate.memoizedState!==null&&o.alternate.memoizedState.cachePool!==null&&(f=o.alternate.memoizedState.cachePool.pool),h=null,o.memoizedState!==null&&o.memoizedState.cachePool!==null&&(h=o.memoizedState.cachePool.pool),h!==f&&(o.flags|=2048)),i!==e&&i&&(t.child.flags|=8192),Uu(t,t.updateQueue),Yt(t),null);case 4:return Le(),e===null&&xm(t.stateNode.containerInfo),Yt(t),null;case 10:return Ce(t.type),Yt(t),null;case 19:if(W(Vt),o=t.memoizedState,o===null)return Yt(t),null;if(f=(t.flags&128)!==0,h=o.rendering,h===null)if(f)gc(o,!1);else{if(cn!==0||e!==null&&(e.flags&128)!==0)for(e=t.child;e!==null;){if(h=io(e),h!==null){for(t.flags|=128,gc(o,!1),e=h.updateQueue,t.updateQueue=e,Uu(t,e),t.subtreeFlags=0,e=i,i=t.child;i!==null;)sl(i,e),i=i.sibling;return P(Vt,Vt.current&1|2),ft&&$a(t,o.treeForkCount),t.child}e=e.sibling}o.tail!==null&&tt()>Wu&&(t.flags|=128,f=!0,gc(o,!1),t.lanes=4194304)}else{if(!f)if(e=io(h),e!==null){if(t.flags|=128,f=!0,e=e.updateQueue,t.updateQueue=e,Uu(t,e),gc(o,!0),o.tail===null&&o.tailMode==="hidden"&&!h.alternate&&!ft)return Yt(t),null}else 2*tt()-o.renderingStartTime>Wu&&i!==536870912&&(t.flags|=128,f=!0,gc(o,!1),t.lanes=4194304);o.isBackwards?(h.sibling=t.child,t.child=h):(e=o.last,e!==null?e.sibling=h:t.child=h,o.last=h)}return o.tail!==null?(e=o.tail,o.rendering=e,o.tail=e.sibling,o.renderingStartTime=tt(),e.sibling=null,i=Vt.current,P(Vt,f?i&1|2:i&1),ft&&$a(t,o.treeForkCount),e):(Yt(t),null);case 22:case 23:return ua(t),cc(),o=t.memoizedState!==null,e!==null?e.memoizedState!==null!==o&&(t.flags|=8192):o&&(t.flags|=8192),o?(i&536870912)!==0&&(t.flags&128)===0&&(Yt(t),t.subtreeFlags&6&&(t.flags|=8192)):Yt(t),i=t.updateQueue,i!==null&&Uu(t,i.retryQueue),i=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(i=e.memoizedState.cachePool.pool),o=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(o=t.memoizedState.cachePool.pool),o!==i&&(t.flags|=2048),e!==null&&W(Ti),null;case 24:return i=null,e!==null&&(i=e.memoizedState.cache),t.memoizedState.cache!==i&&(t.flags|=2048),Ce(on),Yt(t),null;case 25:return null;case 30:return null}throw Error(l(156,t.tag))}function Mb(e,t){switch(Ql(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ce(on),Le(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return Ve(t),null;case 31:if(t.memoizedState!==null){if(ua(t),t.alternate===null)throw Error(l(340));Ai()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(ua(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(l(340));Ai()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return W(Vt),null;case 4:return Le(),null;case 10:return Ce(t.type),null;case 22:case 23:return ua(t),cc(),e!==null&&W(Ti),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Ce(on),null;case 25:return null;default:return null}}function Sg(e,t){switch(Ql(t),t.tag){case 3:Ce(on),Le();break;case 26:case 27:case 5:Ve(t);break;case 4:Le();break;case 31:t.memoizedState!==null&&ua(t);break;case 13:ua(t);break;case 19:W(Vt);break;case 10:Ce(t.type);break;case 22:case 23:ua(t),cc(),e!==null&&W(Ti);break;case 24:Ce(on)}}function vc(e,t){try{var i=t.updateQueue,o=i!==null?i.lastEffect:null;if(o!==null){var f=o.next;i=f;do{if((i.tag&e)===e){o=void 0;var h=i.create,S=i.inst;o=h(),S.destroy=o}i=i.next}while(i!==f)}}catch(M){Et(t,t.return,M)}}function jr(e,t,i){try{var o=t.updateQueue,f=o!==null?o.lastEffect:null;if(f!==null){var h=f.next;o=h;do{if((o.tag&e)===e){var S=o.inst,M=S.destroy;if(M!==void 0){S.destroy=void 0,f=t;var H=i,se=M;try{se()}catch(xe){Et(f,H,xe)}}}o=o.next}while(o!==h)}}catch(xe){Et(t,t.return,xe)}}function jg(e){var t=e.updateQueue;if(t!==null){var i=e.stateNode;try{lc(t,i)}catch(o){Et(e,e.return,o)}}}function Cg(e,t,i){i.props=ml(e.type,e.memoizedProps),i.state=e.memoizedState;try{i.componentWillUnmount()}catch(o){Et(e,t,o)}}function xc(e,t){try{var i=e.ref;if(i!==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 i=="function"?e.refCleanup=i(o):i.current=o}}catch(f){Et(e,t,f)}}function ni(e,t){var i=e.ref,o=e.refCleanup;if(i!==null)if(typeof o=="function")try{o()}catch(f){Et(e,t,f)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof i=="function")try{i(null)}catch(f){Et(e,t,f)}else i.current=null}function kg(e){var t=e.type,i=e.memoizedProps,o=e.stateNode;try{e:switch(t){case"button":case"input":case"select":case"textarea":i.autoFocus&&o.focus();break e;case"img":i.src?o.src=i.src:i.srcSet&&(o.srcset=i.srcSet)}}catch(f){Et(e,e.return,f)}}function Xf(e,t,i){try{var o=e.stateNode;Qb(o,e.type,i,t),o[Me]=t}catch(f){Et(e,e.return,f)}}function Ag(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&Er(e.type)||e.tag===4}function Zf(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Ag(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&&Er(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 Jf(e,t,i){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?(i.nodeType===9?i.body:i.nodeName==="HTML"?i.ownerDocument.body:i).insertBefore(e,t):(t=i.nodeType===9?i.body:i.nodeName==="HTML"?i.ownerDocument.body:i,t.appendChild(e),i=i._reactRootContainer,i!=null||t.onclick!==null||(t.onclick=Fn));else if(o!==4&&(o===27&&Er(e.type)&&(i=e.stateNode,t=null),e=e.child,e!==null))for(Jf(e,t,i),e=e.sibling;e!==null;)Jf(e,t,i),e=e.sibling}function qu(e,t,i){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?i.insertBefore(e,t):i.appendChild(e);else if(o!==4&&(o===27&&Er(e.type)&&(i=e.stateNode),e=e.child,e!==null))for(qu(e,t,i),e=e.sibling;e!==null;)qu(e,t,i),e=e.sibling}function Ng(e){var t=e.stateNode,i=e.memoizedProps;try{for(var o=e.type,f=t.attributes;f.length;)t.removeAttributeNode(f[0]);Gn(t,o,i),t[te]=e,t[Me]=i}catch(h){Et(e,e.return,h)}}var Ii=!1,bn=!1,em=!1,Mg=typeof WeakSet=="function"?WeakSet:Set,_n=null;function Tb(e,t){if(e=e.containerInfo,bm=dd,e=Yo(e),Gl(e)){if("selectionStart"in e)var i={start:e.selectionStart,end:e.selectionEnd};else e:{i=(i=e.ownerDocument)&&i.defaultView||window;var o=i.getSelection&&i.getSelection();if(o&&o.rangeCount!==0){i=o.anchorNode;var f=o.anchorOffset,h=o.focusNode;o=o.focusOffset;try{i.nodeType,h.nodeType}catch{i=null;break e}var S=0,M=-1,H=-1,se=0,xe=0,Se=e,re=null;t:for(;;){for(var fe;Se!==i||f!==0&&Se.nodeType!==3||(M=S+f),Se!==h||o!==0&&Se.nodeType!==3||(H=S+o),Se.nodeType===3&&(S+=Se.nodeValue.length),(fe=Se.firstChild)!==null;)re=Se,Se=fe;for(;;){if(Se===e)break t;if(re===i&&++se===f&&(M=S),re===h&&++xe===o&&(H=S),(fe=Se.nextSibling)!==null)break;Se=re,re=Se.parentNode}Se=fe}i=M===-1||H===-1?null:{start:M,end:H}}else i=null}i=i||{start:0,end:0}}else i=null;for(Sm={focusedElem:e,selectionRange:i},dd=!1,_n=t;_n!==null;)if(t=_n,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,_n=e;else for(;_n!==null;){switch(t=_n,h=t.alternate,e=t.flags,t.tag){case 0:if((e&4)!==0&&(e=t.updateQueue,e=e!==null?e.events:null,e!==null))for(i=0;i<e.length;i++)f=e[i],f.ref.impl=f.nextImpl;break;case 11:case 15:break;case 1:if((e&1024)!==0&&h!==null){e=void 0,i=t,f=h.memoizedProps,h=h.memoizedState,o=i.stateNode;try{var Ue=ml(i.type,f);e=o.getSnapshotBeforeUpdate(Ue,h),o.__reactInternalSnapshotBeforeUpdate=e}catch(Ze){Et(i,i.return,Ze)}}break;case 3:if((e&1024)!==0){if(e=t.stateNode.containerInfo,i=e.nodeType,i===9)km(e);else if(i===1)switch(e.nodeName){case"HEAD":case"HTML":case"BODY":km(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=t.sibling,e!==null){e.return=t.return,_n=e;break}_n=t.return}}function Tg(e,t,i){var o=i.flags;switch(i.tag){case 0:case 11:case 15:Bi(e,i),o&4&&vc(5,i);break;case 1:if(Bi(e,i),o&4)if(e=i.stateNode,t===null)try{e.componentDidMount()}catch(S){Et(i,i.return,S)}else{var f=ml(i.type,t.memoizedProps);t=t.memoizedState;try{e.componentDidUpdate(f,t,e.__reactInternalSnapshotBeforeUpdate)}catch(S){Et(i,i.return,S)}}o&64&&jg(i),o&512&&xc(i,i.return);break;case 3:if(Bi(e,i),o&64&&(e=i.updateQueue,e!==null)){if(t=null,i.child!==null)switch(i.child.tag){case 27:case 5:t=i.child.stateNode;break;case 1:t=i.child.stateNode}try{lc(e,t)}catch(S){Et(i,i.return,S)}}break;case 27:t===null&&o&4&&Ng(i);case 26:case 5:Bi(e,i),t===null&&o&4&&kg(i),o&512&&xc(i,i.return);break;case 12:Bi(e,i);break;case 31:Bi(e,i),o&4&&Dg(e,i);break;case 13:Bi(e,i),o&4&&_g(e,i),o&64&&(e=i.memoizedState,e!==null&&(e=e.dehydrated,e!==null&&(i=Bb.bind(null,i),sS(e,i))));break;case 22:if(o=i.memoizedState!==null||Ii,!o){t=t!==null&&t.memoizedState!==null||bn,f=Ii;var h=bn;Ii=o,(bn=t)&&!h?Fi(e,i,(i.subtreeFlags&8772)!==0):Bi(e,i),Ii=f,bn=h}break;case 30:break;default:Bi(e,i)}}function Eg(e){var t=e.alternate;t!==null&&(e.alternate=null,Eg(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&Kt(t)),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 Xt=null,ja=!1;function Oi(e,t,i){for(i=i.child;i!==null;)Rg(e,t,i),i=i.sibling}function Rg(e,t,i){if(st&&typeof st.onCommitFiberUnmount=="function")try{st.onCommitFiberUnmount(pt,i)}catch{}switch(i.tag){case 26:bn||ni(i,t),Oi(e,t,i),i.memoizedState?i.memoizedState.count--:i.stateNode&&(i=i.stateNode,i.parentNode.removeChild(i));break;case 27:bn||ni(i,t);var o=Xt,f=ja;Er(i.type)&&(Xt=i.stateNode,ja=!1),Oi(e,t,i),Nc(i.stateNode),Xt=o,ja=f;break;case 5:bn||ni(i,t);case 6:if(o=Xt,f=ja,Xt=null,Oi(e,t,i),Xt=o,ja=f,Xt!==null)if(ja)try{(Xt.nodeType===9?Xt.body:Xt.nodeName==="HTML"?Xt.ownerDocument.body:Xt).removeChild(i.stateNode)}catch(h){Et(i,t,h)}else try{Xt.removeChild(i.stateNode)}catch(h){Et(i,t,h)}break;case 18:Xt!==null&&(ja?(e=Xt,jv(e.nodeType===9?e.body:e.nodeName==="HTML"?e.ownerDocument.body:e,i.stateNode),yo(e)):jv(Xt,i.stateNode));break;case 4:o=Xt,f=ja,Xt=i.stateNode.containerInfo,ja=!0,Oi(e,t,i),Xt=o,ja=f;break;case 0:case 11:case 14:case 15:jr(2,i,t),bn||jr(4,i,t),Oi(e,t,i);break;case 1:bn||(ni(i,t),o=i.stateNode,typeof o.componentWillUnmount=="function"&&Cg(i,t,o)),Oi(e,t,i);break;case 21:Oi(e,t,i);break;case 22:bn=(o=bn)||i.memoizedState!==null,Oi(e,t,i),bn=o;break;default:Oi(e,t,i)}}function Dg(e,t){if(t.memoizedState===null&&(e=t.alternate,e!==null&&(e=e.memoizedState,e!==null))){e=e.dehydrated;try{yo(e)}catch(i){Et(t,t.return,i)}}}function _g(e,t){if(t.memoizedState===null&&(e=t.alternate,e!==null&&(e=e.memoizedState,e!==null&&(e=e.dehydrated,e!==null))))try{yo(e)}catch(i){Et(t,t.return,i)}}function Eb(e){switch(e.tag){case 31:case 13:case 19:var t=e.stateNode;return t===null&&(t=e.stateNode=new Mg),t;case 22:return e=e.stateNode,t=e._retryCache,t===null&&(t=e._retryCache=new Mg),t;default:throw Error(l(435,e.tag))}}function Gu(e,t){var i=Eb(e);t.forEach(function(o){if(!i.has(o)){i.add(o);var f=Fb.bind(null,e,o);o.then(f,f)}})}function Ca(e,t){var i=t.deletions;if(i!==null)for(var o=0;o<i.length;o++){var f=i[o],h=e,S=t,M=S;e:for(;M!==null;){switch(M.tag){case 27:if(Er(M.type)){Xt=M.stateNode,ja=!1;break e}break;case 5:Xt=M.stateNode,ja=!1;break e;case 3:case 4:Xt=M.stateNode.containerInfo,ja=!0;break e}M=M.return}if(Xt===null)throw Error(l(160));Rg(h,S,f),Xt=null,ja=!1,h=f.alternate,h!==null&&(h.return=null),f.return=null}if(t.subtreeFlags&13886)for(t=t.child;t!==null;)Lg(t,e),t=t.sibling}var Ns=null;function Lg(e,t){var i=e.alternate,o=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:Ca(t,e),ka(e),o&4&&(jr(3,e,e.return),vc(3,e),jr(5,e,e.return));break;case 1:Ca(t,e),ka(e),o&512&&(bn||i===null||ni(i,i.return)),o&64&&Ii&&(e=e.updateQueue,e!==null&&(o=e.callbacks,o!==null&&(i=e.shared.hiddenCallbacks,e.shared.hiddenCallbacks=i===null?o:i.concat(o))));break;case 26:var f=Ns;if(Ca(t,e),ka(e),o&512&&(bn||i===null||ni(i,i.return)),o&4){var h=i!==null?i.memoizedState:null;if(o=e.memoizedState,i===null)if(o===null)if(e.stateNode===null){e:{o=e.type,i=e.memoizedProps,f=f.ownerDocument||f;t:switch(o){case"title":h=f.getElementsByTagName("title")[0],(!h||h[rt]||h[te]||h.namespaceURI==="http://www.w3.org/2000/svg"||h.hasAttribute("itemprop"))&&(h=f.createElement(o),f.head.insertBefore(h,f.querySelector("head > title"))),Gn(h,o,i),h[te]=e,Dt(h),o=h;break e;case"link":var S=Lv("link","href",f).get(o+(i.href||""));if(S){for(var M=0;M<S.length;M++)if(h=S[M],h.getAttribute("href")===(i.href==null||i.href===""?null:i.href)&&h.getAttribute("rel")===(i.rel==null?null:i.rel)&&h.getAttribute("title")===(i.title==null?null:i.title)&&h.getAttribute("crossorigin")===(i.crossOrigin==null?null:i.crossOrigin)){S.splice(M,1);break t}}h=f.createElement(o),Gn(h,o,i),f.head.appendChild(h);break;case"meta":if(S=Lv("meta","content",f).get(o+(i.content||""))){for(M=0;M<S.length;M++)if(h=S[M],h.getAttribute("content")===(i.content==null?null:""+i.content)&&h.getAttribute("name")===(i.name==null?null:i.name)&&h.getAttribute("property")===(i.property==null?null:i.property)&&h.getAttribute("http-equiv")===(i.httpEquiv==null?null:i.httpEquiv)&&h.getAttribute("charset")===(i.charSet==null?null:i.charSet)){S.splice(M,1);break t}}h=f.createElement(o),Gn(h,o,i),f.head.appendChild(h);break;default:throw Error(l(468,o))}h[te]=e,Dt(h),o=h}e.stateNode=o}else zv(f,e.type,e.stateNode);else e.stateNode=_v(f,o,e.memoizedProps);else h!==o?(h===null?i.stateNode!==null&&(i=i.stateNode,i.parentNode.removeChild(i)):h.count--,o===null?zv(f,e.type,e.stateNode):_v(f,o,e.memoizedProps)):o===null&&e.stateNode!==null&&Xf(e,e.memoizedProps,i.memoizedProps)}break;case 27:Ca(t,e),ka(e),o&512&&(bn||i===null||ni(i,i.return)),i!==null&&o&4&&Xf(e,e.memoizedProps,i.memoizedProps);break;case 5:if(Ca(t,e),ka(e),o&512&&(bn||i===null||ni(i,i.return)),e.flags&32){f=e.stateNode;try{Os(f,"")}catch(Ue){Et(e,e.return,Ue)}}o&4&&e.stateNode!=null&&(f=e.memoizedProps,Xf(e,f,i!==null?i.memoizedProps:f)),o&1024&&(em=!0);break;case 6:if(Ca(t,e),ka(e),o&4){if(e.stateNode===null)throw Error(l(162));o=e.memoizedProps,i=e.stateNode;try{i.nodeValue=o}catch(Ue){Et(e,e.return,Ue)}}break;case 3:if(ld=null,f=Ns,Ns=id(t.containerInfo),Ca(t,e),Ns=f,ka(e),o&4&&i!==null&&i.memoizedState.isDehydrated)try{yo(t.containerInfo)}catch(Ue){Et(e,e.return,Ue)}em&&(em=!1,zg(e));break;case 4:o=Ns,Ns=id(e.stateNode.containerInfo),Ca(t,e),ka(e),Ns=o;break;case 12:Ca(t,e),ka(e);break;case 31:Ca(t,e),ka(e),o&4&&(o=e.updateQueue,o!==null&&(e.updateQueue=null,Gu(e,o)));break;case 13:Ca(t,e),ka(e),e.child.flags&8192&&e.memoizedState!==null!=(i!==null&&i.memoizedState!==null)&&(Yu=tt()),o&4&&(o=e.updateQueue,o!==null&&(e.updateQueue=null,Gu(e,o)));break;case 22:f=e.memoizedState!==null;var H=i!==null&&i.memoizedState!==null,se=Ii,xe=bn;if(Ii=se||f,bn=xe||H,Ca(t,e),bn=xe,Ii=se,ka(e),o&8192)e:for(t=e.stateNode,t._visibility=f?t._visibility&-2:t._visibility|1,f&&(i===null||H||Ii||bn||hl(e)),i=null,t=e;;){if(t.tag===5||t.tag===26){if(i===null){H=i=t;try{if(h=H.stateNode,f)S=h.style,typeof S.setProperty=="function"?S.setProperty("display","none","important"):S.display="none";else{M=H.stateNode;var Se=H.memoizedProps.style,re=Se!=null&&Se.hasOwnProperty("display")?Se.display:null;M.style.display=re==null||typeof re=="boolean"?"":(""+re).trim()}}catch(Ue){Et(H,H.return,Ue)}}}else if(t.tag===6){if(i===null){H=t;try{H.stateNode.nodeValue=f?"":H.memoizedProps}catch(Ue){Et(H,H.return,Ue)}}}else if(t.tag===18){if(i===null){H=t;try{var fe=H.stateNode;f?Cv(fe,!0):Cv(H.stateNode,!1)}catch(Ue){Et(H,H.return,Ue)}}}else if((t.tag!==22&&t.tag!==23||t.memoizedState===null||t===e)&&t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break e;for(;t.sibling===null;){if(t.return===null||t.return===e)break e;i===t&&(i=null),t=t.return}i===t&&(i=null),t.sibling.return=t.return,t=t.sibling}o&4&&(o=e.updateQueue,o!==null&&(i=o.retryQueue,i!==null&&(o.retryQueue=null,Gu(e,i))));break;case 19:Ca(t,e),ka(e),o&4&&(o=e.updateQueue,o!==null&&(e.updateQueue=null,Gu(e,o)));break;case 30:break;case 21:break;default:Ca(t,e),ka(e)}}function ka(e){var t=e.flags;if(t&2){try{for(var i,o=e.return;o!==null;){if(Ag(o)){i=o;break}o=o.return}if(i==null)throw Error(l(160));switch(i.tag){case 27:var f=i.stateNode,h=Zf(e);qu(e,h,f);break;case 5:var S=i.stateNode;i.flags&32&&(Os(S,""),i.flags&=-33);var M=Zf(e);qu(e,M,S);break;case 3:case 4:var H=i.stateNode.containerInfo,se=Zf(e);Jf(e,se,H);break;default:throw Error(l(161))}}catch(xe){Et(e,e.return,xe)}e.flags&=-3}t&4096&&(e.flags&=-4097)}function zg(e){if(e.subtreeFlags&1024)for(e=e.child;e!==null;){var t=e;zg(t),t.tag===5&&t.flags&1024&&t.stateNode.reset(),e=e.sibling}}function Bi(e,t){if(t.subtreeFlags&8772)for(t=t.child;t!==null;)Tg(e,t.alternate,t),t=t.sibling}function hl(e){for(e=e.child;e!==null;){var t=e;switch(t.tag){case 0:case 11:case 14:case 15:jr(4,t,t.return),hl(t);break;case 1:ni(t,t.return);var i=t.stateNode;typeof i.componentWillUnmount=="function"&&Cg(t,t.return,i),hl(t);break;case 27:Nc(t.stateNode);case 26:case 5:ni(t,t.return),hl(t);break;case 22:t.memoizedState===null&&hl(t);break;case 30:hl(t);break;default:hl(t)}e=e.sibling}}function Fi(e,t,i){for(i=i&&(t.subtreeFlags&8772)!==0,t=t.child;t!==null;){var o=t.alternate,f=e,h=t,S=h.flags;switch(h.tag){case 0:case 11:case 15:Fi(f,h,i),vc(4,h);break;case 1:if(Fi(f,h,i),o=h,f=o.stateNode,typeof f.componentDidMount=="function")try{f.componentDidMount()}catch(se){Et(o,o.return,se)}if(o=h,f=o.updateQueue,f!==null){var M=o.stateNode;try{var H=f.shared.hiddenCallbacks;if(H!==null)for(f.shared.hiddenCallbacks=null,f=0;f<H.length;f++)wr(H[f],M)}catch(se){Et(o,o.return,se)}}i&&S&64&&jg(h),xc(h,h.return);break;case 27:Ng(h);case 26:case 5:Fi(f,h,i),i&&o===null&&S&4&&kg(h),xc(h,h.return);break;case 12:Fi(f,h,i);break;case 31:Fi(f,h,i),i&&S&4&&Dg(f,h);break;case 13:Fi(f,h,i),i&&S&4&&_g(f,h);break;case 22:h.memoizedState===null&&Fi(f,h,i),xc(h,h.return);break;case 30:break;default:Fi(f,h,i)}t=t.sibling}}function tm(e,t){var i=null;e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(i=e.memoizedState.cachePool.pool),e=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(e=t.memoizedState.cachePool.pool),e!==i&&(e!=null&&e.refCount++,i!=null&&rl(i))}function nm(e,t){e=null,t.alternate!==null&&(e=t.alternate.memoizedState.cache),t=t.memoizedState.cache,t!==e&&(t.refCount++,e!=null&&rl(e))}function Ms(e,t,i,o){if(t.subtreeFlags&10256)for(t=t.child;t!==null;)Ig(e,t,i,o),t=t.sibling}function Ig(e,t,i,o){var f=t.flags;switch(t.tag){case 0:case 11:case 15:Ms(e,t,i,o),f&2048&&vc(9,t);break;case 1:Ms(e,t,i,o);break;case 3:Ms(e,t,i,o),f&2048&&(e=null,t.alternate!==null&&(e=t.alternate.memoizedState.cache),t=t.memoizedState.cache,t!==e&&(t.refCount++,e!=null&&rl(e)));break;case 12:if(f&2048){Ms(e,t,i,o),e=t.stateNode;try{var h=t.memoizedProps,S=h.id,M=h.onPostCommit;typeof M=="function"&&M(S,t.alternate===null?"mount":"update",e.passiveEffectDuration,-0)}catch(H){Et(t,t.return,H)}}else Ms(e,t,i,o);break;case 31:Ms(e,t,i,o);break;case 13:Ms(e,t,i,o);break;case 23:break;case 22:h=t.stateNode,S=t.alternate,t.memoizedState!==null?h._visibility&2?Ms(e,t,i,o):yc(e,t):h._visibility&2?Ms(e,t,i,o):(h._visibility|=2,lo(e,t,i,o,(t.subtreeFlags&10256)!==0||!1)),f&2048&&tm(S,t);break;case 24:Ms(e,t,i,o),f&2048&&nm(t.alternate,t);break;default:Ms(e,t,i,o)}}function lo(e,t,i,o,f){for(f=f&&((t.subtreeFlags&10256)!==0||!1),t=t.child;t!==null;){var h=e,S=t,M=i,H=o,se=S.flags;switch(S.tag){case 0:case 11:case 15:lo(h,S,M,H,f),vc(8,S);break;case 23:break;case 22:var xe=S.stateNode;S.memoizedState!==null?xe._visibility&2?lo(h,S,M,H,f):yc(h,S):(xe._visibility|=2,lo(h,S,M,H,f)),f&&se&2048&&tm(S.alternate,S);break;case 24:lo(h,S,M,H,f),f&&se&2048&&nm(S.alternate,S);break;default:lo(h,S,M,H,f)}t=t.sibling}}function yc(e,t){if(t.subtreeFlags&10256)for(t=t.child;t!==null;){var i=e,o=t,f=o.flags;switch(o.tag){case 22:yc(i,o),f&2048&&tm(o.alternate,o);break;case 24:yc(i,o),f&2048&&nm(o.alternate,o);break;default:yc(i,o)}t=t.sibling}}var wc=8192;function oo(e,t,i){if(e.subtreeFlags&wc)for(e=e.child;e!==null;)Og(e,t,i),e=e.sibling}function Og(e,t,i){switch(e.tag){case 26:oo(e,t,i),e.flags&wc&&e.memoizedState!==null&&gS(i,Ns,e.memoizedState,e.memoizedProps);break;case 5:oo(e,t,i);break;case 3:case 4:var o=Ns;Ns=id(e.stateNode.containerInfo),oo(e,t,i),Ns=o;break;case 22:e.memoizedState===null&&(o=e.alternate,o!==null&&o.memoizedState!==null?(o=wc,wc=16777216,oo(e,t,i),wc=o):oo(e,t,i));break;default:oo(e,t,i)}}function Bg(e){var t=e.alternate;if(t!==null&&(e=t.child,e!==null)){t.child=null;do t=e.sibling,e.sibling=null,e=t;while(e!==null)}}function bc(e){var t=e.deletions;if((e.flags&16)!==0){if(t!==null)for(var i=0;i<t.length;i++){var o=t[i];_n=o,Pg(o,e)}Bg(e)}if(e.subtreeFlags&10256)for(e=e.child;e!==null;)Fg(e),e=e.sibling}function Fg(e){switch(e.tag){case 0:case 11:case 15:bc(e),e.flags&2048&&jr(9,e,e.return);break;case 3:bc(e);break;case 12:bc(e);break;case 22:var t=e.stateNode;e.memoizedState!==null&&t._visibility&2&&(e.return===null||e.return.tag!==13)?(t._visibility&=-3,Vu(e)):bc(e);break;default:bc(e)}}function Vu(e){var t=e.deletions;if((e.flags&16)!==0){if(t!==null)for(var i=0;i<t.length;i++){var o=t[i];_n=o,Pg(o,e)}Bg(e)}for(e=e.child;e!==null;){switch(t=e,t.tag){case 0:case 11:case 15:jr(8,t,t.return),Vu(t);break;case 22:i=t.stateNode,i._visibility&2&&(i._visibility&=-3,Vu(t));break;default:Vu(t)}e=e.sibling}}function Pg(e,t){for(;_n!==null;){var i=_n;switch(i.tag){case 0:case 11:case 15:jr(8,i,t);break;case 23:case 22:if(i.memoizedState!==null&&i.memoizedState.cachePool!==null){var o=i.memoizedState.cachePool.pool;o!=null&&o.refCount++}break;case 24:rl(i.memoizedState.cache)}if(o=i.child,o!==null)o.return=i,_n=o;else e:for(i=e;_n!==null;){o=_n;var f=o.sibling,h=o.return;if(Eg(o),o===i){_n=null;break e}if(f!==null){f.return=h,_n=f;break e}_n=h}}}var Rb={getCacheForType:function(e){var t=jn(on),i=t.data.get(e);return i===void 0&&(i=e(),t.data.set(e,i)),i},cacheSignal:function(){return jn(on).controller.signal}},Db=typeof WeakMap=="function"?WeakMap:Map,At=0,Ft=null,xt=null,wt=0,Tt=0,qa=null,Cr=!1,co=!1,am=!1,Pi=0,cn=0,kr=0,pl=0,sm=0,Ga=0,uo=0,Sc=null,Aa=null,im=!1,Yu=0,Hg=0,Wu=1/0,Ku=null,Ar=null,kn=0,Nr=null,fo=null,Hi=0,rm=0,lm=null,$g=null,jc=0,om=null;function Va(){return(At&2)!==0&&wt!==0?wt&-wt:O.T!==null?hm():sn()}function Ug(){if(Ga===0)if((wt&536870912)===0||ft){var e=Bn;Bn<<=1,(Bn&3932160)===0&&(Bn=262144),Ga=e}else Ga=536870912;return e=oa.current,e!==null&&(e.flags|=32),Ga}function Na(e,t,i){(e===Ft&&(Tt===2||Tt===9)||e.cancelPendingCommit!==null)&&(mo(e,0),Mr(e,wt,Ga,!1)),Xa(e,i),((At&2)===0||e!==Ft)&&(e===Ft&&((At&2)===0&&(pl|=i),cn===4&&Mr(e,wt,Ga,!1)),ai(e))}function qg(e,t,i){if((At&6)!==0)throw Error(l(327));var o=!i&&(t&127)===0&&(t&e.expiredLanes)===0||Qa(e,t),f=o?zb(e,t):um(e,t,!0),h=o;do{if(f===0){co&&!o&&Mr(e,t,0,!1);break}else{if(i=e.current.alternate,h&&!_b(i)){f=um(e,t,!1),h=!1;continue}if(f===2){if(h=t,e.errorRecoveryDisabledLanes&h)var S=0;else S=e.pendingLanes&-536870913,S=S!==0?S:S&536870912?536870912:0;if(S!==0){t=S;e:{var M=e;f=Sc;var H=M.current.memoizedState.isDehydrated;if(H&&(mo(M,S).flags|=256),S=um(M,S,!1),S!==2){if(am&&!H){M.errorRecoveryDisabledLanes|=h,pl|=h,f=4;break e}h=Aa,Aa=f,h!==null&&(Aa===null?Aa=h:Aa.push.apply(Aa,h))}f=S}if(h=!1,f!==2)continue}}if(f===1){mo(e,0),Mr(e,t,0,!0);break}e:{switch(o=e,h=f,h){case 0:case 1:throw Error(l(345));case 4:if((t&4194048)!==t)break;case 6:Mr(o,t,Ga,!Cr);break e;case 2:Aa=null;break;case 3:case 5:break;default:throw Error(l(329))}if((t&62914560)===t&&(f=Yu+300-tt(),10<f)){if(Mr(o,t,Ga,!Cr),Mn(o,0,!0)!==0)break e;Hi=t,o.timeoutHandle=bv(Gg.bind(null,o,i,Aa,Ku,im,t,Ga,pl,uo,Cr,h,"Throttled",-0,0),f);break e}Gg(o,i,Aa,Ku,im,t,Ga,pl,uo,Cr,h,null,-0,0)}}break}while(!0);ai(e)}function Gg(e,t,i,o,f,h,S,M,H,se,xe,Se,re,fe){if(e.timeoutHandle=-1,Se=t.subtreeFlags,Se&8192||(Se&16785408)===16785408){Se={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:Fn},Og(t,h,Se);var Ue=(h&62914560)===h?Yu-tt():(h&4194048)===h?Hg-tt():0;if(Ue=vS(Se,Ue),Ue!==null){Hi=h,e.cancelPendingCommit=Ue(Jg.bind(null,e,t,h,i,o,f,S,M,H,xe,Se,null,re,fe)),Mr(e,h,S,!se);return}}Jg(e,t,h,i,o,f,S,M,H)}function _b(e){for(var t=e;;){var i=t.tag;if((i===0||i===11||i===15)&&t.flags&16384&&(i=t.updateQueue,i!==null&&(i=i.stores,i!==null)))for(var o=0;o<i.length;o++){var f=i[o],h=f.getSnapshot;f=f.value;try{if(!ia(h(),f))return!1}catch{return!1}}if(i=t.child,t.subtreeFlags&16384&&i!==null)i.return=t,t=i;else{if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return!0;t=t.return}t.sibling.return=t.return,t=t.sibling}}return!0}function Mr(e,t,i,o){t&=~sm,t&=~pl,e.suspendedLanes|=t,e.pingedLanes&=~t,o&&(e.warmLanes|=t),o=e.expirationTimes;for(var f=t;0<f;){var h=31-Nt(f),S=1<<h;o[h]=-1,f&=~S}i!==0&&zs(e,i,t)}function Qu(){return(At&6)===0?(Cc(0),!1):!0}function cm(){if(xt!==null){if(Tt===0)var e=xt.return;else e=xt,Ua=Ni=null,kf(e),vr=null,us=0,e=xt;for(;e!==null;)Sg(e.alternate,e),e=e.return;xt=null}}function mo(e,t){var i=e.timeoutHandle;i!==-1&&(e.timeoutHandle=-1,Jb(i)),i=e.cancelPendingCommit,i!==null&&(e.cancelPendingCommit=null,i()),Hi=0,cm(),Ft=e,xt=i=xa(e.current,null),wt=t,Tt=0,qa=null,Cr=!1,co=Qa(e,t),am=!1,uo=Ga=sm=pl=kr=cn=0,Aa=Sc=null,im=!1,(t&8)!==0&&(t|=t&32);var o=e.entangledLanes;if(o!==0)for(e=e.entanglements,o&=t;0<o;){var f=31-Nt(o),h=1<<f;t|=e[f],o&=~h}return Pi=t,sr(),i}function Vg(e,t){x=null,O.H=hc,t===Zs||t===eo?(t=Mu(),Tt=3):t===ol?(t=Mu(),Tt=4):Tt=t===Hf?8:t!==null&&typeof t=="object"&&typeof t.then=="function"?6:1,qa=t,xt===null&&(cn=1,Fu(e,ra(t,e.current)))}function Yg(){var e=oa.current;return e===null?!0:(wt&4194048)===wt?Sa===null:(wt&62914560)===wt||(wt&536870912)!==0?e===Sa:!1}function Wg(){var e=O.H;return O.H=hc,e===null?hc:e}function Kg(){var e=O.A;return O.A=Rb,e}function Xu(){cn=4,Cr||(wt&4194048)!==wt&&oa.current!==null||(co=!0),(kr&134217727)===0&&(pl&134217727)===0||Ft===null||Mr(Ft,wt,Ga,!1)}function um(e,t,i){var o=At;At|=2;var f=Wg(),h=Kg();(Ft!==e||wt!==t)&&(Ku=null,mo(e,t)),t=!1;var S=cn;e:do try{if(Tt!==0&&xt!==null){var M=xt,H=qa;switch(Tt){case 8:cm(),S=6;break e;case 3:case 2:case 9:case 6:oa.current===null&&(t=!0);var se=Tt;if(Tt=0,qa=null,ho(e,M,H,se),i&&co){S=0;break e}break;default:se=Tt,Tt=0,qa=null,ho(e,M,H,se)}}Lb(),S=cn;break}catch(xe){Vg(e,xe)}while(!0);return t&&e.shellSuspendCounter++,Ua=Ni=null,At=o,O.H=f,O.A=h,xt===null&&(Ft=null,wt=0,sr()),S}function Lb(){for(;xt!==null;)Qg(xt)}function zb(e,t){var i=At;At|=2;var o=Wg(),f=Kg();Ft!==e||wt!==t?(Ku=null,Wu=tt()+500,mo(e,t)):co=Qa(e,t);e:do try{if(Tt!==0&&xt!==null){t=xt;var h=qa;t:switch(Tt){case 1:Tt=0,qa=null,ho(e,t,h,1);break;case 2:case 9:if(Au(h)){Tt=0,qa=null,Xg(t);break}t=function(){Tt!==2&&Tt!==9||Ft!==e||(Tt=7),ai(e)},h.then(t,t);break e;case 3:Tt=7;break e;case 4:Tt=5;break e;case 7:Au(h)?(Tt=0,qa=null,Xg(t)):(Tt=0,qa=null,ho(e,t,h,7));break;case 5:var S=null;switch(xt.tag){case 26:S=xt.memoizedState;case 5:case 27:var M=xt;if(S?Iv(S):M.stateNode.complete){Tt=0,qa=null;var H=M.sibling;if(H!==null)xt=H;else{var se=M.return;se!==null?(xt=se,Zu(se)):xt=null}break t}}Tt=0,qa=null,ho(e,t,h,5);break;case 6:Tt=0,qa=null,ho(e,t,h,6);break;case 8:cm(),cn=6;break e;default:throw Error(l(462))}}Ib();break}catch(xe){Vg(e,xe)}while(!0);return Ua=Ni=null,O.H=o,O.A=f,At=i,xt!==null?0:(Ft=null,wt=0,sr(),cn)}function Ib(){for(;xt!==null&&!ye();)Qg(xt)}function Qg(e){var t=wg(e.alternate,e,Pi);e.memoizedProps=e.pendingProps,t===null?Zu(e):xt=t}function Xg(e){var t=e,i=t.alternate;switch(t.tag){case 15:case 0:t=hg(i,t,t.pendingProps,t.type,void 0,wt);break;case 11:t=hg(i,t,t.pendingProps,t.type.render,t.ref,wt);break;case 5:kf(t);default:Sg(i,t),t=xt=sl(t,Pi),t=wg(i,t,Pi)}e.memoizedProps=e.pendingProps,t===null?Zu(e):xt=t}function ho(e,t,i,o){Ua=Ni=null,kf(t),vr=null,us=0;var f=t.return;try{if(Cb(e,f,t,i,wt)){cn=1,Fu(e,ra(i,e.current)),xt=null;return}}catch(h){if(f!==null)throw xt=f,h;cn=1,Fu(e,ra(i,e.current)),xt=null;return}t.flags&32768?(ft||o===1?e=!0:co||(wt&536870912)!==0?e=!1:(Cr=e=!0,(o===2||o===9||o===3||o===6)&&(o=oa.current,o!==null&&o.tag===13&&(o.flags|=16384))),Zg(t,e)):Zu(t)}function Zu(e){var t=e;do{if((t.flags&32768)!==0){Zg(t,Cr);return}e=t.return;var i=Nb(t.alternate,t,Pi);if(i!==null){xt=i;return}if(t=t.sibling,t!==null){xt=t;return}xt=t=e}while(t!==null);cn===0&&(cn=5)}function Zg(e,t){do{var i=Mb(e.alternate,e);if(i!==null){i.flags&=32767,xt=i;return}if(i=e.return,i!==null&&(i.flags|=32768,i.subtreeFlags=0,i.deletions=null),!t&&(e=e.sibling,e!==null)){xt=e;return}xt=e=i}while(e!==null);cn=6,xt=null}function Jg(e,t,i,o,f,h,S,M,H){e.cancelPendingCommit=null;do Ju();while(kn!==0);if((At&6)!==0)throw Error(l(327));if(t!==null){if(t===e.current)throw Error(l(177));if(h=t.lanes|t.childLanes,h|=ar,qt(e,i,h,S,M,H),e===Ft&&(xt=Ft=null,wt=0),fo=t,Nr=e,Hi=i,rm=h,lm=f,$g=o,(t.subtreeFlags&10256)!==0||(t.flags&10256)!==0?(e.callbackNode=null,e.callbackPriority=0,Pb(St,function(){return sv(),null})):(e.callbackNode=null,e.callbackPriority=0),o=(t.flags&13878)!==0,(t.subtreeFlags&13878)!==0||o){o=O.T,O.T=null,f=Z.p,Z.p=2,S=At,At|=4;try{Tb(e,t,i)}finally{At=S,Z.p=f,O.T=o}}kn=1,ev(),tv(),nv()}}function ev(){if(kn===1){kn=0;var e=Nr,t=fo,i=(t.flags&13878)!==0;if((t.subtreeFlags&13878)!==0||i){i=O.T,O.T=null;var o=Z.p;Z.p=2;var f=At;At|=4;try{Lg(t,e);var h=Sm,S=Yo(e.containerInfo),M=h.focusedElem,H=h.selectionRange;if(S!==M&&M&&M.ownerDocument&&gi(M.ownerDocument.documentElement,M)){if(H!==null&&Gl(M)){var se=H.start,xe=H.end;if(xe===void 0&&(xe=se),"selectionStart"in M)M.selectionStart=se,M.selectionEnd=Math.min(xe,M.value.length);else{var Se=M.ownerDocument||document,re=Se&&Se.defaultView||window;if(re.getSelection){var fe=re.getSelection(),Ue=M.textContent.length,Ze=Math.min(H.start,Ue),Lt=H.end===void 0?Ze:Math.min(H.end,Ue);!fe.extend&&Ze>Lt&&(S=Lt,Lt=Ze,Ze=S);var ee=Vo(M,Ze),G=Vo(M,Lt);if(ee&&G&&(fe.rangeCount!==1||fe.anchorNode!==ee.node||fe.anchorOffset!==ee.offset||fe.focusNode!==G.node||fe.focusOffset!==G.offset)){var ae=Se.createRange();ae.setStart(ee.node,ee.offset),fe.removeAllRanges(),Ze>Lt?(fe.addRange(ae),fe.extend(G.node,G.offset)):(ae.setEnd(G.node,G.offset),fe.addRange(ae))}}}}for(Se=[],fe=M;fe=fe.parentNode;)fe.nodeType===1&&Se.push({element:fe,left:fe.scrollLeft,top:fe.scrollTop});for(typeof M.focus=="function"&&M.focus(),M=0;M<Se.length;M++){var be=Se[M];be.element.scrollLeft=be.left,be.element.scrollTop=be.top}}dd=!!bm,Sm=bm=null}finally{At=f,Z.p=o,O.T=i}}e.current=t,kn=2}}function tv(){if(kn===2){kn=0;var e=Nr,t=fo,i=(t.flags&8772)!==0;if((t.subtreeFlags&8772)!==0||i){i=O.T,O.T=null;var o=Z.p;Z.p=2;var f=At;At|=4;try{Tg(e,t.alternate,t)}finally{At=f,Z.p=o,O.T=i}}kn=3}}function nv(){if(kn===4||kn===3){kn=0,qe();var e=Nr,t=fo,i=Hi,o=$g;(t.subtreeFlags&10256)!==0||(t.flags&10256)!==0?kn=5:(kn=0,fo=Nr=null,av(e,e.pendingLanes));var f=e.pendingLanes;if(f===0&&(Ar=null),en(i),t=t.stateNode,st&&typeof st.onCommitFiberRoot=="function")try{st.onCommitFiberRoot(pt,t,void 0,(t.current.flags&128)===128)}catch{}if(o!==null){t=O.T,f=Z.p,Z.p=2,O.T=null;try{for(var h=e.onRecoverableError,S=0;S<o.length;S++){var M=o[S];h(M.value,{componentStack:M.stack})}}finally{O.T=t,Z.p=f}}(Hi&3)!==0&&Ju(),ai(e),f=e.pendingLanes,(i&261930)!==0&&(f&42)!==0?e===om?jc++:(jc=0,om=e):jc=0,Cc(0)}}function av(e,t){(e.pooledCacheLanes&=t)===0&&(t=e.pooledCache,t!=null&&(e.pooledCache=null,rl(t)))}function Ju(){return ev(),tv(),nv(),sv()}function sv(){if(kn!==5)return!1;var e=Nr,t=rm;rm=0;var i=en(Hi),o=O.T,f=Z.p;try{Z.p=32>i?32:i,O.T=null,i=lm,lm=null;var h=Nr,S=Hi;if(kn=0,fo=Nr=null,Hi=0,(At&6)!==0)throw Error(l(331));var M=At;if(At|=4,Fg(h.current),Ig(h,h.current,S,i),At=M,Cc(0,!1),st&&typeof st.onPostCommitFiberRoot=="function")try{st.onPostCommitFiberRoot(pt,h)}catch{}return!0}finally{Z.p=f,O.T=o,av(e,t)}}function iv(e,t,i){t=ra(i,t),t=Pf(e.stateNode,t,2),e=ei(e,t,2),e!==null&&(Xa(e,2),ai(e))}function Et(e,t,i){if(e.tag===3)iv(e,e,i);else for(;t!==null;){if(t.tag===3){iv(t,e,i);break}else if(t.tag===1){var o=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof o.componentDidCatch=="function"&&(Ar===null||!Ar.has(o))){e=ra(i,e),i=rg(2),o=ei(t,i,2),o!==null&&(lg(i,o,t,e),Xa(o,2),ai(o));break}}t=t.return}}function dm(e,t,i){var o=e.pingCache;if(o===null){o=e.pingCache=new Db;var f=new Set;o.set(t,f)}else f=o.get(t),f===void 0&&(f=new Set,o.set(t,f));f.has(i)||(am=!0,f.add(i),e=Ob.bind(null,e,t,i),t.then(e,e))}function Ob(e,t,i){var o=e.pingCache;o!==null&&o.delete(t),e.pingedLanes|=e.suspendedLanes&i,e.warmLanes&=~i,Ft===e&&(wt&i)===i&&(cn===4||cn===3&&(wt&62914560)===wt&&300>tt()-Yu?(At&2)===0&&mo(e,0):sm|=i,uo===wt&&(uo=0)),ai(e)}function rv(e,t){t===0&&(t=ri()),e=rs(e,t),e!==null&&(Xa(e,t),ai(e))}function Bb(e){var t=e.memoizedState,i=0;t!==null&&(i=t.retryLane),rv(e,i)}function Fb(e,t){var i=0;switch(e.tag){case 31:case 13:var o=e.stateNode,f=e.memoizedState;f!==null&&(i=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(t),rv(e,i)}function Pb(e,t){return Ae(e,t)}var ed=null,po=null,fm=!1,td=!1,mm=!1,Tr=0;function ai(e){e!==po&&e.next===null&&(po===null?ed=po=e:po=po.next=e),td=!0,fm||(fm=!0,$b())}function Cc(e,t){if(!mm&&td){mm=!0;do for(var i=!1,o=ed;o!==null;){if(e!==0){var f=o.pendingLanes;if(f===0)var h=0;else{var S=o.suspendedLanes,M=o.pingedLanes;h=(1<<31-Nt(42|e)+1)-1,h&=f&~(S&~M),h=h&201326741?h&201326741|1:h?h|2:0}h!==0&&(i=!0,uv(o,h))}else h=wt,h=Mn(o,o===Ft?h:0,o.cancelPendingCommit!==null||o.timeoutHandle!==-1),(h&3)===0||Qa(o,h)||(i=!0,uv(o,h));o=o.next}while(i);mm=!1}}function Hb(){lv()}function lv(){td=fm=!1;var e=0;Tr!==0&&Zb()&&(e=Tr);for(var t=tt(),i=null,o=ed;o!==null;){var f=o.next,h=ov(o,t);h===0?(o.next=null,i===null?ed=f:i.next=f,f===null&&(po=i)):(i=o,(e!==0||(h&3)!==0)&&(td=!0)),o=f}kn!==0&&kn!==5||Cc(e),Tr!==0&&(Tr=0)}function ov(e,t){for(var i=e.suspendedLanes,o=e.pingedLanes,f=e.expirationTimes,h=e.pendingLanes&-62914561;0<h;){var S=31-Nt(h),M=1<<S,H=f[S];H===-1?((M&i)===0||(M&o)!==0)&&(f[S]=Ie(M,t)):H<=t&&(e.expiredLanes|=M),h&=~M}if(t=Ft,i=wt,i=Mn(e,e===t?i:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),o=e.callbackNode,i===0||e===t&&(Tt===2||Tt===9)||e.cancelPendingCommit!==null)return o!==null&&o!==null&&de(o),e.callbackNode=null,e.callbackPriority=0;if((i&3)===0||Qa(e,i)){if(t=i&-i,t===e.callbackPriority)return t;switch(o!==null&&de(o),en(i)){case 2:case 8:i=ht;break;case 32:i=St;break;case 268435456:i=Oe;break;default:i=St}return o=cv.bind(null,e),i=Ae(i,o),e.callbackPriority=t,e.callbackNode=i,t}return o!==null&&o!==null&&de(o),e.callbackPriority=2,e.callbackNode=null,2}function cv(e,t){if(kn!==0&&kn!==5)return e.callbackNode=null,e.callbackPriority=0,null;var i=e.callbackNode;if(Ju()&&e.callbackNode!==i)return null;var o=wt;return o=Mn(e,e===Ft?o:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),o===0?null:(qg(e,o,t),ov(e,tt()),e.callbackNode!=null&&e.callbackNode===i?cv.bind(null,e):null)}function uv(e,t){if(Ju())return null;qg(e,t,!0)}function $b(){eS(function(){(At&6)!==0?Ae(Ke,Hb):lv()})}function hm(){if(Tr===0){var e=pr;e===0&&(e=un,un<<=1,(un&261888)===0&&(un=256)),Tr=e}return Tr}function dv(e){return e==null||typeof e=="symbol"||typeof e=="boolean"?null:typeof e=="function"?e:Ia(""+e)}function fv(e,t){var i=t.ownerDocument.createElement("input");return i.name=t.name,i.value=t.value,e.id&&i.setAttribute("form",e.id),t.parentNode.insertBefore(i,t),e=new FormData(e),i.parentNode.removeChild(i),e}function Ub(e,t,i,o,f){if(t==="submit"&&i&&i.stateNode===f){var h=dv((f[Me]||null).action),S=o.submitter;S&&(t=(t=S[Me]||null)?dv(t.formAction):S.getAttribute("formAction"),t!==null&&(h=t,S=null));var M=new Ps("action","action",null,o,f);e.push({event:M,listeners:[{instance:null,listener:function(){if(o.defaultPrevented){if(Tr!==0){var H=S?fv(f,S):new FormData(f);Lf(i,{pending:!0,data:H,method:f.method,action:h},null,H)}}else typeof h=="function"&&(M.preventDefault(),H=S?fv(f,S):new FormData(f),Lf(i,{pending:!0,data:H,method:f.method,action:h},h,H))},currentTarget:f}]})}}for(var pm=0;pm<nl.length;pm++){var gm=nl[pm],qb=gm.toLowerCase(),Gb=gm[0].toUpperCase()+gm.slice(1);$n(qb,"on"+Gb)}$n(bs,"onAnimationEnd"),$n(tl,"onAnimationIteration"),$n(vi,"onAnimationStart"),$n("dblclick","onDoubleClick"),$n("focusin","onFocus"),$n("focusout","onBlur"),$n(xi,"onTransitionRun"),$n(Qo,"onTransitionStart"),$n(wf,"onTransitionCancel"),$n(Xo,"onTransitionEnd"),Qt("onMouseEnter",["mouseout","mouseover"]),Qt("onMouseLeave",["mouseout","mouseover"]),Qt("onPointerEnter",["pointerout","pointerover"]),Qt("onPointerLeave",["pointerout","pointerover"]),rn("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),rn("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),rn("onBeforeInput",["compositionend","keypress","textInput","paste"]),rn("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),rn("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),rn("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var kc="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(" "),Vb=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(kc));function mv(e,t){t=(t&4)!==0;for(var i=0;i<e.length;i++){var o=e[i],f=o.event;o=o.listeners;e:{var h=void 0;if(t)for(var S=o.length-1;0<=S;S--){var M=o[S],H=M.instance,se=M.currentTarget;if(M=M.listener,H!==h&&f.isPropagationStopped())break e;h=M,f.currentTarget=se;try{h(f)}catch(xe){Wl(xe)}f.currentTarget=null,h=H}else for(S=0;S<o.length;S++){if(M=o[S],H=M.instance,se=M.currentTarget,M=M.listener,H!==h&&f.isPropagationStopped())break e;h=M,f.currentTarget=se;try{h(f)}catch(xe){Wl(xe)}f.currentTarget=null,h=H}}}}function yt(e,t){var i=t[at];i===void 0&&(i=t[at]=new Set);var o=e+"__bubble";i.has(o)||(hv(t,e,2,!1),i.add(o))}function vm(e,t,i){var o=0;t&&(o|=4),hv(i,e,o,t)}var nd="_reactListening"+Math.random().toString(36).slice(2);function xm(e){if(!e[nd]){e[nd]=!0,Tn.forEach(function(i){i!=="selectionchange"&&(Vb.has(i)||vm(i,!1,e),vm(i,!0,e))});var t=e.nodeType===9?e:e.ownerDocument;t===null||t[nd]||(t[nd]=!0,vm("selectionchange",!1,t))}}function hv(e,t,i,o){switch(Uv(t)){case 2:var f=wS;break;case 8:f=bS;break;default:f=_m}i=f.bind(null,t,i,e),f=void 0,!cu||t!=="touchstart"&&t!=="touchmove"&&t!=="wheel"||(f=!0),o?f!==void 0?e.addEventListener(t,i,{capture:!0,passive:f}):e.addEventListener(t,i,!0):f!==void 0?e.addEventListener(t,i,{passive:f}):e.addEventListener(t,i,!1)}function ym(e,t,i,o,f){var h=o;if((t&1)===0&&(t&2)===0&&o!==null)e:for(;;){if(o===null)return;var S=o.tag;if(S===3||S===4){var M=o.stateNode.containerInfo;if(M===f)break;if(S===4)for(S=o.return;S!==null;){var H=S.tag;if((H===3||H===4)&&S.stateNode.containerInfo===f)return;S=S.return}for(;M!==null;){if(S=Pt(M),S===null)return;if(H=S.tag,H===5||H===6||H===26||H===27){o=h=S;continue e}M=M.parentNode}}o=o.return}ou(function(){var se=h,xe=Oo(i),Se=[];e:{var re=Yl.get(e);if(re!==void 0){var fe=Ps,Ue=e;switch(e){case"keypress":if(Ll(i)===0)break e;case"keydown":case"keyup":fe=qs;break;case"focusin":Ue="focus",fe=Kn;break;case"focusout":Ue="blur",fe=Kn;break;case"beforeblur":case"afterblur":fe=Kn;break;case"click":if(i.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":fe=Fl;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":fe=et;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":fe=ns;break;case bs:case tl:case vi:fe=$s;break;case Xo:fe=Uo;break;case"scroll":case"scrollend":fe=Il;break;case"wheel":fe=mu;break;case"copy":case"cut":case"paste":fe=fu;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":fe=$o;break;case"toggle":case"beforetoggle":fe=hu}var Ze=(t&4)!==0,Lt=!Ze&&(e==="scroll"||e==="scrollend"),ee=Ze?re!==null?re+"Capture":null:re;Ze=[];for(var G=se,ae;G!==null;){var be=G;if(ae=be.stateNode,be=be.tag,be!==5&&be!==26&&be!==27||ae===null||ee===null||(be=ts(G,ee),be!=null&&Ze.push(Ac(G,be,ae))),Lt)break;G=G.return}0<Ze.length&&(re=new fe(re,Ue,null,i,xe),Se.push({event:re,listeners:Ze}))}}if((t&7)===0){e:{if(re=e==="mouseover"||e==="pointerover",fe=e==="mouseout"||e==="pointerout",re&&i!==es&&(Ue=i.relatedTarget||i.fromElement)&&(Pt(Ue)||Ue[Pe]))break e;if((fe||re)&&(re=xe.window===xe?xe:(re=xe.ownerDocument)?re.defaultView||re.parentWindow:window,fe?(Ue=i.relatedTarget||i.toElement,fe=se,Ue=Ue?Pt(Ue):null,Ue!==null&&(Lt=d(Ue),Ze=Ue.tag,Ue!==Lt||Ze!==5&&Ze!==27&&Ze!==6)&&(Ue=null)):(fe=null,Ue=se),fe!==Ue)){if(Ze=Fl,be="onMouseLeave",ee="onMouseEnter",G="mouse",(e==="pointerout"||e==="pointerover")&&(Ze=$o,be="onPointerLeave",ee="onPointerEnter",G="pointer"),Lt=fe==null?re:Ot(fe),ae=Ue==null?re:Ot(Ue),re=new Ze(be,G+"leave",fe,i,xe),re.target=Lt,re.relatedTarget=ae,be=null,Pt(xe)===se&&(Ze=new Ze(ee,G+"enter",Ue,i,xe),Ze.target=ae,Ze.relatedTarget=Lt,be=Ze),Lt=be,fe&&Ue)t:{for(Ze=Yb,ee=fe,G=Ue,ae=0,be=ee;be;be=Ze(be))ae++;be=0;for(var We=G;We;We=Ze(We))be++;for(;0<ae-be;)ee=Ze(ee),ae--;for(;0<be-ae;)G=Ze(G),be--;for(;ae--;){if(ee===G||G!==null&&ee===G.alternate){Ze=ee;break t}ee=Ze(ee),G=Ze(G)}Ze=null}else Ze=null;fe!==null&&pv(Se,re,fe,Ze,!1),Ue!==null&&Lt!==null&&pv(Se,Lt,Ue,Ze,!0)}}e:{if(re=se?Ot(se):window,fe=re.nodeName&&re.nodeName.toLowerCase(),fe==="select"||fe==="input"&&re.type==="file")var Ct=yu;else if(Jr(re))if(qo)Ct=ws;else{Ct=Ul;var Ge=Ji}else fe=re.nodeName,!fe||fe.toLowerCase()!=="input"||re.type!=="checkbox"&&re.type!=="radio"?se&&Qi(se.elementType)&&(Ct=yu):Ct=ql;if(Ct&&(Ct=Ct(e,se))){Fa(Se,Ct,i,xe);break e}Ge&&Ge(e,re,se),e==="focusout"&&se&&re.type==="number"&&se.memoizedProps.value!=null&&Ki(re,"number",re.value)}switch(Ge=se?Ot(se):window,e){case"focusin":(Jr(Ge)||Ge.contentEditable==="true")&&(Pa=Ge,Wo=se,er=null);break;case"focusout":er=Wo=Pa=null;break;case"mousedown":Ko=!0;break;case"contextmenu":case"mouseup":case"dragend":Ko=!1,bu(Se,i,xe);break;case"selectionchange":if(yf)break;case"keydown":case"keyup":bu(Se,i,xe)}var ct;if(Hl)e:{switch(e){case"compositionstart":var bt="onCompositionStart";break e;case"compositionend":bt="onCompositionEnd";break e;case"compositionupdate":bt="onCompositionUpdate";break e}bt=void 0}else hi?mi(e,i)&&(bt="onCompositionEnd"):e==="keydown"&&i.keyCode===229&&(bt="onCompositionStart");bt&&(pu&&i.locale!=="ko"&&(hi||bt!=="onCompositionStart"?bt==="onCompositionEnd"&&hi&&(ct=Fo()):(di=xe,Bo="value"in di?di.value:di.textContent,hi=!0)),Ge=ad(se,bt),0<Ge.length&&(bt=new Qr(bt,e,null,i,xe),Se.push({event:bt,listeners:Ge}),ct?bt.data=ct:(ct=vu(i),ct!==null&&(bt.data=ct)))),(ct=fi?ys(e,i):xu(e,i))&&(bt=ad(se,"onBeforeInput"),0<bt.length&&(Ge=new Qr("onBeforeInput","beforeinput",null,i,xe),Se.push({event:Ge,listeners:bt}),Ge.data=ct)),Ub(Se,e,se,i,xe)}mv(Se,t)})}function Ac(e,t,i){return{instance:e,listener:t,currentTarget:i}}function ad(e,t){for(var i=t+"Capture",o=[];e!==null;){var f=e,h=f.stateNode;if(f=f.tag,f!==5&&f!==26&&f!==27||h===null||(f=ts(e,i),f!=null&&o.unshift(Ac(e,f,h)),f=ts(e,t),f!=null&&o.push(Ac(e,f,h))),e.tag===3)return o;e=e.return}return[]}function Yb(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5&&e.tag!==27);return e||null}function pv(e,t,i,o,f){for(var h=t._reactName,S=[];i!==null&&i!==o;){var M=i,H=M.alternate,se=M.stateNode;if(M=M.tag,H!==null&&H===o)break;M!==5&&M!==26&&M!==27||se===null||(H=se,f?(se=ts(i,h),se!=null&&S.unshift(Ac(i,se,H))):f||(se=ts(i,h),se!=null&&S.push(Ac(i,se,H)))),i=i.return}S.length!==0&&e.push({event:t,listeners:S})}var Wb=/\r\n?/g,Kb=/\u0000|\uFFFD/g;function gv(e){return(typeof e=="string"?e:""+e).replace(Wb,`
9
+ `).replace(Kb,"")}function vv(e,t){return t=gv(t),gv(e)===t}function _t(e,t,i,o,f,h){switch(i){case"children":typeof o=="string"?t==="body"||t==="textarea"&&o===""||Os(e,o):(typeof o=="number"||typeof o=="bigint")&&t!=="body"&&Os(e,""+o);break;case"className":Rl(e,"class",o);break;case"tabIndex":Rl(e,"tabindex",o);break;case"dir":case"role":case"viewBox":case"width":case"height":Rl(e,i,o);break;case"style":Yr(e,o,h);break;case"data":if(t!=="object"){Rl(e,"data",o);break}case"src":case"href":if(o===""&&(t!=="a"||i!=="href")){e.removeAttribute(i);break}if(o==null||typeof o=="function"||typeof o=="symbol"||typeof o=="boolean"){e.removeAttribute(i);break}o=Ia(""+o),e.setAttribute(i,o);break;case"action":case"formAction":if(typeof o=="function"){e.setAttribute(i,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof h=="function"&&(i==="formAction"?(t!=="input"&&_t(e,t,"name",f.name,f,null),_t(e,t,"formEncType",f.formEncType,f,null),_t(e,t,"formMethod",f.formMethod,f,null),_t(e,t,"formTarget",f.formTarget,f,null)):(_t(e,t,"encType",f.encType,f,null),_t(e,t,"method",f.method,f,null),_t(e,t,"target",f.target,f,null)));if(o==null||typeof o=="symbol"||typeof o=="boolean"){e.removeAttribute(i);break}o=Ia(""+o),e.setAttribute(i,o);break;case"onClick":o!=null&&(e.onclick=Fn);break;case"onScroll":o!=null&&yt("scroll",e);break;case"onScrollEnd":o!=null&&yt("scrollend",e);break;case"dangerouslySetInnerHTML":if(o!=null){if(typeof o!="object"||!("__html"in o))throw Error(l(61));if(i=o.__html,i!=null){if(f.children!=null)throw Error(l(60));e.innerHTML=i}}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}i=Ia(""+o),e.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",i);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":o!=null&&typeof o!="function"&&typeof o!="symbol"?e.setAttribute(i,""+o):e.removeAttribute(i);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":o&&typeof o!="function"&&typeof o!="symbol"?e.setAttribute(i,""):e.removeAttribute(i);break;case"capture":case"download":o===!0?e.setAttribute(i,""):o!==!1&&o!=null&&typeof o!="function"&&typeof o!="symbol"?e.setAttribute(i,o):e.removeAttribute(i);break;case"cols":case"rows":case"size":case"span":o!=null&&typeof o!="function"&&typeof o!="symbol"&&!isNaN(o)&&1<=o?e.setAttribute(i,o):e.removeAttribute(i);break;case"rowSpan":case"start":o==null||typeof o=="function"||typeof o=="symbol"||isNaN(o)?e.removeAttribute(i):e.setAttribute(i,o);break;case"popover":yt("beforetoggle",e),yt("toggle",e),Yi(e,"popover",o);break;case"xlinkActuate":La(e,"http://www.w3.org/1999/xlink","xlink:actuate",o);break;case"xlinkArcrole":La(e,"http://www.w3.org/1999/xlink","xlink:arcrole",o);break;case"xlinkRole":La(e,"http://www.w3.org/1999/xlink","xlink:role",o);break;case"xlinkShow":La(e,"http://www.w3.org/1999/xlink","xlink:show",o);break;case"xlinkTitle":La(e,"http://www.w3.org/1999/xlink","xlink:title",o);break;case"xlinkType":La(e,"http://www.w3.org/1999/xlink","xlink:type",o);break;case"xmlBase":La(e,"http://www.w3.org/XML/1998/namespace","xml:base",o);break;case"xmlLang":La(e,"http://www.w3.org/XML/1998/namespace","xml:lang",o);break;case"xmlSpace":La(e,"http://www.w3.org/XML/1998/namespace","xml:space",o);break;case"is":Yi(e,"is",o);break;case"innerText":case"textContent":break;default:(!(2<i.length)||i[0]!=="o"&&i[0]!=="O"||i[1]!=="n"&&i[1]!=="N")&&(i=Io.get(i)||i,Yi(e,i,o))}}function wm(e,t,i,o,f,h){switch(i){case"style":Yr(e,o,h);break;case"dangerouslySetInnerHTML":if(o!=null){if(typeof o!="object"||!("__html"in o))throw Error(l(61));if(i=o.__html,i!=null){if(f.children!=null)throw Error(l(60));e.innerHTML=i}}break;case"children":typeof o=="string"?Os(e,o):(typeof o=="number"||typeof o=="bigint")&&Os(e,""+o);break;case"onScroll":o!=null&&yt("scroll",e);break;case"onScrollEnd":o!=null&&yt("scrollend",e);break;case"onClick":o!=null&&(e.onclick=Fn);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!Za.hasOwnProperty(i))e:{if(i[0]==="o"&&i[1]==="n"&&(f=i.endsWith("Capture"),t=i.slice(2,f?i.length-7:void 0),h=e[Me]||null,h=h!=null?h[i]:null,typeof h=="function"&&e.removeEventListener(t,h,f),typeof o=="function")){typeof h!="function"&&h!==null&&(i in e?e[i]=null:e.hasAttribute(i)&&e.removeAttribute(i)),e.addEventListener(t,o,f);break e}i in e?e[i]=o:o===!0?e.setAttribute(i,""):Yi(e,i,o)}}}function Gn(e,t,i){switch(t){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":yt("error",e),yt("load",e);var o=!1,f=!1,h;for(h in i)if(i.hasOwnProperty(h)){var S=i[h];if(S!=null)switch(h){case"src":o=!0;break;case"srcSet":f=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(l(137,t));default:_t(e,t,h,S,i,null)}}f&&_t(e,t,"srcSet",i.srcSet,i,null),o&&_t(e,t,"src",i.src,i,null);return;case"input":yt("invalid",e);var M=h=S=f=null,H=null,se=null;for(o in i)if(i.hasOwnProperty(o)){var xe=i[o];if(xe!=null)switch(o){case"name":f=xe;break;case"type":S=xe;break;case"checked":H=xe;break;case"defaultChecked":se=xe;break;case"value":h=xe;break;case"defaultValue":M=xe;break;case"children":case"dangerouslySetInnerHTML":if(xe!=null)throw Error(l(137,t));break;default:_t(e,t,o,xe,i,null)}}Wi(e,h,M,H,se,S,f,!1);return;case"select":yt("invalid",e),o=S=h=null;for(f in i)if(i.hasOwnProperty(f)&&(M=i[f],M!=null))switch(f){case"value":h=M;break;case"defaultValue":S=M;break;case"multiple":o=M;default:_t(e,t,f,M,i,null)}t=h,i=S,e.multiple=!!o,t!=null?Ja(e,!!o,t,!1):i!=null&&Ja(e,!!o,i,!0);return;case"textarea":yt("invalid",e),h=f=o=null;for(S in i)if(i.hasOwnProperty(S)&&(M=i[S],M!=null))switch(S){case"value":o=M;break;case"defaultValue":f=M;break;case"children":h=M;break;case"dangerouslySetInnerHTML":if(M!=null)throw Error(l(91));break;default:_t(e,t,S,M,i,null)}ui(e,o,f,h);return;case"option":for(H in i)i.hasOwnProperty(H)&&(o=i[H],o!=null)&&(H==="selected"?e.selected=o&&typeof o!="function"&&typeof o!="symbol":_t(e,t,H,o,i,null));return;case"dialog":yt("beforetoggle",e),yt("toggle",e),yt("cancel",e),yt("close",e);break;case"iframe":case"object":yt("load",e);break;case"video":case"audio":for(o=0;o<kc.length;o++)yt(kc[o],e);break;case"image":yt("error",e),yt("load",e);break;case"details":yt("toggle",e);break;case"embed":case"source":case"link":yt("error",e),yt("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(se in i)if(i.hasOwnProperty(se)&&(o=i[se],o!=null))switch(se){case"children":case"dangerouslySetInnerHTML":throw Error(l(137,t));default:_t(e,t,se,o,i,null)}return;default:if(Qi(t)){for(xe in i)i.hasOwnProperty(xe)&&(o=i[xe],o!==void 0&&wm(e,t,xe,o,i,void 0));return}}for(M in i)i.hasOwnProperty(M)&&(o=i[M],o!=null&&_t(e,t,M,o,i,null))}function Qb(e,t,i,o){switch(t){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var f=null,h=null,S=null,M=null,H=null,se=null,xe=null;for(fe in i){var Se=i[fe];if(i.hasOwnProperty(fe)&&Se!=null)switch(fe){case"checked":break;case"value":break;case"defaultValue":H=Se;default:o.hasOwnProperty(fe)||_t(e,t,fe,null,o,Se)}}for(var re in o){var fe=o[re];if(Se=i[re],o.hasOwnProperty(re)&&(fe!=null||Se!=null))switch(re){case"type":h=fe;break;case"name":f=fe;break;case"checked":se=fe;break;case"defaultChecked":xe=fe;break;case"value":S=fe;break;case"defaultValue":M=fe;break;case"children":case"dangerouslySetInnerHTML":if(fe!=null)throw Error(l(137,t));break;default:fe!==Se&&_t(e,t,re,fe,o,Se)}}oi(e,S,M,H,se,xe,h,f);return;case"select":fe=S=M=re=null;for(h in i)if(H=i[h],i.hasOwnProperty(h)&&H!=null)switch(h){case"value":break;case"multiple":fe=H;default:o.hasOwnProperty(h)||_t(e,t,h,null,o,H)}for(f in o)if(h=o[f],H=i[f],o.hasOwnProperty(f)&&(h!=null||H!=null))switch(f){case"value":re=h;break;case"defaultValue":M=h;break;case"multiple":S=h;default:h!==H&&_t(e,t,f,h,o,H)}t=M,i=S,o=fe,re!=null?Ja(e,!!i,re,!1):!!o!=!!i&&(t!=null?Ja(e,!!i,t,!0):Ja(e,!!i,i?[]:"",!1));return;case"textarea":fe=re=null;for(M in i)if(f=i[M],i.hasOwnProperty(M)&&f!=null&&!o.hasOwnProperty(M))switch(M){case"value":break;case"children":break;default:_t(e,t,M,null,o,f)}for(S in o)if(f=o[S],h=i[S],o.hasOwnProperty(S)&&(f!=null||h!=null))switch(S){case"value":re=f;break;case"defaultValue":fe=f;break;case"children":break;case"dangerouslySetInnerHTML":if(f!=null)throw Error(l(91));break;default:f!==h&&_t(e,t,S,f,o,h)}ci(e,re,fe);return;case"option":for(var Ue in i)re=i[Ue],i.hasOwnProperty(Ue)&&re!=null&&!o.hasOwnProperty(Ue)&&(Ue==="selected"?e.selected=!1:_t(e,t,Ue,null,o,re));for(H in o)re=o[H],fe=i[H],o.hasOwnProperty(H)&&re!==fe&&(re!=null||fe!=null)&&(H==="selected"?e.selected=re&&typeof re!="function"&&typeof re!="symbol":_t(e,t,H,re,o,fe));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 Ze in i)re=i[Ze],i.hasOwnProperty(Ze)&&re!=null&&!o.hasOwnProperty(Ze)&&_t(e,t,Ze,null,o,re);for(se in o)if(re=o[se],fe=i[se],o.hasOwnProperty(se)&&re!==fe&&(re!=null||fe!=null))switch(se){case"children":case"dangerouslySetInnerHTML":if(re!=null)throw Error(l(137,t));break;default:_t(e,t,se,re,o,fe)}return;default:if(Qi(t)){for(var Lt in i)re=i[Lt],i.hasOwnProperty(Lt)&&re!==void 0&&!o.hasOwnProperty(Lt)&&wm(e,t,Lt,void 0,o,re);for(xe in o)re=o[xe],fe=i[xe],!o.hasOwnProperty(xe)||re===fe||re===void 0&&fe===void 0||wm(e,t,xe,re,o,fe);return}}for(var ee in i)re=i[ee],i.hasOwnProperty(ee)&&re!=null&&!o.hasOwnProperty(ee)&&_t(e,t,ee,null,o,re);for(Se in o)re=o[Se],fe=i[Se],!o.hasOwnProperty(Se)||re===fe||re==null&&fe==null||_t(e,t,Se,re,o,fe)}function xv(e){switch(e){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function Xb(){if(typeof performance.getEntriesByType=="function"){for(var e=0,t=0,i=performance.getEntriesByType("resource"),o=0;o<i.length;o++){var f=i[o],h=f.transferSize,S=f.initiatorType,M=f.duration;if(h&&M&&xv(S)){for(S=0,M=f.responseEnd,o+=1;o<i.length;o++){var H=i[o],se=H.startTime;if(se>M)break;var xe=H.transferSize,Se=H.initiatorType;xe&&xv(Se)&&(H=H.responseEnd,S+=xe*(H<M?1:(M-se)/(H-se)))}if(--o,t+=8*(h+S)/(f.duration/1e3),e++,10<e)break}}if(0<e)return t/e/1e6}return navigator.connection&&(e=navigator.connection.downlink,typeof e=="number")?e:5}var bm=null,Sm=null;function sd(e){return e.nodeType===9?e:e.ownerDocument}function yv(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 wv(e,t){if(e===0)switch(t){case"svg":return 1;case"math":return 2;default:return 0}return e===1&&t==="foreignObject"?0:e}function jm(e,t){return e==="textarea"||e==="noscript"||typeof t.children=="string"||typeof t.children=="number"||typeof t.children=="bigint"||typeof t.dangerouslySetInnerHTML=="object"&&t.dangerouslySetInnerHTML!==null&&t.dangerouslySetInnerHTML.__html!=null}var Cm=null;function Zb(){var e=window.event;return e&&e.type==="popstate"?e===Cm?!1:(Cm=e,!0):(Cm=null,!1)}var bv=typeof setTimeout=="function"?setTimeout:void 0,Jb=typeof clearTimeout=="function"?clearTimeout:void 0,Sv=typeof Promise=="function"?Promise:void 0,eS=typeof queueMicrotask=="function"?queueMicrotask:typeof Sv<"u"?function(e){return Sv.resolve(null).then(e).catch(tS)}:bv;function tS(e){setTimeout(function(){throw e})}function Er(e){return e==="head"}function jv(e,t){var i=t,o=0;do{var f=i.nextSibling;if(e.removeChild(i),f&&f.nodeType===8)if(i=f.data,i==="/$"||i==="/&"){if(o===0){e.removeChild(f),yo(t);return}o--}else if(i==="$"||i==="$?"||i==="$~"||i==="$!"||i==="&")o++;else if(i==="html")Nc(e.ownerDocument.documentElement);else if(i==="head"){i=e.ownerDocument.head,Nc(i);for(var h=i.firstChild;h;){var S=h.nextSibling,M=h.nodeName;h[rt]||M==="SCRIPT"||M==="STYLE"||M==="LINK"&&h.rel.toLowerCase()==="stylesheet"||i.removeChild(h),h=S}}else i==="body"&&Nc(e.ownerDocument.body);i=f}while(i);yo(t)}function Cv(e,t){var i=e;e=0;do{var o=i.nextSibling;if(i.nodeType===1?t?(i._stashedDisplay=i.style.display,i.style.display="none"):(i.style.display=i._stashedDisplay||"",i.getAttribute("style")===""&&i.removeAttribute("style")):i.nodeType===3&&(t?(i._stashedText=i.nodeValue,i.nodeValue=""):i.nodeValue=i._stashedText||""),o&&o.nodeType===8)if(i=o.data,i==="/$"){if(e===0)break;e--}else i!=="$"&&i!=="$?"&&i!=="$~"&&i!=="$!"||e++;i=o}while(i)}function km(e){var t=e.firstChild;for(t&&t.nodeType===10&&(t=t.nextSibling);t;){var i=t;switch(t=t.nextSibling,i.nodeName){case"HTML":case"HEAD":case"BODY":km(i),Kt(i);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(i.rel.toLowerCase()==="stylesheet")continue}e.removeChild(i)}}function nS(e,t,i,o){for(;e.nodeType===1;){var f=i;if(e.nodeName.toLowerCase()!==t.toLowerCase()){if(!o&&(e.nodeName!=="INPUT"||e.type!=="hidden"))break}else if(o){if(!e[rt])switch(t){case"meta":if(!e.hasAttribute("itemprop"))break;return e;case"link":if(h=e.getAttribute("rel"),h==="stylesheet"&&e.hasAttribute("data-precedence"))break;if(h!==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(h=e.getAttribute("src"),(h!==(f.src==null?null:f.src)||e.getAttribute("type")!==(f.type==null?null:f.type)||e.getAttribute("crossorigin")!==(f.crossOrigin==null?null:f.crossOrigin))&&h&&e.hasAttribute("async")&&!e.hasAttribute("itemprop"))break;return e;default:return e}}else if(t==="input"&&e.type==="hidden"){var h=f.name==null?null:""+f.name;if(f.type==="hidden"&&e.getAttribute("name")===h)return e}else return e;if(e=fs(e.nextSibling),e===null)break}return null}function aS(e,t,i){if(t==="")return null;for(;e.nodeType!==3;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!i||(e=fs(e.nextSibling),e===null))return null;return e}function kv(e,t){for(;e.nodeType!==8;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!t||(e=fs(e.nextSibling),e===null))return null;return e}function Am(e){return e.data==="$?"||e.data==="$~"}function Nm(e){return e.data==="$!"||e.data==="$?"&&e.ownerDocument.readyState!=="loading"}function sS(e,t){var i=e.ownerDocument;if(e.data==="$~")e._reactRetry=t;else if(e.data!=="$?"||i.readyState!=="loading")t();else{var o=function(){t(),i.removeEventListener("DOMContentLoaded",o)};i.addEventListener("DOMContentLoaded",o),e._reactRetry=o}}function fs(e){for(;e!=null;e=e.nextSibling){var t=e.nodeType;if(t===1||t===3)break;if(t===8){if(t=e.data,t==="$"||t==="$!"||t==="$?"||t==="$~"||t==="&"||t==="F!"||t==="F")break;if(t==="/$"||t==="/&")return null}}return e}var Mm=null;function Av(e){e=e.nextSibling;for(var t=0;e;){if(e.nodeType===8){var i=e.data;if(i==="/$"||i==="/&"){if(t===0)return fs(e.nextSibling);t--}else i!=="$"&&i!=="$!"&&i!=="$?"&&i!=="$~"&&i!=="&"||t++}e=e.nextSibling}return null}function Nv(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var i=e.data;if(i==="$"||i==="$!"||i==="$?"||i==="$~"||i==="&"){if(t===0)return e;t--}else i!=="/$"&&i!=="/&"||t++}e=e.previousSibling}return null}function Mv(e,t,i){switch(t=sd(i),e){case"html":if(e=t.documentElement,!e)throw Error(l(452));return e;case"head":if(e=t.head,!e)throw Error(l(453));return e;case"body":if(e=t.body,!e)throw Error(l(454));return e;default:throw Error(l(451))}}function Nc(e){for(var t=e.attributes;t.length;)e.removeAttributeNode(t[0]);Kt(e)}var ms=new Map,Tv=new Set;function id(e){return typeof e.getRootNode=="function"?e.getRootNode():e.nodeType===9?e:e.ownerDocument}var $i=Z.d;Z.d={f:iS,r:rS,D:lS,C:oS,L:cS,m:uS,X:fS,S:dS,M:mS};function iS(){var e=$i.f(),t=Qu();return e||t}function rS(e){var t=Rt(e);t!==null&&t.tag===5&&t.type==="form"?Vp(t):$i.r(e)}var go=typeof document>"u"?null:document;function Ev(e,t,i){var o=go;if(o&&typeof t=="string"&&t){var f=gn(t);f='link[rel="'+e+'"][href="'+f+'"]',typeof i=="string"&&(f+='[crossorigin="'+i+'"]'),Tv.has(f)||(Tv.add(f),e={rel:e,crossOrigin:i,href:t},o.querySelector(f)===null&&(t=o.createElement("link"),Gn(t,"link",e),Dt(t),o.head.appendChild(t)))}}function lS(e){$i.D(e),Ev("dns-prefetch",e,null)}function oS(e,t){$i.C(e,t),Ev("preconnect",e,t)}function cS(e,t,i){$i.L(e,t,i);var o=go;if(o&&e&&t){var f='link[rel="preload"][as="'+gn(t)+'"]';t==="image"&&i&&i.imageSrcSet?(f+='[imagesrcset="'+gn(i.imageSrcSet)+'"]',typeof i.imageSizes=="string"&&(f+='[imagesizes="'+gn(i.imageSizes)+'"]')):f+='[href="'+gn(e)+'"]';var h=f;switch(t){case"style":h=vo(e);break;case"script":h=xo(e)}ms.has(h)||(e=y({rel:"preload",href:t==="image"&&i&&i.imageSrcSet?void 0:e,as:t},i),ms.set(h,e),o.querySelector(f)!==null||t==="style"&&o.querySelector(Mc(h))||t==="script"&&o.querySelector(Tc(h))||(t=o.createElement("link"),Gn(t,"link",e),Dt(t),o.head.appendChild(t)))}}function uS(e,t){$i.m(e,t);var i=go;if(i&&e){var o=t&&typeof t.as=="string"?t.as:"script",f='link[rel="modulepreload"][as="'+gn(o)+'"][href="'+gn(e)+'"]',h=f;switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":h=xo(e)}if(!ms.has(h)&&(e=y({rel:"modulepreload",href:e},t),ms.set(h,e),i.querySelector(f)===null)){switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(i.querySelector(Tc(h)))return}o=i.createElement("link"),Gn(o,"link",e),Dt(o),i.head.appendChild(o)}}}function dS(e,t,i){$i.S(e,t,i);var o=go;if(o&&e){var f=Ht(o).hoistableStyles,h=vo(e);t=t||"default";var S=f.get(h);if(!S){var M={loading:0,preload:null};if(S=o.querySelector(Mc(h)))M.loading=5;else{e=y({rel:"stylesheet",href:e,"data-precedence":t},i),(i=ms.get(h))&&Tm(e,i);var H=S=o.createElement("link");Dt(H),Gn(H,"link",e),H._p=new Promise(function(se,xe){H.onload=se,H.onerror=xe}),H.addEventListener("load",function(){M.loading|=1}),H.addEventListener("error",function(){M.loading|=2}),M.loading|=4,rd(S,t,o)}S={type:"stylesheet",instance:S,count:1,state:M},f.set(h,S)}}}function fS(e,t){$i.X(e,t);var i=go;if(i&&e){var o=Ht(i).hoistableScripts,f=xo(e),h=o.get(f);h||(h=i.querySelector(Tc(f)),h||(e=y({src:e,async:!0},t),(t=ms.get(f))&&Em(e,t),h=i.createElement("script"),Dt(h),Gn(h,"link",e),i.head.appendChild(h)),h={type:"script",instance:h,count:1,state:null},o.set(f,h))}}function mS(e,t){$i.M(e,t);var i=go;if(i&&e){var o=Ht(i).hoistableScripts,f=xo(e),h=o.get(f);h||(h=i.querySelector(Tc(f)),h||(e=y({src:e,async:!0,type:"module"},t),(t=ms.get(f))&&Em(e,t),h=i.createElement("script"),Dt(h),Gn(h,"link",e),i.head.appendChild(h)),h={type:"script",instance:h,count:1,state:null},o.set(f,h))}}function Rv(e,t,i,o){var f=(f=ve.current)?id(f):null;if(!f)throw Error(l(446));switch(e){case"meta":case"title":return null;case"style":return typeof i.precedence=="string"&&typeof i.href=="string"?(t=vo(i.href),i=Ht(f).hoistableStyles,o=i.get(t),o||(o={type:"style",instance:null,count:0,state:null},i.set(t,o)),o):{type:"void",instance:null,count:0,state:null};case"link":if(i.rel==="stylesheet"&&typeof i.href=="string"&&typeof i.precedence=="string"){e=vo(i.href);var h=Ht(f).hoistableStyles,S=h.get(e);if(S||(f=f.ownerDocument||f,S={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},h.set(e,S),(h=f.querySelector(Mc(e)))&&!h._p&&(S.instance=h,S.state.loading=5),ms.has(e)||(i={rel:"preload",as:"style",href:i.href,crossOrigin:i.crossOrigin,integrity:i.integrity,media:i.media,hrefLang:i.hrefLang,referrerPolicy:i.referrerPolicy},ms.set(e,i),h||hS(f,e,i,S.state))),t&&o===null)throw Error(l(528,""));return S}if(t&&o!==null)throw Error(l(529,""));return null;case"script":return t=i.async,i=i.src,typeof i=="string"&&t&&typeof t!="function"&&typeof t!="symbol"?(t=xo(i),i=Ht(f).hoistableScripts,o=i.get(t),o||(o={type:"script",instance:null,count:0,state:null},i.set(t,o)),o):{type:"void",instance:null,count:0,state:null};default:throw Error(l(444,e))}}function vo(e){return'href="'+gn(e)+'"'}function Mc(e){return'link[rel="stylesheet"]['+e+"]"}function Dv(e){return y({},e,{"data-precedence":e.precedence,precedence:null})}function hS(e,t,i,o){e.querySelector('link[rel="preload"][as="style"]['+t+"]")?o.loading=1:(t=e.createElement("link"),o.preload=t,t.addEventListener("load",function(){return o.loading|=1}),t.addEventListener("error",function(){return o.loading|=2}),Gn(t,"link",i),Dt(t),e.head.appendChild(t))}function xo(e){return'[src="'+gn(e)+'"]'}function Tc(e){return"script[async]"+e}function _v(e,t,i){if(t.count++,t.instance===null)switch(t.type){case"style":var o=e.querySelector('style[data-href~="'+gn(i.href)+'"]');if(o)return t.instance=o,Dt(o),o;var f=y({},i,{"data-href":i.href,"data-precedence":i.precedence,href:null,precedence:null});return o=(e.ownerDocument||e).createElement("style"),Dt(o),Gn(o,"style",f),rd(o,i.precedence,e),t.instance=o;case"stylesheet":f=vo(i.href);var h=e.querySelector(Mc(f));if(h)return t.state.loading|=4,t.instance=h,Dt(h),h;o=Dv(i),(f=ms.get(f))&&Tm(o,f),h=(e.ownerDocument||e).createElement("link"),Dt(h);var S=h;return S._p=new Promise(function(M,H){S.onload=M,S.onerror=H}),Gn(h,"link",o),t.state.loading|=4,rd(h,i.precedence,e),t.instance=h;case"script":return h=xo(i.src),(f=e.querySelector(Tc(h)))?(t.instance=f,Dt(f),f):(o=i,(f=ms.get(h))&&(o=y({},i),Em(o,f)),e=e.ownerDocument||e,f=e.createElement("script"),Dt(f),Gn(f,"link",o),e.head.appendChild(f),t.instance=f);case"void":return null;default:throw Error(l(443,t.type))}else t.type==="stylesheet"&&(t.state.loading&4)===0&&(o=t.instance,t.state.loading|=4,rd(o,i.precedence,e));return t.instance}function rd(e,t,i){for(var o=i.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),f=o.length?o[o.length-1]:null,h=f,S=0;S<o.length;S++){var M=o[S];if(M.dataset.precedence===t)h=M;else if(h!==f)break}h?h.parentNode.insertBefore(e,h.nextSibling):(t=i.nodeType===9?i.head:i,t.insertBefore(e,t.firstChild))}function Tm(e,t){e.crossOrigin==null&&(e.crossOrigin=t.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=t.referrerPolicy),e.title==null&&(e.title=t.title)}function Em(e,t){e.crossOrigin==null&&(e.crossOrigin=t.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=t.referrerPolicy),e.integrity==null&&(e.integrity=t.integrity)}var ld=null;function Lv(e,t,i){if(ld===null){var o=new Map,f=ld=new Map;f.set(i,o)}else f=ld,o=f.get(i),o||(o=new Map,f.set(i,o));if(o.has(e))return o;for(o.set(e,null),i=i.getElementsByTagName(e),f=0;f<i.length;f++){var h=i[f];if(!(h[rt]||h[te]||e==="link"&&h.getAttribute("rel")==="stylesheet")&&h.namespaceURI!=="http://www.w3.org/2000/svg"){var S=h.getAttribute(t)||"";S=e+S;var M=o.get(S);M?M.push(h):o.set(S,[h])}}return o}function zv(e,t,i){e=e.ownerDocument||e,e.head.insertBefore(i,t==="title"?e.querySelector("head > title"):null)}function pS(e,t,i){if(i===1||t.itemProp!=null)return!1;switch(e){case"meta":case"title":return!0;case"style":if(typeof t.precedence!="string"||typeof t.href!="string"||t.href==="")break;return!0;case"link":if(typeof t.rel!="string"||typeof t.href!="string"||t.href===""||t.onLoad||t.onError)break;return t.rel==="stylesheet"?(e=t.disabled,typeof t.precedence=="string"&&e==null):!0;case"script":if(t.async&&typeof t.async!="function"&&typeof t.async!="symbol"&&!t.onLoad&&!t.onError&&t.src&&typeof t.src=="string")return!0}return!1}function Iv(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function gS(e,t,i,o){if(i.type==="stylesheet"&&(typeof o.media!="string"||matchMedia(o.media).matches!==!1)&&(i.state.loading&4)===0){if(i.instance===null){var f=vo(o.href),h=t.querySelector(Mc(f));if(h){t=h._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(e.count++,e=od.bind(e),t.then(e,e)),i.state.loading|=4,i.instance=h,Dt(h);return}h=t.ownerDocument||t,o=Dv(o),(f=ms.get(f))&&Tm(o,f),h=h.createElement("link"),Dt(h);var S=h;S._p=new Promise(function(M,H){S.onload=M,S.onerror=H}),Gn(h,"link",o),i.instance=h}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(i,t),(t=i.state.preload)&&(i.state.loading&3)===0&&(e.count++,i=od.bind(e),t.addEventListener("load",i),t.addEventListener("error",i))}}var Rm=0;function vS(e,t){return e.stylesheets&&e.count===0&&ud(e,e.stylesheets),0<e.count||0<e.imgCount?function(i){var o=setTimeout(function(){if(e.stylesheets&&ud(e,e.stylesheets),e.unsuspend){var h=e.unsuspend;e.unsuspend=null,h()}},6e4+t);0<e.imgBytes&&Rm===0&&(Rm=62500*Xb());var f=setTimeout(function(){if(e.waitingForImages=!1,e.count===0&&(e.stylesheets&&ud(e,e.stylesheets),e.unsuspend)){var h=e.unsuspend;e.unsuspend=null,h()}},(e.imgBytes>Rm?50:800)+t);return e.unsuspend=i,function(){e.unsuspend=null,clearTimeout(o),clearTimeout(f)}}:null}function od(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)ud(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var cd=null;function ud(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,cd=new Map,t.forEach(xS,e),cd=null,od.call(e))}function xS(e,t){if(!(t.state.loading&4)){var i=cd.get(e);if(i)var o=i.get(null);else{i=new Map,cd.set(e,i);for(var f=e.querySelectorAll("link[data-precedence],style[data-precedence]"),h=0;h<f.length;h++){var S=f[h];(S.nodeName==="LINK"||S.getAttribute("media")!=="not all")&&(i.set(S.dataset.precedence,S),o=S)}o&&i.set(null,o)}f=t.instance,S=f.getAttribute("data-precedence"),h=i.get(S)||o,h===o&&i.set(null,f),i.set(S,f),this.count++,o=od.bind(this),f.addEventListener("load",o),f.addEventListener("error",o),h?h.parentNode.insertBefore(f,h.nextSibling):(e=e.nodeType===9?e.head:e,e.insertBefore(f,e.firstChild)),t.state.loading|=4}}var Ec={$$typeof:R,Provider:null,Consumer:null,_currentValue:X,_currentValue2:X,_threadCount:0};function yS(e,t,i,o,f,h,S,M,H){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=ut(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=ut(0),this.hiddenUpdates=ut(null),this.identifierPrefix=o,this.onUncaughtError=f,this.onCaughtError=h,this.onRecoverableError=S,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=H,this.incompleteTransitions=new Map}function Ov(e,t,i,o,f,h,S,M,H,se,xe,Se){return e=new yS(e,t,i,S,H,se,xe,Se,M),t=1,h===!0&&(t|=24),h=Xn(3,null,null,t),e.current=h,h.stateNode=e,t=nc(),t.refCount++,e.pooledCache=t,t.refCount++,h.memoizedState={element:o,isDehydrated:i,cache:t},Cn(h),e}function Bv(e){return e?(e=Ha,e):Ha}function Fv(e,t,i,o,f,h){f=Bv(f),o.context===null?o.context=f:o.pendingContext=f,o=As(t),o.payload={element:i},h=h===void 0?null:h,h!==null&&(o.callback=h),i=ei(e,o,t),i!==null&&(Na(i,e,t),ao(i,e,t))}function Pv(e,t){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var i=e.retryLane;e.retryLane=i!==0&&i<t?i:t}}function Dm(e,t){Pv(e,t),(e=e.alternate)&&Pv(e,t)}function Hv(e){if(e.tag===13||e.tag===31){var t=rs(e,67108864);t!==null&&Na(t,e,67108864),Dm(e,67108864)}}function $v(e){if(e.tag===13||e.tag===31){var t=Va();t=dt(t);var i=rs(e,t);i!==null&&Na(i,e,t),Dm(e,t)}}var dd=!0;function wS(e,t,i,o){var f=O.T;O.T=null;var h=Z.p;try{Z.p=2,_m(e,t,i,o)}finally{Z.p=h,O.T=f}}function bS(e,t,i,o){var f=O.T;O.T=null;var h=Z.p;try{Z.p=8,_m(e,t,i,o)}finally{Z.p=h,O.T=f}}function _m(e,t,i,o){if(dd){var f=Lm(o);if(f===null)ym(e,t,o,fd,i),qv(e,o);else if(jS(f,e,t,i,o))o.stopPropagation();else if(qv(e,o),t&4&&-1<SS.indexOf(e)){for(;f!==null;){var h=Rt(f);if(h!==null)switch(h.tag){case 3:if(h=h.stateNode,h.current.memoizedState.isDehydrated){var S=Ka(h.pendingLanes);if(S!==0){var M=h;for(M.pendingLanes|=2,M.entangledLanes|=2;S;){var H=1<<31-Nt(S);M.entanglements[1]|=H,S&=~H}ai(h),(At&6)===0&&(Wu=tt()+500,Cc(0))}}break;case 31:case 13:M=rs(h,2),M!==null&&Na(M,h,2),Qu(),Dm(h,2)}if(h=Lm(o),h===null&&ym(e,t,o,fd,i),h===f)break;f=h}f!==null&&o.stopPropagation()}else ym(e,t,o,null,i)}}function Lm(e){return e=Oo(e),zm(e)}var fd=null;function zm(e){if(fd=null,e=Pt(e),e!==null){var t=d(e);if(t===null)e=null;else{var i=t.tag;if(i===13){if(e=m(t),e!==null)return e;e=null}else if(i===31){if(e=p(t),e!==null)return e;e=null}else if(i===3){if(t.stateNode.current.memoizedState.isDehydrated)return t.tag===3?t.stateNode.containerInfo:null;e=null}else t!==e&&(e=null)}}return fd=e,null}function Uv(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(pn()){case Ke:return 2;case ht:return 8;case St:case An:return 32;case Oe:return 268435456;default:return 32}default:return 32}}var Im=!1,Rr=null,Dr=null,_r=null,Rc=new Map,Dc=new Map,Lr=[],SS="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 qv(e,t){switch(e){case"focusin":case"focusout":Rr=null;break;case"dragenter":case"dragleave":Dr=null;break;case"mouseover":case"mouseout":_r=null;break;case"pointerover":case"pointerout":Rc.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":Dc.delete(t.pointerId)}}function _c(e,t,i,o,f,h){return e===null||e.nativeEvent!==h?(e={blockedOn:t,domEventName:i,eventSystemFlags:o,nativeEvent:h,targetContainers:[f]},t!==null&&(t=Rt(t),t!==null&&Hv(t)),e):(e.eventSystemFlags|=o,t=e.targetContainers,f!==null&&t.indexOf(f)===-1&&t.push(f),e)}function jS(e,t,i,o,f){switch(t){case"focusin":return Rr=_c(Rr,e,t,i,o,f),!0;case"dragenter":return Dr=_c(Dr,e,t,i,o,f),!0;case"mouseover":return _r=_c(_r,e,t,i,o,f),!0;case"pointerover":var h=f.pointerId;return Rc.set(h,_c(Rc.get(h)||null,e,t,i,o,f)),!0;case"gotpointercapture":return h=f.pointerId,Dc.set(h,_c(Dc.get(h)||null,e,t,i,o,f)),!0}return!1}function Gv(e){var t=Pt(e.target);if(t!==null){var i=d(t);if(i!==null){if(t=i.tag,t===13){if(t=m(i),t!==null){e.blockedOn=t,Is(e.priority,function(){$v(i)});return}}else if(t===31){if(t=p(i),t!==null){e.blockedOn=t,Is(e.priority,function(){$v(i)});return}}else if(t===3&&i.stateNode.current.memoizedState.isDehydrated){e.blockedOn=i.tag===3?i.stateNode.containerInfo:null;return}}}e.blockedOn=null}function md(e){if(e.blockedOn!==null)return!1;for(var t=e.targetContainers;0<t.length;){var i=Lm(e.nativeEvent);if(i===null){i=e.nativeEvent;var o=new i.constructor(i.type,i);es=o,i.target.dispatchEvent(o),es=null}else return t=Rt(i),t!==null&&Hv(t),e.blockedOn=i,!1;t.shift()}return!0}function Vv(e,t,i){md(e)&&i.delete(t)}function CS(){Im=!1,Rr!==null&&md(Rr)&&(Rr=null),Dr!==null&&md(Dr)&&(Dr=null),_r!==null&&md(_r)&&(_r=null),Rc.forEach(Vv),Dc.forEach(Vv)}function hd(e,t){e.blockedOn===t&&(e.blockedOn=null,Im||(Im=!0,n.unstable_scheduleCallback(n.unstable_NormalPriority,CS)))}var pd=null;function Yv(e){pd!==e&&(pd=e,n.unstable_scheduleCallback(n.unstable_NormalPriority,function(){pd===e&&(pd=null);for(var t=0;t<e.length;t+=3){var i=e[t],o=e[t+1],f=e[t+2];if(typeof o!="function"){if(zm(o||i)===null)continue;break}var h=Rt(i);h!==null&&(e.splice(t,3),t-=3,Lf(h,{pending:!0,data:f,method:i.method,action:o},o,f))}}))}function yo(e){function t(H){return hd(H,e)}Rr!==null&&hd(Rr,e),Dr!==null&&hd(Dr,e),_r!==null&&hd(_r,e),Rc.forEach(t),Dc.forEach(t);for(var i=0;i<Lr.length;i++){var o=Lr[i];o.blockedOn===e&&(o.blockedOn=null)}for(;0<Lr.length&&(i=Lr[0],i.blockedOn===null);)Gv(i),i.blockedOn===null&&Lr.shift();if(i=(e.ownerDocument||e).$$reactFormReplay,i!=null)for(o=0;o<i.length;o+=3){var f=i[o],h=i[o+1],S=f[Me]||null;if(typeof h=="function")S||Yv(i);else if(S){var M=null;if(h&&h.hasAttribute("formAction")){if(f=h,S=h[Me]||null)M=S.formAction;else if(zm(f)!==null)continue}else M=S.action;typeof M=="function"?i[o+1]=M:(i.splice(o,3),o-=3),Yv(i)}}}function Wv(){function e(h){h.canIntercept&&h.info==="react-transition"&&h.intercept({handler:function(){return new Promise(function(S){return f=S})},focusReset:"manual",scroll:"manual"})}function t(){f!==null&&(f(),f=null),o||setTimeout(i,20)}function i(){if(!o&&!navigation.transition){var h=navigation.currentEntry;h&&h.url!=null&&navigation.navigate(h.url,{state:h.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var o=!1,f=null;return navigation.addEventListener("navigate",e),navigation.addEventListener("navigatesuccess",t),navigation.addEventListener("navigateerror",t),setTimeout(i,100),function(){o=!0,navigation.removeEventListener("navigate",e),navigation.removeEventListener("navigatesuccess",t),navigation.removeEventListener("navigateerror",t),f!==null&&(f(),f=null)}}}function Om(e){this._internalRoot=e}gd.prototype.render=Om.prototype.render=function(e){var t=this._internalRoot;if(t===null)throw Error(l(409));var i=t.current,o=Va();Fv(i,o,e,t,null,null)},gd.prototype.unmount=Om.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var t=e.containerInfo;Fv(e.current,2,null,e,null,null),Qu(),t[Pe]=null}};function gd(e){this._internalRoot=e}gd.prototype.unstable_scheduleHydration=function(e){if(e){var t=sn();e={blockedOn:null,target:e,priority:t};for(var i=0;i<Lr.length&&t!==0&&t<Lr[i].priority;i++);Lr.splice(i,0,e),i===0&&Gv(e)}};var Kv=a.version;if(Kv!=="19.2.7")throw Error(l(527,Kv,"19.2.7"));Z.findDOMNode=function(e){var t=e._reactInternals;if(t===void 0)throw typeof e.render=="function"?Error(l(188)):(e=Object.keys(e).join(","),Error(l(268,e)));return e=g(t),e=e!==null?w(e):null,e=e===null?null:e.stateNode,e};var kS={bundleType:0,version:"19.2.7",rendererPackageName:"react-dom",currentDispatcherRef:O,reconcilerVersion:"19.2.7"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var vd=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!vd.isDisabled&&vd.supportsFiber)try{pt=vd.inject(kS),st=vd}catch{}}return zc.createRoot=function(e,t){if(!c(e))throw Error(l(299));var i=!1,o="",f=ng,h=ag,S=sg;return t!=null&&(t.unstable_strictMode===!0&&(i=!0),t.identifierPrefix!==void 0&&(o=t.identifierPrefix),t.onUncaughtError!==void 0&&(f=t.onUncaughtError),t.onCaughtError!==void 0&&(h=t.onCaughtError),t.onRecoverableError!==void 0&&(S=t.onRecoverableError)),t=Ov(e,1,!1,null,null,i,o,null,f,h,S,Wv),e[Pe]=t.current,xm(e),new Om(t)},zc.hydrateRoot=function(e,t,i){if(!c(e))throw Error(l(299));var o=!1,f="",h=ng,S=ag,M=sg,H=null;return i!=null&&(i.unstable_strictMode===!0&&(o=!0),i.identifierPrefix!==void 0&&(f=i.identifierPrefix),i.onUncaughtError!==void 0&&(h=i.onUncaughtError),i.onCaughtError!==void 0&&(S=i.onCaughtError),i.onRecoverableError!==void 0&&(M=i.onRecoverableError),i.formState!==void 0&&(H=i.formState)),t=Ov(e,1,!0,t,i??null,o,f,H,h,S,M,Wv),t.context=Bv(null),i=t.current,o=Va(),o=dt(o),f=As(o),f.callback=null,ei(i,f,o),i=o,t.current.lanes=i,Xa(t,i),ai(t),e[Pe]=t.current,xm(e),new gd(t)},zc.version="19.2.7",zc}var ux;function m0(){if(ux)return Pm.exports;ux=1;function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(a){console.error(a)}}return n(),Pm.exports=f0(),Pm.exports}var h0=m0();const p0="https://otbyfkjxrkngvjziawki.supabase.co",g0="sb_publishable_NpUs0RDJH2YnllsqTKO6TQ_1jTdSsNQ",v0={getItem:()=>null,setItem:()=>{},removeItem:()=>{}},dx=typeof window<"u"&&!!window.liveDesk,ot=l0(p0,g0,{auth:{autoRefreshToken:!0,persistSession:!dx,storage:dx?v0:void 0,detectSessionInUrl:!0,flowType:"pkce",storageKey:"livedesk.mindexec.supabase.auth"}}),x0=new Set(["browserLanguage","platform","online","viewport","timezone","screen"]),y0={id:"browser-safe-v1",collect(){if(typeof navigator>"u")return{};const n={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(n).filter(([a,r])=>x0.has(a)&&r!==void 0))}};function w0(n,a="Support request failed."){if(n&&typeof n=="object"&&"message"in n){const r=String(n.message||"").trim();if(r)return r.replace(/^.*Support request failed:\s*/i,"")}return n instanceof Error?n.message:a}function b0(n=y0){return n.collect()}async function S0(n,a="livedesk"){const{data:r,error:l}=await ot.from("app_admins").select("role").eq("user_id",n).limit(1);if(l)throw l;const c=r?.[0]?.role||"user";if(c!=="owner"){const{error:j}=await ot.rpc("register_product_access",{p_product_key:a,p_access_type:"free"});if(j)throw j}const[d,m,p]=await Promise.all([ot.from("products").select("id, product_key, name, description, sort_order").order("sort_order"),ot.from("product_admins").select("product_id, role").eq("user_id",n),ot.from("user_products").select("product_id").eq("user_id",n).eq("is_active",!0)]);if(d.error)throw d.error;if(m.error)throw m.error;if(p.error)throw p.error;const v=d.data||[],g=(m.data||[]).map(j=>String(j.product_id)),w=(p.data||[]).map(j=>String(j.product_id)),y=c==="owner",b=y?v.map(j=>j.id):[...new Set([...g,...w])];return{products:v,access:{userId:n,globalRole:c,accessibleProductIds:b,managedProductIds:y?v.map(j=>j.id):g,canViewAllProducts:y,canViewAllPrivatePosts:y,canManageAllProducts:y,canCreateAnnouncements:y||g.length>0}}}async function j0(n=""){const{data:a,error:r}=await ot.rpc("search_support_posts",{p_query:n.trim()||null,p_limit:250});if(r)throw r;return a||[]}async function C0(n){const{data:a,error:r}=await ot.from("support_attachments").select("*").eq("post_id",n).order("created_at");if(r)throw r;const l=a||[];return Promise.all(l.map(async c=>{const d=await ot.storage.from("support-attachments").createSignedUrl(c.storage_path,3600);return{...c,signed_url:d.data?.signedUrl||void 0}}))}async function k0(){const{data:n,error:a}=await ot.from("support_notifications").select("*").order("created_at",{ascending:!1}).limit(30);if(a)throw a;return n||[]}async function A0(n){const{error:a}=await ot.rpc("mark_support_notification_read",{p_notification_id:n});if(a)throw a}async function fx(n){const{data:a,error:r}=await ot.from("support_comments").select("*").eq("post_id",n).order("created_at");if(r)throw r;return a||[]}async function N0(n){const{data:a,error:r}=await ot.from("support_votes").select("post_id").eq("user_id",n);if(r)throw r;return new Set((a||[]).map(l=>String(l.post_id)))}async function M0(n){const{data:a,error:r}=await ot.rpc("create_support_post",{p_product_id:n.productId,p_post_type:n.postType,p_title:n.title,p_body:n.body,p_visibility:n.visibility,p_app_version:n.appVersion||null,p_platform:typeof navigator>"u"?null:navigator.platform||null,p_os_version:typeof navigator>"u"?null:navigator.platform||null,p_environment:n.includeEnvironment?b0():{}});if(r)throw r;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 T0=new Set(["image/png","image/jpeg","image/webp","text/plain","text/markdown","application/json","application/pdf"]);async function E0(n,a){if(!T0.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 r=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=`${n}/${l}-${r}`,d=await ot.storage.from("support-attachments").upload(c,a,{contentType:a.type,upsert:!1});if(d.error)throw d.error;const{data:m,error:p}=await ot.rpc("add_support_attachment",{p_post_id:n,p_storage_path:c,p_file_name:r,p_mime_type:a.type,p_size_bytes:a.size});if(p)throw await ot.storage.from("support-attachments").remove([c]),p;const v=Array.isArray(m)?m[0]?.attachment_id:m?.attachment_id;if(!v)throw new Error("Attachment metadata was not created.");return String(v)}async function R0(n,a,r,l){const{error:c}=await ot.rpc("update_support_post",{p_post_id:n,p_title:a,p_body:r,p_visibility:l});if(c)throw c}async function D0(n,a){const{error:r}=await ot.rpc("add_support_comment",{p_post_id:n,p_body:a});if(r)throw r}async function _0(n){const{data:a,error:r}=await ot.rpc("toggle_support_vote",{p_post_id:n});if(r)throw r;const l=Array.isArray(a)?a[0]:a;return{voted:!!l?.voted,totalVotes:Number(l?.total_votes||0)}}async function L0(n,a){const{error:r}=await ot.rpc("change_support_post_status",{p_post_id:n,p_target_status:a});if(r)throw r}async function z0(n){const{error:a}=await ot.rpc("set_support_post_hidden",{p_post_id:n,p_hidden:!0});if(a)throw a}async function I0(n,a){const{error:r}=await ot.rpc("set_support_post_locked",{p_post_id:n,p_locked:a});if(r)throw r}async function O0(n,a){const{error:r}=await ot.rpc("set_support_post_pinned",{p_post_id:n,p_pinned:a});if(r)throw r}async function B0(n,a){const{error:r}=await ot.rpc("mark_support_duplicate",{p_post_id:n,p_duplicate_of_post_id:a});if(r)throw r}async function F0(n,a){const{error:r}=await ot.rpc("accept_support_answer",{p_post_id:n,p_comment_id:a});if(r)throw r}async function P0(n,a=!0){const{error:r}=await ot.rpc("hide_support_comment",{p_comment_id:n,p_hidden:a});if(r)throw r}const Sh=[{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"}],H0=[{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"}],$0={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"]},U0={type:"all",product:"",status:"all",visibility:"all",sort:"recent",query:""};function Um(){if(typeof window>"u")return U0;const n=new URLSearchParams(window.location.search),a=window.location.pathname.match(/^\/support\/(questions|issues|features|announcements)$/)?.[1],r=n.get("type")||a||"",l=r==="questions"||r==="question"?"question":r==="issues"||r==="issue"?"issue":r==="features"||r==="feature"?"feature":r==="announcements"||r==="announcement"?"announcement":"all",c=n.get("visibility"),d=n.get("sort");return{type:l,product:n.get("product")||"",status:n.get("status")||"all",visibility:c==="public"||c==="private"?c:"all",sort:d==="votes"||d==="newest"?d:"recent",query:n.get("q")||""}}function q0(n){return n==="all"?"":n==="question"?"questions":n==="issue"?"issues":n==="feature"?"features":"announcements"}function G0(n,a){const r={...n,...a},l=new URLSearchParams;r.product&&l.set("product",r.product),r.status!=="all"&&l.set("status",r.status),r.visibility!=="all"&&l.set("visibility",r.visibility),r.sort!=="recent"&&l.set("sort",r.sort),r.query&&l.set("q",r.query);const c=q0(r.type),d=l.toString();return`/support${c?`/${c}`:""}${d?`?${d}`:""}`}function xd(n){const a=new Date(n);return Number.isFinite(a.getTime())?a.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"}):n}function qm(n){return n.replaceAll("-"," ").replace(/\b\w/g,a=>a.toUpperCase())}function mx(n){return n==="question"?RS:n==="issue"?DS:n==="feature"?_S:LS}function hx(n){return Sh.find(a=>a.id===n)?.shortLabel||n}function Gm(n,a){return n.find(r=>r.id===a)?.name||"Product"}function Ma(n){const a=w0(n);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 Zy({session:n,currentProductKey:a="livedesk",appVersion:r="",onSignIn:l}){const[c,d]=u.useState(()=>Um()),[m,p]=u.useState(null),[v,g]=u.useState([]),[w,y]=u.useState([]),[b,j]=u.useState(""),[C,N]=u.useState([]),[T,k]=u.useState([]),[E,R]=u.useState([]),[$,F]=u.useState(()=>new Set),[q,z]=u.useState(!0),[L,ie]=u.useState(""),[V,ne]=u.useState(""),[Q,J]=u.useState(!1),[le,Y]=u.useState(!1),[O,Z]=u.useState(""),[X,D]=u.useState(()=>Um().query),[K,ce]=u.useState(!1),[W,P]=u.useState(!1),[me,pe]=u.useState(""),[ve,ke]=u.useState(""),[_e,Le]=u.useState("free"),[ue,Ve]=u.useState(""),[Ye,oe]=u.useState(""),[Ne,je]=u.useState("admin"),[Ee,Re]=u.useState(""),[Fe,he]=u.useState(""),[Ae,de]=u.useState(""),[ye,qe]=u.useState(""),[tt,pn]=u.useState(""),[Ke,ht]=u.useState([]),[St,An]=u.useState({productId:"",postType:"question",title:"",body:"",visibility:"public",includeEnvironment:!0,files:[]}),Oe=u.useCallback(B=>{const He={...c,...B};d(He),typeof window<"u"&&window.history.pushState({},"",G0(c,B))},[c]);u.useEffect(()=>{const B=()=>d(Um());return window.addEventListener("popstate",B),()=>window.removeEventListener("popstate",B)},[]);const It=u.useCallback(async()=>{const B=await j0(c.query);return y(B),n?.user.id&&F(await N0(n.user.id)),B},[c.query,n?.user.id]),Ut=u.useCallback(async()=>{if(!n?.user.id){p(null),g([]),y([]),j(""),R([]),z(!1);return}z(!0),ne("");try{const B=await S0(n.user.id,a);p(B.access),g(B.products),await It(),R(await k0())}catch(B){ne(Ma(B))}finally{z(!1)}},[a,It,n?.user.id]);u.useEffect(()=>{Ut()},[Ut]);const pt=u.useMemo(()=>m?m.canViewAllProducts?v:v.filter(B=>m.accessibleProductIds.includes(B.id)):[],[m,v]),st=u.useMemo(()=>{const B=pt.find(He=>He.product_key===c.product);return m?.canViewAllProducts&&!c.product||c.product==="all"&&m?.canViewAllProducts?"all":B?B.product_key:pt.some(He=>He.product_key===a)?a:pt[0]?.product_key||""},[m?.canViewAllProducts,pt,a,c.product]),Jt=st==="all"?"":pt.find(B=>B.product_key===st)?.id||"",Nt=u.useMemo(()=>{const B=new Map(v.map(dt=>[dt.id,dt.product_key]));return[...w.filter(dt=>c.type!=="all"&&dt.post_type!==c.type||st!=="all"&&Jt&&dt.product_id!==Jt||c.status==="needs-response"&&!["open","needs-info"].includes(dt.status)||c.status!=="all"&&c.status!=="needs-response"&&dt.status!==c.status||c.visibility!=="all"&&dt.visibility!==c.visibility?!1:B.has(dt.product_id))].sort((dt,en)=>c.sort==="votes"?en.vote_count-dt.vote_count||en.updated_at.localeCompare(dt.updated_at):c.sort==="newest"?en.created_at.localeCompare(dt.created_at):Number(en.is_pinned)-Number(dt.is_pinned)||en.updated_at.localeCompare(dt.updated_at))},[w,v,c.sort,c.status,c.type,c.visibility,Jt,st]),De=Nt.find(B=>B.id===b)||Nt[0]||null,Nn=!!(De&&m&&(m.canViewAllProducts||m.managedProductIds.includes(De.product_id))),Vi=!!(De&&n?.user.id===De.author_id)||Nn;u.useEffect(()=>{if(!De){j(""),N([]),Y(!1);return}De.id!==b&&j(De.id)},[De,b]),u.useEffect(()=>{let B=!0;return b?(fx(b).then(He=>{B&&N(He)}).catch(He=>{B&&ne(Ma(He))}),C0(b).then(He=>{B&&k(He)}).catch(He=>{B&&ne(Ma(He))}),()=>{B=!1}):(N([]),k([]),()=>{B=!1})},[b]),u.useEffect(()=>{!St.productId&&pt[0]&&An(B=>({...B,productId:Jt||pt[0].id}))},[pt,St.productId,Jt]),u.useEffect(()=>{D(c.query)},[c.query]),u.useEffect(()=>{!ve&&pt[0]&&ke(pt[0].id),!Ye&&pt[0]&&oe(pt[0].id)},[pt,ve,Ye]);const un=B=>{De&&y(He=>He.map(dt=>dt.id===De.id?{...dt,...B}:dt))},Bn=async B=>{if(B.preventDefault(),!(!n||!St.productId)){ie("create"),ne("");try{const He=await M0({productId:St.productId,postType:St.postType,title:St.title,body:St.body,visibility:St.postType==="announcement"?"public":St.visibility,appVersion:r,includeEnvironment:St.postType==="issue"&&St.includeEnvironment});for(const en of Ke)await E0(He,en);const dt=await It();J(!1),ht([]),An(en=>({...en,title:"",body:"",files:[]})),j(He),dt.some(en=>en.id===He)||await Ut()}catch(He){ne(Ma(He))}finally{ie("")}}},ga=async B=>{if(B.preventDefault(),!!De){ie("edit"),ne("");try{await R0(De.id,De.title,De.body,De.visibility),Y(!1),await It()}catch(He){ne(Ma(He))}finally{ie("")}}},Ka=async B=>{if(B.preventDefault(),!(!De||!O.trim())){ie("comment"),ne("");try{await D0(De.id,O),Z(""),N(await fx(De.id)),await It()}catch(He){ne(Ma(He))}finally{ie("")}}},Mn=async()=>{if(!(!De||De.post_type!=="feature")){ie("vote"),ne("");try{const B=await _0(De.id);F(He=>{const dt=new Set(He);return B.voted?dt.add(De.id):dt.delete(De.id),dt}),un({vote_count:B.totalVotes})}catch(B){ne(Ma(B))}finally{ie("")}}},Qa=async B=>{if(De){ie("status"),ne("");try{await L0(De.id,B),un({status:B}),await It()}catch(He){ne(Ma(He))}finally{ie("")}}},Ie=async()=>{if(!(!De||!window.confirm("Hide this Support post from the board?"))){ie("hide"),ne("");try{await z0(De.id),j(""),await It()}catch(B){ne(Ma(B))}finally{ie("")}}},ri=async()=>{if(De){ie("lock"),ne("");try{await I0(De.id,!De.is_locked),un({is_locked:!De.is_locked}),await It()}catch(B){ne(Ma(B))}finally{ie("")}}},ut=async()=>{if(De){ie("pin"),ne("");try{await O0(De.id,!De.is_pinned),un({is_pinned:!De.is_pinned}),await It()}catch(B){ne(Ma(B))}finally{ie("")}}},Xa=async B=>{if(De){ie(`accept-${B}`),ne("");try{await F0(De.id,B),un({accepted_comment_id:B,status:De.post_type==="question"?"answered":De.status}),await It()}catch(He){ne(Ma(He))}finally{ie("")}}},qt=async()=>{if(!(!De||!ye||ye===De.id)){ie("duplicate"),ne("");try{await B0(De.id,ye),j(""),qe(""),await It()}catch(B){ne(Ma(B))}finally{ie("")}}},zs=async B=>{if(!B.read_at)try{await A0(B.id),R(He=>He.map(dt=>dt.id===B.id?{...dt,read_at:new Date().toISOString()}:dt))}catch(He){ne(Ma(He))}B.post_id&&j(B.post_id),ce(!1)};return n?q&&!m?s.jsxs("section",{className:"support-page support-loading",children:[s.jsx(Ro,{className:"support-spin",size:23})," Loading Support Board..."]}):s.jsxs("section",{className:"support-page",children:[s.jsx("header",{className:"support-page-header support-page-actions-only",children:s.jsxs("div",{className:"support-header-actions",children:[s.jsxs("div",{className:"support-notification-wrap",children:[s.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>ce(B=>!B),title:"Notifications",children:[s.jsx(MS,{size:16})," ",E.filter(B=>!B.read_at).length>0&&s.jsx("b",{children:E.filter(B=>!B.read_at).length})]}),K&&s.jsxs("div",{className:"support-notification-popover",children:[s.jsx("strong",{children:"Notifications"}),E.length===0?s.jsx("span",{className:"support-muted",children:"No notifications yet."}):E.map(B=>s.jsxs("button",{type:"button",className:B.read_at?"":"unread",onClick:()=>{zs(B)},children:[s.jsx("b",{children:B.title}),s.jsx("span",{children:B.body}),s.jsx("small",{children:xd(B.created_at)})]},B.id))]})]}),m?.canViewAllProducts&&s.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>P(B=>!B),children:[s.jsx(zt,{size:16})," Admin"]}),s.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{Ut()},disabled:q,children:[s.jsx(Ro,{size:16,className:q?"support-spin":""})," Refresh"]}),s.jsxs("button",{className:"support-primary-button",type:"button",onClick:()=>J(!0),disabled:pt.length===0,children:[s.jsx(Bm,{size:17})," New request"]})]})}),V&&s.jsxs("div",{className:"support-error",role:"alert",children:[s.jsx(Ds,{size:17})," ",s.jsx("span",{children:V}),s.jsx("button",{type:"button",onClick:()=>ne(""),"aria-label":"Dismiss error",children:s.jsx(Ds,{size:15})})]}),Q&&s.jsxs("form",{className:"support-composer",onSubmit:B=>{Bn(B)},children:[s.jsxs("div",{className:"support-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"New Support request"}),s.jsx("strong",{children:"Describe one actionable problem or idea."})]}),s.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>J(!1),"aria-label":"Close composer",children:s.jsx(Ds,{size:18})})]}),s.jsxs("div",{className:"support-form-grid",children:[s.jsxs("label",{children:[s.jsx("span",{children:"Product"}),s.jsx("select",{value:St.productId,onChange:B=>An(He=>({...He,productId:B.target.value})),children:pt.map(B=>s.jsx("option",{value:B.id,children:B.name},B.id))})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Type"}),s.jsx("select",{value:St.postType,onChange:B=>An(He=>({...He,postType:B.target.value})),children:Sh.filter(B=>B.id!=="announcement"||m?.canCreateAnnouncements).map(B=>s.jsx("option",{value:B.id,children:B.label},B.id))})]}),s.jsxs("label",{className:"support-form-wide",children:[s.jsx("span",{children:"Title"}),s.jsx("input",{required:!0,minLength:3,maxLength:180,value:St.title,onChange:B=>An(He=>({...He,title:B.target.value})),placeholder:"A short, searchable summary"})]}),s.jsxs("label",{className:"support-form-wide",children:[s.jsx("span",{children:St.postType==="issue"?"What happened?":St.postType==="feature"?"Describe the desired behavior":St.postType==="announcement"?"Announcement":"Question"}),s.jsx("textarea",{required:!0,value:St.body,onChange:B=>An(He=>({...He,body:B.target.value})),placeholder:"Include the context another person needs to respond.",rows:6})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Visibility"}),s.jsxs("select",{value:St.visibility,disabled:St.postType==="announcement",onChange:B=>An(He=>({...He,visibility:B.target.value})),children:[s.jsx("option",{value:"public",children:"Public"}),s.jsx("option",{value:"private",children:"Private"})]})]}),St.postType==="issue"&&s.jsxs("label",{className:"support-checkbox",children:[s.jsx("input",{type:"checkbox",checked:St.includeEnvironment,onChange:B=>An(He=>({...He,includeEnvironment:B.target.checked}))}),s.jsx("span",{children:"Attach safe browser/runtime details"})]}),s.jsxs("label",{className:"support-form-wide",children:[s.jsx("span",{children:"Attachments"}),s.jsx("input",{type:"file",multiple:!0,accept:"image/png,image/jpeg,image/webp,text/plain,text/markdown,application/json,application/pdf",onChange:B=>ht(Array.from(B.target.files||[]).slice(0,5))}),s.jsx("small",{className:"support-muted",children:"Up to 5 files, 10 MB each. Images, text, JSON, Markdown, and PDF."})]})]}),s.jsxs("div",{className:"support-composer-footer",children:[s.jsx("span",{children:Ke.length>0?`${Ke.length} attachment${Ke.length===1?"":"s"} selected.`:"Private posts are visible only to you and the product support staff."}),s.jsxs("button",{className:"support-primary-button",type:"submit",disabled:L==="create",children:[s.jsx(Do,{size:16})," ",L==="create"?"Submitting...":"Submit request"]})]})]}),s.jsxs("div",{className:"support-tabs",role:"tablist","aria-label":"Support post type",children:[s.jsx("button",{className:c.type==="all"?"active":"",type:"button",onClick:()=>Oe({type:"all"}),children:"All"}),Sh.map(B=>{const He=mx(B.id);return s.jsxs("button",{className:c.type===B.id?"active":"",type:"button",onClick:()=>Oe({type:B.id}),children:[s.jsx(He,{size:15})," ",B.label]},B.id)})]}),W&&m?.canViewAllProducts&&s.jsxs("section",{className:"support-admin-panel",children:[s.jsxs("div",{className:"support-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Owner controls"}),s.jsx("strong",{children:"Products and access are managed by immutable user IDs behind these email lookup forms."})]}),s.jsx(zt,{size:19})]}),s.jsxs("div",{className:"support-admin-grid",children:[s.jsxs("form",{onSubmit:B=>{},children:[s.jsx("strong",{children:"Grant product access"}),s.jsx("input",{type:"email",required:!0,placeholder:"User email",value:me,onChange:B=>pe(B.target.value)}),s.jsx("select",{value:ve,onChange:B=>ke(B.target.value),children:pt.map(B=>s.jsx("option",{value:B.id,children:B.name},B.id))}),s.jsxs("select",{value:_e,onChange:B=>Le(B.target.value),children:[s.jsx("option",{value:"free",children:"Free"}),s.jsx("option",{value:"user",children:"User"}),s.jsx("option",{value:"paid",children:"Paid"}),s.jsx("option",{value:"beta",children:"Beta"}),s.jsx("option",{value:"staff",children:"Staff"})]}),s.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:tt==="access",children:[s.jsx(Pr,{size:15})," Grant access"]})]}),s.jsxs("form",{onSubmit:B=>{},children:[s.jsx("strong",{children:"Assign product admin"}),s.jsx("input",{type:"email",required:!0,placeholder:"Admin email",value:ue,onChange:B=>Ve(B.target.value)}),s.jsx("select",{value:Ye,onChange:B=>oe(B.target.value),children:pt.map(B=>s.jsx("option",{value:B.id,children:B.name},B.id))}),s.jsxs("select",{value:Ne,onChange:B=>je(B.target.value),children:[s.jsx("option",{value:"admin",children:"Admin"}),s.jsx("option",{value:"support",children:"Support"}),s.jsx("option",{value:"moderator",children:"Moderator"})]}),s.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:tt==="product-admin",children:[s.jsx(zt,{size:15})," Assign admin"]})]}),s.jsxs("form",{onSubmit:B=>{},children:[s.jsx("strong",{children:"Add a product"}),s.jsx("input",{required:!0,pattern:"[a-z0-9][a-z0-9_-]{1,48}",placeholder:"product-key",value:Ee,onChange:B=>Re(B.target.value)}),s.jsx("input",{required:!0,placeholder:"Product name",value:Fe,onChange:B=>he(B.target.value)}),s.jsx("input",{placeholder:"Description",value:Ae,onChange:B=>de(B.target.value)}),s.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:tt==="product",children:[s.jsx(Bm,{size:15})," Add product"]})]})]})]}),s.jsxs("form",{className:"support-search-bar",onSubmit:B=>{B.preventDefault(),Oe({query:X.trim()})},children:[s.jsxs("label",{children:[s.jsx("span",{children:"Search Support"}),s.jsx("input",{value:X,onChange:B=>D(B.target.value),placeholder:"Search titles and request details"})]}),s.jsxs("button",{className:"support-secondary-button",type:"submit",children:[s.jsx(Qv,{size:15})," Search"]}),c.query&&s.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{D(""),Oe({query:""})},"aria-label":"Clear search",children:s.jsx(Ds,{size:16})})]}),s.jsxs("div",{className:"support-filter-bar",children:[s.jsxs("div",{className:"support-filter-title",children:[s.jsx(Qv,{size:16}),s.jsx("span",{children:"Filter"})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Product"}),s.jsxs("select",{value:st,onChange:B=>Oe({product:B.target.value}),disabled:!m?.canViewAllProducts&&pt.length<=1,children:[s.jsx("option",{value:"all",children:"All products"}),pt.map(B=>s.jsx("option",{value:B.product_key,children:B.name},B.id))]})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Status"}),s.jsx("select",{value:c.status,onChange:B=>Oe({status:B.target.value}),children:H0.map(B=>s.jsx("option",{value:B.id,children:B.label},B.id))})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Visibility"}),s.jsxs("select",{value:c.visibility,onChange:B=>Oe({visibility:B.target.value}),children:[s.jsx("option",{value:"all",children:"All visibility"}),s.jsx("option",{value:"public",children:"Public"}),s.jsx("option",{value:"private",children:"Private"})]})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Sort"}),s.jsxs("select",{value:c.sort,onChange:B=>Oe({sort:B.target.value}),children:[s.jsx("option",{value:"recent",children:"Recently updated"}),s.jsx("option",{value:"newest",children:"Newest"}),s.jsx("option",{value:"votes",children:"Most votes"})]})]})]}),m?.canViewAllProducts&&s.jsxs("div",{className:"support-admin-shortcuts",children:[s.jsxs("span",{children:[s.jsx(zt,{size:15})," Owner view"]}),s.jsx("button",{type:"button",onClick:()=>Oe({status:"needs-response"}),children:"Needs response"}),s.jsx("button",{type:"button",onClick:()=>Oe({visibility:"private"}),children:"Private requests"}),s.jsx("button",{type:"button",onClick:()=>Oe({type:"feature",status:"all",sort:"votes"}),children:"High-vote features"})]}),s.jsxs("div",{className:"support-board-layout",children:[s.jsxs("section",{className:"support-post-list","aria-label":"Support posts",children:[s.jsxs("div",{className:"support-list-heading",children:[s.jsxs("span",{children:[Nt.length," request",Nt.length===1?"":"s"]}),s.jsx("small",{children:st==="all"?"All products":Gm(pt,Jt)})]}),Nt.length===0?s.jsxs("div",{className:"support-list-empty",children:[s.jsx(qc,{size:25}),s.jsx("strong",{children:"No posts match these filters."}),s.jsx("span",{children:"Start with a focused question, issue report, or feature request."}),pt.length>0&&s.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>J(!0),children:[s.jsx(Bm,{size:16})," Create the first request"]})]}):Nt.map(B=>{const He=mx(B.post_type);return s.jsxs("button",{type:"button",className:`support-post-row ${B.id===De?.id?"active":""}`,onClick:()=>{j(B.id),Y(!1)},children:[s.jsx("span",{className:"support-post-row-icon",children:s.jsx(He,{size:17})}),s.jsxs("span",{className:"support-post-row-copy",children:[s.jsxs("span",{className:"support-post-row-meta",children:[s.jsx("b",{children:Gm(v,B.product_id)}),s.jsx("em",{children:hx(B.post_type)}),B.visibility==="private"&&s.jsx(Rs,{size:13})]}),s.jsx("strong",{children:B.title}),s.jsxs("small",{children:[qm(B.status)," · ",xd(B.updated_at)," · ",B.comment_count," comments"]})]}),B.post_type==="feature"&&s.jsxs("span",{className:"support-vote-count",children:[s.jsx(Fy,{size:14})," ",B.vote_count]})]},B.id)})]}),s.jsx("section",{className:"support-post-detail","aria-label":"Support post detail",children:De?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"support-detail-head",children:[s.jsxs("div",{className:"support-detail-badges",children:[s.jsx("span",{className:"support-product-badge",children:Gm(v,De.product_id)}),s.jsx("span",{className:"support-type-badge",children:hx(De.post_type)}),s.jsx("span",{className:`support-status-badge status-${De.status}`,children:qm(De.status)}),De.visibility==="private"&&s.jsxs("span",{className:"support-private-badge",children:[s.jsx(Rs,{size:13})," Private"]})]}),s.jsxs("div",{className:"support-detail-actions",children:[Vi&&s.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>Y(B=>!B),title:"Edit post",children:s.jsx(TS,{size:16})}),Nn&&s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{ut()},disabled:L==="pin",title:De.is_pinned?"Unpin post":"Pin post",children:s.jsx(Xv,{size:16})}),s.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{ri()},disabled:L==="lock",title:De.is_locked?"Unlock post":"Lock post",children:s.jsx(Rs,{size:16})}),s.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{Ie()},disabled:L==="hide",title:"Hide post",children:s.jsx(Zv,{size:16})})]})]})]}),le?s.jsxs("form",{className:"support-edit-form",onSubmit:B=>{ga(B)},children:[s.jsx("input",{value:De.title,onChange:B=>un({title:B.target.value}),minLength:3,maxLength:180,required:!0}),s.jsx("textarea",{value:De.body,onChange:B=>un({body:B.target.value}),rows:9,required:!0}),s.jsxs("div",{className:"support-edit-actions",children:[s.jsxs("select",{value:De.visibility,onChange:B=>un({visibility:B.target.value}),children:[s.jsx("option",{value:"public",children:"Public"}),s.jsx("option",{value:"private",children:"Private"})]}),s.jsxs("button",{className:"support-primary-button",type:"submit",disabled:L==="edit",children:[s.jsx(Pr,{size:16})," Save changes"]})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("h3",{children:De.title}),s.jsx("div",{className:"support-detail-body",children:De.body.split(`
10
+ `).map((B,He)=>s.jsx("p",{children:B||" "},`${De.id}-body-${He}`))})]}),s.jsxs("div",{className:"support-detail-meta",children:[s.jsxs("span",{children:["Opened ",xd(De.created_at)]}),De.app_version&&s.jsxs("span",{children:["Version ",De.app_version]}),De.platform&&s.jsx("span",{children:De.platform}),De.is_locked&&s.jsxs("span",{children:[s.jsx(Rs,{size:13})," Locked"]}),De.is_pinned&&s.jsxs("span",{children:[s.jsx(Xv,{size:13})," Pinned"]})]}),s.jsxs("div",{className:"support-detail-controls",children:[De.post_type==="feature"&&s.jsxs("button",{className:`support-vote-button ${$.has(De.id)?"voted":""}`,type:"button",onClick:()=>{Mn()},disabled:L==="vote",children:[s.jsx(ES,{size:16})," ",$.has(De.id)?"Voted":"Vote"," ",s.jsx("b",{children:De.vote_count})]}),Nn&&s.jsxs("label",{className:"support-status-control",children:[s.jsx("span",{children:"Change status"}),s.jsx("select",{value:De.status,onChange:B=>{Qa(B.target.value)},disabled:L==="status",children:($0[De.post_type]||[]).map(B=>s.jsx("option",{value:B,children:qm(B)},B))})]}),Nn&&s.jsxs(s.Fragment,{children:[s.jsxs("select",{className:"support-status-control",value:ye,onChange:B=>qe(B.target.value),children:[s.jsx("option",{value:"",children:"Duplicate of..."}),Nt.filter(B=>B.id!==De.id&&B.product_id===De.product_id).map(B=>s.jsx("option",{value:B.id,children:B.title.slice(0,55)},B.id))]}),s.jsx("button",{className:"support-secondary-button",type:"button",onClick:()=>{qt()},disabled:!ye||L==="duplicate",children:"Merge duplicate"})]})]}),T.length>0&&s.jsxs("div",{className:"support-attachments",children:[s.jsx("div",{className:"support-section-heading",children:s.jsxs("div",{children:[s.jsx("span",{children:"Attachments"}),s.jsxs("strong",{children:[T.length," file",T.length===1?"":"s"]})]})}),T.map(B=>s.jsxs("a",{href:B.signed_url,target:"_blank",rel:"noreferrer",children:[s.jsx(Gh,{size:14})," ",B.file_name,s.jsxs("small",{children:[Math.ceil(B.size_bytes/1024)," KB"]})]},B.id))]}),s.jsxs("div",{className:"support-comments",children:[s.jsxs("div",{className:"support-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Discussion"}),s.jsxs("strong",{children:[C.length," comment",C.length===1?"":"s"]})]}),De.is_locked&&s.jsxs("span",{className:"support-locked-label",children:[s.jsx(Rs,{size:14})," Locked"]})]}),C.length===0?s.jsx("p",{className:"support-muted",children:"No response yet. Keep the conversation focused on this request."}):s.jsx("div",{className:"support-comment-list",children:C.map(B=>s.jsxs("article",{className:`support-comment ${B.is_staff_answer?"staff":""} ${De.accepted_comment_id===B.id?"accepted":""}`,children:[s.jsxs("div",{className:"support-comment-head",children:[s.jsx("strong",{children:B.is_staff_answer?"LiveDesk Support":B.author_id===n.user.id?"You":"Support user"}),B.is_staff_answer&&s.jsxs("span",{children:[s.jsx(zt,{size:13})," Staff answer"]}),De.accepted_comment_id===B.id&&s.jsxs("span",{children:[s.jsx(Ln,{size:13})," Accepted"]}),s.jsx("time",{children:xd(B.created_at)})]}),s.jsx("p",{children:B.body}),s.jsxs("div",{className:"support-comment-actions",children:[(n.user.id===De.author_id||Nn)&&De.post_type==="question"&&De.accepted_comment_id!==B.id&&s.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{Xa(B.id)},disabled:L===`accept-${B.id}`,children:[s.jsx(Pr,{size:14})," Accept answer"]}),Nn&&s.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{P0(B.id)},title:"Hide comment",children:s.jsx(Zv,{size:14})})]})]},B.id))}),!De.is_locked&&s.jsxs("form",{className:"support-comment-form",onSubmit:B=>{Ka(B)},children:[s.jsx("textarea",{value:O,onChange:B=>Z(B.target.value),placeholder:"Add a focused reply...",rows:3}),s.jsxs("button",{className:"support-primary-button",type:"submit",disabled:L==="comment"||!O.trim(),children:[s.jsx(Do,{size:15})," Reply"]})]})]})]}):s.jsxs("div",{className:"support-detail-empty",children:[s.jsx(qc,{size:28}),s.jsx("strong",{children:"Select a Support request"}),s.jsx("span",{children:"Its discussion and staff actions will appear here."})]})})]})]}):s.jsx("section",{className:"support-page support-auth-page",children:s.jsxs("div",{className:"support-empty-hero",children:[s.jsx("span",{className:"support-hero-icon",children:s.jsx(qc,{size:28})}),s.jsx("p",{className:"support-eyebrow",children:"LiveDesk Support"}),s.jsx("h2",{children:"Get help, report issues, and shape the product."}),s.jsx("p",{children:"Sign in to see the products attached to your account and submit a private or public request."}),s.jsxs("button",{className:"support-primary-button",type:"button",onClick:l,children:[s.jsx(zt,{size:17})," Sign in with Google"]})]})})}function yd(n){return!!n&&typeof n=="object"}function Jy(n){let a=n;return yd(a)&&"data"in a&&(a=a.data),yd(a)&&"session"in a&&(a=a.session),!yd(a)||typeof a.access_token!="string"||!a.access_token||!yd(a.user)||typeof a.user.id!="string"||!a.user.id?null:a}function px(n){return n?.access_token?n.refresh_token?"":"refresh-token-required":"access-token-required"}const Vc=5179,hn=qr(`http://127.0.0.1:${Vc}`);function V0(n){const a=n.split(".").map(r=>Number(r));return a.length===4&&a.every(r=>Number.isInteger(r)&&r>=0&&r<=255)?a:[]}function Y0(n){const a=n.trim().toLowerCase();return a==="localhost"||a==="127.0.0.1"||a==="::1"||a==="[::1]"}function W0(n){const a=n.trim().toLowerCase();return!a||a==="0.0.0.0"||a==="::"||a==="[::]"}function K0(n){const a=V0(n);return a.length===0?!1:a[0]===10||a[0]===172&&a[1]>=16&&a[1]<=31||a[0]===192&&a[1]===168}function Q0(n){return n.includes(":")&&!n.startsWith("[")?`[${n}]`:n}function X0(n){const a=String(n||"").trim();if(!a)return null;const r=/^[a-z][a-z\d+.-]*:\/\//i.test(a)?a:`tcp://${a}`;try{const l=new URL(r),c=l.hostname.replace(/^\[|\]$/g,""),d=Number(l.port);return!c||!Number.isInteger(d)||d<1||d>65535||W0(c)?null:{host:c,port:d}}catch{return null}}function qr(n){const a=String(n||"").trim()||`http://127.0.0.1:${Vc}`,r=/^[a-z][a-z\d+.-]*:\/\//i.test(a)?a:`http://${a}`;try{const l=new URL(r);return l.port||(l.port=String(Vc)),l.hash="",l.search="",l.toString().replace(/\/+$/,"")}catch{return`http://127.0.0.1:${Vc}`}}function Z0(n){const a=X0(n);return a?qr(`http://${Q0(a.host)}:${Vc}`):""}function gx(n){const r=[n?.endpoint,...Array.isArray(n?.endpoint_candidates)?n.endpoint_candidates:[]].map(l=>Z0(String(l||""))).filter(Boolean);return[...new Set(r)]}function Yc(n=hn){if(!(typeof window>"u"||window.location.protocol!=="https:"))try{const a=new URL(n);if(a.protocol!=="http:")return;if(Y0(a.hostname))return"loopback";if(K0(a.hostname))return"local"}catch{return}}function of(n,a=hn){const r=new URL(n,qr(a));return r.protocol=r.protocol==="https:"?"wss:":"ws:",r.toString()}async function $e(n,a,r=hn){const l=qr(r),c={...a,headers:{"Content-Type":"application/json",...a?.headers||{}},cache:"no-store"},d=Yc(l);d&&(c.targetAddressSpace=d);let m;try{m=await fetch(`${l}${n}`,c)}catch(v){throw d?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."):v}let p=null;try{p=await m.json()}catch{p=null}if(!m.ok){const v=p&&typeof p=="object"&&"error"in p?String(p.error||""):"";throw new Error(`${m.status} ${v||m.statusText}`)}return p}async function ew({baseUrl:n=hn,targetRole:a,previousRuntimePid:r=0,allowedStates:l=["running","waiting-auth"],timeoutMs:c=3e4}){const d=Date.now()+c;let m=null;for(;Date.now()<d;){try{const v=await $e("/api/runtime/status",void 0,n),g=String(v.role||"").toLowerCase(),w=String(v.state||"").toLowerCase(),y=Number(v.runtimePid||0),b=r>1?y>1&&y!==r:y>1;if(g===a&&l.map(j=>j.toLowerCase()).includes(w)&&b)return v}catch(v){m=v}await new Promise(v=>setTimeout(v,300))}const p=m instanceof Error?` ${m.message}`:"";throw new Error(`LiveDesk runtime did not become ${a} with a new process.${p}`)}function J0(n,a=120){if(typeof window>"u")return;const r=new URL(window.location.href);r.port=String(n),r.pathname="/",r.search="",r.hash="";const l=r.toString();let c=0;const d=()=>{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(d,250)})};d()}function jh(n){if(!n)return"-";const a=Date.now()-Date.parse(n);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 Sl(n){await navigator.clipboard.writeText(n)}function tw({size:n=22}){return s.jsxs("svg",{width:n,height:n,viewBox:"0 0 28 28",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[s.jsx("rect",{x:"2.5",y:"4",width:"14",height:"9",rx:"1.5",stroke:"currentColor",strokeWidth:"1.7",opacity:"0.42"}),s.jsx("path",{d:"M7 16v1.5h5",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",opacity:"0.42"}),s.jsx("rect",{x:"10.5",y:"2.5",width:"14",height:"9",rx:"1.5",stroke:"currentColor",strokeWidth:"1.7",opacity:"0.62"}),s.jsx("path",{d:"M15 14.5V16h5",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",opacity:"0.62"}),s.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"}),s.jsx("path",{d:"M12 21v1.5H9.5M16 21v1.5h2.5M9.5 22.5h9",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round"})]})}const ej=[{id:"docs",label:"Doc",icon:Wd},{id:"support",label:"Support",icon:qc},{id:"pricing",label:"Pricing",icon:Co},{id:"settings",label:"Settings",icon:Py}],vx=[0,1e3,2e3,5e3,1e4,2e4,3e4];function tj(){return typeof window>"u"?"":window.location.port==="5179"?window.location.origin:"http://127.0.0.1:5179"}async function Ic(n,a=!1){const r=a?"":sessionStorage.getItem("livedesk.client.csrf");if(r)return r;const l=await fetch(`${n}/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 d=String(c.csrfToken||"");return d&&sessionStorage.setItem("livedesk.client.csrf",d),d}function Ch(n){return`${Math.max(0,Math.min(100,Number(n||0))).toFixed(0)}%`}function Vm(n){return Number.isFinite(n)?`${Math.max(0,Math.min(100,Number(n))).toFixed(0)}%`:"—"}function nw(n){return Number.isFinite(n)?Ch(Number(n)):"0%"}function kl(n){const a=Number(n);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 xx(n){const a=Math.max(0,Number(n||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 nj(n,a){const r=Number(n||0)/1073741824,l=Number(a||0)/1024**3;return l>0?`${r.toFixed(1)} / ${l.toFixed(1)} GB`:"Checking..."}function aj(n,a){return!Number.isFinite(a)||Number(a)<=0?"Dedicated memory unavailable":Number.isFinite(n)?`${kl(n)} / ${kl(a)}`:`${kl(a)} available`}function sj(n){const a=Math.max(0,Math.floor(Number(n||0)/60)),r=Math.floor(a/1440),l=Math.floor(a%1440/60),c=a%60;return r>0?`${r}d ${l}h`:l>0?`${l}h ${c}m`:`${c}m`}function wd({icon:n,label:a,value:r,detail:l,percent:c}){return s.jsxs("article",{className:"client-resource-metric",children:[s.jsxs("div",{className:"client-resource-metric-head",children:[s.jsx(n,{size:17}),s.jsx("span",{children:a}),s.jsx("strong",{children:r})]}),s.jsx("small",{title:l,children:l}),s.jsx("i",{"aria-hidden":"true",children:s.jsx("b",{style:{width:nw(c)}})})]})}function ij(n){const a=n?.user.user_metadata||{},r=a.full_name||a.name||a.preferred_username||n?.user.email||n?.user.id||"Account";return String(r).trim()||"Account"}function rj(n){const a=n?.user.user_metadata||{},r=a.avatar_url||a.picture;return typeof r=="string"?r.trim():""}function lj({page:n,status:a}){const l={docs:{label:"DOC",title:"Using this computer",body:"This computer connects to its assigned Sync Server 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."}}[n];return s.jsxs("section",{className:"client-service-page",children:[s.jsx("span",{className:"client-unified-section-label",children:l.label}),s.jsx("h2",{children:l.title}),s.jsx("p",{children:l.body}),s.jsxs("div",{className:"client-service-page-card",children:[n==="docs"&&s.jsxs(s.Fragment,{children:[s.jsx("strong",{children:"Automatic connection"}),s.jsx("span",{children:"Start LiveDesk. This computer signs in, finds the Hub, and becomes available without another action."})]}),n==="pricing"&&s.jsxs(s.Fragment,{children:[s.jsx("strong",{children:"One plan, managed at the Hub"}),s.jsx("span",{children:"Computer access follows the account and plan used by the Sync Server."})]}),n==="settings"&&s.jsxs(s.Fragment,{children:[s.jsx("strong",{children:"Saved sign-in"}),s.jsx("span",{children:a?.auth?.persisted?"Enabled on this computer":"Sign in once to enable automatic reconnection"})]})]})]})}function oj({session:n,status:a,pin:r,error:l,roleChangeMessage:c,roleChangeBusy:d,onSignIn:m,onPinChange:p,onSubmitPin:v,onSwitchToHub:g}){const w=a?.connectionState==="connected",y=a?.system?.memoryTotalBytes?Number(a.system.memoryUsedBytes||0)/a.system.memoryTotalBytes*100:0,b=a?.system?.gpus||[],j=b.find(F=>Number.isFinite(F.usagePercent)||Number.isFinite(F.memoryTotalBytes))||b[0],C=Number.isFinite(j?.usagePercent)?Number(j?.usagePercent):null,N=Number.isFinite(j?.memoryTotalBytes)&&Number(j?.memoryTotalBytes)>0&&Number.isFinite(j?.memoryUsedBytes)?Number(j?.memoryUsedBytes)/Number(j?.memoryTotalBytes)*100:null,T=a?.system?.disks||[],k=a?.system?.network,E=k?.interfaces||[],R=[...new Set(E.map(F=>F.name).filter(Boolean))],$=E.map(F=>F.address).filter(Boolean);return s.jsxs("section",{className:"client-home-page",children:[s.jsxs("header",{className:"client-home-heading",children:[s.jsxs("div",{children:[s.jsx("p",{className:"client-unified-eyebrow",children:"THIS COMPUTER"}),s.jsx("h2",{children:a?.deviceName||"This Computer"})]}),s.jsxs("span",{className:`client-unified-role-chip ${w?"connected":""}`,children:[s.jsx(Zt,{size:15})," ",w?"Online":"Connecting"]})]}),s.jsxs("div",{className:"client-home-layout",children:[s.jsxs("section",{className:"client-main-surface","aria-label":"Client computer",children:[s.jsxs("div",{className:"client-main-surface-head",children:[s.jsxs("div",{children:[s.jsx("span",{className:"client-unified-section-label",children:"SYSTEM STATUS"}),s.jsx("strong",{children:"Hardware at a glance"})]}),s.jsxs("small",{children:[s.jsx($y,{size:14})," Uptime ",sj(a?.system?.uptimeSeconds)]})]}),s.jsxs("div",{className:"client-system-dashboard",children:[s.jsxs("section",{className:"client-performance-panel","aria-label":"Performance",children:[s.jsxs("div",{className:"client-system-subhead",children:[s.jsxs("div",{children:[s.jsx("span",{className:"client-unified-section-label",children:"PERFORMANCE"}),s.jsx("strong",{children:"Live resources"})]}),s.jsx("small",{children:"Live updates"})]}),s.jsxs("div",{className:"client-live-metrics",children:[s.jsx(wd,{icon:Uy,label:"CPU",value:Ch(a?.system?.cpuUsagePercent),detail:"Current processor usage",percent:a?.system?.cpuUsagePercent}),s.jsx(wd,{icon:zS,label:"Memory",value:Ch(y),detail:nj(a?.system?.memoryUsedBytes,a?.system?.memoryTotalBytes),percent:y}),s.jsx(wd,{icon:IS,label:"GPU",value:Vm(C),detail:j?.name||(a?.system?.hardwareCollecting?"Detecting graphics hardware…":"Graphics usage unavailable"),percent:C}),s.jsx(wd,{icon:Kd,label:"VRAM",value:Vm(N),detail:aj(j?.memoryUsedBytes,j?.memoryTotalBytes),percent:N})]})]}),s.jsxs("section",{className:"client-storage-panel","aria-label":"Local storage",children:[s.jsxs("div",{className:"client-system-subhead",children:[s.jsxs("div",{children:[s.jsx("span",{className:"client-unified-section-label",children:"STORAGE"}),s.jsx("strong",{children:"Local drives"})]}),s.jsx("small",{children:T.length>0?`${T.length} ${T.length===1?"drive":"drives"}`:a?.system?.hardwareCollecting?"Detecting…":"Unavailable"})]}),s.jsxs("div",{className:"client-disk-list",children:[T.map(F=>s.jsxs("article",{className:"client-disk-row",children:[s.jsxs("div",{className:"client-disk-row-head",children:[s.jsxs("span",{children:[s.jsx(Cl,{size:16}),s.jsx("strong",{children:F.mount||"Disk"}),s.jsx("small",{children:F.name||"Local disk"})]}),s.jsx("strong",{children:Vm(F.usedPercent)})]}),s.jsxs("small",{children:[kl(F.freeBytes)," free · ",kl(F.totalBytes)," total"]}),s.jsx("i",{"aria-hidden":"true",children:s.jsx("b",{style:{width:nw(F.usedPercent)}})})]},`${F.mount}-${F.name||""}`)),T.length===0&&s.jsxs("div",{className:"client-disk-empty",children:[s.jsx(Cl,{size:18}),s.jsx("span",{children:a?.system?.hardwareCollecting?"Detecting local drives…":"Storage information is not available."})]})]})]}),s.jsxs("section",{className:"client-network-panel","aria-label":"Network activity",children:[s.jsxs("div",{className:"client-system-subhead",children:[s.jsxs("div",{children:[s.jsx("span",{className:"client-unified-section-label",children:"NETWORK"}),s.jsx("strong",{children:"Live traffic"})]}),s.jsx("small",{children:R.length>0?R.join(", "):"Detecting adapter"})]}),s.jsxs("div",{className:"client-network-live",children:[s.jsxs("div",{className:"client-network-adapter",children:[s.jsx(ko,{size:18}),s.jsxs("span",{children:[s.jsx("strong",{children:R.join(", ")||"Network"}),s.jsx("small",{children:$.join(" / ")||"Checking active connection"})]})]}),s.jsxs("div",{className:"client-network-rate download",children:[s.jsx(OS,{size:17}),s.jsxs("span",{children:[s.jsx("small",{children:"Receive"}),s.jsx("strong",{children:xx(k?.receiveBytesPerSecond)})]})]}),s.jsxs("div",{className:"client-network-rate upload",children:[s.jsx(BS,{size:17}),s.jsxs("span",{children:[s.jsx("small",{children:"Send"}),s.jsx("strong",{children:xx(k?.sendBytesPerSecond)})]})]}),s.jsxs("small",{className:"client-network-total",children:["Total ",kl(k?.receivedBytes)," received / ",kl(k?.sentBytes)," sent"]})]})]})]})]}),s.jsxs("aside",{className:"client-connection-panel",children:[s.jsx("span",{className:"client-unified-section-label",children:"LIVEDESK SERVICES"}),s.jsx("h3",{children:w?"Connected to the Hub":a?.authenticated?"Finding the Hub":"Connect this computer"}),w?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"client-unified-copy",children:"This computer is available from the LiveDesk Hub."}),s.jsxs("div",{className:"client-service-status-list",children:[s.jsxs("div",{children:[s.jsx(Zt,{size:17}),s.jsxs("span",{children:[s.jsx("strong",{children:"Screen sharing"}),s.jsx("small",{children:a?.permissions?.screenCapture?"Active":"Waiting"})]})]}),s.jsxs("div",{children:[s.jsx(zt,{size:17}),s.jsxs("span",{children:[s.jsx("strong",{children:"Remote control"}),s.jsx("small",{children:a?.permissions?.remoteInput?"Available":"Unavailable"})]})]}),s.jsxs("div",{children:[s.jsx(Ao,{size:17}),s.jsxs("span",{children:[s.jsx("strong",{children:"File delivery"}),s.jsx("small",{children:a?.permissions?.files?"Ready to receive":"Unavailable"})]})]}),s.jsxs("div",{children:[s.jsx(an,{size:17}),s.jsxs("span",{children:[s.jsx("strong",{children:"Computer audio"}),s.jsx("small",{children:a?.permissions?.audio?"Available":"Unavailable"})]})]})]})]}):s.jsxs(s.Fragment,{children:[s.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."}),!n&&!a?.authenticated?s.jsxs("button",{className:"client-unified-primary",type:"button",onClick:m,children:[s.jsx(Al,{size:16})," Sign in with Google"]}):s.jsxs("p",{className:"client-unified-success",children:[s.jsx(Ln,{size:16})," Signed in as ",n?.user.email||n?.user.id||a?.userEmail||a?.userId||"saved account"]}),s.jsxs("div",{className:"client-unified-pin-row",children:[s.jsx(No,{size:16}),s.jsx("input",{value:r,onChange:F=>p(F.target.value),placeholder:"6-digit Hub PIN",inputMode:"numeric","aria-label":"6-digit Hub PIN"}),s.jsx("button",{className:"client-unified-secondary",type:"button",onClick:v,disabled:r.length!==6,children:"Connect"})]})]}),(l||a?.lastError)&&s.jsxs("p",{className:"client-unified-error",role:"alert",children:[s.jsx(qy,{size:15})," ",l||a?.lastError]}),c&&s.jsx("p",{className:"client-unified-success",children:c}),s.jsxs("button",{className:"client-unified-secondary full",type:"button",onClick:g,disabled:d||!a?.authenticated,children:[s.jsx(Kd,{size:16})," ",d?"Switching to Hub…":"Become Sync Server (Hub)"]})]})]})]})}function cj(){const[n,a]=u.useState(null),[r,l]=u.useState(null),[c,d]=u.useState(!1),[m,p]=u.useState(""),[v,g]=u.useState(""),[w,y]=u.useState(""),[b,j]=u.useState(!1),[C,N]=u.useState("computer"),[T,k]=u.useState(!1),E=u.useRef(!1),R=u.useRef(!1),$=u.useRef(!1),F=u.useRef(0),q=u.useMemo(tj,[]),z=u.useMemo(()=>ij(r),[r]),L=u.useMemo(()=>rj(r),[r]),ie=z.slice(0,1).toUpperCase()||"L",V=u.useCallback(async()=>{if(g(""),window.liveDesk?.auth?.signInWithGoogle){const D=await window.liveDesk.auth.signInWithGoogle();return D?.ok===!1?(g(D.error||"LiveDesk could not open the system browser for Google sign-in."),!1):!0}return window.location.assign(`${q}/auth/google`),!0},[q]),ne=u.useCallback(async()=>{$.current||($.current=!0,g("Your saved Google sign-in is incomplete. LiveDesk is reopening sign-in once to repair it."),await ot.auth.signOut({scope:"local"}).catch(()=>{}),l(null),await V()||($.current=!1))},[V]),Q=u.useCallback(async D=>{const K=px(D);if(K)throw new Error(K);if(E.current)return!1;E.current=!0;try{const ce=await window.liveDesk?.auth?.persistSession?.(D);if(ce?.ok===!1)throw new Error(ce.error||"LiveDesk could not validate the desktop session.");for(let W=0;W<2;W+=1){const P=await Ic(q,W>0),me=await fetch(`${q}/api/auth/session`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":P},signal:AbortSignal.timeout(1e4),body:JSON.stringify({accessToken:D.access_token,refreshToken:D.refresh_token,expiresAt:D.expires_at,user:{id:D.user.id,email:D.user.email}})}),pe=await me.json().catch(()=>({}));if(me.status===403&&W===0){sessionStorage.removeItem("livedesk.client.csrf");continue}if(!me.ok)throw new Error(pe.error||`Client runtime returned HTTP ${me.status}.`);return g(""),!0}throw new Error("Client runtime rejected the session transfer.")}finally{E.current=!1}},[q]),J=u.useCallback(async()=>{try{const D=await fetch(`${q}/api/client/status`,{cache:"no-store"}),K=await D.json().catch(()=>({}));if(!D.ok)throw new Error(K.error||`Client runtime returned HTTP ${D.status}.`);if(K.csrfToken&&sessionStorage.setItem("livedesk.client.csrf",K.csrfToken),String(K.role||"").toLowerCase()==="hub")throw new Error("This computer is assigned to the Hub role.");a(K)}catch(D){g(D instanceof Error?D.message:String(D))}},[q]);u.useEffect(()=>{J();const D=window.setInterval(()=>{J()},2e3);return()=>window.clearInterval(D)},[J]);const le=u.useCallback(async()=>{const D=Date.now();if(!(!n?.authenticated||n.connectionState==="connected"||!["waiting","reconnecting"].includes(String(n.agent?.state||""))||D-F.current<4e3)){F.current=D;try{const K=await fetch(`${q}/api/client/reconnect`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Ic(q)},body:JSON.stringify({onlyIfWaiting:!0,reason:"app-active"})});if(!K.ok)throw new Error(`Client reconnect returned HTTP ${K.status}.`);await J()}catch(K){g(K instanceof Error?K.message:String(K))}}},[q,J,n]);u.useEffect(()=>{const D=()=>{le()},K=()=>{le()},ce=()=>{document.visibilityState==="visible"&&le()};return window.addEventListener("online",D),window.addEventListener("focus",K),document.addEventListener("visibilitychange",ce),()=>{window.removeEventListener("online",D),window.removeEventListener("focus",K),document.removeEventListener("visibilitychange",ce)}},[le]),u.useEffect(()=>{if(!c||!n||!r?.access_token||n.authenticated)return;if(px(r)==="refresh-token-required"){ne().catch(P=>{$.current=!1,g(P instanceof Error?P.message:String(P))});return}let D=!1,K,ce=0;const W=async()=>{if(D)return;try{const me=await Q(r);if(await J(),me)return}catch(me){g(me instanceof Error?me.message:String(me))}if(D)return;const P=vx[Math.min(ce,vx.length-1)];ce+=1,K=window.setTimeout(()=>{W()},P)};return W(),()=>{D=!0,K!==void 0&&window.clearTimeout(K)}},[c,J,ne,r,n,Q]),u.useEffect(()=>{const D=new URLSearchParams(window.location.search),K=D.get("auth_error");if(!K)return;g(K),D.delete("auth_error");const ce=D.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${ce?`?${ce}`:""}${window.location.hash}`)},[]),u.useEffect(()=>{let D=!0;if(!window.liveDesk?.auth)return l(null),d(!0),J(),()=>{D=!1};const K=window.liveDesk?.auth?.onComplete?.(W=>{W.ok&&W.session?ot.auth.setSession(W.session).catch(P=>g(P instanceof Error?P.message:String(P))):W.error&&g(W.error)});(async()=>{try{const W=window.liveDesk?.auth?.getSession?await window.liveDesk.auth.getSession():await ot.auth.getSession();if(!D)return;const P=Jy(W);l(P),J()}catch(W){D&&g(W instanceof Error?W.message:String(W))}finally{D&&d(!0)}})();const{data:ce}=ot.auth.onAuthStateChange((W,P)=>{D&&(l(P),d(!0),J())});return()=>{D=!1,K?.(),ce.subscription.unsubscribe()}},[J]),u.useEffect(()=>{if(!c||!n||R.current||$.current||r||n.authenticated)return;const D=new URLSearchParams(window.location.search);if(!D.has("livedesk_launch"))return;R.current=!0,D.delete("livedesk_launch");const K=D.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${K?`?${K}`:""}${window.location.hash}`),V().catch(ce=>g(ce instanceof Error?ce.message:String(ce)))},[c,r,V,n]);const Y=async()=>{k(!1),window.liveDesk?.auth?.persistSession?(await ot.auth.signOut(),(await window.liveDesk.auth.persistSession(null))?.runtimeCleared===!1&&g("Signed out locally. The LiveDesk runtime could not be reached to clear its session.")):await fetch(`${q}/api/auth/session`,{method:"DELETE",headers:{"X-LiveDesk-CSRF":await Ic(q)}}).catch(()=>{}),l(null),await J()};u.useEffect(()=>{if(!T)return;const D=ce=>{ce.target instanceof Element&&ce.target.closest(".account-popover, .rail-account")||k(!1)},K=ce=>{ce.key==="Escape"&&k(!1)};return window.addEventListener("pointerdown",D),window.addEventListener("keydown",K),()=>{window.removeEventListener("pointerdown",D),window.removeEventListener("keydown",K)}},[T]);const O=async()=>{g("");try{const D=await fetch(`${q}/api/client/pin`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Ic(q)},body:JSON.stringify({pin:m})}),K=await D.json().catch(()=>({}));if(!D.ok||K?.ok===!1)throw new Error(K?.error||"PIN could not be accepted.");p(""),await J()}catch(D){g(D instanceof Error?D.message:String(D))}},Z=async()=>{j(!0),y(""),g("");try{const D=await fetch(`${q}/api/runtime/switch-role`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Ic(q)},body:JSON.stringify({role:"hub"})}),K=await D.json().catch(()=>({}));if(!D.ok||K?.ok===!1)throw new Error(K?.error||`Role change failed with HTTP ${D.status}.`);y("Hub role accepted. LiveDesk is restarting this computer with the Hub Wall.");const ce=Number(n?.runtimePid||0);await ew({baseUrl:q,targetRole:"hub",previousRuntimePid:ce,allowedStates:["running"]}),window.location.reload()}catch(D){g(D instanceof Error?D.message:String(D)),j(!1)}},X=!!(n?.authenticated||r);return s.jsxs("main",{className:"app-shell client-unified-shell",children:[s.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk Client tools",children:[s.jsx("div",{className:"rail-brand",title:"LiveDesk",children:s.jsx(tw,{size:25})}),s.jsx("nav",{className:"rail-tools","aria-label":"Client navigation",children:s.jsx("div",{className:"client-main-tool-slot",children:s.jsxs("button",{className:`rail-tool client-main-tool ${C==="computer"?"active":""}`,type:"button",onClick:()=>N("computer"),"aria-current":C==="computer"?"page":void 0,title:"Client",children:[s.jsx(Zt,{size:19}),s.jsx("span",{children:"Client"})]})})}),s.jsxs("div",{className:"rail-footer",children:[ej.map(D=>{const K=D.icon;return s.jsxs("button",{className:`rail-tool compact ${C===D.id?"active":""}`,type:"button",onClick:()=>N(D.id),title:D.label,children:[s.jsx(K,{size:18}),s.jsx("span",{children:D.label})]},D.id)}),s.jsxs("button",{className:`rail-account ${X?"signed-in":""}`,type:"button",onClick:()=>k(D=>!D),"aria-expanded":T,"aria-haspopup":"dialog",title:X?"Account":"Sign in",children:[r&&L?s.jsx("img",{src:L,alt:z,referrerPolicy:"no-referrer"}):r?s.jsx("span",{className:"avatar-fallback",children:ie}):X?s.jsx(zt,{size:18}):s.jsx(Al,{size:18}),s.jsx("span",{children:X?"Account":"Sign in"})]})]})]}),T&&s.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[s.jsxs("div",{className:"account-popover-head",children:[s.jsx("div",{className:"account-popover-avatar",children:r&&L?s.jsx("img",{src:L,alt:z,referrerPolicy:"no-referrer"}):r?s.jsx("span",{children:ie}):s.jsx(Al,{size:18})}),s.jsxs("div",{children:[s.jsx("strong",{children:r?z:X?"Saved account":"Account"}),s.jsx("p",{children:r?.user.email||n?.userEmail||n?.userId||"Not signed in"})]})]}),s.jsxs("dl",{className:"account-popover-facts",children:[s.jsx("dt",{children:"User"}),s.jsx("dd",{children:r?.user.email||n?.userEmail||n?.userId||"Not signed in"}),s.jsx("dt",{children:"Runtime"}),s.jsx("dd",{children:n?"Local app ready":"Checking local app"}),s.jsx("dt",{children:"Session"}),s.jsx("dd",{children:n?.auth?.persisted?"Saved on this computer":X?"Active for this run":"Not saved"}),s.jsx("dt",{children:"Role"}),s.jsx("dd",{children:"Client"})]}),X?s.jsxs("button",{className:"account-popover-action",onClick:()=>{Y()},type:"button",children:[s.jsx(Hy,{size:16}),"Logout"]}):s.jsxs("button",{className:"account-popover-action primary",onClick:()=>{k(!1),V()},type:"button",children:[s.jsx(Al,{size:16}),"Sign in with Google"]})]}),s.jsxs("section",{className:"desk-stage client-unified-stage",children:[s.jsx("header",{className:"topbar",children:s.jsxs("div",{className:"brand",children:[s.jsx("span",{className:"brand-mark",children:s.jsx(an,{size:18})}),s.jsxs("div",{children:[s.jsx("h1",{children:"LiveDesk"}),s.jsx("p",{children:"Client workspace"})]})]})}),C==="support"?s.jsx("section",{className:"client-unified-page",children:s.jsx(Zy,{session:r,currentProductKey:"livedesk",appVersion:n?.appVersion||"",onSignIn:()=>{V()}})}):C!=="computer"?s.jsx("section",{className:"client-unified-page",children:s.jsx(lj,{page:C,status:n})}):s.jsx(oj,{session:r,status:n,pin:m,error:v,roleChangeMessage:w,roleChangeBusy:b,onSignIn:()=>{V()},onPinChange:D=>p(D.replace(/\D/g,"").slice(0,6)),onSubmitPin:()=>{O()},onSwitchToHub:()=>{Z()}})]})]})}function Or(n,a,r){if(r<0||a<0||a+r>n.length)throw new Error("Invalid LZO1X block: input overrun.")}function Ym(n,a,r){let l=0;for(;Or(n,a.inputIndex,1),n[a.inputIndex]===0;)l+=1,a.inputIndex+=1;const c=l*255+r+n[a.inputIndex];return a.inputIndex+=1,c}function bd(n,a,r,l){if(Or(n,a.inputIndex,l),a.outputIndex+l>r.length)throw new Error("Invalid LZO1X block: output overrun.");r.set(n.subarray(a.inputIndex,a.inputIndex+l),a.outputIndex),a.inputIndex+=l,a.outputIndex+=l}function uj(n,a,r,l){const c=a-r;if(c<=0||l<=0)throw new Error("Invalid LZO1X block: invalid match distance.");let d=Math.min(c,l);for(n.set(n.subarray(r,r+d),a);d<l;){const m=Math.min(d,l-d);n.copyWithin(a+d,a,a+m),d+=m}return a+l}function aw(n,a){if(!(n instanceof Uint8Array)||n.length<3||a<0)throw new Error("Invalid LZO1X block.");const r=new Uint8Array(a),l={inputIndex:0,outputIndex:0};let c=0,d=0;if(n[l.inputIndex]>=22){const m=n[l.inputIndex]-17;l.inputIndex+=1,bd(n,l,r,m),c=4}else n[l.inputIndex]>=18&&(c=n[l.inputIndex]-17,l.inputIndex+=1,bd(n,l,r,c));for(;;){Or(n,l.inputIndex,1);const m=n[l.inputIndex];l.inputIndex+=1;let p,v;if((m&192)!==0)Or(n,l.inputIndex,1),v=l.outputIndex-((n[l.inputIndex]<<3)+(m>>2&7)+1),l.inputIndex+=1,d=(m>>5)+1,p=m&3;else if((m&32)!==0){d=(m&31)+2,d===2&&(d+=Ym(n,l,31)),Or(n,l.inputIndex,2);const g=n[l.inputIndex]|n[l.inputIndex+1]<<8;l.inputIndex+=2,v=l.outputIndex-((g>>2)+1),p=g&3}else if((m&16)!==0){d=(m&7)+2,d===2&&(d+=Ym(n,l,7)),Or(n,l.inputIndex,2);const g=n[l.inputIndex]|n[l.inputIndex+1]<<8;if(l.inputIndex+=2,v=l.outputIndex-(((m&8)<<11)+(g>>2)),p=g&3,v===l.outputIndex)break;v-=16384}else if(c===0){let g=m+3;g===3&&(g+=Ym(n,l,15)),bd(n,l,r,g),c=4;continue}else c!==4?(Or(n,l.inputIndex,1),p=m&3,v=l.outputIndex-((m>>2)+(n[l.inputIndex]<<2)+1),l.inputIndex+=1,d=2):(Or(n,l.inputIndex,1),p=m&3,v=l.outputIndex-((m>>2)+(n[l.inputIndex]<<2)+2049),l.inputIndex+=1,d=3);if(v<0||l.outputIndex+d+p>r.length)throw new Error("Invalid LZO1X block: lookbehind overrun.");l.outputIndex=uj(r,l.outputIndex,v,d),c=p,bd(n,l,r,p)}if(d!==3||l.inputIndex!==n.length||l.outputIndex!==r.length)throw new Error("Invalid LZO1X block: incomplete output.");return r}const yx=16,wx=8,dj=24*1024*1024,sw=new Uint8Array(new Uint32Array([16909060]).buffer)[0]===4,kh=new Uint32Array(65536);for(let n=0;n<kh.length;n+=1){const a=Math.round((n>>11&31)*255/31),r=Math.round((n>>5&63)*255/63),l=Math.round((n&31)*255/31);kh[n]=sw?(a|r<<8|l<<16|4278190080)>>>0:(a<<24|r<<16|l<<8|255)>>>0}function Ir(n,a){return n[a]|n[a+1]<<8}function fj(n,a){const r=Number(a);if(!Number.isSafeInteger(r)||r<yx||r>dj)throw new Error(`Invalid Mode 5 packet length: ${a}.`);const l=n instanceof Uint8Array?n:new Uint8Array(n),c=aw(l,r);if(c[0]!==76||c[1]!==68||c[2]!==53||c[3]!==68)throw new Error("Invalid Mode 5 packet magic.");if(c[4]!==1)throw new Error(`Unsupported Mode 5 packet version: ${c[4]}.`);const d=(c[5]&1)!==0,m=Ir(c,6),p=Ir(c,8),v=Ir(c,10),g=Ir(c,12);if(m<=0||p<=0||m>3840||p>2160)throw new Error(`Invalid Mode 5 frame size: ${m}x${p}.`);if(v<=0||v>256||g>8192)throw new Error(`Invalid Mode 5 tile header: ${v}/${g}.`);const w=[];let y=yx;for(let b=0;b<g;b+=1){if(y+wx>c.length)throw new Error("Mode 5 tile header is truncated.");const j=Ir(c,y),C=Ir(c,y+2),N=Ir(c,y+4),T=Ir(c,y+6);y+=wx;const k=N*T*2;if(N<=0||T<=0||N>v||T>v||j+N>m||C+T>p||y+k>c.length)throw new Error(`Invalid Mode 5 tile ${b}.`);w.push({x:j,y:C,width:N,height:T,pixels:c.subarray(y,y+k)}),y+=k}if(y!==c.length)throw new Error(`Mode 5 packet has ${c.length-y} trailing bytes.`);return{keyFrame:d,width:m,height:p,tileSize:v,tiles:w}}function mj(n,a,r,l){if(!(n instanceof Uint8ClampedArray)||n.length!==a*r*4||l.width!==a||l.height!==r)throw new Error("Mode 5 canvas state does not match the packet dimensions.");let c=a,d=r,m=0,p=0;const v=new Uint32Array(n.buffer,n.byteOffset,n.byteLength>>>2);for(const g of l.tiles){const w=sw&&(g.pixels.byteOffset&1)===0?new Uint16Array(g.pixels.buffer,g.pixels.byteOffset,g.pixels.byteLength>>>1):null;let y=0;for(let b=0;b<g.height;b+=1){let j=(g.y+b)*a+g.x;for(let C=0;C<g.width;C+=1){const N=y<<1,T=w?w[y]:g.pixels[N]|g.pixels[N+1]<<8;v[j]=kh[T],y+=1,j+=1}}c=Math.min(c,g.x),d=Math.min(d,g.y),m=Math.max(m,g.x+g.width),p=Math.max(p,g.y+g.height)}return l.tiles.length>0?{x:c,y:d,width:m-c,height:p-d}:null}const Da=new WeakMap,Zc=new WeakMap,Ah=new WeakMap,Jc=new Set,jl=new Set,Xd=new WeakMap,Nh=new WeakMap,Mh=new WeakMap,Zd=new WeakMap,iw=4,hj=2,pj=2,gj=2,vj=18,xj=40,yj=0,wj=250,rw=80,bx=5,bj=150,Sj=24,jj=180,Cj=1200,kj=18,Aj=.65,Nj=2e3,Mj=500,Qh=250,Tj=globalThis.LIVEDESK_ENABLE_CANVAS_VISUAL_SAMPLING===!0;let Jd=!1;function Ej(){return typeof navigator>"u"?!1:/mac/i.test(`${navigator.platform||""} ${navigator.userAgent||""}`)}function Rj(){const n=Math.max(1,Number(navigator.hardwareConcurrency||8));return Math.max(4,Math.min(16,Math.round(n/2)))}let Ml={h264DecodeAcceleration:"prefer-hardware",h264HardwareDecoderBudget:Rj()};function Dj(n){n.h264DecodeAcceleration&&(Ml={...Ml,h264DecodeAcceleration:n.h264DecodeAcceleration}),Number.isFinite(Number(n.h264HardwareDecoderBudget))&&(Ml.h264HardwareDecoderBudget=Math.max(1,Math.min(64,Math.round(Number(n.h264HardwareDecoderBudget)))))}function lw(n,a=Ml.h264DecodeAcceleration){const r=Xd.get(n);return r?.requested===a?(r.actual!=="prefer-hardware"&&jl.delete(n),r.actual):(r&&Xd.delete(n),a!=="prefer-hardware"?(jl.delete(n),a):jl.has(n)?"prefer-hardware":jl.size<Ml.h264HardwareDecoderBudget?(jl.add(n),"prefer-hardware"):"prefer-software")}function cf(n,a){return a!=="prefer-hardware"?!1:(Xd.set(n,{requested:a,actual:"prefer-software"}),jl.delete(n),!0)}function _j(n,a,r,l=64){try{let c=Nh.get(n);c||(c={canvas:document.createElement("canvas"),lastHash:"",initialized:!1},Nh.set(n,c));const d=Math.max(8,Math.min(64,Math.round(l))),m=Math.max(1,Math.round(d*Math.max(1,r)/Math.max(1,a)));(c.canvas.width!==d||c.canvas.height!==m)&&(c.canvas.width=d,c.canvas.height=m);const p=c.canvas.getContext("2d",{willReadFrequently:!0});if(!p)return{visualHash:"",visualChanged:!0};p.drawImage(n,0,0,Math.max(1,a),Math.max(1,r),0,0,d,m);const v=p.getImageData(0,0,d,m).data;let g=2166136261;for(let b=0;b<v.length;b+=4)g^=v[b],g=Math.imul(g,16777619),g^=v[b+1],g=Math.imul(g,16777619),g^=v[b+2],g=Math.imul(g,16777619);const w=(g>>>0).toString(16).padStart(8,"0"),y=!c.initialized||w!==c.lastHash;return c.initialized=!0,c.lastHash=w,{visualHash:w,visualChanged:y}}catch{return{visualHash:"",visualChanged:!0}}}function Th(n,a,r,l=Qh,c=64,d){if(!Tj&&d)return ow(n,d);let m=Mh.get(n);m||(m={lastHash:"",initialized:!1,lastCanvasSampleAt:0},Mh.set(n,m));const p=performance.now();if(m.initialized&&l>0&&p-m.lastCanvasSampleAt<l)return{visualHash:m.lastHash,visualChanged:!1};const v=_j(n,a,r,c);return m.initialized=!0,m.lastHash=v.visualHash,m.lastCanvasSampleAt=p,v}function ow(n,a){let r=Zd.get(n);r||(r={lastHash:"",initialized:!1},Zd.set(n,r));const l=String(a.contentHash||""),c=!r.initialized||!l||l!==r.lastHash;return r.initialized=!0,r.lastHash=l,{visualHash:l,visualChanged:c}}function cw(n,a){const r=Ah.get(n);if(r)return r;const l=n.getContext("2d",{alpha:!1,desynchronized:a==="interactive"});if(l){const c=l.getContextAttributes?.(),d={context:l,presentation:c?.desynchronized?"desync":"sync"};return Ah.set(n,d),d}return null}function Lj(n){const a=String(n.frameMode||n.mode||"").toLowerCase(),r=String(n.compression||"").toLowerCase(),l=String(n.mimeType||"").toLowerCase();return a==="mode2-lzo"||r==="lzo1x"||l==="application/vnd.livedesk.lzo-rgb565"||a==="mode2-lz4"||String(n.compression||"").toLowerCase()==="lz4"||l==="application/vnd.livedesk.lz4-raw"}function zj(n){return String(n.frameMode||n.mode||"").toLowerCase()==="mode3-h264-hw"||String(n.codec||"").toLowerCase()==="h264"||String(n.mimeType||"").toLowerCase()==="video/h264"}function Ij(n){const a=String(n.frameMode||n.mode||"").toLowerCase(),r=String(n.mimeType||"").toLowerCase();return a==="mode5-lzo-delta"||r==="application/vnd.livedesk.lzo-rgb565-delta"}function Sx(n,a,r){let l=r,c=a;if(l===15){let d=255;for(;d===255;){if(c>=n.length)throw new Error("Invalid LZ4 block: length overrun.");d=n[c],c+=1,l+=d}}return{length:l,cursor:c}}function Oj(n,a){const r=new Uint8Array(a);let l=0,c=0;for(;l<n.length;){const d=n[l];l+=1;const m=Sx(n,l,d>>4);l=m.cursor;const p=m.length;if(l+p>n.length||c+p>r.length)throw new Error("Invalid LZ4 block: literal overrun.");if(r.set(n.subarray(l,l+p),c),l+=p,c+=p,l>=n.length)break;if(l+2>n.length)throw new Error("Invalid LZ4 block: missing offset.");const v=n[l]|n[l+1]<<8;if(l+=2,v<=0||v>c)throw new Error("Invalid LZ4 block: bad match offset.");const g=Sx(n,l,d&15);l=g.cursor;const w=g.length+4;if(c+w>r.length)throw new Error("Invalid LZ4 block: match overrun.");let y=c-v;for(let b=0;b<w;b+=1)r[c]=r[y],c+=1,y+=1}if(c!==r.length)throw new Error("Invalid LZ4 block: incomplete output.");return r}function Bj(n){const a=Math.max(1,Math.floor(n.width||0)),r=Math.max(1,Math.floor(n.height||0)),l=String(n.compression||"").toLowerCase(),c=String(n.pixelFormat||n.codec||"").toLowerCase();if(l==="lzo1x"||String(n.frameMode||n.mode||"").toLowerCase()==="mode2-lzo"||String(n.mimeType||"").toLowerCase()==="application/vnd.livedesk.lzo-rgb565"){const w=Math.max(1,Math.floor(n.bytesPerPixel||2)),y=a*r*2,b=Math.floor(n.uncompressedByteLength||y);if(w!==2||b!==y)throw new Error(`Invalid mode2 RGB565 frame size: ${b} for ${a}x${r}.`);if(c&&c!=="rgb565le"&&c!=="rgb565")throw new Error(`Unsupported mode2 pixel format: ${c}`);const j=aw(n.payload,y),C=new Uint8ClampedArray(a*r*4);for(let N=0,T=0;N<j.length;N+=2,T+=4){const k=j[N]|j[N+1]<<8,E=k>>11&31,R=k>>5&63,$=k&31;C[T]=E<<3|E>>2,C[T+1]=R<<2|R>>4,C[T+2]=$<<3|$>>2,C[T+3]=255}return new ImageData(C,a,r)}const m=Math.max(1,Math.floor(n.bytesPerPixel||4)),p=Math.max(a*r*m,Math.floor(n.uncompressedByteLength||0)),v=Oj(n.payload,p);if(m!==4)throw new Error(`Unsupported mode2 pixel size: ${m}`);const g=new Uint8ClampedArray(a*r*4);if(c==="rgba32"||c==="rgba")g.set(v.subarray(0,g.length));else for(let w=0,y=0;y<g.length;w+=4,y+=4)g[y]=v[w+2],g[y+1]=v[w+1],g[y+2]=v[w],g[y+3]=v[w+3];return new ImageData(g,a,r)}function jx(n,a="smooth"){const r=window.VideoDecoder;if(!r||!window.EncodedVideoChunk)throw new Error("WebCodecs H.264 decode is not supported in this browser.");const l=Da.get(n);if(l&&l.decoder.state!=="closed"&&l.latencyMode===a)return l;l&&_s(n);let c;return c={decoder:new r({output:m=>{if(Da.get(n)!==c){m.close();return}const p=Number(m.timestamp||0);c.outputSerial+=1;let v=c.pendingFrames.get(p);if(v)c.pendingFrames.delete(p);else if(c.pendingFrames.size>0){const C=c.pendingFrames.entries().next().value;C&&(c.pendingFrames.delete(C[0]),v=C[1],c.timestampFallbacks+=1)}const g=m.displayWidth||m.codedWidth||n.width||960,w=m.displayHeight||m.codedHeight||n.height||540,y=Number(v?.frame.durationUs||0),b=Number(m.duration||0),j=Math.max(16,Math.min(250,(y>0?y:b||83333)/1e3));for(c.targetPaintIntervalMs=j,c.decodedFrames.push({videoFrame:m,pending:v,decodedAt:performance.now(),width:g,height:w,durationMs:j}),c.lastOutputAt=performance.now();c.decodedFrames.length>Zh(c);)ef(c,c.decodedFrames.shift());uw(c),c.renderTimer!==null&&c.renderScheduledAt>0&&performance.now()-c.renderScheduledAt>Mj&&(typeof document>"u"||document.visibilityState==="visible")&&(window.cancelAnimationFrame(c.renderTimer),c.renderTimer=null,c.renderScheduledAt=0),c.renderTimer!==null&&c.decodedFrames.length>=iw&&(window.cancelAnimationFrame(c.renderTimer),c.renderTimer=null,c.renderScheduledAt=0),tf(n,c)},error:()=>{Da.get(n)===c&&(cf(n,c.hardwareAcceleration),Xh(c),Jc.delete(n),Da.delete(n))}}),configured:!1,configKey:"",codec:"",hardwareAcceleration:lw(n),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},Da.set(n,c),Jc.add(n),c}function Xh(n){n.renderTimer!==null&&(window.cancelAnimationFrame(n.renderTimer),n.renderTimer=null),n.renderScheduledAt=0,n.flushTimer!==null&&(window.clearTimeout(n.flushTimer),n.flushTimer=null),n.flushInFlight=!1;for(const a of n.decodedFrames)a.videoFrame.close();n.decodedFrames=[],n.interactiveBufferPrimed=!1,n.interactiveBufferStartedAt=0}function ef(n,a){a&&(a.videoFrame.close(),n.droppedForLatency+=1)}function Zh(n){return n.latencyMode==="interactive"?pj:String(n.decodedFrames[0]?.pending?.frame.frameMode||n.decodedFrames[0]?.pending?.frame.mode||"").toLowerCase()==="mode4-h264-atlas"?hj:iw}function uw(n,a=performance.now()){const r=Zh(n);for(;n.decodedFrames.length>r;)ef(n,n.decodedFrames.shift());const l=n.latencyMode==="interactive"?rw:wj;let c=n.decodedFrames[0];for(;n.decodedFrames.length>1&&c?.pending&&a-c.pending.queuedAt>l;)ef(n,n.decodedFrames.shift()),c=n.decodedFrames[0]}function dw(n,a){if(a.hardwareAcceleration!=="prefer-hardware"||a.flushTimer!==null||a.flushInFlight)return;const r=a.latencyMode==="interactive"?Sj:bj,l=a.latencyMode==="interactive";a.flushTimer=window.setTimeout(async()=>{a.flushTimer=null;const c=performance.now();for(const[p,v]of a.pendingFrames.entries())c-v.queuedAt>Nj&&a.pendingFrames.delete(p);if(Da.get(n)!==a||a.decoder.state!=="configured"||a.pendingFrames.size===0||a.inputSerial<=a.lastFlushInputSerial||!l&&a.lastOutputAt>0&&c-a.lastOutputAt<r)return;const d=a.inputSerial,m=performance.now();a.flushInFlight=!0,a.flushCount+=1;try{await a.decoder.flush(),a.lastFlushInputSerial=Math.max(a.lastFlushInputSerial,d)}catch{Da.get(n)===a&&$d(a)}finally{a.flushInFlight=!1;const p=performance.now()-m;if(l&&p>=jj&&a.hardwareAcceleration==="prefer-hardware"){Jd=!0,cf(n,a.hardwareAcceleration),_s(n);return}Da.get(n)===a&&a.inputSerial>d&&a.pendingFrames.size>0&&(l||performance.now()-a.lastOutputAt>=r)&&dw(n,a)}},r)}function Cx(n,a,r){const l=performance.now();try{(n.width!==r.width||n.height!==r.height)&&(n.width=r.width,n.height=r.height);const c=cw(n,a.latencyMode);if(c?.context.drawImage(r.videoFrame,0,0,r.width,r.height),r.pending){const d=performance.now(),p=a.latencyMode==="interactive"?ow(n,r.pending.frame):Th(n,r.width,r.height,Qh,64,r.pending.frame);try{a.onPaint?.(r.pending.frame,{deviceId:r.pending.frame.deviceId,frameSeq:r.pending.frame.frameSeq,mode:r.pending.frame.frameMode||r.pending.frame.mode||r.pending.frame.codec||r.pending.frame.mimeType,width:r.width,height:r.height,byteLength:r.pending.frame.byteLength,queuedForMs:Math.max(0,l-r.pending.queuedAt),decodedForMs:Math.max(0,r.decodedAt-r.pending.queuedAt),scheduledForMs:Math.max(0,l-r.decodedAt),drawMs:Math.max(0,d-l),queueSize:r.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:p.visualHash,visualChanged:p.visualChanged,paintedAt:d})}catch{}}a.lastPaintAt=performance.now()}finally{r.videoFrame.close()}}function tf(n,a){if(a.renderTimer!==null||a.decodedFrames.length===0)return;const r=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(uw(a,c),a.decodedFrames.length===0)return;if(a.latencyMode==="interactive"){const v=a.targetPaintIntervalMs<=xj,g=a.targetPaintIntervalMs<=20;if(g&&!a.interactiveBufferPrimed){a.interactiveBufferStartedAt<=0&&(a.interactiveBufferStartedAt=c,a.interactiveBufferWaitCount+=1);const N=a.decodedFrames.length>=gj,T=c-a.interactiveBufferStartedAt>=vj;if(!N&&!T){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}a.interactiveBufferWaitMs+=Math.max(0,c-a.interactiveBufferStartedAt),a.interactiveBufferPrimed=!0}else g||(a.interactiveBufferPrimed=!0);const w=a.decodedFrames[0],y=w?.pending?Math.max(0,c-w.pending.queuedAt):0,b=a.lastPaintAt>0?a.lastPaintAt+r:c;if(!(!v||c+bx>=b||y>=rw)){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}const C=a.decodedFrames.shift();if(C)try{Cx(n,a,C)}catch{}a.decodedFrames.length===0&&(a.interactiveQueueDrainCount+=1,a.interactiveBufferPrimed=!1,a.interactiveBufferStartedAt=0),tf(n,a);return}const d=a.lastPaintAt>0?a.lastPaintAt+r:c+yj;if(!(c+bx>=d||a.decodedFrames.length>=Math.max(1,Zh(a)-1))){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}const p=a.decodedFrames.shift();if(p)try{Cx(n,a,p)}catch{}tf(n,a)};a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l)}function fw(n,a){if(Da.get(n)!==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;)ef(a,a.decodedFrames.shift());return a.lastPaintAt=0,a.interactiveBufferPrimed=!1,a.interactiveBufferStartedAt=0,tf(n,a),!0}function Wm(){if(!(typeof document>"u"||document.visibilityState!=="visible"))for(const n of Jc){const a=Da.get(n);if(!a||a.decoder.state==="closed"){Jc.delete(n);continue}fw(n,a)}}typeof document<"u"&&typeof window<"u"&&(document.addEventListener("visibilitychange",Wm),window.addEventListener("focus",Wm),window.addEventListener("pageshow",Wm));function _s(n){jl.delete(n),Jc.delete(n),Zd.delete(n);const a=Da.get(n);if(a){Da.delete(n);try{Xh(a),a.decoder.state!=="closed"&&a.decoder.close()}catch{}}}function Oc(n){n&&(Xd.delete(n),Ah.delete(n),Mh.delete(n),Nh.delete(n),Zd.delete(n),Zc.delete(n),_s(n))}function $d(n,a=1){try{n.decoder.state!=="closed"&&n.decoder.reset()}catch{}n.configured=!1,n.configKey="",n.keyFrameSeen=!1,n.pendingFrames.clear(),Xh(n),n.lastPaintAt=0,n.lastOutputAt=0,n.lastInputAt=0,n.interactiveBufferPrimed=!1,n.interactiveBufferStartedAt=0,n.lastInputFrameSeq=void 0,n.nextChunkTimestampUs=0,n.healthSampleStartedAt=performance.now(),n.healthInputSerial=n.inputSerial,n.healthOutputSerial=n.outputSerial,n.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(a)))}function Sd(n,a,r,l){n.decoder.configure(a),n.configured=!0,n.configKey=r,n.codec=a.codec,n.hardwareAcceleration=l,n.keyFrameSeen=!1,n.nextChunkTimestampUs=0,n.lastInputFrameSeq=void 0}function Fj(n,a){if(a.latencyMode!=="interactive"||a.hardwareAcceleration!=="prefer-hardware")return!1;const r=performance.now();if(r-a.healthSampleStartedAt<Cj)return!1;const l=a.inputSerial-a.healthInputSerial,c=a.outputSerial-a.healthOutputSerial;return a.healthSampleStartedAt=r,a.healthInputSerial=a.inputSerial,a.healthOutputSerial=a.outputSerial,l<kj||c/Math.max(1,l)>=Aj?!1:(Jd=!0,cf(n,a.hardwareAcceleration),_s(n),!0)}function Km(n,a=1){if(!n)return!1;const r=Da.get(n);return r?(r.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(a))),_s(n),!0):!1}function Pj(n){if(!n)return!1;const a=Da.get(n);return a?fw(n,a):!1}function Hj(n,a,r,l="interactive"){_s(n);const c=performance.now(),d=fj(a.payload,a.uncompressedByteLength||0),m=String(a.streamId||"mode5");let p=Zc.get(n);if(!p||p.streamId!==m||p.width!==d.width||p.height!==d.height){const N=new Uint8ClampedArray(d.width*d.height*4);for(let T=3;T<N.length;T+=4)N[T]=255;p={streamId:m,width:d.width,height:d.height,rgba:N,imageData:new ImageData(N,d.width,d.height),keyFrameSeen:!1,inputSerial:0,outputSerial:0},Zc.set(n,p)}if(!p)throw new Error("Mode 5 canvas state could not be initialized.");p.inputSerial+=1;const g=Number(a.streamFrameSeq||0);if(g>0&&(p.lastStreamFrameSeq=g),!d.keyFrame&&!p.keyFrameSeen)return;d.keyFrame&&(p.keyFrameSeen=!0);const w=mj(p.rgba,p.width,p.height,d),y=performance.now();(n.width!==p.width||n.height!==p.height)&&(n.width=p.width,n.height=p.height);const b=cw(n,l),j=performance.now();w&&b?.context.putImageData(p.imageData,0,0,w.x,w.y,w.width,w.height);const C=performance.now();p.outputSerial+=1,r?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.mimeType,width:p.width,height:p.height,byteLength:a.byteLength,queuedForMs:Math.max(0,C-c),decodedForMs:Math.max(0,y-c),scheduledForMs:0,drawMs:Math.max(0,C-j),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:"prefer-software",decoderLabel:"lzo-rgb565-delta",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:p.inputSerial,decoderOutputCount:p.outputSerial,targetPaintIntervalMs:Math.max(1,Number(a.durationUs||0)/1e3||1e3/30),canvasPresentation:b?.presentation||"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:String(a.contentHash||""),visualChanged:Number(a.deltaVisualTileCount||0)>0,paintedAt:C})}const Qm=[{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 kx(n,a){for(let r=Math.max(0,a);r+3<n.length;r+=1)if(!(n[r]!==0||n[r+1]!==0)){if(n[r+2]===1)return{index:r,length:3};if(n[r+2]===0&&n[r+3]===1)return{index:r,length:4}}return null}function $j(n){let a=0;for(;a<n.length;){const r=kx(n,a);if(!r)break;const l=r.index+r.length,c=kx(n,l),d=c?.index??n.length;if(l<d&&(n[l]&31)===7){const m=[];let p=0;for(let v=l+1;v<d;v+=1){const g=n[v];if(p>=2&&g===3){p=0;continue}m.push(g),p=g===0?p+1:0}if(m.length>=3)return`avc1.${m.slice(0,3).map(v=>v.toString(16).toUpperCase().padStart(2,"0")).join("")}`}a=c?c.index:n.length}return""}function Uj(n,a,r,l,c=""){const d=Math.ceil(n/16)*Math.ceil(a/16),m=r>0?1e6/r:30,p=d*m,v=Qm.find(g=>d<=g.maxFrameSize&&p<=g.maxMacroblocksPerSecond)||Qm[Qm.length-1];return $j(l)||c||`avc1.42E0${v.code.toString(16).toUpperCase().padStart(2,"0")}`}function qj(n,a,r,l,c="smooth"){Zc.delete(n);const d=String(a.h264Format||"").toLowerCase()==="avc"?"avc":"annexb",m=Math.max(1,Math.floor(a.width||960)),p=Math.max(1,Math.floor(a.height||540)),v=Math.max(1,Math.floor(a.durationUs||1e6/12));let g=jx(n,c);const w=Uj(m,p,v,a.payload,g.codec),y=String(a.frameMode||a.mode||"").toLowerCase(),b=c==="interactive"&&l==="prefer-hardware"&&Ej(),C=y==="mode4-h264-atlas"?"prefer-software":lw(n,c==="interactive"&&(Jd||b)?"prefer-software":l),N=[a.streamId||"",a.commandId||"",m,p,w,d,C,c].join("|");g.onPaint=r,g.configured&&g.decoder.state!=="configured"&&(g.configured=!1,g.configKey=""),g.configured&&g.configKey!==N&&(_s(n),g=jx(n,c),g.onPaint=r);const T={codec:w,codedWidth:m,codedHeight:p,hardwareAcceleration:C,optimizeForLatency:!0,avc:{format:d}};g.configured||Sd(g,T,N,C);const k=a.isKeyFrame===!0||String(a.chunkType||"").toLowerCase()==="key";Number(a.frameSeq||0);const E=Number(a.streamFrameSeq||0);if(E>0&&g.lastInputFrameSeq!==void 0){if(E<=g.lastInputFrameSeq){if(!k||E===g.lastInputFrameSeq)return;$d(g,g.lastInputFrameSeq-E+1),Sd(g,T,N,C)}if(E>g.lastInputFrameSeq+1){if($d(g,E-g.lastInputFrameSeq-1),!k)return;Sd(g,T,N,C)}}if(E>0&&(g.lastInputFrameSeq=E),!k&&!g.keyFrameSeen)return;k&&(g.keyFrameSeen=!0);const R=Number(g.decoder.decodeQueueSize||0);if(R>8){if(g.latencyMode==="interactive"&&g.hardwareAcceleration==="prefer-hardware"){Jd=!0,cf(n,g.hardwareAcceleration),_s(n);return}if($d(g),!k)return;Sd(g,T,N,C),g.keyFrameSeen=!0}const $=g.nextChunkTimestampUs;g.nextChunkTimestampUs+=v,g.pendingFrames.set($,{frame:a,queuedAt:performance.now(),queueSize:R}),g.inputSerial+=1,g.lastInputAt=performance.now();const F=new EncodedVideoChunk({type:k?"key":"delta",timestamp:$,duration:v,data:a.payload});try{g.decoder.decode(F)}catch(q){throw _s(n),q}dw(n,g),Fj(n,g)}async function Xm(n,a,r,l,c,d="smooth"){if(Ij(a)){r()||Hj(n,a,l,d);return}if(zj(a)){r()||qj(n,a,l,c,d);return}if(Zc.delete(n),Lj(a)){_s(n);const y=Bj(a);if(r())return;(n.width!==y.width||n.height!==y.height)&&(n.width=y.width,n.height=y.height);const b=n.getContext("2d"),j=performance.now();b?.putImageData(y,0,0);const C=performance.now(),N=Th(n,y.width,y.height,Qh,64,a);l?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.codec||a.mimeType,width:y.width,height:y.height,byteLength:a.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,C-j),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:Ml.h264DecodeAcceleration,decoderLabel:"lzo-rgb565",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:N.visualHash,visualChanged:N.visualChanged,paintedAt:C});return}_s(n);const m=new Blob([a.payload],{type:a.mimeType}),p=await createImageBitmap(m);if(r()){p.close();return}const v=a.width||p.width||960,g=a.height||p.height||540;(n.width!==v||n.height!==g)&&(n.width=v,n.height=g);const w=n.getContext("2d");if(w){const y=performance.now();w.clearRect(0,0,v,g),w.drawImage(p,0,0,v,g);const b=performance.now(),j=Th(n,v,g);l?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.codec||a.mimeType,width:v,height:g,byteLength:a.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,b-y),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:Ml.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:b})}p.close()}const Ax="livedesk_remote_host_targets",Gj="livedesk_entitlements",Jh=new TextDecoder;function Vj(n){const r=(Array.isArray(n)?n:[n||hn]).map(l=>qr(l||hn));return[...new Set(r.filter(Boolean))]}function Yj(){const[n,a]=u.useState(null),[r,l]=u.useState(!0);return u.useEffect(()=>{let c=!0;const d=window.liveDesk?.auth?.onComplete?.(p=>{p.ok&&p.session&&ot.auth.setSession(p.session)});(window.liveDesk?.auth?.getSession?.()||ot.auth.getSession()).then(p=>{c&&(a(Jy(p)),l(!1))});const{data:{subscription:m}}=ot.auth.onAuthStateChange((p,v)=>{a(v),l(!1),window.liveDesk?.auth?.persistSession?.(v)});return()=>{c=!1,d?.(),m.unsubscribe()}},[]),{session:n,loading:r}}function Wj(n,a=!0){const[r,l]=u.useState(null),[c,d]=u.useState([]),[m,p]=u.useState(""),[v,g]=u.useState(""),[w,y]=u.useState(0),b=u.useRef(new Map),j=Array.isArray(n)?n.join(`
11
+ `):String(n||""),C=u.useMemo(()=>Vj(n),[j]),N=u.useMemo(()=>C.find(E=>Yc(E)==="loopback")||C[0]||hn,[C]),T=u.useCallback(async()=>{if(!a){l(null),d([]),g(""),p("");return}let E=null;const R=Date.now(),$=C.filter(F=>(b.current.get(F)||0)<=R);if($.length===0)throw new Error("No LiveDesk Hub endpoint is reachable. Retrying shortly.");for(const F of $)try{const[q,z]=await Promise.all([$e("/api/remote/status",void 0,F),$e("/api/remote/devices",void 0,F)]);if(!Array.isArray(z.devices))throw new Error("Invalid Hub devices response.");b.current.delete(F),l(q),d(z.devices),g(F),p("");return}catch(q){E=q,b.current.set(F,Date.now()+1e4)}throw g(""),E||new Error("No LiveDesk Hub endpoint is reachable.")},[a,C]),k=u.useCallback(()=>{b.current.clear(),T().catch(E=>{p(E instanceof Error?E.message:String(E))}),y(E=>E+1)},[T]);return u.useEffect(()=>{if(!a){l(null),d([]),g(""),p("");return}let E=!0;const R=async()=>{try{await T()}catch(F){E&&p(F instanceof Error?F.message:String(F))}};R();const $=window.setInterval(R,2500);return()=>{E=!1,window.clearInterval($)}},[a,T,w]),{status:r,devices:c,error:m,refresh:k,hubBaseUrl:v||N,hubCandidates:C}}function Kj(n){const[a,r]=u.useState(null),[l,c]=u.useState(""),d=n?.user?.id||"",m=u.useCallback(async()=>{if(!d){r(null);return}const{data:p,error:v}=await ot.from(Ax).select("*").eq("user_id",d).maybeSingle();if(v){c(v.message);return}r(p),c("")},[d]);return u.useEffect(()=>{m()},[m]),u.useEffect(()=>{if(!d)return;const p=ot.channel(`livedesk-remote-host-targets-${d.replace(/[^a-zA-Z0-9]/g,"")}`).on("postgres_changes",{event:"*",schema:"public",table:Ax,filter:`user_id=eq.${d}`},v=>r(v.new)).subscribe();return()=>{ot.removeChannel(p)}},[d]),{target:a,error:l,refresh:m}}function Qj(n){const[a,r]=u.useState(null),[l,c]=u.useState(!1),[d,m]=u.useState(""),p=n?.user?.id||"",v=u.useCallback(async()=>{if(!p){r(null),m(""),c(!1);return}c(!0);const{data:w,error:y}=await ot.from(Gj).select("*").eq("user_id",p).eq("product_key","livedesk").maybeSingle();if(y){m(y.message),c(!1);return}r(w),m(""),c(!1)},[p]);u.useEffect(()=>{v()},[v]);const g=u.useMemo(()=>!a||a.status!=="active"?!1:a.expires_at?new Date(a.expires_at).getTime()>Date.now():!0,[a]);return{entitlement:a,licensed:g,loading:l,error:d,refresh:v}}const Wc={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},Xj=2500,Zj=3e4,Jj=64*1024,e1=6,t1=e1,mw=new Map;function n1(n){return mw.get(n)}const Nx={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function Mx(n){const a=Date.parse(String(n||""));if(!Number.isFinite(a))return 0;const r=Date.now()-a;return r>0&&r<=Zj?r:0}function Tx(n,a,r=hn,l={}){const[c,d]=u.useState(new Map),[m,p]=u.useState("idle"),[v,g]=u.useState(""),[w,y]=u.useState(Wc),b=u.useRef(new Map),j=u.useRef(new Map),C=u.useRef(0),N=u.useRef(new Map),T=u.useRef({enabled:!1,token:"",reason:""}),k=u.useRef(new Set),[E,R]=u.useState(0),$=u.useRef(l.onFrame),F=u.useRef(l.onStreamReady),q=u.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),z=u.useMemo(()=>[...n].sort().join(","),[n]),L=Number.isFinite(l.fps)?Number(l.fps):2,ie=Number.isFinite(l.maxWidth)?Number(l.maxWidth):640,V=Number.isFinite(l.maxHeight)?Number(l.maxHeight):360,ne=Number.isFinite(l.quality)?Number(l.quality):45,Q=String(l.frameMode||l.mode||"mode3-h264-hw").trim()||"mode3-h264-hw",J=l.streamPurpose==="control"?"control":"wall",le=l.forceRestart===!0,Y=String(l.forceRestartToken||"").trim(),O=String(l.restartReason||"").trim();T.current={enabled:le,token:Y,reason:O};const Z=u.useMemo(()=>{const me=Object.entries(l.monitorSelections||{}).filter(([pe])=>!!pe).sort(([pe],[ve])=>pe.localeCompare(ve));return JSON.stringify(Object.fromEntries(me))},[l.monitorSelections]);u.useEffect(()=>{$.current=l.onFrame},[l.onFrame]),u.useEffect(()=>{F.current=l.onStreamReady},[l.onStreamReady]);const X=u.useCallback((me,pe="livedesk-frame-socket-release")=>{me.disposed=!0;try{me.socket.readyState===WebSocket.CONNECTING||me.socket.readyState===WebSocket.OPEN?me.socket.close(1e3,pe):me.socket.close()}catch{}},[]),D=u.useCallback(()=>{const me=[...j.current.values()].map(pe=>pe.socket);if(me.length===0){p("idle");return}if(me.some(pe=>pe.readyState===WebSocket.OPEN)){p("open");return}if(me.some(pe=>pe.readyState===WebSocket.CONNECTING)){p("connecting");return}p("closed")},[]),K=u.useCallback((me,pe,ve,ke)=>{if(pe.disposed||pe.socket.readyState!==WebSocket.OPEN)return!1;try{return pe.socket.send(JSON.stringify({...pe.payload,type:"restart-live",deviceIds:[me],forceRestart:!0,restartReason:ve,restartToken:ke})),!0}catch{return!1}},[]),ce=u.useCallback((me,pe)=>{if(!me||me.byteLength<5)return;const ve=Date.now(),_e=new DataView(me).getUint32(0,!1);if(_e<=0||_e+4>me.byteLength)return;const Le=new Uint8Array(me,4,_e),ue=JSON.parse(Jh.decode(Le));if(Math.max(Mx(ue.receivedAt),Mx(ue.capturedAt))>Xj)return;const Ye=new Uint8Array(me,4+_e),oe={deviceId:String(ue.deviceId||""),kind:ue.kind==="thumbnail"?"thumbnail":"live",frameSeq:Number(ue.frameSeq||0),streamFrameSeq:Number(ue.streamFrameSeq||0)||void 0,streamId:String(ue.streamId||""),commandId:ue.commandId?String(ue.commandId):void 0,sessionId:ue.sessionId?String(ue.sessionId):void 0,captureGeneration:Number(ue.captureGeneration||0)||void 0,streamPurpose:ue.streamPurpose?String(ue.streamPurpose):void 0,width:Number(ue.width||0),height:Number(ue.height||0),sourceWidth:Number(ue.sourceWidth||0)||void 0,sourceHeight:Number(ue.sourceHeight||0)||void 0,mimeType:String(ue.mimeType||"image/jpeg"),mode:ue.mode?String(ue.mode):void 0,frameMode:ue.frameMode?String(ue.frameMode):void 0,frameProfile:ue.frameProfile?String(ue.frameProfile):void 0,encoding:ue.encoding?String(ue.encoding):void 0,codec:ue.codec?String(ue.codec):void 0,compression:ue.compression?String(ue.compression):void 0,pixelFormat:ue.pixelFormat?String(ue.pixelFormat):void 0,bytesPerPixel:Number(ue.bytesPerPixel||0)||0,uncompressedByteLength:Number(ue.uncompressedByteLength||0)||0,h264Format:ue.h264Format?String(ue.h264Format):void 0,isKeyFrame:ue.isKeyFrame===!0,chunkType:ue.chunkType?String(ue.chunkType):void 0,timestampUs:Number(ue.timestampUs||0)||0,durationUs:Number(ue.durationUs||0)||0,sourceGapMs:Number(ue.sourceGapMs||0)||0,agentSendGapMs:Number(ue.agentSendGapMs||0)||0,agentSendDurationMs:Number(ue.agentSendDurationMs||0)||0,agentSendDurationFrameSeq:Number(ue.agentSendDurationFrameSeq||0)||0,agentPaceMs:Number(ue.agentPaceMs||0)||0,agentQueueBeforePaceMs:Number(ue.agentQueueBeforePaceMs||0)||0,agentFrameAgeMs:Number(ue.agentFrameAgeMs||0)||0,droppedByAgent:Number(ue.droppedByAgent||0)||0,hubIngressDropped:Number(ue.hubIngressDropped||0)||0,hubClientDropped:Number(ue.hubClientDropped||0)||0,hardwareEncoder:ue.hardwareEncoder?String(ue.hardwareEncoder):void 0,platformProfile:ue.platformProfile?String(ue.platformProfile):void 0,monitorIndex:Number.isFinite(Number(ue.monitorIndex))?Number(ue.monitorIndex):void 0,monitorCount:Number.isFinite(Number(ue.monitorCount))?Number(ue.monitorCount):void 0,requestedFps:Number(ue.requestedFps||0)||0,effectiveFps:Number(ue.effectiveFps||0)||0,captureAverageMs:Number(ue.captureAverageMs||0)||0,captureP95Ms:Number(ue.captureP95Ms||0)||0,slowFrameCount:Number(ue.slowFrameCount||0)||0,captureHelperRestarts:Number(ue.captureHelperRestarts||0)||0,capturedAt:String(ue.capturedAt||""),receivedAt:String(ue.receivedAt||""),hubPacketAt:ue.hubPacketAt?String(ue.hubPacketAt):void 0,hubPacketEpochMs:Number.isFinite(Number(ue.hubPacketEpochMs))?Number(ue.hubPacketEpochMs):void 0,browserReceivedEpochMs:ve,byteLength:Number(ue.byteLength||Ye.byteLength),contentHash:ue.contentHash?String(ue.contentHash):void 0,captureMs:Number(ue.captureMs||0)||0,captureStageMs:Number(ue.captureStageMs||0)||0,convertMs:Number(ue.convertMs||0)||0,compressMs:Number(ue.compressMs||0)||0,captureSourceSerial:Number(ue.captureSourceSerial||0)||0,captureSourceSkipped:Number(ue.captureSourceSkipped||0)||0,deltaTileSize:Number(ue.deltaTileSize||0)||0,deltaTileCount:Number(ue.deltaTileCount||0)||0,deltaVisualTileCount:Number(ue.deltaVisualTileCount||0)||0,deltaRefreshTileCount:Number(ue.deltaRefreshTileCount||0)||0,deltaTotalTiles:Number(ue.deltaTotalTiles||0)||0,payload:Ye};if(!oe.deviceId)return;const Ne={streamId:pe.lastFrameStreamId,commandId:pe.lastFrameCommandId,order:pe.lastFrameOrder},je=Number(oe.streamFrameSeq||oe.frameSeq||0),Ee=!!Ne.commandId&&!!oe.commandId,Re=Ne.streamId===oe.streamId&&(!Ee||Ne.commandId===oe.commandId),Fe=Ne.order;if(Re&&Fe>=je&&(Fe===je||Ee))return;pe.lastFrameStreamId=oe.streamId,pe.lastFrameCommandId=oe.commandId||"",pe.lastFrameOrder=je;const he=q.current;he.totalFrames+=1,he.totalBytes+=Ye.byteLength,he.sampleFrames+=1,he.sampleBytes+=Ye.byteLength;const Ae=!b.current.has(oe.deviceId);b.current.set(oe.deviceId,oe),Ae&&d(new Map(b.current)),$.current?.(oe)},[]);u.useEffect(()=>{const me=window.setInterval(()=>{const pe=performance.now(),ve=q.current,ke=Math.max(1,pe-ve.sampleStartedAt);y({totalFrames:ve.totalFrames,totalBytes:ve.totalBytes,framesPerSecond:ve.sampleFrames*1e3/ke,bytesPerSecond:ve.sampleBytes*1e3/ke,sampleMs:ke,lastUpdatedAt:Date.now()}),d(new Map(b.current)),ve.sampleFrames=0,ve.sampleBytes=0,ve.sampleStartedAt=pe},2e3);return()=>{window.clearInterval(me)}},[]),u.useEffect(()=>{const me=z?z.split(",").filter(Boolean):[],pe=new Set(me),ve=performance.now();for(const[ke,_e]of j.current.entries())pe.has(ke)||(X(_e,"livedesk-device-unsubscribed"),j.current.delete(ke),N.current.delete(ke),b.current.delete(ke));if(me.length===0){for(const ke of j.current.values())X(ke,"livedesk-no-devices");j.current.clear(),N.current.clear(),b.current=new Map,d(new Map),g(""),q.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},y(Wc),D();return}q.current.sampleStartedAt<=0&&(q.current.sampleStartedAt=ve,y({...Wc,lastUpdatedAt:Date.now()}));for(const ke of me){const _e=l.monitorSelections?.[ke],Le=Number.isFinite(Number(_e))?{[ke]:Number(_e)}:{},ue={type:"subscribe",deviceIds:[ke],autoStartLive:a,fps:L,maxWidth:ie,maxHeight:V,quality:ne,mode:Q,frameMode:Q,streamPurpose:J,monitorSelections:Le},Ve=JSON.stringify(ue),Ye=j.current.get(ke);if(Ye){const Ee=Ye.socket.readyState===WebSocket.CONNECTING||Ye.socket.readyState===WebSocket.OPEN;if(Ye.payloadKey===Ve&&Ee&&!Ye.disposed)continue}const oe=Ye&&(Ye.socket.readyState===WebSocket.CONNECTING||Ye.socket.readyState===WebSocket.OPEN)&&!Ye.disposed?Ye.handoffFrom&&!Ye.handoffCompleted?Ye.handoffFrom:Ye:void 0;Ye&&Ye!==oe&&X(Ye,"livedesk-subscription-superseded");const Ne=new WebSocket(of(`/api/remote/frames/ws?devices=${encodeURIComponent(ke)}`,r));Ne.binaryType="arraybuffer";const je={socket:Ne,payload:ue,payloadKey:Ve,generation:C.current+1,disposed:!1,handoffFrom:oe,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1};C.current=je.generation,j.current.set(ke,je),Ne.addEventListener("open",()=>{if(je.disposed||j.current.get(ke)!==je){X(je,"livedesk-stale-frame-socket");return}g("");const Ee=T.current,Re=Ee.enabled&&(!Ee.token||N.current.get(ke)!==Ee.token);Ne.send(JSON.stringify({...je.payload,forceRestart:Re,restartReason:Re?Ee.reason:"",restartToken:Re?Ee.token:""})),Re&&Ee.token&&N.current.set(ke,Ee.token);const Fe=je.handoffFrom;je.handoffFrom=void 0,je.handoffCompleted=!0,Fe&&!Fe.disposed&&X(Fe,"livedesk-subscription-replaced"),D()}),Ne.addEventListener("message",Ee=>{if(je.disposed||j.current.get(ke)!==je)return;if(typeof Ee.data=="string"){try{const Fe=JSON.parse(Ee.data);if(Fe?.type==="RemoteFrameSubscriptionError")g(String(Fe.error||"control-stream-start-failed"));else if(Fe?.type==="RemoteFrameLiveAutoStart"){const Ae=(Array.isArray(Fe.skipped)?Fe.skipped:[]).find(de=>de?.deviceId===ke);if(Ae)g(String(Ae.reason||"control-stream-start-failed"));else if(Array.isArray(Fe.started)){const de=Fe.started.find(ye=>ye?.deviceId===ke);de&&(g(""),de.ready===!0&&de.streamPurpose==="control"&&de.sessionId&&de.commandId&&Number(de.captureGeneration||0)>0&&F.current?.({deviceId:ke,sessionId:String(de.sessionId),streamId:String(de.streamId||""),streamPurpose:"control",commandId:String(de.commandId),captureGeneration:Number(de.captureGeneration),monitorIndex:Number(de.monitorIndex||0)}))}}else Fe?.type==="RemoteFrameStreamReady"&&Fe.deviceId===ke&&Fe.streamPurpose==="control"&&Fe.sessionId&&Fe.commandId&&Number(Fe.captureGeneration||0)>0&&(g(""),F.current?.({deviceId:ke,sessionId:String(Fe.sessionId),streamId:String(Fe.streamId||""),streamPurpose:"control",commandId:String(Fe.commandId),captureGeneration:Number(Fe.captureGeneration),monitorIndex:Number(Fe.monitorIndex||0)}))}catch{}return}const Re=Ee.data instanceof ArrayBuffer?Ee.data:null;Re&&(g(""),ce(Re,je))}),Ne.addEventListener("error",()=>{je.disposed||j.current.get(ke)!==je||p("connecting")}),Ne.addEventListener("close",()=>{const Ee=!je.disposed;je.disposed=!0;const Re=j.current.get(ke);let Fe=!1;if(Re===je){const he=je.handoffFrom;je.handoffFrom=void 0,he&&!he.disposed&&(he.socket.readyState===WebSocket.CONNECTING||he.socket.readyState===WebSocket.OPEN)?(j.current.set(ke,he),Fe=!0):j.current.delete(ke)}if(D(),Ee&&Re===je&&!Fe){const he=window.setTimeout(()=>{k.current.delete(he),R(Ae=>Ae+1)},750);k.current.add(he)}})}D()},[a,X,z,L,Q,ce,r,V,ie,Z,l.monitorSelections,ne,E,J,D]),u.useEffect(()=>{if(!le||!Y)return;const me=z?z.split(",").filter(Boolean):[];for(const pe of me){if(N.current.get(pe)===Y)continue;const ve=j.current.get(pe);!ve||!K(pe,ve,O,Y)||N.current.set(pe,Y)}},[z,le,Y,O,K]),u.useEffect(()=>()=>{for(const me of j.current.values())X(me,"livedesk-hook-unmount");j.current.clear();for(const me of k.current)window.clearTimeout(me);k.current.clear()},[X]);const W=u.useCallback((me,pe="browser-stale")=>{const ve=Array.isArray(me)&&me.length>0?me:z.split(",").filter(Boolean);if(ve.length===0)return!1;let ke=!1;for(const _e of ve){const Le=j.current.get(_e);!Le||Le.socket.readyState!==WebSocket.OPEN||(ke=K(_e,Le,pe,`${Date.now()}-${Math.random().toString(36).slice(2)}`)||ke)}return ke},[z,K]),P=u.useCallback((me,pe="browser-reconnect")=>{const ve=Array.isArray(me)&&me.length>0?me:z.split(",").filter(Boolean);if(ve.length===0)return!1;let ke=!1;for(const _e of ve){const Le=j.current.get(_e);Le&&(X(Le,`livedesk-${pe}`),j.current.delete(_e),N.current.delete(_e),b.current.delete(_e),ke=!0)}return ke&&d(new Map(b.current)),R(_e=>_e+1),D(),!0},[X,z,D]);return{frames:c,state:m,error:v,stats:w,restartLive:W,reconnectLive:P}}function a1(n,a,r=hn,l={}){const[c,d]=u.useState(null),[m,p]=u.useState(null),[v,g]=u.useState("idle"),[w,y]=u.useState(Wc),b=u.useRef(null),j=u.useRef(l.onFrame),C=u.useRef(null),N=u.useRef(0),T=u.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),k=u.useMemo(()=>[...new Set(n.filter(Boolean))].join(","),[n]),E=u.useMemo(()=>[...new Set((l.captureDeviceIds||n).filter(Boolean))].join(","),[n,l.captureDeviceIds]),R=u.useMemo(()=>JSON.stringify(l.monitorSelections||{}),[l.monitorSelections]),$=u.useMemo(()=>({deviceIds:k.split(",").filter(Boolean),captureDeviceIds:E.split(",").filter(Boolean),fps:Number(l.fps||20),width:Number(l.width||1920),height:Number(l.height||1080),tileWidth:Number(l.tileWidth||320),tileHeight:Number(l.tileHeight||180),monitorSelections:l.monitorSelections||{}}),[E,k,R,l.fps,l.height,l.monitorSelections,l.tileHeight,l.tileWidth,l.width]),F=u.useMemo(()=>JSON.stringify($),[$]),q=u.useRef($);q.current=$;const z=a&&$.deviceIds.length>0,L=u.useCallback(V=>V.readyState!==WebSocket.OPEN?!1:(V.send(JSON.stringify({type:"configure",...q.current})),!0),[]);u.useEffect(()=>{j.current=l.onFrame},[l.onFrame]),u.useEffect(()=>{const V=window.setInterval(()=>{const ne=T.current,Q=performance.now(),J=Math.max(1,Q-ne.sampleStartedAt);y({totalFrames:ne.totalFrames,totalBytes:ne.totalBytes,framesPerSecond:ne.sampleFrames*1e3/J,bytesPerSecond:ne.sampleBytes*1e3/J,sampleMs:J,lastUpdatedAt:Date.now()});const le=C.current;le&&le.frameSeq!==N.current&&(N.current=le.frameSeq,d(le)),ne.sampleFrames=0,ne.sampleBytes=0,ne.sampleStartedAt=Q},1e3);return()=>window.clearInterval(V)},[]),u.useEffect(()=>{if(!z){b.current?.close(),b.current=null,d(null),C.current=null,N.current=0,p(null),g("idle"),y(Wc);return}let V=!1,ne=0;const Q=()=>{if(V)return;const J=new WebSocket(of("/api/remote/atlas/ws",r));J.binaryType="arraybuffer",b.current=J,g("connecting"),J.addEventListener("open",()=>{T.current.sampleStartedAt=performance.now(),g("open"),L(J)}),J.addEventListener("message",le=>{if(typeof le.data=="string"){try{const O=JSON.parse(le.data);O?.type==="Mode4AtlasLayout"&&p({layoutVersion:Number(O.layoutVersion||0),width:Number(O.width||1920),height:Number(O.height||1080),columns:Number(O.columns||1),rows:Number(O.rows||1),tiles:Array.isArray(O.tiles)?O.tiles:[]})}catch{}return}const Y=le.data instanceof ArrayBuffer?le.data:null;if(!(!Y||Y.byteLength<5))try{const O=Date.now(),X=new DataView(Y).getUint32(0,!1);if(X<=0||X+4>Y.byteLength)return;const D=JSON.parse(Jh.decode(new Uint8Array(Y,4,X))),K=new Uint8Array(Y,4+X),ce={deviceId:String(D.deviceId||"__livedesk_mode4_atlas__"),kind:"live",frameSeq:Number(D.frameSeq||0),streamFrameSeq:Number(D.streamFrameSeq||0)||void 0,streamId:String(D.streamId||"mode4-atlas"),commandId:D.commandId?String(D.commandId):void 0,width:Number(D.width||1920),height:Number(D.height||1080),sourceWidth:Number(D.sourceWidth||D.width||1920),sourceHeight:Number(D.sourceHeight||D.height||1080),mimeType:String(D.mimeType||"video/h264"),mode:String(D.mode||"mode4-h264-atlas"),frameMode:String(D.frameMode||"mode4-h264-atlas"),frameProfile:String(D.frameProfile||"mode4-h264-atlas-v1"),encoding:String(D.encoding||"video-atlas"),codec:String(D.codec||"h264"),compression:String(D.compression||"video/h264"),h264Format:String(D.h264Format||"annexb"),isKeyFrame:D.isKeyFrame===!0,chunkType:String(D.chunkType||""),timestampUs:Number(D.timestampUs||0),durationUs:Number(D.durationUs||0),hardwareEncoder:D.hardwareEncoder?String(D.hardwareEncoder):void 0,platformProfile:D.platformProfile?String(D.platformProfile):void 0,capturedAt:String(D.capturedAt||""),receivedAt:String(D.receivedAt||""),hubPacketAt:D.hubPacketAt?String(D.hubPacketAt):void 0,hubPacketEpochMs:Number(D.hubPacketEpochMs||0)||void 0,browserReceivedEpochMs:O,byteLength:K.byteLength,layoutVersion:Number(D.layoutVersion||0),atlasComposeMs:Number(D.atlasComposeMs||0),atlasPoolStarved:Number(D.atlasPoolStarved||0),atlasReadyTiles:Number(D.atlasReadyTiles||0),atlasTileCount:Number(D.atlasTileCount||0),atlasInputRevision:Number(D.atlasInputRevision||0),atlasSourceNewestAtEpochMs:Number(D.atlasSourceNewestAtEpochMs||0),atlasSourceOldestAtEpochMs:Number(D.atlasSourceOldestAtEpochMs||0),atlasSourceMaxAgeMs:Number(D.atlasSourceMaxAgeMs||0),payload:K},W=T.current;W.totalFrames+=1,W.totalBytes+=K.byteLength,W.sampleFrames+=1,W.sampleBytes+=K.byteLength,C.current=ce,N.current===0&&(N.current=ce.frameSeq,d(ce)),j.current?.(ce)}catch{}}),J.addEventListener("error",()=>g("error")),J.addEventListener("close",()=>{b.current===J&&(b.current=null),!V&&(g("closed"),ne=window.setTimeout(Q,1200))})};return Q(),()=>{V=!0,window.clearTimeout(ne),b.current?.close(),b.current=null}},[z,r,L]),u.useEffect(()=>{if(!z)return;const V=b.current;V&&L(V)},[F,z,L]);const ie=u.useCallback(()=>{const V=b.current;return V?L(V):!1},[L]);return{frame:c,layout:m,state:v,stats:w,refreshInputs:ie}}function s1(n,a=hn){const r=u.useRef(null),l=u.useRef(0),c=u.useRef(0),d=u.useRef(new Map),[m,p]=u.useState("idle"),[v,g]=u.useState(""),[w,y]=u.useState(Nx),b=u.useRef({totalSent:0,totalDropped:0,sampleSent:0,sampleDropped:0,sampleStartedAt:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0});u.useEffect(()=>{if(!n){r.current?.close(),r.current=null,c.current=0,p("idle"),g(""),y(Nx);return}let C=!1,N=0;const T=()=>{if(C)return;const k=new WebSocket(of("/api/remote/input/ws",a));r.current=k,b.current.sampleStartedAt=performance.now(),p("connecting"),g(""),k.addEventListener("open",()=>{C||r.current!==k||(g(""),p("open"))}),k.addEventListener("message",E=>{if(!(C||r.current!==k||typeof E.data!="string"))try{const R=JSON.parse(E.data);if(R?.type==="RemoteInputError"){g(String(R.error||R.result?.error||"Remote input failed.")),p("error");return}if(R?.type!=="RemoteInputApplied")return;const $=Number(R.inputSeq||0),F=d.current.get($);F!==void 0&&(b.current.lastRoundTripMs=Math.max(0,performance.now()-F),d.current.delete($)),b.current.lastInputSeq=$,b.current.lastAgentApplyMs=Math.max(0,Number(R.agentApplyMs||0))}catch{}}),k.addEventListener("close",()=>{C||r.current!==k||(r.current=null,p("closed"),N=window.setTimeout(T,1200))}),k.addEventListener("error",()=>{!C&&r.current===k&&p("error")})};return T(),()=>{C=!0,window.clearTimeout(N);const k=r.current;r.current=null,k?.close(),d.current.clear()}},[n,a]),u.useEffect(()=>{if(!n)return;const C=window.setInterval(()=>{const N=performance.now(),T=b.current,k=Math.max(1,N-T.sampleStartedAt);y({totalSent:T.totalSent,totalDropped:T.totalDropped,sentPerSecond:T.sampleSent*1e3/k,droppedPerSecond:T.sampleDropped*1e3/k,bufferedAmount:r.current?.bufferedAmount||0,lastInputType:T.lastInputType,lastInputSeq:T.lastInputSeq,lastRoundTripMs:T.lastRoundTripMs,lastAgentApplyMs:T.lastAgentApplyMs,lastUpdatedAt:Date.now()}),T.sampleSent=0,T.sampleDropped=0,T.sampleStartedAt=N},1e3);return()=>window.clearInterval(C)},[n]);const j=u.useCallback((C,N)=>{const T=r.current;if(!T||T.readyState!==WebSocket.OPEN||!C)return!1;const k=String(N.type||"").toLowerCase(),E=k==="pointermove",$=E||k==="wheel",F=b.current;if(E&&T.bufferedAmount>Jj)return F.totalDropped+=1,F.sampleDropped+=1,F.lastInputType="pointermove-drop",!1;const q=l.current+1;l.current=q;const z=Date.now(),L=!$||q-c.current>=t1;for(L&&(d.current.set(q,performance.now()),$&&(c.current=q)),E||mw.set(C,{inputSeq:q,inputType:k||"input",sentAt:performance.now()});d.current.size>256;){const ie=d.current.keys().next().value;if(ie===void 0)break;d.current.delete(ie)}return T.send(JSON.stringify({type:"input",requestId:$?"":crypto.randomUUID(),fireAndForget:$,deviceId:C,input:{...N,inputSeq:q,requestAck:L,issuedAtEpochMs:z,issuedAt:new Date(z).toISOString()}})),F.totalSent+=1,F.sampleSent+=1,F.lastInputType=k||"input",!0},[]);return{state:m,sendInput:j,stats:w,error:v}}function i1(n){const a=String(n||"").toLowerCase();return a.includes("audio/pcm")||a.includes("audio/l16")||a.includes("f32le")||a.includes("s16le")}const jd={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},r1=.08,l1=.25,o1=.02,Ex=300,c1=4,Cd=1500,Zm=5e3,u1=2e3,d1=1e4,kd=[0,1e3,3e3];function Rx(n){const a=Date.parse(String(n||""));return Number.isFinite(a)?Math.max(0,Date.now()-a):0}function f1(n,a,r){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))),d=String(a.mimeType||"").toLowerCase(),m=d.includes("s16le")||d.includes("audio/l16"),p=m?2:4,v=Math.floor(r.byteLength/p),g=Math.floor(v/l),w=n.createBuffer(l,g,c),y=new DataView(r);for(let b=0;b<l;b+=1){const j=w.getChannelData(b);for(let C=0;C<g;C+=1){const T=(C*l+b)*p;j[C]=m?Math.max(-1,Math.min(1,y.getInt16(T,!0)/32768)):Math.max(-1,Math.min(1,y.getFloat32(T,!0)))}}return w}function m1(n,a,r=hn){const l=u.useRef(null),c=u.useRef(0),[d,m]=u.useState("idle"),[p,v]=u.useState(null),[g,w]=u.useState(jd),[y,b]=u.useState("");return u.useEffect(()=>{if(!a||!n){m("idle"),v(null),w(jd),b("");return}m("connecting"),v(null),w(jd),b("");const j=window.AudioContext||window.webkitAudioContext;if(!j){m("unsupported"),w(jd),b("Audio playback is not supported in this browser.");return}const C=new j;l.current=C,c.current=C.currentTime;const N=new WebSocket(of("/api/remote/audio/ws?devices="+encodeURIComponent(n),r));N.binaryType="arraybuffer";const T=new Set,k={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(C.state),stalledCount:0,automaticRestarts:0,activeStreamId:"",lastCaptureStatusAt:0,lastPcmAtEpochMs:0};let E=!1,R=0,$=!1,F=0,q=0;const z=(O=!0)=>{for(const Z of T)try{Z.stop()}catch{}T.clear(),O&&(c.current=C.currentTime+r1)},L=()=>{k.audioContextState=String(C.state),!E&&(k.audioContextState==="suspended"||k.audioContextState==="interrupted"?m("suspended"):k.audioContextState==="closed"&&(m("error"),b("The browser audio context is closed. Toggle Remote Audio off and on to recover.")))},ie=async()=>{if(E||String(C.state)==="closed")return!1;try{if(String(C.state)!=="running"&&await C.resume(),k.audioContextState=String(C.state),!E&&!$&&k.audioContextState==="running"){const O=k.lastAcceptedAt>0&&performance.now()-k.lastAcceptedAt<=Cd,Z=k.lastCaptureStatusAt>0&&performance.now()-k.lastCaptureStatusAt<=Zm&&k.captureAlive&&k.helperAlive;m(O?"playing":Z?"silent":"open")}return k.audioContextState==="running"}catch(O){return E||(m("suspended"),b(O instanceof Error?"Audio playback is suspended: "+O.message:"Audio playback is suspended.")),!1}},V=async()=>{if(E||$||N.readyState!==WebSocket.OPEN)return;if(F>=kd.length){m("error"),b("Remote audio stopped sending frames. Toggle Audio off and on to retry.");return}const O=F;F+=1,$=!0,k.stalledCount+=1,k.automaticRestarts+=1,m("reconnecting");try{const Z=await $e("/api/remote/devices/"+encodeURIComponent(n)+"/audio/stop",{method:"POST",body:JSON.stringify({})},r);if(Z.ok===!1)throw new Error(Z.error||"Remote audio stop failed.");if(E)return;const X=await $e("/api/remote/devices/"+encodeURIComponent(n)+"/audio/start",{method:"POST",body:JSON.stringify({streamId:"audio-restart-"+Date.now(),mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},r);if(X.ok===!1)throw new Error(X.error||"Remote audio start failed.");const D=performance.now();R=D,k.lastPacketAt=D,k.lastAcceptedAt=0,k.lastCaptureStatusAt=0,k.lastPcmAtEpochMs=0,k.captureAlive=!1,k.helperAlive=!1,k.silentForMs=0,q=D+(kd[O+1]??3e3),b(""),E||m("open")}catch(Z){E||(q=performance.now()+(kd[O+1]??3e3),m("error"),b(Z instanceof Error?"Remote audio restart failed: "+Z.message:"Remote audio restart failed."))}finally{$=!1}},ne=()=>{k.drops+=1},Q=window.setInterval(()=>{if(E)return;const O=performance.now(),Z=k.lastPacketAt>0?Math.max(0,O-k.lastPacketAt):R>0?Math.max(0,O-R):0,X=k.lastAcceptedAt>0?Math.max(0,O-k.lastAcceptedAt):0,D=k.lastCaptureStatusAt>0?Math.max(0,O-k.lastCaptureStatusAt):0,K=N.readyState===WebSocket.OPEN,ce=k.lastCaptureStatusAt>0,W=ce&&D<=Zm,P=ce&&(!k.captureAlive||!k.helperAlive)&&D>u1,me=ce&&D>Zm,pe=!ce&&R>0&&O-R>d1,ve=R>0&&(k.lastAcceptedAt<=0?O-R>Cd:X>Cd);K&&R>0&&(P||me||pe)?F>=kd.length&&!$?(m("error"),b("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!$&&O>=q?V():$||m("stalled"):K&&ve&&!$&&k.audioContextState!=="suspended"&&k.audioContextState!=="interrupted"&&m(W?"silent":"open"),w({queuedMs:Math.max(0,(c.current-C.currentTime)*1e3),browserAgeMs:k.browserAgeMs,captureAgeMs:k.captureAgeMs,captureStatusAgeMs:D,silentForMs:k.silentForMs,captureAlive:k.captureAlive,helperAlive:k.helperAlive,captureRestartCount:k.captureRestartCount,localProcessingAgeMs:k.localProcessingAgeMs,lastPacketAgeMs:Z,lastAcceptedAgeMs:X,framesReceived:k.framesReceived,drops:k.drops,resyncs:k.resyncs,pendingDecodes:k.pendingDecodes,lastFrameSeq:k.lastFrameSeq,audioContextState:k.audioContextState,stalledCount:k.stalledCount,automaticRestarts:k.automaticRestarts,lastUpdatedAt:Date.now()})},250),J=()=>{L(),(String(C.state)==="suspended"||String(C.state)==="interrupted")&&ie()},le=()=>{document.visibilityState==="visible"&&ie()},Y=()=>{ie()};return C.addEventListener("statechange",J),document.addEventListener("visibilitychange",le),window.addEventListener("pageshow",Y),window.addEventListener("pointerdown",Y),window.addEventListener("keydown",Y),m("connecting"),b(""),L(),N.addEventListener("open",()=>{E||(R=performance.now(),k.lastPacketAt=R,k.lastAcceptedAt=0,k.lastCaptureStatusAt=0,k.lastPcmAtEpochMs=0,k.captureAlive=!1,k.helperAlive=!1,k.silentForMs=0,m("open"),N.send(JSON.stringify({type:"subscribe",deviceIds:[n]})),ie())}),N.addEventListener("message",O=>{if(typeof O.data=="string")return;const Z=O.data instanceof ArrayBuffer?O.data:null;if(!Z||Z.byteLength<5)return;const X=performance.now();k.lastPacketAt=X,(async()=>{try{const K=new DataView(Z).getUint32(0,!1);if(K<=0||K+4>Z.byteLength){ne();return}const ce=new Uint8Array(Z,4,K),W=JSON.parse(Jh.decode(ce)),P=Z.slice(4+K),me=String(W.frameKind||W.kind||"").toLowerCase();if(W.type==="remote.audio.status"||me==="audio-status"){if(k.lastCaptureStatusAt=X,k.captureAlive=W.captureAlive===!0,k.helperAlive=W.helperAlive===!0,k.captureRestartCount=Math.max(0,Number(W.restartCount||0)||0),k.lastPcmAtEpochMs=Math.max(0,Number(W.lastPcmAtEpochMs||0)||0),k.silentForMs=Math.max(0,Number(W.silentForMs||0)||0),k.captureAgeMs=k.lastPcmAtEpochMs>0?Math.max(0,Date.now()-k.lastPcmAtEpochMs):k.silentForMs,k.captureAlive&&k.helperAlive){if(F=0,q=0,!$){b("");const ve=String(C.state)==="running",ke=k.lastAcceptedAt>0&&performance.now()-k.lastAcceptedAt<=Cd;m(ve?ke?"playing":"silent":"suspended")}}else $||m("stalled");return}const pe={deviceId:String(W.deviceId||""),frameSeq:Number(W.frameSeq||0),streamId:String(W.streamId||""),mimeType:String(W.mimeType||"audio/webm;codecs=opus"),sampleRate:Number(W.sampleRate||48e3),channels:Number(W.channels||2),capturedAt:String(W.capturedAt||""),receivedAt:String(W.receivedAt||""),byteLength:Number(W.byteLength||P.byteLength),payload:P};if(!pe.deviceId||E)return;if(performance.now()-X>Ex){ne();return}if(k.pendingDecodes>=c1){ne();return}k.pendingDecodes+=1;try{const ve=i1(pe.mimeType)?f1(C,pe,P):await C.decodeAudioData(P.slice(0));if(k.localProcessingAgeMs=Math.max(0,performance.now()-X),E)return;if(k.localProcessingAgeMs>Ex){ne();return}if(pe.frameSeq>0&&pe.frameSeq<=k.lastFrameSeq){ne();return}if(k.activeStreamId&&pe.streamId!==k.activeStreamId&&pe.frameSeq<=k.lastFrameSeq){ne();return}pe.streamId&&pe.streamId!==k.activeStreamId&&(k.activeStreamId=pe.streamId,k.lastFrameSeq=0,z());const ke=C.currentTime;Math.max(0,c.current-ke)>l1&&(z(),k.resyncs+=1);const Le=C.createBufferSource();Le.buffer=ve,Le.connect(C.destination),T.add(Le),Le.onended=()=>{T.delete(Le),Le.onended=null};const ue=Math.max(C.currentTime+o1,c.current);Le.start(ue),c.current=ue+ve.duration,k.browserAgeMs=Rx(pe.receivedAt),k.captureAgeMs=Rx(pe.capturedAt),k.lastAcceptedAt=performance.now(),k.framesReceived+=1,k.lastFrameSeq=pe.frameSeq,F=0,q=0,v(pe),ie();const Ve=String(C.state)==="running";Ve&&b(""),m(Ve?"playing":"suspended")}finally{k.pendingDecodes=Math.max(0,k.pendingDecodes-1)}}catch(D){E||(m("error"),b(D instanceof Error?D.message:String(D)))}})()}),N.addEventListener("error",()=>{E||(m("error"),b("Remote audio WebSocket error."))}),N.addEventListener("close",()=>{E||m("closed")}),()=>{E=!0,window.clearInterval(Q),C.removeEventListener("statechange",J),document.removeEventListener("visibilitychange",le),window.removeEventListener("pageshow",Y),window.removeEventListener("pointerdown",Y),window.removeEventListener("keydown",Y),z(!1),N.close(),C.close().catch(()=>{}),l.current===C&&(l.current=null)}},[n,a,r]),{state:d,lastFrame:p,stats:g,error:y}}const h1=3;function Dx(n,a,r){const l=Math.max(1,Number(r)||1),c=Math.max(0,Math.min(l,Number(n)-Number(a))),d=Math.min(l/2,h1);return c<=d?0:c>=l-d?1:c/l}function p1(n,a,r){return{normalizedX:Dx(n,r.left,r.width),normalizedY:Dx(a,r.top,r.height)}}const Eh={revision:0,settings:{connection:{usePinToAddDevices:!0,pinValidityMinutes:30,rotatePinAfterPairing:!0,allowNewDevices:!0,approveNewDevices:!0,startWithComputer:!0,keepRunningInTray:!0,showConnectionNotifications:!0},security:{accessMode:"trusted-only",requireEncryptedConnections:!0,allowInternetConnections:!1,allowLanConnections:!0,allowUnencryptedLanFallback:!1,requireNewDeviceApproval:!0,requireAdministratorForSecurityChanges:!0,visibleControlIndicator:!0,lockOnControlEnd:!0,disconnectIdleControlSessions:!0,idleControlMinutes:30,keepSessionHistory:!0,sessionHistoryDays:30},control:{allowKeyboardMouse:!0,allowSystemShortcuts:!0,allowClipboardText:!0,allowRemoteRestart:!1,reconnectAfterRemoteRestart:!0,allowSwitchingMonitors:!0,showConnectionToolbar:!0,showRemoteCursor:!0,openControlOnDoubleClick:!0,startRemoteAudioWithControl:!1,fitRemoteScreen:!0,rememberLastMonitor:!0,keepControlReadyBetweenPages:!0},wall:{performanceMode:"auto",autoStart:!0,connectedOnly:!1,keepEmptySlots:!0,showDeviceStatus:!0,showPerformanceDetails:!1,pauseHiddenTiles:!0,reduceWhenHidden:!0,autoAdjustTileQuality:!0,rememberDevicePositions:!0},filesAudio:{allowFileTransfer:!0,allowFolderSync:!1,askBeforeReceivingFiles:!0,openReceivedFolder:!1,notifyTransferComplete:!0,allowOverwrite:!1,defaultReceiveFolder:"Desktop/LiveDeskFiles",maxFileSizeBytes:1073741824,allowRemoteAudio:!0,startAudioMuted:!1,rememberVolume:!0,automaticallyRecoverAudio:!0,showAudioTroubleshooting:!1,rollingBufferEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0,captureSaveLocation:"LiveDesk Captures",captureAutoDelete:"never"},agent:{enabled:!1,defaultPermissionMode:"safe-auto",askBeforeDestructive:!0,allowProcessManagement:!0,allowServiceManagement:!0,allowFileChanges:!0,allowCommandExecution:!1,allowSoftwareInstallation:!1,allowPowerActions:!1,keepAuditHistory:!0,timeoutMinutes:10},advanced:{wallFrameMode:"auto",wallFps:20,wallMaxWidth:960,wallMaxHeight:540,wallQuality:55,controlFrameMode:"mode3-h264-hw",controlFps:30,controlMaxWidth:1920,controlMaxHeight:1080,controlQuality:60,transport:"auto",allowPlainLanFallback:!1,verboseLogs:!1,frameStatistics:!1}}},g1=[{id:"connection",label:"Connection",icon:ko},{id:"security",label:"Security",icon:zt},{id:"control",label:"Control",icon:Zt},{id:"wall",label:"Wall",icon:Xc},{id:"files-audio",label:"Files & Audio",icon:jo},{id:"agent",label:"Agent",icon:Nl},{id:"advanced",label:"Advanced",icon:Qd}];function vl(n,a){return n?.settings?.[a]||Eh.settings[a]}function lt({icon:n,title:a,description:r,children:l,disabled:c=!1,recommended:d=!1}){return s.jsxs("div",{className:`product-setting-row ${c?"disabled":""}`,children:[s.jsx("div",{className:"product-setting-control",children:l}),n&&s.jsx("span",{className:"product-setting-icon",children:s.jsx(n,{size:17})}),s.jsxs("div",{className:"product-setting-copy",children:[s.jsx("strong",{children:a}),d&&s.jsx("em",{children:"Recommended"}),s.jsx("small",{children:r})]})]})}function jt({checked:n,onChange:a,disabled:r=!1,label:l}){return s.jsxs("label",{className:"product-switch",children:[s.jsx("input",{"aria-label":l,type:"checkbox",checked:n,disabled:r,onChange:c=>a(c.target.checked)}),s.jsx("span",{})]})}function Ui({value:n,onChange:a,options:r,disabled:l=!1,label:c}){return s.jsx("select",{"aria-label":c,value:String(n),disabled:l,onChange:d=>a(d.target.value),children:r.map(([d,m])=>s.jsx("option",{value:d,children:m},d))})}function v1({hubUrl:n="",runtimeRole:a="hub",runtimeDeviceId:r="",sessionAccessToken:l="",initialTab:c="connection",pin:d,wall:m,control:p,agent:v,advancedExtras:g,captureGallery:w}){const[y,b]=u.useState(c),[j,C]=u.useState(null),[N,T]=u.useState("loading"),[k,E]=u.useState(""),[R,$]=u.useState("idle"),[F,q]=u.useState("");u.useEffect(()=>{let ve=!0;return T("loading"),$e("/api/settings",void 0,n).then(ke=>{ve&&(C({revision:Number(ke.revision||0),updatedAt:ke.updatedAt,settings:ke.settings}),T("saved"))}).catch(ke=>{ve&&(E(ke instanceof Error?ke.message:String(ke)),C(Eh),T("failed"))}),()=>{ve=!1}},[n]);const z=async(ve,ke,_e)=>{const Le=j||Eh,ue=Le,Ve={...Le,settings:{...Le.settings,[ve]:{...vl(Le,ve),[ke]:_e}}};C(Ve),T("saving"),E("");try{const Ye=await $e("/api/settings",{method:"PATCH",body:JSON.stringify({revision:Le.revision,[ve]:{[ke]:_e}})},n);C({revision:Ye.revision,updatedAt:Ye.updatedAt,settings:Ye.settings}),T("saved")}catch(Ye){C(ue),T("failed"),E(Ye instanceof Error?Ye.message:String(Ye))}},L=(ve,ke)=>_e=>{z(ve,ke,_e)},ie=async()=>{if(a!=="hub"||!r||!l){$("failed"),q("Sign in to this Hub before changing its runtime role.");return}$("changing"),q("");try{const ve=await $e("/api/runtime/status",void 0,n);await $e("/api/runtime/role",{method:"POST",headers:{Authorization:`Bearer ${l}`},body:JSON.stringify({role:"client"})},n),$("accepted"),await ew({baseUrl:n,targetRole:"client",previousRuntimePid:Number(ve.runtimePid||0),allowedStates:["running","waiting-auth"]}),J0(5179)}catch(ve){$("failed"),q(ve instanceof Error?ve.message:String(ve))}},V=vl(j,"security"),ne=vl(j,"connection"),Q=vl(j,"control"),J=vl(j,"wall"),le=vl(j,"filesAudio"),Y=vl(j,"agent"),O=u.useMemo(()=>V.allowInternetConnections===!1?{label:"Local only",tone:"local",detail:"Internet connections are disabled."}:V.requireEncryptedConnections&&V.requireNewDeviceApproval&&V.accessMode==="trusted-only"?{label:"Protected",tone:"protected",detail:"Encrypted connections and trusted-device approval are active."}:{label:"Needs attention",tone:"attention",detail:"Review access and encryption settings before sharing this Hub."},[V]),Z=`settings-panel-${y}`,X=s.jsxs("div",{className:"settings-tab-content product-settings-content",children:[s.jsxs("section",{className:"product-settings-hero",children:[s.jsxs("div",{children:[s.jsxs("span",{className:"settings-eyebrow",children:[s.jsx(ko,{size:14})," Connection"]}),s.jsx("h2",{children:"Connect a device"}),s.jsx("p",{children:"Use the short PIN on the computer you want to add. The PIN is temporary and can be replaced at any time."})]}),s.jsxs("div",{className:"product-save-state",role:"status",children:[s.jsx(Gy,{size:14})," ",N==="saving"?"Saving":N==="failed"?"Failed":N==="loading"?"Loading":"Saved"]})]}),d,s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Connection behavior"}),s.jsx("h3",{children:"New device access"})]}),s.jsx(No,{size:20})]}),s.jsx(lt,{icon:No,title:"Use PIN to add new devices",description:"Allow temporary PIN pairing from the client.",recommended:!0,children:s.jsx(jt,{checked:!!ne.usePinToAddDevices,onChange:L("connection","usePinToAddDevices"),label:"Use PIN to add new devices"})}),s.jsx(lt,{icon:zt,title:"Approve new devices on this Hub",description:"Ask for approval before an unfamiliar computer becomes trusted.",children:s.jsx(jt,{checked:!!ne.approveNewDevices,onChange:L("connection","approveNewDevices"),label:"Approve new devices"})}),s.jsx(lt,{icon:an,title:"Show connection notifications",description:"Show a short notice when a computer connects or leaves.",children:s.jsx(jt,{checked:!!ne.showConnectionNotifications,onChange:L("connection","showConnectionNotifications"),label:"Show connection notifications"})})]}),s.jsxs("section",{className:"settings-section-card runtime-role-settings",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Runtime role"}),s.jsx("h3",{children:"Use this computer as a Client"})]}),s.jsx(Qd,{size:20})]}),s.jsx("p",{className:"settings-help",children:"This stops the Hub listener, saves the Client role in Supabase, and restarts LiveDesk through the unified launcher."}),R==="accepted"?s.jsx("p",{className:"settings-help runtime-role-success",children:"Role change accepted. LiveDesk is restarting as Client."}):F?s.jsx("p",{className:"settings-help runtime-role-error",role:"alert",children:F}):null,s.jsx("button",{className:"settings-reset",onClick:()=>{ie()},disabled:R==="changing"||a!=="hub",type:"button",children:R==="changing"?"Switching role…":"Switch this computer to Client"})]})]}),D=s.jsxs("div",{className:"settings-tab-content product-settings-content",children:[s.jsxs("section",{className:`security-status-card ${O.tone}`,children:[s.jsxs("div",{children:[s.jsx("span",{children:"Security status"}),s.jsx("strong",{children:O.label}),s.jsx("small",{children:O.detail})]}),s.jsx(zt,{size:28})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Access mode"}),s.jsx("h3",{children:"Who may use this Hub?"})]}),s.jsx(Rs,{size:20})]}),s.jsx(lt,{icon:zt,title:"Access mode",description:"Choose the default boundary for remote sessions.",recommended:!0,children:s.jsx(Ui,{value:String(V.accessMode),onChange:L("security","accessMode"),label:"Access mode",options:[["trusted-only","Trusted devices only"],["ask-every-time","Ask every time"],["view-only","View only"],["block-remote-access","Block remote access"]]})}),s.jsx(lt,{icon:ko,title:"Require encrypted connections",description:"External connections cannot disable this protection.",recommended:!0,children:s.jsx(jt,{checked:!!V.requireEncryptedConnections,onChange:L("security","requireEncryptedConnections"),label:"Require encrypted connections"})}),s.jsx(lt,{icon:ko,title:"Allow internet connections",description:"Keep off unless you intentionally expose this Hub beyond the LAN.",children:s.jsx(jt,{checked:!!V.allowInternetConnections,onChange:L("security","allowInternetConnections"),label:"Allow internet connections"})}),s.jsx(lt,{icon:Zt,title:"Allow LAN connections",description:"Permit connections from the local network.",children:s.jsx(jt,{checked:!!V.allowLanConnections,onChange:L("security","allowLanConnections"),label:"Allow LAN connections"})}),s.jsx(lt,{icon:zt,title:"Require approval for new devices",description:"New computers must be approved before remote access is granted.",children:s.jsx(jt,{checked:!!V.requireNewDeviceApproval,onChange:L("security","requireNewDeviceApproval"),label:"Require approval for new devices"})})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Session protection"}),s.jsx("h3",{children:"End sessions safely"})]}),s.jsx(an,{size:20})]}),s.jsx(lt,{icon:Zt,title:"Show an indicator while Control is active",description:"Make active remote control visible on the local computer.",children:s.jsx(jt,{checked:!!V.visibleControlIndicator,onChange:L("security","visibleControlIndicator"),label:"Show Control indicator"})}),s.jsx(lt,{icon:Rs,title:"Lock the remote computer when Control ends",description:"Protect the local screen after a Control session.",children:s.jsx(jt,{checked:!!V.lockOnControlEnd,onChange:L("security","lockOnControlEnd"),label:"Lock after Control ends"})}),s.jsx(lt,{icon:an,title:"Disconnect idle Control sessions",description:"Automatically close inactive Control sessions.",children:s.jsx(jt,{checked:!!V.disconnectIdleControlSessions,onChange:L("security","disconnectIdleControlSessions"),label:"Disconnect idle sessions"})}),s.jsx(lt,{icon:an,title:"Idle timeout",description:"Time before an inactive Control session closes.",disabled:!V.disconnectIdleControlSessions,children:s.jsx(Ui,{value:Number(V.idleControlMinutes),onChange:ve=>L("security","idleControlMinutes")(Number(ve)),disabled:!V.disconnectIdleControlSessions,label:"Idle timeout",options:[["5","5 minutes"],["15","15 minutes"],["30","30 minutes"],["60","1 hour"],["1440","Never"]]})})]})]}),K=s.jsxs("div",{className:"settings-tab-content product-settings-content",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Remote use"}),s.jsx("h3",{children:"What can a connected user do?"})]}),s.jsx(Zt,{size:20})]}),s.jsx(lt,{icon:Zt,title:"Keyboard and mouse control",description:"Allow the Hub to send keyboard and pointer input.",recommended:!0,children:s.jsx(jt,{checked:!!Q.allowKeyboardMouse,onChange:L("control","allowKeyboardMouse"),label:"Keyboard and mouse control"})}),s.jsx(lt,{icon:FS,title:"System shortcuts",description:"Allow shortcut keys such as Alt-Tab and the system key.",children:s.jsx(jt,{checked:!!Q.allowSystemShortcuts,onChange:L("control","allowSystemShortcuts"),label:"System shortcuts"})}),s.jsx(lt,{icon:No,title:"Clipboard text sharing",description:"Share plain text through the remote session.",children:s.jsx(jt,{checked:!!Q.allowClipboardText,onChange:L("control","allowClipboardText"),label:"Clipboard text sharing"})}),s.jsx(lt,{icon:an,title:"Remote restart",description:"Allow restart requests from Control.",disabled:!Q.allowKeyboardMouse,children:s.jsx(jt,{checked:!!Q.allowRemoteRestart,onChange:L("control","allowRemoteRestart"),disabled:!Q.allowKeyboardMouse,label:"Remote restart"})}),s.jsx(lt,{icon:Zt,title:"Switching monitors",description:"Allow the viewer to select another connected display.",children:s.jsx(jt,{checked:!!Q.allowSwitchingMonitors,onChange:L("control","allowSwitchingMonitors"),label:"Switching monitors"})})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Session behavior"}),s.jsx("h3",{children:"Make Control predictable"})]}),s.jsx(Ln,{size:20})]}),s.jsx(lt,{icon:Zt,title:"Open Control on double-click",description:"Double-clicking a Wall tile opens its Control view.",children:s.jsx(jt,{checked:!!Q.openControlOnDoubleClick,onChange:L("control","openControlOnDoubleClick"),label:"Open Control on double-click"})}),s.jsx(lt,{icon:an,title:"Start audio with Control",description:"Keep audio muted by default for new sessions.",children:s.jsx(jt,{checked:!!Q.startRemoteAudioWithControl,onChange:L("control","startRemoteAudioWithControl"),label:"Start audio with Control"})}),s.jsx(lt,{icon:Zt,title:"Fit remote screen to window",description:"Scale the remote display to the available Control area.",children:s.jsx(jt,{checked:!!Q.fitRemoteScreen,onChange:L("control","fitRemoteScreen"),label:"Fit remote screen"})}),s.jsx(lt,{icon:an,title:"Keep Control ready between pages",description:"Faster reconnection for 1 minute.",recommended:!0,children:s.jsx(jt,{checked:!!Q.keepControlReadyBetweenPages,onChange:L("control","keepControlReadyBetweenPages"),label:"Keep Control ready between pages"})})]})]}),ce=s.jsxs("div",{className:"settings-tab-content product-settings-content",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Performance mode"}),s.jsx("h3",{children:"Let LiveDesk choose the best path"})]}),s.jsx(Xc,{size:20})]}),s.jsx(lt,{icon:Nl,title:"Performance mode",description:"Automatic mode balances responsiveness and image quality.",recommended:!0,children:s.jsx(Ui,{value:String(J.performanceMode),onChange:L("wall","performanceMode"),label:"Performance mode",options:[["auto","Auto"],["responsive","Prioritize responsiveness"],["quality","Prioritize image quality"],["custom","Custom"]]})}),s.jsx("p",{className:"settings-help",children:"Streaming details are available under Advanced for diagnostics and development."})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Wall behavior"}),s.jsx("h3",{children:"What should the Wall show?"})]}),s.jsx(an,{size:20})]}),[["autoStart","Start Wall automatically","Start a live view when a computer connects."],["connectedOnly","Show only connected devices","Hide disconnected slots."],["keepEmptySlots","Keep empty slots visible","Preserve the layout when a device leaves."],["showDeviceStatus","Show device status on tiles","Display compact machine status."],["showPerformanceDetails","Show performance details","Show advanced frame diagnostics on tiles."],["pauseHiddenTiles","Pause hidden tiles","Reduce capture work for tiles outside the visible area."],["reduceWhenHidden","Reduce activity when the window is hidden","Lower background work when the browser is not visible."],["autoAdjustTileQuality","Automatically adjust tile quality","Adapt tile quality to Wall size and load."]].map(([ve,ke,_e])=>s.jsx(lt,{icon:Zt,title:ke,description:_e,children:s.jsx(jt,{checked:!!J[ve],onChange:L("wall",ve),label:ke})},ve))]})]}),W=s.jsxs("div",{className:"settings-tab-content product-settings-content",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"File permissions"}),s.jsx("h3",{children:"Move files deliberately"})]}),s.jsx(jo,{size:20})]}),s.jsx(lt,{icon:jo,title:"Allow file transfer",description:"Permit Hub-to-device file delivery.",recommended:!0,children:s.jsx(jt,{checked:!!le.allowFileTransfer,onChange:L("filesAudio","allowFileTransfer"),label:"Allow file transfer"})}),s.jsx(lt,{icon:Xc,title:"Allow folder sync",description:"Enable recurring folder synchronization.",disabled:!le.allowFileTransfer,children:s.jsx(jt,{checked:!!le.allowFolderSync,onChange:L("filesAudio","allowFolderSync"),disabled:!le.allowFileTransfer,label:"Allow folder sync"})}),s.jsx(lt,{icon:zt,title:"Ask before receiving files",description:"Require local confirmation before a transfer is written.",children:s.jsx(jt,{checked:!!le.askBeforeReceivingFiles,onChange:L("filesAudio","askBeforeReceivingFiles"),label:"Ask before receiving files"})}),s.jsx(lt,{icon:jo,title:"Allow overwrite",description:"Permit replacing an existing destination file.",children:s.jsx(jt,{checked:!!le.allowOverwrite,onChange:L("filesAudio","allowOverwrite"),label:"Allow overwrite"})})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Audio permissions"}),s.jsx("h3",{children:"Remote sound"})]}),s.jsx(an,{size:20})]}),s.jsx(lt,{icon:an,title:"Allow remote audio",description:"Permit audio capture from connected computers.",recommended:!0,children:s.jsx(jt,{checked:!!le.allowRemoteAudio,onChange:L("filesAudio","allowRemoteAudio"),label:"Allow remote audio"})}),s.jsx(lt,{icon:an,title:"Start audio muted",description:"New audio sessions begin silent.",children:s.jsx(jt,{checked:!!le.startAudioMuted,onChange:L("filesAudio","startAudioMuted"),label:"Start audio muted"})}),s.jsx(lt,{icon:an,title:"Automatically recover audio",description:"Recover from temporary capture or transport stalls.",children:s.jsx(jt,{checked:!!le.automaticallyRecoverAudio,onChange:L("filesAudio","automaticallyRecoverAudio"),label:"Automatically recover audio"})})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Capture defaults"}),s.jsx("h3",{children:"Screen recording"})]}),s.jsx(Zt,{size:20})]}),s.jsx(lt,{icon:an,title:"Keep a Last 30s buffer",description:"Keep recent video in memory only until you explicitly save it.",children:s.jsx(jt,{checked:!!le.rollingBufferEnabled,onChange:L("filesAudio","rollingBufferEnabled"),label:"Keep a Last 30s buffer"})}),s.jsx(lt,{icon:an,title:"Recording quality",description:"Choose the WebM bitrate profile.",children:s.jsx(Ui,{value:String(le.recordingQuality),onChange:L("filesAudio","recordingQuality"),label:"Recording quality",options:[["standard","Standard"],["high","High"]]})}),s.jsx(lt,{icon:an,title:"Timelapse interval",description:"Capture one frame at the selected interval.",children:s.jsx(Ui,{value:Number(le.timelapseIntervalSeconds),onChange:ve=>L("filesAudio","timelapseIntervalSeconds")(Number(ve)),label:"Timelapse interval",options:[["5","5 seconds"],["10","10 seconds"],["30","30 seconds"],["60","60 seconds"]]})}),s.jsx(lt,{icon:Zt,title:"Include remote cursor",description:"Include the cursor indicator when the source provides it.",children:s.jsx(jt,{checked:!!le.includeRemoteCursor,onChange:L("filesAudio","includeRemoteCursor"),label:"Include remote cursor"})}),s.jsx(lt,{icon:jo,title:"Capture save location",description:"Captures are stored inside the Hub capture library.",children:s.jsx(Ui,{value:String(le.captureSaveLocation),onChange:L("filesAudio","captureSaveLocation"),label:"Capture save location",options:[[String(le.captureSaveLocation||"LiveDesk Captures"),"LiveDesk Captures"]]})}),s.jsx(lt,{icon:jo,title:"Automatic deletion",description:"Keep saved captures until you delete them.",children:s.jsx(Ui,{value:String(le.captureAutoDelete),onChange:L("filesAudio","captureAutoDelete"),label:"Automatic deletion",options:[["never","Never"],["7-days","After 7 days"],["30-days","After 30 days"]]})})]}),w]}),P=s.jsxs("div",{className:"settings-tab-content product-settings-content",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Agent safety"}),s.jsx("h3",{children:"AI workstation operations"})]}),s.jsx(Nl,{size:20})]}),s.jsx(lt,{icon:Nl,title:"Enable AI Agent on devices",description:"Allow Agent runs to reach connected workstations.",recommended:!0,children:s.jsx(jt,{checked:!!Y.enabled,onChange:L("agent","enabled"),label:"Enable AI Agent"})}),s.jsx(lt,{icon:zt,title:"Default permission mode",description:"Safe Auto keeps destructive operations behind approval.",children:s.jsx(Ui,{value:String(Y.defaultPermissionMode),onChange:L("agent","defaultPermissionMode"),label:"Default Agent permission mode",options:[["ask","Ask"],["safe-auto","Safe Auto"],["full-access","Full Access"],["custom","Custom"]]})}),s.jsx(lt,{icon:zt,title:"Ask before destructive operations",description:"Locked on for Safe Auto and destructive actions.",disabled:!Y.enabled,children:s.jsx(jt,{checked:!!Y.askBeforeDestructive,onChange:L("agent","askBeforeDestructive"),disabled:!Y.enabled,label:"Ask before destructive operations"})}),s.jsx(lt,{icon:an,title:"Keep Agent audit history",description:"Retain an inspectable record of Agent runs.",children:s.jsx(jt,{checked:!!Y.keepAuditHistory,onChange:L("agent","keepAuditHistory"),label:"Keep Agent audit history"})}),s.jsx(lt,{icon:an,title:"Stop Agent tasks after timeout",description:"Maximum runtime for one task.",children:s.jsx(Ui,{value:Number(Y.timeoutMinutes),onChange:ve=>L("agent","timeoutMinutes")(Number(ve)),label:"Agent task timeout",options:[["1","1 minute"],["5","5 minutes"],["10","10 minutes"],["30","30 minutes"],["60","1 hour"]]})})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Detailed permissions"}),s.jsx("h3",{children:"Capabilities"})]}),s.jsx(zt,{size:20})]}),[["allowProcessManagement","Allow process management"],["allowServiceManagement","Allow service management"],["allowFileChanges","Allow file changes"],["allowCommandExecution","Allow command execution"],["allowSoftwareInstallation","Allow software installation"],["allowPowerActions","Allow power actions"]].map(([ve,ke])=>s.jsx(lt,{icon:zt,title:ke,description:ve.includes("allowCommand")||ve.includes("Installation")||ve.includes("Power")?"Disabled by default for safety.":"Applied by the Hub and checked again by the Client.",children:s.jsx(jt,{checked:!!Y[ve],onChange:L("agent",ve),label:ke})},ve))]}),s.jsx("p",{className:"settings-help",children:"The existing Codex runtime and audit controls remain available below in Advanced and the Agent diagnostics panel."})]}),pe=y==="connection"?X:y==="security"?D:y==="control"?K:y==="wall"?ce:y==="files-audio"?W:y==="agent"?s.jsxs(s.Fragment,{children:[P,v]}):s.jsxs("div",{className:"settings-tab-content product-settings-content",children:[g,s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Developer controls"}),s.jsx("h3",{children:"Streaming and diagnostics"})]}),s.jsx(Qd,{size:20})]}),s.jsx("p",{className:"settings-help",children:"Codec, frame rate, resolution, quality, Atlas layout, and decoder preferences are intentionally kept here."}),m,p]})]});return s.jsxs("section",{className:"settings-page",children:[s.jsx("div",{className:"settings-page-tabs",role:"tablist","aria-label":"LiveDesk settings",children:g1.map(({id:ve,label:ke,icon:_e})=>s.jsxs("button",{className:y===ve?"active":"",id:`settings-tab-${ve}`,role:"tab","aria-selected":y===ve,"aria-controls":`settings-panel-${ve}`,tabIndex:y===ve?0:-1,onClick:()=>b(ve),type:"button",children:[s.jsx(_e,{size:16}),ke]},ve))}),k&&s.jsx("div",{className:"agent-settings-alert error",role:"alert",children:k}),s.jsx("section",{className:"settings-page-panel",id:Z,role:"tabpanel","aria-labelledby":`settings-tab-${y}`,tabIndex:0,children:pe})]})}function x1({children:n}){return s.jsx("div",{className:"settings-tab-content",children:n})}function y1({children:n}){return s.jsx("div",{className:"settings-tab-content",children:n})}function w1({children:n}){return s.jsx("div",{className:"settings-tab-content",children:n})}const hw={enabled:!0,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 _x(n){return{...hw,...n||{}}}function b1({hubUrl:n}){const[a,r]=u.useState(hw),[l,c]=u.useState(null),[d,m]=u.useState(""),[p,v]=u.useState(""),[g,w]=u.useState(""),[y,b]=u.useState("");u.useEffect(()=>{let L=!0;return $e("/api/settings/agent",void 0,n).then(ie=>{L&&(c(ie.settings),r(_x(ie.settings)))}).catch(ie=>{L&&b(ie instanceof Error?ie.message:String(ie))}),()=>{L=!1}},[n]);const j=(L,ie)=>r(V=>({...V,[L]:ie})),C=L=>{c(L),r(_x(L))},N=async()=>{v("save"),b(""),w("");try{const L={...a};d.trim()&&(L.apiKey=d.trim());const ie=await $e("/api/settings/agent",{method:"PUT",body:JSON.stringify(L)},n);C(ie.settings),m(""),w("Agent settings saved.")}catch(L){b(L instanceof Error?L.message:String(L))}finally{v("")}},T=async()=>{v("reset"),b("");try{const L=await $e("/api/settings/agent/reset",{method:"POST",body:JSON.stringify({})},n);C(L.settings),w("Codex defaults restored.")}catch(L){b(L instanceof Error?L.message:String(L))}finally{v("")}},k=async()=>{v("test"),b(""),w("");try{const L=await $e("/api/settings/agent/test",{method:"POST",body:JSON.stringify({})},n),ie=await $e("/api/settings/agent",void 0,n);C(ie.settings),w(`Codex connection verified with ${L.connection?.modelName||"the configured model"}${L.connection?.latencyMs?` in ${L.connection.latencyMs} ms.`:"."}`)}catch(L){b(L instanceof Error?L.message:String(L))}finally{v("")}},E=async()=>{v("clear-key"),b("");try{const L=await $e("/api/settings/agent/api-key",{method:"DELETE"},n);C(L.settings),m(""),w("The optional OpenCode Go key was removed.")}catch(L){b(L instanceof Error?L.message:String(L))}finally{v("")}},R=l?.codexInstallation==="installed"&&l.codexAuth==="signed-in",$=l?.securityStatus,F=$?.state||"unavailable",q=F==="verified"?"Verified":F==="configured"?"Configured":"Unavailable",z=[["Codex home",$?.isolatedCodexHome],["Environment variables",$?.restrictedEnvironment],["LiveDesk MCP only",$?.livedeskMcpOnly],["Selected-device scope",$?.selectedDeviceScopeEnforced],["Fail-closed execution",$?.failClosed]];return s.jsxs("div",{className:"settings-tab-content agent-settings-content",children:[s.jsxs("header",{className:"agent-settings-header",children:[s.jsxs("div",{children:[s.jsxs("span",{className:"settings-eyebrow",children:[s.jsx(Jv,{size:14})," Agent AI"]}),s.jsx("h2",{children:"Codex SDK"}),s.jsx("p",{children:"Codex owns the agent reasoning loop. LiveDesk keeps the existing task manager and exposes only safe, read-only workstation tools."})]}),s.jsxs("label",{className:"settings-toggle agent-enable-toggle",children:[s.jsx("input",{type:"checkbox",checked:a.enabled,onChange:L=>j("enabled",L.target.checked)}),s.jsx("span",{children:"Enable Agent AI"})]})]}),y&&s.jsx("div",{className:"agent-settings-alert error",role:"alert",children:y}),g&&s.jsx("div",{className:"agent-settings-alert success",role:"status",children:g}),s.jsxs("div",{className:"settings-section-grid",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Provider"}),s.jsx("h3",{children:"Codex is the default"})]}),s.jsx(No,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Agent provider"}),s.jsxs("select",{value:a.provider,onChange:L=>j("provider",L.target.value),children:[s.jsx("option",{value:"codex",children:"Codex SDK"}),s.jsx("option",{value:"opencode-go",children:"OpenCode Go (optional legacy)"})]})]}),s.jsxs("div",{className:"agent-connection-row",children:[s.jsx("span",{className:`agent-connection-dot ${R?"connected":l?.codexAuth==="not-signed-in"?"unavailable":""}`}),s.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"}),s.jsxs("button",{className:"settings-reset",onClick:()=>{k()},disabled:p!==""||a.provider!=="codex",type:"button",children:[s.jsx(PS,{size:15})," ",p==="test"?"Testing":"Test connection"]})]}),s.jsxs("p",{className:"settings-help",children:[s.jsx(HS,{size:12})," Authentication is owned by the installed Codex CLI. LiveDesk never asks for or stores a ChatGPT token."]}),l?.codexPath&&s.jsxs("p",{className:"settings-help",children:["CLI: ",l.codexPath]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Codex runtime"}),s.jsx("h3",{children:"Model and reasoning"})]}),s.jsx(Jv,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Model"}),s.jsx("input",{value:a.codexModelId,onChange:L=>j("codexModelId",L.target.value),placeholder:"Codex default",disabled:a.provider!=="codex"})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Reasoning effort"}),s.jsxs("select",{value:a.codexReasoningEffort,onChange:L=>j("codexReasoningEffort",L.target.value),disabled:a.provider!=="codex",children:[s.jsx("option",{value:"minimal",children:"Minimal"}),s.jsx("option",{value:"low",children:"Low"}),s.jsx("option",{value:"medium",children:"Medium"}),s.jsx("option",{value:"high",children:"High"}),s.jsx("option",{value:"xhigh",children:"Extra high"})]})]}),s.jsxs("div",{className:"settings-field-grid",children:[s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Task timeout (ms)"}),s.jsx("input",{type:"number",min:"30000",max:"1800000",step:"10000",value:a.codexTaskTimeoutMs,onChange:L=>j("codexTaskTimeoutMs",Number(L.target.value)),disabled:a.provider!=="codex"})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Max tool calls"}),s.jsx("input",{type:"number",min:"1",max:"100",value:a.codexMaxToolCalls,onChange:L=>j("codexMaxToolCalls",Number(L.target.value)),disabled:a.provider!=="codex"})]})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Workspace"}),s.jsx("h3",{children:"Restricted execution context"})]}),s.jsx(zt,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Working directory"}),s.jsx("input",{value:l?.agentWorkspacePath||a.codexWorkingDirectory,readOnly:!0})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:a.codexResumeSessions,onChange:L=>j("codexResumeSessions",L.target.checked),disabled:a.provider!=="codex"}),s.jsx("span",{children:"Allow session resume"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:a.codexShowDetailedEvents,onChange:L=>j("codexShowDetailedEvents",L.target.checked),disabled:a.provider!=="codex"}),s.jsx("span",{children:"Show detailed Codex events"})]}),s.jsx("p",{className:"settings-help",children:"The agent receives no project path or arbitrary filesystem directory. It can call LiveDesk MCP tools only."})]})]}),a.provider==="opencode-go"&&s.jsxs("section",{className:"settings-section-card agent-legacy-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Developer fallback"}),s.jsx("h3",{children:"OpenCode Go"})]}),s.jsx(No,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Base URL"}),s.jsx("input",{value:a.baseUrl,onChange:L=>j("baseUrl",L.target.value)})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"API key"}),s.jsx("input",{type:"password",value:d,onChange:L=>m(L.target.value),placeholder:l?.hasApiKey?l.apiKeyPreview:"Stored only in the Hub",autoComplete:"new-password"})]}),s.jsxs("div",{className:"settings-action-row",children:[s.jsxs("button",{className:"settings-reset",onClick:()=>{E()},disabled:p!==""||!l?.hasApiKey,type:"button",children:[s.jsx(Vh,{size:15})," Clear key"]}),s.jsx("span",{className:"settings-help",children:"This provider does not run the Codex MCP tool loop."})]})]}),s.jsxs("div",{className:"settings-section-grid",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Agent behavior"}),s.jsx("h3",{children:"Predictable operation"})]}),s.jsx(Ln,{size:20})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:a.deterministicParserFirst,onChange:L=>j("deterministicParserFirst",L.target.checked)}),s.jsx("span",{children:"Use deterministic parser before Codex"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:a.generateSummary,onChange:L=>j("generateSummary",L.target.checked)}),s.jsx("span",{children:"Generate task summaries"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:a.fallbackSummary,onChange:L=>j("fallbackSummary",L.target.checked)}),s.jsx("span",{children:"Fallback to deterministic summaries"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:a.includeRawDeviceDetails,onChange:L=>j("includeRawDeviceDetails",L.target.checked)}),s.jsx("span",{children:"Include raw device details in summaries"})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Safety"}),s.jsx("h3",{children:"Locked execution boundary"})]}),s.jsx(zt,{size:20})]}),["Arbitrary shell commands","PowerShell and Bash","Filesystem writes, deletes, and installs","Reboot, shutdown, and process termination","Network access and web search"].map(L=>s.jsxs("div",{className:"agent-safety-row",children:[s.jsx(qy,{size:15}),s.jsx("span",{children:L}),s.jsx("strong",{children:"Blocked"})]},L)),z.map(([L])=>s.jsxs("div",{className:"agent-safety-row",children:[s.jsx(zt,{size:15}),s.jsx("span",{children:L}),s.jsx("strong",{className:F==="unavailable"?"agent-safety-failed":F==="configured"?"agent-safety-configured":"agent-safety-verified",children:q})]},L)),s.jsx("p",{className:"settings-help",children:"Configured means the boundary is present but has not completed runtime verification. Test the connection or start an Agent run to verify it."})]})]}),s.jsxs("div",{className:"settings-action-row agent-settings-actions",children:[s.jsxs("button",{className:"settings-reset",onClick:()=>{T()},disabled:p!=="",type:"button",children:[s.jsx(Gc,{size:15})," Reset defaults"]}),s.jsxs("button",{className:"text-button primary",onClick:()=>{N()},disabled:p!=="",type:"button",children:[s.jsx(Gy,{size:15})," ",p==="save"?"Saving":"Save Agent settings"]})]})]})}new Date().valueOf();function si(n){const[a,r]=u.useState(n),l=u.useRef(n);return u.useEffect(()=>{if(l.current!==n){if(Array.isArray(l.current)&&Array.isArray(n)&&l.current.length===0&&n.length===0)return;l.current=n,r(n)}},[n]),[a,r]}function ep(n,a){return typeof n=="function"?typeof a=="object"?n(a):n():n}function _o(n,a="data-id"){let r=n;for(!r.tagName&&n.target&&(r=n.target);r;){if(r.getAttribute&&r.getAttribute(a))return r;r=r.parentNode}return null}function S1(n,a="data-id"){const r=_o(n,a);return r?r.getAttribute(a):null}function eu(n,a="data-id"){const r=_o(n,a);return r?uf(r,a):null}function uf(n,a="data-id"){const r=n.getAttribute(a);return r?j1(r):null}function zn(n){return typeof n=="string"?":"+n:n}function j1(n){if(n.startsWith(":"))return n.substring(1);const a=n*1;return isNaN(a)?n:a}function C1(){return{detect:()=>!0,addEvent:function(n,a,r){return n.addEventListener(a,r),()=>n.removeEventListener(a,r)},addGlobalEvent:function(n,a){return document.addEventListener(n,a),()=>document.removeEventListener(n,a)},getTopNode:function(){return window.document.body}}}var _a=C1();function tp(n){Object.assign(_a,n)}function Lx(n,a,r){function l(c){const d=_o(c);if(!d)return;const m=uf(d);if(typeof a=="function")return a(m,c);let p,v=c.target;for(;v!=d;){if(p=v.dataset?v.dataset.action:null,p&&a[p]){a[p](m,c);return}v=v.parentNode}a[r]&&a[r](m,c)}_a.addEvent(n,r,l)}function Lo(n,a){Lx(n,a,"click"),a.dblclick&&Lx(n,a.dblclick,"dblclick")}function k1(n,a){for(let r=n.length-1;r>=0;r--)if(n[r]===a){n.splice(r,1);break}}function A1(n,a,r){for(let l=0;l<Gi.length;l++){if(l===r)continue;const c=Gi[l],d=c.props.parent?.();if(d&&n.contains(d)&&c.node.contains(a))return!0}return!1}var pw=new Date,nf=!1,Ad=[],Gi=[],zx=n=>{const a=n.target;if(nf||!a.isConnected){nf=!1;return}for(let r=Gi.length-1;r>=0;r--){const{node:l,date:c,props:d}=Gi[r];if(!(c>pw)&&!l.contains(a)&&l!==a&&(A1(l,a,r)||(d.callback&&d.callback(n),d.modal||n.defaultPrevented)))break}},N1=n=>{pw=new Date,nf=!0;for(let a=Gi.length-1;a>=0;a--){const{node:r}=Gi[a];if(!r.contains(n.target)&&r!==n.target){nf=!1;break}}};function ii(n,a){Ad.length||(Ad=[_a.addGlobalEvent("click",zx,n),_a.addGlobalEvent("contextmenu",zx,n),_a.addGlobalEvent("mousedown",N1,n)]),typeof a!="object"&&(a={callback:a});const r={node:n,date:new Date,props:a};return Gi.push(r),{destroy(){k1(Gi,r),Gi.length||(Ad.forEach(l=>l()),Ad=[])}}}var Nd=n=>n.indexOf("bottom")!==-1,Md=n=>n.indexOf("left")!==-1,Td=n=>n.indexOf("right")!==-1,Jm=n=>n.indexOf("top")!==-1,Ix=n=>n.indexOf("fit")!==-1,Bc=n=>n.indexOf("overlap")!==-1,M1=n=>n.split("-").every(a=>["center","fit"].indexOf(a)>-1),T1=n=>{const a=n.match(/(start|center|end)/);return a?a[0]:null};function E1(n,a){let r=0;const l=_a.getTopNode(n);for(;n&&n!==l;){const c=getComputedStyle(n).position;if((c==="absolute"||c==="relative"||c==="fixed")&&(r=parseInt(getComputedStyle(n).zIndex)||0),n=n.parentNode,n===a)break}return r}var Sn,Zn,Fc,Vn;function gw(n,a,r="bottom",l=0,c=0){if(!n)return null;Sn=l,Zn=c,Fc="auto";let d=0,m=0,p=r;const v=vw(n),g=Bc(r)?_a.getTopNode(n):v;if(!v)return null;const w=v.getBoundingClientRect(),y=n.getBoundingClientRect(),b=g.getBoundingClientRect(),j=window.getComputedStyle(g),C={left:0,top:0,bottom:0,right:0};for(const $ in C){const F=`border-${$}-width`;C[$]=parseFloat(j.getPropertyValue(F))}if(a){const $=E1(a,v);d=Math.max($+1,20)}if(a){if(Vn=a.getBoundingClientRect(),Ix(r)&&(Fc=Vn.width+"px"),r!=="point")if(M1(r))Ix(r)?Sn=0:(Sn=b.width/2,m=1),Zn=(b.height-y.height)/2;else{const $=Bc(r)?0:1;Sn=Td(r)?Vn.right+$:Vn.left-$,Zn=Nd(r)?Vn.bottom+1:Vn.top;const F=T1(r);F&&(Td(r)||Md(r)?F==="center"?Zn-=(y.height-Vn.height)/2:F==="end"&&(Zn-=y.height-Vn.height):(Nd(r)||Jm(r))&&(F==="center"?Sn-=(y.width-Vn.width)/2:F==="end"&&(Sn-=y.width-Vn.width),Bc(r)||(Sn+=1)))}}else Vn={left:l,right:l,top:c,bottom:c};const N=(Md(r)||Td(r))&&(Nd(r)||Jm(r));Md(r)&&(m=2);const T=Sn-y.width-b.left;a&&Md(r)&&!N&&T<0&&(Sn=Vn.right,m=0,p=p.replace("left","right"));const k=Sn+y.width*(1-m/2)-b.right;if(k>0)if(!Td(r))Sn=b.right-C.right-y.width;else{const $=Vn.left-b.x-y.width;a&&!N&&$>=0?(Sn=Vn.left-y.width,p=p.replace("right","left")):Sn-=k+C.right}m&&(Sn=Math.round(Sn-y.width*m/2));const E=T<0||k>0||!N;Jm(r)&&(Zn=Vn.top-y.height,a&&Zn<b.y&&E&&(Zn=Vn.bottom,p=p.replace("top","bottom")));const R=Zn+y.height-b.bottom;return R>0&&(a&&Nd(r)&&E?(Zn-=y.height+Vn.height+1,p=p.replace("bottom","top")):Zn-=R+C.bottom),Sn-=w.left+C.left,Zn-=w.top+C.top,Sn=(Bc(r)?Sn:Math.max(Sn,0))+g.scrollLeft,Zn=(Bc(r)?Zn:Math.max(Zn,0))+g.scrollTop,Fc=Fc||"auto",{at:p,x:Sn,y:Zn,z:d,width:Fc}}function vw(n){const a=_a.getTopNode(n);for(n&&(n=n.parentElement);n;){const r=getComputedStyle(n).position;if(n===a||r==="relative"||r==="absolute"||r==="fixed")return n;n=n.parentNode}return null}function R1(n){const a=[];let r=n;const l=_a.getTopNode(n);for(;r&&r!==l&&!r.getAttribute("data-wx-portal-root");)getComputedStyle(r).position==="absolute"&&a.push(r),r=r.parentNode;return a}var Ox=new Date().valueOf();function np(){return Ox+=1,Ox}function ea(n){return n<10?"0"+n:n.toString()}function D1(n){const a=ea(n);return a.length==2?"0"+a:a}function xw(n){const a=Math.floor(n/11)*11;return{start:a,end:a+11}}function eh(n){const a=(n.getDay()+6)%7,r=new Date(n.valueOf());r.setDate(n.getDate()+(3-a)),r.setHours(0,0,0,0);const l=new Date(r.getFullYear(),0,1),c=Math.round((r.getTime()-l.getTime())/864e5);return 1+Math.floor(c/7)}var Bx=["",""];function _1(n,a,r){switch(n){case"%d":return ea(a.getDate());case"%m":return ea(a.getMonth()+1);case"%j":return a.getDate();case"%n":return a.getMonth()+1;case"%y":return ea(a.getFullYear()%100);case"%Y":return a.getFullYear();case"%D":return r.dayShort[a.getDay()];case"%l":return r.dayFull[a.getDay()];case"%M":return r.monthShort[a.getMonth()];case"%F":return r.monthFull[a.getMonth()];case"%h":return ea((a.getHours()+11)%12+1);case"%g":return(a.getHours()+11)%12+1;case"%G":return a.getHours();case"%H":return ea(a.getHours());case"%i":return ea(a.getMinutes());case"%a":return((a.getHours()>11?r.pm:r.am)||Bx)[0];case"%A":return((a.getHours()>11?r.pm:r.am)||Bx)[1];case"%s":return ea(a.getSeconds());case"%S":return D1(a.getMilliseconds());case"%W":return ea(eh(a));case"%w":{const l=r.weekStart??1;if(l===1)return ea(eh(a));const c=(a.getDay()-l+7)%7,d=(1-l+7)%7,m=new Date(a.valueOf());return m.setDate(a.getDate()+(d-c)),ea(eh(m))}case"%c":{let l=a.getFullYear()+"";return l+="-"+ea(a.getMonth()+1),l+="-"+ea(a.getDate()),l+="T",l+=ea(a.getHours()),l+=":"+ea(a.getMinutes()),l+=":"+ea(a.getSeconds()),l}case"%Q":return Math.floor(a.getMonth()/3)+1;default:return n}}var L1=/%[a-zA-Z]/g;function Mo(n,a){return typeof n=="function"?n:function(r){return r?(r.getMonth||(r=new Date(r)),n.replace(L1,l=>_1(l,r,a))):""}}function Fx(n){return n&&typeof n=="object"&&!Array.isArray(n)}function Rh(n,a){for(const r in a){const l=a[r];Fx(n[r])&&Fx(l)?n[r]=Rh({...n[r]},a[r]):n[r]=a[r]}return n}function nu(n){return{getGroup(a){const r=n[a];return l=>r&&r[l]||l},getRaw(){return n},extend(a,r){if(!a)return this;let l;return r?l=Rh({...a},n):l=Rh({...n},a),nu(l)}}}var z1=Xy();const I1="en-US",O1={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},B1={ok:"OK",cancel:"Cancel",select:"Select","No data":"No data","Rows per page":"Rows per page","Total pages":"Total pages"},F1={timeFormat:"%H:%i",dateFormat:"%m/%d/%Y",monthYearFormat:"%F %Y",yearFormat:"%Y"},yw={core:B1,calendar:O1,formats:F1,lang:I1},ap=u.createContext(""),ww=u.createContext({}),Ls=u.createContext(null),bw=u.createContext(null),On=Object.freeze(Object.defineProperty({__proto__:null,fieldId:bw,helpers:ww,i18n:Ls,theme:ap},Symbol.toStringTag,{value:"Module"}));function Sw(n){const a=u.useContext(bw),[r]=u.useState(()=>n||a||np());return r}function Kc({type:n="",css:a="",icon:r="",disabled:l=!1,title:c="",tooltip:d,text:m="",children:p,onClick:v}){const g=u.useMemo(()=>{let y=n?n.split(" ").filter(b=>b!=="").map(b=>"wx-"+b).join(" "):"";return a+(a?" ":"")+y},[n,a]),w=y=>{v&&v(y)};return s.jsxs("button",{title:c,className:`wx-2ZWgb4 wx-button ${g} ${r&&!p?"wx-icon":""}`,disabled:l,onClick:w,"data-tooltip-text":d,children:[r&&s.jsx("i",{className:"wx-2ZWgb4 "+r}),p||m||" "]})}function P1({id:n,label:a="",inputValue:r="",value:l=!1,onChange:c,disabled:d=!1,css:m=""}){const p=Sw(n),[v,g]=si(l),w=({target:y})=>{const b=y.checked;g(b),c&&c({value:b,inputValue:r})};return s.jsxs("div",{className:`wx-2IvefP wx-checkbox ${m}`,children:[s.jsx("input",{type:"checkbox",id:p,disabled:d,className:"wx-2IvefP wx-check",checked:v,value:r,onChange:w}),s.jsxs("label",{htmlFor:p,className:"wx-2IvefP wx-label",children:[s.jsx("span",{className:"wx-2IvefP wx-before"}),a&&s.jsx("span",{className:"wx-2IvefP wx-after",children:a})]})]})}function sp({theme:n="",target:a,children:r}){const l=u.useRef(null),c=u.useRef(null),[d,m]=u.useState(null);l.current||(l.current=document.createElement("div"));const p=u.useContext(ap);return u.useEffect(()=>{m(a||H1(c.current)||_a.getTopNode(c.current))},[c.current]),s.jsxs(s.Fragment,{children:[s.jsx("span",{ref:c,style:{display:"none"}}),c.current&&d?z1.createPortal(s.jsx("div",{className:`wx-3ZWsT0 wx-${n||p}-theme`,children:r}),d):null]})}function H1(n){const a=_a.getTopNode(n);for(;n&&n!==a&&!n.getAttribute("data-wx-portal-root");)n=n.parentNode;return n}function $1({left:n=0,top:a=0,at:r="bottom",parent:l=null,width:c="auto",css:d="",onCancel:m,children:p,trackScroll:v=!1}){const[g,w]=u.useState(0),[y,b]=u.useState(0),[j,C]=u.useState("auto"),[N,T]=u.useState(!1),k=u.useRef(null),E=u.useRef(null),R=u.useRef(m);u.useEffect(()=>{R.current=m},[m]);function $(q){return l&&(c+"").indexOf("%")>-1?c.replace(/(\d+)%/,(z,L)=>(L=L*l.offsetWidth/100+"px",c.replace(z,L))):c&&c!=="auto"?c:q}const F=u.useCallback(()=>{if(!k.current)return;const q=gw(k.current,l,r,n,a);q&&(w(q.x),b(q.y),C($(q.width)))},[k,l,r,n,a,c]);return u.useLayoutEffect(()=>{const q=L=>{R.current&&L.target!==E.current&&k.current&&!k.current.contains(L.target)&&R.current(L)};let z;return requestAnimationFrame(()=>{F(),T(!0),v&&k.current&&(E.current=vw(k.current),E.current&&E.current.addEventListener("scroll",q,!0)),l&&(z=new ResizeObserver(F),z.observe(l))}),()=>{v&&E.current&&E.current.removeEventListener("scroll",q,!0),z?.disconnect()}},[]),u.useLayoutEffect(()=>{F()},[l,r,n,a]),u.useEffect(()=>{const q=z=>{R.current&&R.current(z)};if(k.current)return ii(k.current,{callback:q,parent:()=>l}).destroy},[l]),s.jsx("div",{ref:k,className:["wx-37M6Fj","wx-popup",d].filter(Boolean).join(" "),style:{position:"absolute",visibility:N?"visible":"hidden",top:y+"px",left:g+"px",width:j},children:p})}function U1({position:n="bottom",align:a="start",autoFit:r=!0,onCancel:l=null,width:c="100%",css:d="",children:m}){const p=u.useRef(null),[v,g]=u.useState(n),[w,y]=u.useState(a),b=u.useRef(l);return u.useEffect(()=>{b.current=l},[l]),u.useEffect(()=>{if(r){const j=p.current;if(j){const C=j.getBoundingClientRect(),N=document.body.getBoundingClientRect();C.right>=N.right&&y("end"),C.bottom>=N.bottom&&g("top")}}},[]),u.useEffect(()=>{if(p.current){const j=C=>{b.current&&b.current(C)};return ii(p.current,j).destroy}},[]),s.jsx("div",{ref:p,className:["wx-dropdown",`wx-${v}-${w}`,d||"","wx-aaaVytZW"].filter(Boolean).join(" "),style:{width:c},children:m})}function ip({position:n="bottom",align:a="start",autoFit:r=!0,inline:l=!1,onCancel:c,width:d="100%",children:m,...p}){const[v,g]=u.useState(void 0),w=u.useRef(null),y=u.useMemo(()=>`${n}-${a}`,[n,a]);return u.useLayoutEffect(()=>{w.current&&g(w.current.parentNode)},[]),s.jsxs(s.Fragment,{children:[v&&(l?s.jsx(U1,{onCancel:c,position:n,align:a,autoFit:r,width:d,...p,children:m}):s.jsx(sp,{children:s.jsx($1,{parent:v,at:y,onCancel:c,width:d,...p,children:m})})),s.jsx("span",{ref:w,className:"wx-portal-node wx-32GZ52"})]})}function df(){return nu(yw)}function q1(){let n=null,a=!1,r=!1,l,c,d,m;const p=(y,b,j,C,N)=>{l=y,c=b,d=j,m=C,r=N},v=y=>{n=y,a=n!==null,d(n)},g=(y,b)=>{if(!r&&y!==null&&l){const j=l.querySelectorAll(".wx-list > .wx-item")[y];j&&(j.scrollIntoView({block:"nearest"}),b&&b.preventDefault())}},w=(y,b)=>{const j=y===null?null:Math.max(0,Math.min(n+y,c.length-1));j!==n&&(v(j),l?g(j,b):requestAnimationFrame(()=>g(j,b)))};return{move:y=>{const b=eu(y),j=c.findIndex(C=>C.id===b);j!==n&&v(j)},keydown:(y,b)=>{switch(y.code){case"Enter":a?m():v(0);break;case"Space":a||v(0);break;case"Escape":d(n=null);break;case"Tab":d(n=null);break;case"ArrowDown":w(a?1:b||0,y);break;case"ArrowUp":w(a?-1:b||0,y);break}},init:p,navigate:w}}const Px=10,G1=u.memo(function({data:n,checkboxes:a,itemTemplate:r,value:l}){return s.jsxs(s.Fragment,{children:[a&&s.jsx(P1,{id:n.id,css:"wx-list-checkbox",value:l&&l.includes(n.id)}),r?ep(r,{option:n}):n.label]})});function Hx({visibleItems:n,visibleRange:a,navIndex:r,checkboxes:l,itemTemplate:c,value:d,measureRefCallback:m}){return n.map((p,v)=>{const g=a.start+v;return s.jsx("div",{ref:v===0?m:void 0,className:`wx-233fr7 wx-item ${g===r?"wx-focus":""}`,"data-id":p.id,children:s.jsx(G1,{data:p,checkboxes:l,itemTemplate:c,value:d})},p.id)})}function ff({items:n=[],children:a,onSelect:r,onReady:l,virtualized:c=!1,checkboxes:d,multiselect:m,value:p,...v}){const g=u.useRef(),w=u.useRef(!1),y=u.useRef(q1()),[b,j]=u.useState(null),C=u.useRef(b),[N,T]=u.useState(0),[k,E]=u.useState(24),R=u.useRef(!1),$=(u.useContext(Ls)||df()).getGroup("core"),F=u.useRef(n);u.useEffect(()=>{F.current=n},[n]);const q=u.useRef(p);u.useEffect(()=>{q.current=p},[p]);const z=u.useRef(0);u.useEffect(()=>{z.current=k},[k]);const L=u.useCallback(W=>{W&&W.stopPropagation();const P=F.current,me=q.current,pe=C.current;let ve;const ke=P[pe]?.id;m?me&&me.includes(ke)?ve=me.filter(_e=>_e!==ke):ve=[...me||[],ke]:ve=ke,r&&r({id:ve})},[m,r]),ie=u.useRef(L);u.useEffect(()=>{ie.current=L},[L]);const V=u.useCallback(W=>{if(g.current){let P=W*z.current-g.current.clientHeight+z.current;T(P),g.current.scrollTop=P}},[z.current]),ne=u.useCallback(W=>{g.current=W,c&&(W&&!w.current&&C.current!==null&&requestAnimationFrame(()=>{g.current&&(V(C.current),w.current=!0)}),W||(w.current=!1))},[V]),Q=u.useCallback(W=>{if(!W||R.current)return;const P=W.getBoundingClientRect().height;P&&(E(P),z.current=P,R.current=!0)},[]);u.useEffect(()=>{y.current.init(g.current,n,W=>{j(W),C.current=W},W=>ie.current(W),c)},[n,g.current,c]),u.useEffect(()=>{const W=(me,pe)=>{y.current.navigate(me,pe),V(C.current)},P=(me,pe)=>{const ve=C.current,ke=F.current;if(ve!==0&&ve!==ke.length-1&&(me.key==="ArrowDown"||me.key==="ArrowUp")&&me.preventDefault(),y.current.keydown(me,pe),g.current){const _e=g.current.scrollTop<=C.current*z.current,Le=g.current.scrollTop+g.current.clientHeight>=C.current*z.current+z.current;_e?Le||V(C.current):(g.current.scrollTop=C.current*z.current,T(g.current.scrollTop))}};l&&l({navigate:c?W:y.current.navigate,keydown:c?P:y.current.keydown,move:y.current.move})},[]);const J=u.useRef(0),le=u.useRef(n);le.current!==n&&(le.current=n,J.current+=1);const Y=u.useCallback(()=>{y.current.navigate(null)},[y]),O=u.useCallback(W=>{c&&T(W.target.scrollTop)},[c]),Z=u.useMemo(()=>Math.ceil((g.current?.clientHeight||0)/k),[k,N]),X=u.useMemo(()=>{if(!c)return{start:0,end:n.length};if(!n.length)return{start:0,end:0};const W=Math.floor(N/k),P=W+Z;return{start:Math.max(0,W-Px),end:Math.min(n.length,P+Px)}},[c,n,N,k,Z]),D=u.useMemo(()=>{if(!c)return n;const{start:W,end:P}=X;return n.slice(W,P).map(me=>({...me}))},[c,n,X]),K=X.start*k,ce=n.length*k;return u.useEffect(()=>{c&&T(0)},[n,c]),u.useEffect(()=>{b===null&&(w.current=!1)},[b]),b===null?null:s.jsx(ip,{onCancel:Y,...v,children:s.jsx("div",{className:"wx-233fr7 wx-list",ref:ne,onClick:L,onMouseMove:y.current.move,onScroll:O,children:n.length?c?s.jsx("div",{className:"wx-233fr7 wx-list-wrapper",style:{height:`${ce}px`},children:s.jsx("div",{className:"wx-233fr7 wx-list-content",style:{transform:`translateY(${K}px)`},children:s.jsx(Hx,{visibleRange:X,visibleItems:D,navIndex:b,measureRefCallback:Q,checkboxes:d,itemTemplate:a,value:p})})}):s.jsx(Hx,{visibleRange:X,visibleItems:D,navIndex:b,measureRefCallback:Q,checkboxes:d,itemTemplate:a,value:p}):s.jsx("div",{className:"wx-233fr7 wx-no-data",children:$("No data")})})},J.current)}function rp({value:n="",id:a,readonly:r=!1,focus:l=!1,select:c=!1,type:d="text",placeholder:m="",disabled:p=!1,error:v=!1,title:g="",tooltip:w,css:y="",icon:b="",clear:j=!1,onChange:C}){const N=Sw(a),[T,k]=si(n),E=u.useRef(null),R=u.useMemo(()=>b&&y.indexOf("wx-icon-left")===-1?"wx-icon-right "+y:y,[b,y]),$=u.useMemo(()=>b&&y.indexOf("wx-icon-left")!==-1,[b,y]);u.useEffect(()=>{const ie=setTimeout(()=>{l&&E.current&&E.current.focus(),c&&E.current&&E.current.select()},1);return()=>clearTimeout(ie)},[l,c]);const F=u.useCallback(ie=>{const V=ie.target.value;k(V),C&&C({value:V,input:!0})},[C]),q=u.useCallback(ie=>C&&C({value:ie.target.value}),[C]);function z(ie){ie.stopPropagation(),k(""),C&&C({value:""})}let L=d;return d!=="password"&&d!=="number"&&(L="text"),u.useEffect(()=>{const ie=q,V=E.current;return V.addEventListener("change",ie),()=>{V&&V.removeEventListener("change",ie)}},[q]),s.jsxs("div",{className:`wx-hQ64J4 wx-text ${R} ${v?"wx-error":""} ${p?"wx-disabled":""} ${j?"wx-clear":""}`,"data-tooltip-text":w,children:[s.jsx("input",{className:"wx-hQ64J4 wx-input",ref:E,id:N,readOnly:r,disabled:p,placeholder:m,type:L,title:g,value:T,onInput:F}),j&&!p&&T?s.jsxs(s.Fragment,{children:[s.jsx("i",{className:"wx-hQ64J4 wx-icon wxi-close",onClick:z}),$&&s.jsx("i",{className:`wx-hQ64J4 wx-icon ${b}`})]}):b?s.jsx("i",{className:`wx-hQ64J4 wx-icon ${b}`}):null]})}function V1({date:n,type:a,part:r,onShift:l}){const{calendar:c,formats:d}=u.useContext(Ls).getRaw(),m=n.getFullYear(),p=u.useMemo(()=>{switch(a){case"month":return Mo(d.monthYearFormat,c)(n);case"year":return Mo(d.yearFormat,c)(n);case"duodecade":{const{start:g,end:w}=xw(m),y=Mo(d.yearFormat,c);return`${y(new Date(g,0,1))} - ${y(new Date(w,11,31))}`}default:return""}},[n,a,m,c,d]);function v(){l&&l({diff:0,type:a})}return s.jsxs("div",{className:"wx-8HQVQV wx-header",children:[r!=="right"?s.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-left",onClick:()=>l&&l({diff:-1,type:a})}):s.jsx("span",{className:"wx-8HQVQV wx-spacer"}),s.jsx("span",{className:"wx-8HQVQV wx-label",onClick:v,children:p}),r!=="left"?s.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-right",onClick:()=>l&&l({diff:1,type:a})}):s.jsx("span",{className:"wx-8HQVQV wx-spacer"})]})}function lp({onClick:n,children:a}){return s.jsx("button",{className:"wx-3s8W4d wx-button",onClick:n,children:a})}function Y1({value:n,current:a,part:r="",markers:l=null,css:c="",onCancel:d,onChange:m}){const p=(u.useContext(Ls)||df()).getRaw().calendar,v=(p.weekStart||7)%7,g=p.dayShort.slice(v).concat(p.dayShort.slice(0,v)),w=(F,q,z)=>new Date(F.getFullYear(),F.getMonth()+(q||0),F.getDate()+(z||0));let y=r!=="normal";function b(F){const q=F.getDay();return q===0||q===6}function j(){const F=w(a,0,1-a.getDate());return F.setDate(F.getDate()-(F.getDay()-(v-7))%7),F}function C(){const F=w(a,1,-a.getDate());return F.setDate(F.getDate()+(6-F.getDay()+v)%7),F}const N=u.useRef(0);function T(F,q){q.timeStamp!==N.current&&(N.current=q.timeStamp,q.stopPropagation(),m&&m(new Date(F)),d&&d())}const k=u.useMemo(()=>r=="normal"?[n?w(n).valueOf():0]:n?[n.start?w(n.start).valueOf():0,n.end?w(n.end).valueOf():0]:[0,0],[r,n]),E=u.useMemo(()=>{const F=j(),q=C(),z=a.getMonth();let L=[];for(let ie=F;ie<=q;ie.setDate(ie.getDate()+1)){const V={day:ie.getDate(),in:ie.getMonth()===z,date:ie.valueOf()};let ne="";if(ne+=V.in?"":" wx-inactive",ne+=k.indexOf(V.date)>-1?" wx-selected":"",y){const Q=V.date==k[0],J=V.date==k[1];Q&&!J?ne+=" wx-left":J&&!Q&&(ne+=" wx-right"),V.date>k[0]&&V.date<k[1]&&(ne+=" wx-inrange")}if(ne+=b(ie)?" wx-weekend":"",l){const Q=l(ie);Q&&(ne+=" "+Q)}L.push({...V,css:ne})}return L},[a,k,y,l]),R=u.useRef(null);let $=u.useRef({});return $.current.click=T,u.useEffect(()=>{Lo(R.current,$.current)},[]),s.jsxs("div",{className:`wx-398RBS wx-month ${c}`,children:[s.jsx("div",{className:"wx-398RBS wx-weekdays",children:g.map(F=>s.jsx("div",{className:"wx-398RBS wx-weekday",children:F},F))}),s.jsx("div",{className:"wx-398RBS wx-days",ref:R,children:E.map(F=>s.jsx("div",{className:`wx-398RBS wx-day ${F.css} ${F.in?"":"wx-out"}`,"data-id":F.date,children:F.day},F.date))})]})}function W1({value:n,current:a,part:r,onCancel:l,onChange:c,onShift:d}){const m=u.useRef(new Date),[p,v]=si(n||m.current),[g,w]=si(a||m.current),y=u.useContext(Ls).getRaw().calendar,b=y.monthShort||[],j=u.useMemo(()=>g.getMonth(),[g]),C=u.useCallback((k,E)=>{if(k!=null){E.stopPropagation();const R=new Date(g);R.setMonth(k),w(R),d&&d({current:R})}r==="normal"&&v(new Date(g)),l&&l()},[g,r,d,l]),N=u.useCallback(()=>{const k=new Date(jw(p,r)||g);k.setMonth(g.getMonth()),k.setFullYear(g.getFullYear()),c&&c(k)},[p,g,r,c]),T=u.useCallback(k=>{const E=k.target.closest("[data-id]");if(E){const R=parseInt(E.getAttribute("data-id"),10);C(R,k)}},[C]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"wx-34U8T8 wx-months",onClick:T,children:b.map((k,E)=>s.jsx("div",{className:"wx-34U8T8 wx-month"+(j===E?" wx-current":""),"data-id":E,children:k},E))}),s.jsx("div",{className:"wx-34U8T8 wx-buttons",children:s.jsx(lp,{onClick:N,children:y.done})})]})}const th="wx-1XEF33",K1=({value:n,current:a,onCancel:r,onChange:l,onShift:c,part:d})=>{const m=u.useContext(Ls).getRaw().calendar,[p,v]=si(a),[g,w]=si(n),y=u.useMemo(()=>p.getFullYear(),[p]),b=u.useMemo(()=>{const{start:k,end:E}=xw(y),R=[];for(let $=k;$<=E;++$)R.push($);return R},[y]),j={click:C};function C(k,E){if(k){E.stopPropagation();const R=new Date(p);R.setFullYear(k),v(R),c&&c({current:R})}d==="normal"&&w(new Date(p)),r&&r()}function N(){const k=new Date(jw(g,d)||p);k.setFullYear(p.getFullYear()),l&&l(k)}const T=u.useRef(null);return u.useEffect(()=>{T.current&&Lo(T.current,j)},[]),s.jsxs(s.Fragment,{children:[s.jsx("div",{className:th+" wx-years",ref:T,children:b.map((k,E)=>s.jsx("div",{className:th+` wx-year ${y==k?"wx-current":""} ${E===0?"wx-prev-decade":""} ${E===11?"wx-next-decade":""}`,"data-id":k,children:k},E))}),s.jsx("div",{className:th+" wx-buttons",children:s.jsx(lp,{onClick:N,children:m.done})})]})},$x={month:{component:Y1,next:X1,prev:Q1},year:{component:W1,next:J1,prev:Z1},duodecade:{component:K1,next:tC,prev:eC}};function Q1(n){return n=new Date(n),n.setMonth(n.getMonth()-1),n}function X1(n){return n=new Date(n),n.setMonth(n.getMonth()+1),n}function Z1(n){return n=new Date(n),n.setFullYear(n.getFullYear()-1),n}function J1(n){return n=new Date(n),n.setFullYear(n.getFullYear()+1),n}function eC(n){return n=new Date(n),n.setFullYear(n.getFullYear()-10),n}function tC(n){return n=new Date(n),n.setFullYear(n.getFullYear()+10),n}function jw(n,a){let r;if(a==="normal")r=n;else{const{start:l,end:c}=n;a==="left"?r=l:a=="right"?r=c:r=l&&c}return r}const nC=["clear","today"];function aC(n){if(n==="done")return-1;if(n==="clear")return null;if(n==="today")return new Date}function sC({value:n,current:a,onCurrentChange:r,part:l="normal",markers:c=null,buttons:d,css:m="",onShift:p,onChange:v}){const g=u.useContext(Ls).getGroup("calendar"),[w,y]=u.useState("month"),b=Array.isArray(d)?d:d?nC:[],j=(E,R)=>{E.preventDefault(),v&&v({value:R})},C=()=>{w==="duodecade"?y("year"):w==="year"&&y("month")},N=E=>{const{diff:R,current:$}=E;if(R===0){w==="month"?y("year"):w==="year"&&y("duodecade");return}if(R){const F=$x[w];r(R>0?F.next(a):F.prev(a))}else $&&r($);p&&p()},T=E=>{y("month"),v&&v({select:!0,value:E})},k=u.useMemo(()=>$x[w].component,[w]);return s.jsx("div",{className:`wx-2Gr4AS wx-calendar ${l!=="normal"&&l!=="both"?"wx-part":""} ${m}`,children:s.jsxs("div",{className:"wx-2Gr4AS wx-wrap",children:[s.jsx(V1,{date:a,part:l,type:w,onShift:N}),s.jsxs("div",{children:[s.jsx(k,{value:n,current:a,onCurrentChange:r,part:l,markers:c,onCancel:C,onChange:T,onShift:N}),w==="month"&&b.length>0&&s.jsx("div",{className:"wx-2Gr4AS wx-buttons",children:b.map(E=>s.jsx("div",{className:"wx-2Gr4AS wx-button-item",children:s.jsx(lp,{onClick:R=>j(R,aC(E)),children:g(E)})},E))})]})]})})}function op(n){let{words:a=null,optional:r=!1,children:l}=n,c=u.useContext(Ls);const d=u.useMemo(()=>{let m=c;return(!m||!m.extend)&&(m=nu(yw)),a!==null&&(m=m.extend(a,r)),m},[a,r,c]);return s.jsx(Ls.Provider,{value:d,children:l})}function Ux(n,a,r,l){if(!n||l){const c=a?new Date(a):new Date;c.setDate(1),r(c)}else if(n.getDate()!==1){const c=new Date(n);c.setDate(1),r(c)}}const iC=["clear","today"];function Cw({value:n,current:a,markers:r=null,buttons:l=iC,css:c="",onChange:d}){const[m,p]=si(n),[v,g]=si(a);u.useEffect(()=>{Ux(v,m,g,!1)},[m,v]);const w=u.useCallback(b=>{const j=b.value;j?(p(new Date(j)),Ux(v,new Date(j),g,!0)):p(null),d&&d({value:j?new Date(j):null})},[d,v]),y=u.useCallback(b=>{g(b)},[g]);return v?s.jsx(op,{children:s.jsx(sC,{value:m,current:v,markers:r,buttons:l,css:c,onChange:w,onCurrentChange:y})}):null}function rC(n){return n||(n={}),n.width||(n.width="unset"),n}const lC=["clear","today"];function oC({value:n,id:a,disabled:r=!1,error:l=!1,placeholder:c="",format:d="",buttons:m=lC,css:p="",title:v="",tooltip:g,editable:w=!1,clear:y=!1,onChange:b,dropdown:j={}}){const{calendar:C,formats:N}=(u.useContext(Ls)||df()).getRaw(),T=d||N?.dateFormat;let k=typeof T=="function"?T:Mo(T,C);const[E,R]=u.useState(n),[$,F]=u.useState(!1);u.useEffect(()=>{R(n)},[n]);function q(){F(!1)}function z(V){const ne=V===E||V&&E&&V.valueOf()===E.valueOf()||!V&&!E;R(V),ne||b&&b({value:V}),setTimeout(q,1)}const L=u.useMemo(()=>E?k(E):"",[E,k]);function ie({value:V,input:ne}){if(!w&&!y||ne)return;let Q=typeof w=="function"?w(V):V?new Date(V):null;Q=isNaN(Q)?E||null:Q||null,z(Q)}return u.useEffect(()=>{const V=q;return window.addEventListener("scroll",V),()=>window.removeEventListener("scroll",V)},[]),s.jsxs("div",{className:"wx-1lKOFG wx-datepicker",onClick:()=>F(!0),children:[s.jsx(rp,{css:`wx-date-input ${p}`,title:v,tooltip:g,value:L,id:a,readonly:!w,disabled:r,error:l,placeholder:c,onInput:q,onChange:ie,icon:"wxi-calendar",clear:y}),$&&!r&&s.jsx(ip,{onCancel:q,...rC(j),children:s.jsx(Cw,{buttons:m,value:E,onChange:V=>z(V.value)})})]})}function cC({value:n="",options:a=[],textOptions:r=null,placeholder:l="",disabled:c=!1,error:d=!1,title:m="",tooltip:p,textField:v="label",clear:g=!1,css:w="",children:y,onChange:b,dropdown:j={}}){const C=u.useRef(null),N=u.useRef(null);let[T,k]=si(n);function E(z){C.current=z.navigate,N.current=z.keydown}const R=u.useMemo(()=>T||T===0?(r||a).find(z=>z.id===T):null,[T,r,a]),$=u.useCallback(({id:z})=>{(z||z===0)&&(k(z),C.current(null),b&&b({value:z}))},[k,b]),F=u.useCallback(z=>{z.stopPropagation(),k(""),b&&b({value:""})},[k,b]),q=u.useCallback(()=>a.findIndex(z=>z.id===T),[a,T]);return s.jsxs("div",{className:`wx-2YgblL wx-richselect ${w} ${d?"wx-2YgblL wx-error":""} ${c?"wx-2YgblL wx-disabled":""} ${y?"":"wx-2YgblL wx-nowrap"}`,title:m,onClick:()=>C.current(q()),onKeyDown:z=>N.current(z,q()),tabIndex:0,"data-tooltip-text":p,children:[s.jsx("div",{className:"wx-2YgblL wx-label",children:R?y?y(R):R[v]:l?s.jsx("span",{className:"wx-2YgblL wx-placeholder",children:l}):" "}),g&&!c&&T?s.jsx("i",{className:"wx-2YgblL wx-icon wxi-close",onClick:F}):s.jsx("i",{className:"wx-2YgblL wx-icon wxi-angle-down"}),!c&&s.jsx(ff,{items:a,onReady:E,onSelect:$,...j,children:({option:z})=>y?y(z):z[v]})]})}const uC=({options:n=[],value:a="",css:r="",children:l,onChange:c})=>{const[d,m]=u.useState(a),p=v=>{m(v),c&&c({value:v})};return u.useEffect(()=>{m(a)},[a]),s.jsx("div",{className:`wx-0hMO7P wx-segmented ${r}`,children:n.map(v=>s.jsx("button",{className:`wx-0hMO7P wx-segment ${v.css} ${v.id===d?"wx-selected":""}`,title:v.title,onClick:()=>p(v.id),"data-tooltip-text":v.tooltip,children:l?ep(l,{option:v}):s.jsxs(s.Fragment,{children:[v.icon&&s.jsx("i",{className:`wx-0hMO7P wx-icon ${v.icon} ${v.label?"":"wx-only"}`}),v.label&&s.jsx("span",{className:"wx-0hMO7P wx-label",children:v.label})]})},v.id))})};function dC({notice:n={}}){function a(){n.remove&&n.remove()}return s.jsxs("div",{className:`wx-11sNg5 wx-notice wx-${n.type?n.type:""}`,role:"status","aria-live":"polite",children:[s.jsx("div",{className:"wx-11sNg5 wx-text",children:n.text}),s.jsx("div",{className:"wx-11sNg5 wx-button",children:s.jsx("i",{className:"wx-11sNg5 wxi-close",onClick:a})})]})}function fC({data:n=[]}){return s.jsx("div",{className:"wx-3nwoO9 wx-notices",children:n.map(a=>s.jsx(dC,{notice:a},a.id))})}function Dh({title:n="",buttons:a=["cancel","ok"],header:r,children:l,footer:c,css:d="",onConfirm:m,onCancel:p}){const v=(u.useContext(Ls)||df()).getGroup("core"),g=u.useRef(null);u.useEffect(()=>{g.current?.focus()},[]);function w(b){switch(b.code){case"Enter":{const j=b.target.tagName;if(j==="TEXTAREA"||j==="BUTTON")return;m&&m({event:b});break}case"Escape":p&&p({event:b});break}}function y(b,j){const C={event:b,button:j};j==="cancel"?p&&p(C):m&&m(C)}return s.jsx("div",{className:`wx-1FxkZa wx-modal ${d}`,ref:g,tabIndex:0,onKeyDown:w,children:s.jsxs("div",{className:"wx-1FxkZa wx-window",children:[r||(n?s.jsx("div",{className:"wx-1FxkZa wx-header",children:n}):null),s.jsx("div",{children:l}),c||a&&s.jsx("div",{className:"wx-1FxkZa wx-buttons",children:a.map(b=>s.jsx("div",{className:"wx-1FxkZa wx-button",children:s.jsx(Kc,{type:`block ${b==="ok"?"primary":"secondary"}`,onClick:j=>y(j,b),children:v(b)})},b))})]})})}function mC({children:n},a){const[r,l]=u.useState(null),[c,d]=u.useState([]);return u.useImperativeHandle(a,()=>({showModal:m=>{const p={...m};return l(p),new Promise((v,g)=>{p.resolve=w=>{l(null),v(w)},p.reject=w=>{l(null),g(w)}})},showNotice:m=>{m={...m},m.id=m.id||np(),m.remove=()=>d(p=>p.filter(v=>v.id!==m.id)),m.expire!=-1&&setTimeout(m.remove,m.expire||5100),d(p=>[...p,m])}}),[]),s.jsxs(s.Fragment,{children:[n,r&&s.jsx(Dh,{title:r.title,buttons:r.buttons,onConfirm:r.resolve,onCancel:r.reject,children:r.message}),s.jsx(fC,{data:c})]})}const hC=u.forwardRef(mC);function pC(n){let{children:a}=n,r=u.useRef();const l=u.useMemo(()=>({showNotice:c=>r.current.showNotice(c),showModal:c=>r.current.showModal(c)}),[]);return s.jsx(ww.Provider,{value:l,children:s.jsx(hC,{ref:r,children:a})})}const gC=({value:n=!1,type:a="",icon:r="",disabled:l=!1,iconActive:c="",onClick:d,title:m="",tooltip:p,css:v="",text:g="",textActive:w="",children:y,active:b,onChange:j})=>{const[C,N]=si(n),T=u.useMemo(()=>(C?"pressed":"")+(a?" "+a:""),[C,a]),k=u.useCallback(E=>{let R=!C;d&&d(E),E.defaultPrevented||(N(R),j&&j({value:R}))},[C,d,j]);return C&&b?s.jsx(Kc,{title:m,tooltip:p,text:C&&w||g,css:v,type:T,icon:C&&c||r,onClick:k,disabled:l,children:ep(b,{value:C})}):y?s.jsx(Kc,{title:m,tooltip:p,text:C&&w||g,css:v,type:T,icon:C&&c||r,onClick:k,disabled:l,children:y}):s.jsx(Kc,{title:m,tooltip:p,text:C&&w||g,css:v,type:T,icon:C&&c||r,onClick:k,disabled:l})};function vC(){return s.jsx(s.Fragment,{})}function qx(n){const{fonts:a=!0,children:r}=n;return s.jsx(ap.Provider,{value:"willow",children:s.jsxs(s.Fragment,{children:[r&&r&&s.jsx("div",{className:"wx-theme wx-willow-theme",children:r}),a&&s.jsxs(s.Fragment,{children:[s.jsx("link",{rel:"preconnect",href:"https://cdn.svar.dev",crossOrigin:"true"}),s.jsx(vC,{}),s.jsx("link",{rel:"stylesheet",href:"https://cdn.svar.dev/fonts/wxi/wx-icons.css"})]})]})})}tp(_a);const cp={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 kw=class{constructor(n){this._nextHandler=null,this._dispatch=n,this.exec=this.exec.bind(this)}async exec(n,a){return this._dispatch(n,a),this._nextHandler&&await this._nextHandler.exec(n,a),a}setNext(n){return this._nextHandler=n}};new Date().valueOf();var xC=class{constructor(n){const a={id:0,$level:0,data:[],parent:null},r=new Map;r.set(0,a),this._pool=r,n&&n.length&&this.parse(n,0)}parse(n,a){const r=this._pool;for(let c=0;c<n.length;c++){const d=n[c];d.parent=d.parent||a,d.data=null,r.set(d.id,d)}for(let c=0;c<n.length;c++){const d=n[c],m=r.get(d.parent);m&&(m.data||(m.data=[]),m.data.push(d))}const l=r.get(a);this.setLevel(l,l.$level+1,!1)}add(n,a){const r=this._pool.get(n.parent||0);n.$level=r.$level+1,this._pool.set(n.id,n),r.data?a===-1?r.data=[...r.data,n]:Gx(r,a,n):r.data=[n]}addAfter(n,a){if(!a)return this.add(n,-1);const r=this.byId(a),l=this.byId(r.parent),c=Ed(l,r.id)+1;n.parent=l.id,n.$level=l.$level+1,this.add(n,c)}remove(n){const a=this._pool.get(n);this._remove(a);const r=this._pool.get(a.parent);r.data=r.data.filter(l=>l.id!=n),this._clearBranch(r)}_remove(n){n.data&&n.data.forEach(a=>this._remove(a)),this._pool.delete(n.id)}update(n,a){let r=this._pool.get(n);const l=this._pool.get(r.parent),c=Ed(l,r.id);r={...r,...a},l&&c>=0&&(l.data[c]=r,l.data=[...l.data]),this._pool.set(r.id,r)}move(n,a,r){const l=this._pool.get(n),c=a==="child",d=this._pool.get(r),m=d.$level+(c?1:0);if(!l||!d)return;const p=this._pool.get(l.parent),v=c?d:this._pool.get(d.parent);v.data||(v.data=[]);const g=Ed(p,l.id);yC(p,g);const w=c?v.data.length:Ed(v,d.id)+(a==="after"?1:0);if(Gx(v,w,l),p.id===v.id&&g===w)return null;l.parent=v.id,l.$level!==m&&(l.$level=m,this.setLevel(l,m+1,!0)),this.update(l.id,l),this._clearBranch(p)}_clearBranch(n){n.data&&!n.data.length&&(n.open&&delete n.open,this.update(n.id,{data:null}))}toArray(){const n=[],a=this._pool.get(0).data;return a&&Aw(a,n),n}byId(n){return this._pool.get(n)}getBranch(n){return this._pool.get(n).data}forEach(n){this._pool.forEach((a,r)=>{r!==0&&n(a)})}eachChild(n,a){const r=this.byId(a);!r||!r.data||r.data.forEach((l,c)=>{n(this.byId(l.id),c),this.eachChild(n,l.id)})}setLevel(n,a,r){n.data&&(n.data=n.data.map(l=>(r&&(l={...l},this._pool.set(l.id,l)),l.$level=a,l.data&&this.setLevel(l,a+1,r),l)))}};function Aw(n,a){n.forEach(r=>{a.push(r),r.open===!0&&Aw(r.data,a)})}function yC(n,a){const r=[...n.data];r.splice(a,1),n.data=r}function Gx(n,a,r){const l=[...n.data];l.splice(a,0,r),n.data=l}function Ed(n,a){return n?.data.findIndex(r=>r.id===a)}var Nw=2,wC=class{constructor(a){a&&(this._writable=a.writable,this._async=a.async),this._values={},this._state={}}setState(a,r=0){const l={};return this._wrapProperties(a,this._state,this._values,"",l,r),l}getState(){return this._values}getReactive(){return this._state}_wrapProperties(a,r,l,c,d,m){for(const p in a){const v=r[p],g=l[p],w=a[p];if(v&&(g===w&&typeof w!="object"||w instanceof Date&&g instanceof Date&&g.getTime()===w.getTime()))continue;const y=c+(c?".":"")+p;v?(v.__parse(w,y,d,m)&&(l[p]=w),m&Nw?d[y]=v.__trigger:v.__trigger()):(w&&w.__reactive?r[p]=this._wrapNested(w,w,y,d):r[p]=this._wrapWritable(w),l[p]=w),d[y]=d[y]||null}}_wrapNested(a,r,l,c){const d=this._wrapWritable(a);return this._wrapProperties(a,d,r,l,c,0),d.__parse=(m,p,v,g)=>(this._wrapProperties(m,d,r,p,v,g),!1),d}_wrapWritable(a){const r=[],l=function(){for(let c=0;c<r.length;c++)r[c](a)};return{subscribe:c=>(r.push(c),this._async?setTimeout(c,1,a):c(a),()=>{const d=r.indexOf(c);d>=0&&r.splice(d,1)}),__trigger:()=>{r.length&&(this._async?setTimeout(l,1):l())},__parse:function(c){return a=c,!0}}}};function Vx(n,a){return Object.defineProperty(n,"__reactive",{value:!0,enumerable:!1,writable:!1}),n}var bC=class{constructor(a,r,l,c){typeof a=="function"?this._setter=a:this._setter=a.setState.bind(a),this._routes=r,this._parsers=l,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(d=>{d.in.forEach(m=>{const p=this._triggers.get(m)||[];p.push(d),this._triggers.set(m,p)}),d.out.forEach(m=>{const p=this._sources.get(m)||{};d.in.forEach(v=>p[v]=!0),this._sources.set(m,p)})}),this._routes.forEach(d=>{d.length=Math.max(...d.in.map(m=>Mw(m,this._sources,1)))}),this._bus=c}init(a){const r={};for(const l in a)if(this._prev[l]!==a[l]){const c=this._parsers[l];r[l]=c?c(a[l]):a[l]}this._prev=this._prev?{...this._prev,...a}:{...a},this.setState(r),this._bus&&this._bus.exec("init-state",r)}setStateAsync(a){const r=this._setter(a,Nw);return this._async?Object.assign(this._async.signals,r):this._async={signals:r,timer:setTimeout(this._applyState.bind(this),1)},r}_applyState(){const a=this._async;if(a){this._async=null,this._triggerUpdates(a.signals,[]);for(const r in a.signals){const l=a.signals[r];l&&l()}}}setState(a,r=[]){const l=this._setter(a);return this._triggerUpdates(l,r),l}_triggerUpdates(a,r){const l=Object.keys(a),c=!r.length;r=r||[];for(let d=0;d<l.length;d++){const m=l[d],p=this._triggers.get(m);p&&p.forEach(v=>{r.indexOf(v)==-1&&r.push(v)})}c&&this._execNext(r)}_execNext(a){for(;a.length;){a.sort((l,c)=>l.length<c.length?1:-1);const r=a[a.length-1];a.splice(a.length-1),r.exec(a)}}};function Mw(n,a,r){const l=a.get(n);if(!l)return r;const c=Object.keys(l).map(d=>Mw(d,a,r+1));return Math.max(...c)}var SC=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(a,r,l){let c=this._handlers[a];c?l&&l.intercept?c.unshift(r):c.push(r):c=this._handlers[a]=[r],l&&l.tag&&this._tag.set(r,l.tag)}intercept(a,r,l){this.on(a,r,{...l,intercept:!0})}detach(a){for(const r in this._handlers){const l=this._handlers[r];for(let c=l.length-1;c>=0;c--)this._tag.get(l[c])===a&&l.splice(c,1)}}async exec(a,r){const l=this._handlers[a];if(l)for(let c=0;c<l.length;c++){const d=l[c](r);if(d===!1||d&&d.then&&await d===!1)return}return this._nextHandler&&await this._nextHandler.exec(a,r),r}setNext(a){return this._nextHandler=a}};const wo=1024;function tu(n){return n<wo?`${n} B`:n<wo**2?`${(n/wo).toFixed(1)} KB`:n<wo**3?`${(n/wo**2).toFixed(1)} MB`:`${(n/wo**3).toFixed(1)} GB`}function Yx(n,a){a||(a={key:"name",order:"asc"});const r=n.filter(m=>m.type==="folder"),l=n.filter(m=>m.type!=="folder"),c=r.sort(Wx(a)),d=l.sort(Wx(a));return[...c,...d]}function jC(n,a){return typeof n=="string"?n.localeCompare(a,void 0,{numeric:!0}):typeof n=="object"?n.getTime()-a.getTime():(n??0)-(a??0)}function CC(n,a){return typeof n=="string"?-n.localeCompare(a,void 0,{numeric:!0}):typeof a=="object"?a.getTime()-n.getTime():(a??0)-(n??0)}function Wx({key:n,order:a}){const r=a==="asc"?jC:CC;return(l,c)=>r(l[n],c[n])}function up(n,a){const r=n==="/"?1:n.split("/").length;return r>=a.length?null:a[r].id}function kC(n){return n.length>1?n[n.length-2].id:null}let AC=class extends xC{constructor(a){const r={id:"/",name:"My files",open:!0,$level:1,parent:0,ext:"",type:"folder"};super([r]),this.parse(a,"/")}parse(a,r,l){!a||!a.length||(a.forEach(c=>this.parseId(c,l?r:void 0)),super.parse(a,r))}parseId(a,r){if(a.parent===0)return;const l=a.id,c=l.lastIndexOf("/");if(a.parent=r??(c===0?"/":l.slice(0,c)),a.name=l.slice(c+1),a.type=a.type||"file",a.type!=="folder"){const d=a.name.lastIndexOf("."),m=d!==-1?a.name.slice(d+1):"";a.ext=m!=="new"?m?.toLocaleLowerCase():""}}getParents(a){const r=[];let l=this.byId(a);if(!l)return r;for(;l.id!==0;)r.push(l),l=this.byId(l.parent);return r.reverse()}findFiles(a,r="/"){const l=[],c=a.toLocaleLowerCase();return this.eachChild(d=>{d.name.toLowerCase().indexOf(c)!==-1&&l.push(d)},r),l}add(a,r){const l=this.byId(a.parent||"/"),c=a.data?[...a.data]:null;a.data=null,super.add(a,r??l.data?l.data.length:0),c&&c.forEach(d=>this.add(d))}renameFiles(a,r,l){const c=this.byId(a),d=this.normalizeFile(c,r),m=[];return d.data?.forEach(p=>m.push(this.renameFiles(p.id,d.id,l))),m.length&&(d.data=m),l[a]=d.id,d}copyFiles(a,r,l){const c={};return a.forEach(d=>{const m=this.renameFiles(d,r,c);this.add(m),l&&this.remove(d),c[d]=m.id}),c}moveFiles(a,r){if(this.byId(a[0]).parent!==r)return this.copyFiles(a,r,!0)}serialize(a="/"){const r=[],l=this.byId(a);return l?(l.data?.forEach(c=>{const{id:d,date:m,type:p,size:v,lazy:g}=c,w={id:d,date:m,type:p??"file"};g&&(w.lazy=g),v&&(w.size=v),r.push(w);const y=this.serialize(d);y.length&&r.push(...y)}),r):null}normalizeFile(a,r){const l=a.name,c=l.lastIndexOf("."),d=c!==-1?l.slice(c+1):"",m=d?`.${d}`:"";let p=c!==-1?l.slice(0,c):l,v=r+(r==="/"?"":"/")+p;for(;this.byId(v+m);){const g=".new";v+=g,p+=g}return{...a,id:v+m,name:p+m,parent:r,ext:d.toLocaleLowerCase()}}},NC=class extends wC{in;_router;constructor(a){super({writable:a,async:!1});const r=[];for(let d=0;d<2;d++)r.push({in:["data",`panels.${d}.path`],out:[`panels.${d}._crumbs`],exec:m=>{const{data:p,panels:v}=this.getState(),g=[];g[d]={_crumbs:p.getParents(v[d].path)},this.setState({panels:g},m)}}),r.push({in:["data",`panels.${d}.path`,`panels.${d}._sorts`,"search"],out:[`panels.${d}._files`],exec:m=>{const{data:p,panels:v,search:g}=this.getState();let w;g?w=p.findFiles(g,v[d].path):w=p.byId(v[d].path)?.data||[];const{path:y,_sorts:b}=v[d];w=Yx(w,b[y]);const j=[];j[d]={_files:w},this.setState({panels:j},m)}}),r.push({in:["data",`panels.${d}.selected`,`panels.${d}._sorts`],out:[`panels.${d}._selected`],exec:m=>{const{data:p,panels:v}=this.getState(),g=[];v[d].selected.forEach(C=>{const N=p.byId(C);N&&g.push(N)});const{path:w,_sorts:y}=v[d],b=Yx(g,y[w]),j=[];j[d]={_selected:b},this.setState({panels:j},m)}});this._router=new bC(super.setState.bind(this),r,{data:d=>new AC(d)});const l=this.in=new SC;l.on("select-file",({id:d,toggle:m,range:p,panel:v,type:g})=>{const{panels:w,activePanel:y}=this.getState();typeof v>"u"&&(v=y),d||(m=p=!1);let b=[...w[v].selected];if(m){const C=b.indexOf(d);C===-1?b.push(d):b.splice(C,1)}else if(p&&w[v]._lastSelected){const C=w[v]._files;let N=C.findIndex(E=>E.id==w[v]._lastSelected),T=C.findIndex(E=>E.id==d);T<N&&([N,T]=[T,N]);const k=C.slice(N,T+1).map(E=>E.id);b=[...new Set([...b,...k])]}else b=d?[d]:[];const j=[];j[v]={selected:b,_lastSelected:d,_selectNavigation:g==="navigation"},this.setState({panels:j})}),l.on("set-path",({id:d,panel:m,selected:p})=>{const{data:v,activePanel:g}=this.getState(),w=v.byId(d);if(w){const y=[];typeof m>"u"&&(m=g),y[m]={path:d},this.setState({panels:y}),l.exec("select-file",{panel:m}),p&&p.forEach(b=>l.exec("select-file",{id:b,panel:m,toggle:!0})),w.lazy&&l.exec("request-data",{id:d})}}),l.on("provide-data",({id:d,data:m})=>{const{mode:p,data:v}=this.getState(),g=v.byId(d);g&&(g.lazy||(g.data=[]),g.lazy=!1,v.parse(m,d,p==="search"),this.setState({data:v}))}),l.on("open-tree-folder",({id:d,mode:m})=>{const{data:p}=this.getState();p.update(d,{open:m}),this.setState({data:p})}),l.on("show-preview",({mode:d})=>{this.setState({preview:d})}),l.on("rename-file",d=>{const{id:m,name:p}=d,{data:v,panels:g}=this.getState(),w=v.byId(m);if(w.name!==p){w.name=p;const y=v.normalizeFile(w,w.parent);d.newId=y.id,y.data=null,v.add(y);let b={[m]:y.id};w.data?.forEach(C=>b={...v.moveFiles([C.id],y.id),...b});const j=g.map(C=>({selected:C.selected,_crumbs:C._crumbs,_lastSelected:C._lastSelected,_sorts:C._sorts}));v.remove(m),this._updatePanels(j,b),this.setState({data:v,panels:j})}}),l.on("create-file",d=>{const{file:m,parent:p}=d,{data:v}=this.getState(),g=v.normalizeFile(m,p);g.type=m.type||"file",d.newId=g.id,v.add(g),this.setState({data:v}),l.exec("select-file",{id:g.id})}),l.on("delete-files",({ids:d})=>{const{data:m,panels:p}=this.getState(),v=p.map(g=>({selected:g.selected,_crumbs:g._crumbs,_lastSelected:g._lastSelected,_sorts:g._sorts}));d.forEach(g=>m.remove(g)),this._updatePanels(v,{}),this.setState({data:m,panels:v})}),l.on("copy-files",d=>{const{ids:m,target:p}=d;if(this._isPlacedIntoSelf(m,p)){console.error("You cannot copy a folder into itself"),d.skipProvider=!0;return}const{data:v,panels:g,activePanel:w}=this.getState(),y=v.copyFiles(m,p);d.newIds=m.map(b=>y[b]),this.setState({data:v}),g[w].path==p&&(l.exec("select-file",{}),m.forEach(b=>{l.exec("select-file",{id:y[b],toggle:!0})}))}),l.on("move-files",d=>{const{ids:m,target:p}=d;if(this._isPlacedIntoSelf(m,p)){console.error("You cannot move a folder into itself"),d.skipProvider=!0;return}const{data:v,panels:g,activePanel:w}=this.getState(),y=v.moveFiles(m,p);if(y){d.newIds=m.map(j=>y[j]);const b=g.map(j=>({selected:j.selected,_crumbs:j._crumbs,_lastSelected:j._lastSelected,_sorts:j._sorts}));this._updatePanels(b,y,!0),this.setState({data:v,panels:b}),g[w].path==p&&(l.exec("select-file",{}),m.forEach(j=>{l.exec("select-file",{id:y[j],toggle:!0})}))}});let c=null;l.on("filter-files",({text:d})=>{if(!d){c&&this.setState({...c});return}l.exec("select-file",{});const{panels:m,mode:p}=this.getState();c||(c={panels:m,mode:p,search:""}),this.setState({mode:"search",search:d})}),l.on("set-mode",({mode:d})=>{const{activePanel:m}=this.getState(),p=[];p[m]={_selectNavigation:!1};const v={mode:d,search:"",panels:p};c=null,this.setState(v)}),l.on("set-active-panel",({panel:d})=>{this.setState({activePanel:d})}),l.on("sort-files",({key:d,order:m,panel:p,path:v})=>{const{activePanel:g,panels:w}=this.getState();p=p??g,v=v??w[p].path;const y=[];y[p]={_sorts:{...w[p]._sorts,[v]:{key:d,order:m}}},this.setState({panels:y})}),this.initOnce()}initOnce(){const a=[];for(let l=0;l<2;l++)a[l]=Vx({_crumbs:[],_files:[],_selected:[],_sorts:{},path:"/",selected:[],...a[l]});const r={panels:Vx(a),data:[],search:""};this._router.init(r)}init(a){const r={...a};this._router.init(r)}setState(a,r){return this._router.setState(a,r)}getFile(a){const{data:r}=this.getState();return r.byId(a)||null}serialize(a){const{data:r}=this.getState();return r.serialize(a)}_updatePanels(a,r,l){const{data:c}=this.getState();a.forEach(d=>{const m=[];d.selected.forEach(g=>{c.byId(g)?m.push(g):!l&&r[g]&&m.push(r[g])}),d.selected=m,c.byId(d._lastSelected)||(d._lastSelected=l?null:r[d._lastSelected]||null);const p={};Object.keys(d._sorts).forEach(g=>{c.byId(g)?p[g]=d._sorts[g]:r[g]&&!l&&(p[r[g]]=d._sorts[g])}),d._sorts=p;const v=d._crumbs[d._crumbs.length-1];v?.id!=="/"&&(r[v.id]?d.path=r[v.id]:c.byId(v.id)||(d.path="/"))})}_isPlacedIntoSelf(a,r){return a.some(l=>l===r||this.getState().data.getParents(r).some(c=>c.id===l))}};function MC(n){switch(n){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[n==="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 TC(n,a="data-id"){let r=n;for(!r.tagName&&n.target&&(r=n.target);r;){if(r.getAttribute&&r.getAttribute(a))return r;r=r.parentNode}return null}function EC(n,a="data-id"){const r=TC(n,a);return r?r.getAttribute(a):null}new Date().valueOf();function RC(n,a){const{api:r}=a;function l(d,m){const p=a.getPanel(),v=p.selected,g=m.ctrlKey||m.metaKey,w=m.shiftKey;let y;const b=v?.[0]?r.getFile(v[0]):null;v?.length?v.length>1?y=a.menuOptions("multiselect"):y=a.menuOptions(b.type,b):y=a.menuOptions("body");const j=`${g?"ctrl+":""}${w?"shift+":""}${d}`,C=y?y.find(T=>T.hotkey?.toLowerCase()===j):!1,N=a.performAction;if(C)switch(j){case"ctrl+c":N("copy");break;case"ctrl+x":N("move");break;case"ctrl+v":N("paste",b);break;case"delete":N("delete");break;case"ctrl+r":m.preventDefault(),N("rename",b);break;case"ctrl+d":m.preventDefault(),N("download",b);break;default:C.handler?.({context:b})}switch(d){case"enter":{if(g||w)break;const{_crumbs:T,_selectNavigation:k}=p;if(k){const E=kC(T);if(E){const R=up(E,T);r.exec("set-path",{id:E,selected:[R]})}}else if(v.length===1){const E=r.getFile(v[0]);E&&r.exec(E.type==="folder"?"set-path":"open-file",{id:E.id})}break}case"arrowup":case"arrowleft":{const{_files:T,_selected:k,path:E,_selectNavigation:R}=p;let $;if(k.length){const F=k.at(0).id,q=T.findIndex(z=>z.id===F);if(q!==-1){const z=q-1;T[z]?$=T[z].id:E!=="/"&&!(g||w)&&r.exec("select-file",{type:"navigation"})}}else{if(R)break;if(E!=="/"){r.exec("select-file",{type:"navigation"});break}$=T.at(0)?.id}$&&r.exec("select-file",{id:$,toggle:g,range:w});break}case"arrowdown":case"arrowright":{const{_files:T,_selected:k,path:E,_selectNavigation:R}=p;let $;if(k.length){const F=k.at(-1).id,q=T.findIndex(z=>z.id===F);if(q!==-1){const z=q+1;T[z]&&($=T[z].id)}}else{if(E!=="/"&&!R){r.exec("select-file",{type:"navigation"});break}$=T.at(0)?.id}$&&r.exec("select-file",{id:$,toggle:g,range:w});break}}}function c(d){const m=d.code.replace("Key","").toLowerCase();l(m,d),m=="tab"&&setTimeout(()=>{const p=document.activeElement;p.className.indexOf("table")!=-1&&r.exec("set-active-panel",{panel:+EC(p,"data-panel")})})}return n.addEventListener("keydown",c),{destroy:()=>{n.removeEventListener("keydown",c)}}}function DC(n,a="data-id"){let r=n;for(!r.tagName&&n.target&&(r=n.target);r;){if(r.getAttribute&&r.getAttribute(a))return r;r=r.parentNode}return null}function _C(n,a="data-id"){const r=n.getAttribute(a);return r?LC(r):null}function LC(n){if(n.startsWith(":"))return n.substring(1);const a=n*1;return isNaN(a)?n:a}function zC(){return{detect:()=>!0,addEvent:function(n,a,r){return n.addEventListener(a,r),()=>n.removeEventListener(a,r)},addGlobalEvent:function(n,a){return document.addEventListener(n,a),()=>document.removeEventListener(n,a)},getTopNode:function(){return window.document.body}}}var IC=zC();new Date().valueOf();function Tw(n){const[a,r]=u.useState(n),l=u.useRef(n);return u.useEffect(()=>{if(l.current!==n){if(Array.isArray(l.current)&&Array.isArray(n)&&l.current.length===0&&n.length===0)return;l.current=n,r(n)}},[n]),[a,r]}function OC(n,a,r){const[l,c]=u.useState(()=>a);return n||console.warn(`Writable ${r} is not defined`),u.useEffect(()=>n?n.subscribe(m=>{c(()=>m)}):void 0,[n]),l}function nt(n,a){const r=n.getState(),l=n.getReactiveState();return OC(l[a],r[a],a)}function BC(n,a){const r=u.useRef(a);r.current=a;const[l,c]=u.useState(1);return u.useEffect(()=>n.subscribe(m=>{r.current=m,c(p=>p+1)}),[n]),[r.current,l]}function ps(n,a){const r=n.getState(),l=n.getReactiveState();return BC(l[a],r[a])}function Ew(n){const a={};return n.split(";").forEach(r=>{const[l,c]=r.split(":");if(c){let d=l.trim();d.indexOf("-")&&(d=d.replace(/-([a-z])/g,(m,p)=>p.toUpperCase())),a[d]=c.trim()}}),a}function Rw(n){let a=n,r=[];return{subscribe:p=>{r.push(p),p(a)},unsubscribe:p=>{r=r.filter(v=>v!==p)},set:p=>{a=p,r.forEach(v=>v(a))},update:p=>{a=p(a),r.forEach(v=>v(a))}}}function Kx(n,a,r){function l(c){const d=DC(c);if(!d)return;const m=_C(d);if(typeof a=="function")return a(m,c);let p,v=c.target;for(;v!=d;){if(p=v.dataset?v.dataset.action:null,p&&a[p]){a[p](m,c);return}v=v.parentNode}a[r]&&a[r](m,c)}return IC.addEvent(n,r,l)}function FC(n,a){const r=[Kx(n,a,"click")];return a.dblclick&&r.push(Kx(n,a.dblclick,"dblclick")),()=>{r.forEach(l=>l())}}function Dw(n,a){return n.map((r,l)=>{const c=a(r,l);return r.data&&r.data.length&&(c.data=Dw(r.data,a)),c}).filter(Boolean)}function _w(n,a){const r=[];return n.forEach(l=>{if(l.data){const c=_w(l.data,a);c.length&&r.push({...l,data:c})}else a(l)&&r.push(l)}),r}function PC(n){return Dw(n,(a,r)=>{const l={...a,id:a.id||np()};return l.type&&(l.comp=l.type),l.comp==="separator"&&n[r-1]?.comp==="separator"?null:l})}const Lw={};function HC(n){return Lw[n]||n}function $C(n,a){Lw[n]=a}function UC({onClick:n,onShow:a,option:r}){const l=u.useRef(null),c=u.useCallback(()=>{a(r.data?r.id:!1,l.current)},[a,r]),d=u.useCallback(p=>{if(r.data){p.stopPropagation(),a(r.id,l.current);return}n(p)},[n,a,r]),m=u.useMemo(()=>r&&r.comp?HC(r.comp):null,[r]);return s.jsxs("div",{ref:l,className:`wx-cDCz9rZQ wx-option ${r.css||""} ${r.disabled?"wx-disabled":""}`,"data-id":zn(r.id),onMouseEnter:c,onClick:d,children:[r.icon?s.jsx("i",{className:`wx-cDCz9rZQ wx-icon ${r.icon}`}):null,r.comp?m?s.jsx(m,{item:r,option:r}):null:s.jsxs("span",{className:"wx-cDCz9rZQ wx-value",children:[" ",r.text," "]}),r.subtext?s.jsx("span",{className:"wx-cDCz9rZQ wx-subtext",children:r.subtext}):null,r.data?s.jsx("i",{className:"wx-cDCz9rZQ wx-sub-icon wxi-angle-right"}):null]})}function dp({options:n,left:a=0,top:r=0,at:l="bottom",parent:c=null,mount:d=null,context:m=null,css:p="",onClick:v,onCancel:g}){const[w,y]=u.useState(-1e4),[b,j]=u.useState(-1e4),[C,N]=u.useState(20),[T,k]=u.useState(),E=u.useRef(null),[R,$]=u.useState(!1),[F,q]=u.useState(null),z=u.useCallback(()=>{const le=gw(E.current,c,l,a,r);le&&(y(le.x),j(le.y),k(le.width));let Y=le?.z??20;const O=c?R1(c):[];let Z=0;for(const X of O){const D=parseInt(getComputedStyle(X).zIndex,10);D>Z&&(Z=D)}Z>=Y&&(Y=Z+1),N(Y)},[c,l,a,r]);u.useEffect(()=>{d&&d(z)},[]);const L=u.useCallback(()=>{$(!1)},[]),ie=u.useCallback((le,Y)=>{$(le),q(Y)},[]),V=u.useMemo(()=>PC(n),[n]);u.useEffect(()=>{z()},[c,z]);const ne=u.useRef(v),Q=u.useRef(g),J=u.useRef(c);return u.useEffect(()=>{ne.current=v},[v]),u.useEffect(()=>{Q.current=g},[g]),u.useEffect(()=>{J.current=c},[c]),u.useEffect(()=>{if(!E.current)return;function le(Y){Q.current?Q.current(Y):ne.current&&ne.current({action:null,option:null})}return ii(E.current,{callback:le,modal:!0,parent:()=>J.current}).destroy},[]),s.jsx("div",{ref:E,"data-wx-menu":"true",className:`wx-XMmAGqVx wx-menu ${p}`,style:{position:"absolute",top:b+"px",left:w+"px",width:T,zIndex:C},onMouseLeave:L,children:V.map(le=>s.jsxs(u.Fragment,{children:[le.comp==="separator"?s.jsx("div",{className:"wx-XMmAGqVx wx-separator"}):s.jsx(UC,{option:le,onShow:ie,onClick:Y=>{if(!le.data&&!Y.defaultPrevented){const O={context:m,action:le,option:le,event:Y};le.handler&&le.handler(O),v&&v(O),Y.stopPropagation()}}}),le.data&&R===le.id?s.jsx(dp,{css:p,options:le.data,at:"right-overlap",parent:F,context:m,onClick:v,onCancel:g}):null]},le.id))})}const zw=u.forwardRef(function(n,a){const{options:r,at:l="bottom",resolver:c=null,dataKey:d="contextId",filter:m=null,css:p="",children:v,onClick:g}=n,[w,y]=u.useState(null),[b,j]=u.useState(null),[C,N]=u.useState(0),[T,k]=u.useState(0),E=u.useRef(null),R=u.useMemo(()=>`data-${d.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,[d]),$=u.useMemo(()=>w!==null&&m?_w(r,L=>m(L,w)):r,[w,m,r]);function F(L){j(null),g&&g(L)}function q(L){if(E.current===L){E.current=null;return}j(null),g&&g({action:null,option:null})}const z=u.useCallback((L,ie)=>{if(!L){j(null);return}if(L.defaultPrevented)return;const V=L.target;if(V&&V.dataset&&V.dataset.menuIgnore)return;if(b&&b===V){j(null),L.preventDefault();return}N(L.clientX+1),k(L.clientY+1);let ne=typeof ie<"u"?ie:eu(V,R);c&&(ne=c(ne,L),!ne)||(y(ne),j(V),E.current=L.nativeEvent||L,L.preventDefault())},[b,R,c]);return u.useImperativeHandle(a,()=>({show:z}),[z]),s.jsxs(s.Fragment,{children:[v?s.jsx("span",{onClick:z,"data-menu-ignore":"true",children:typeof v=="function"?v():v}):null,b?s.jsx(sp,{children:s.jsx(dp,{css:p,at:l,top:T,left:C,parent:b,context:w,onClick:F,onCancel:q,options:$},b)}):null]})}),qC=u.forwardRef(function(n,a){const{options:r,at:l="bottom",css:c="",children:d,onClick:m}=n,[p,v]=u.useState(null),g=u.useRef(null);function w(C){v(null),m&&m(C)}function y(C){if(g.current===C){g.current=null;return}v(null),m&&m({action:null,option:null})}const b=u.useCallback(C=>{v(C.target),g.current=C.nativeEvent||C,C.preventDefault()},[]);u.useImperativeHandle(a,()=>({show:b}),[b]);function j(C){let N=C.target;for(;!N.dataset.menuIgnore;)v(N),N=N.parentNode}return s.jsxs(s.Fragment,{children:[s.jsx("span",{onClick:j,"data-menu-ignore":"true",children:d}),p?s.jsx(sp,{children:s.jsx(dp,{css:c,at:l,parent:p,options:r,onClick:w,onCancel:y})}):null]})}),GC=u.forwardRef(function(n,a){const{options:r,at:l="bottom",resolver:c=null,dataKey:d="contextId",filter:m=null,css:p="",children:v,onClick:g}=n,w=u.useRef(null),y=u.useCallback((b,j)=>{w.current.show(b,j)},[]);return u.useImperativeHandle(a,()=>({show:y}),[y]),s.jsxs(s.Fragment,{children:[v?s.jsx("span",{onContextMenu:y,"data-menu-ignore":"true",children:v}):null,s.jsx(zw,{css:p,at:l,options:r,resolver:c,dataKey:d,filter:m,ref:w,onClick:g})]})}),VC={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 YC=class{constructor(a,r,l,c,d){this.setFiles=a,this.setReady=r,this.setSignal=l,this.setDrag=c,d&&d.length&&this.setFiles(d)}open(a){this.setSignal(["click",a||{}])}getState(){let a="server";const r=this.files;for(let l=0;l<r.length;l++){if(r[l].status==="client")return"client";r[l].status==="error"&&(a="error")}return a}droparea(a,r){r=r||{};const l=()=>{r.dragEnter&&r.dragEnter(),this.setDrag(!0)},c=()=>{r.dragLeave&&r.dragLeave(),this.setDrag(!1)},d=p=>{p.preventDefault()},m=p=>{p.preventDefault(),this.setDrag(!1),this.setSignal(["drop",r,p]),r.dragLeave&&r.dragLeave(),r.drop&&r.drop()};return a.addEventListener("dragenter",l),a.addEventListener("dragleave",c),a.addEventListener("dragover",d,!0),a.addEventListener("drop",m,!0),()=>{a.removeEventListener("dragenter",l),a.removeEventListener("dragleave",c),a.removeEventListener("dragover",d,!0),a.removeEventListener("drop",m,!0)}}updateFile(a,r){const l=this.files.findIndex(d=>d.id===a);if(l===-1)return;const c=[...this.files];return c[l]={...c[l],...r},this.files=c,this.setFiles(this.files),this.files[l]}deleteFile(a){this.files=this.files.filter(r=>r.id!==a),this.setFiles(this.files)}addFile(a,r){r?this.files=[...this.files,a]:this.files=[a],this.setFiles(this.files)}deleteAll(){this.files=[],this.setFiles(this.files)}};function Iw(n){const[a,r]=u.useState([]),[l,c]=u.useState(Promise.resolve(null)),[d,m]=u.useState(null),[p,v]=u.useState(!1),g=u.useRef();return g.current||(g.current=new YC(r,c,m,v,n)),g.current.files=a,g.current.ready=l,g.current.signal=d,g.current.drag=p,g.current}function WC(n,a){{if(n){const r=n.getGroup(a);if(r)return r}return nu(VC).getGroup(a)}}const KC=()=>Math.random().toString(36).substr(2,9),QC=({data:n,accept:a="",multiple:r=!0,folder:l=!1,uploadURL:c="",apiOnly:d=!1,disabled:m=!1,children:p,onChange:v,onUpload:g})=>{const w=u.useRef(null),y=u.useRef(null),[b,j]=u.useState({}),C=Iw(),N=n||C,T=u.useContext(On.i18n),k=WC(T,"uploader");u.useEffect(()=>{w.current&&l&&(w.current.webkitdirectory=!0)},[l]),u.useEffect(()=>{if(!d&&y.current&&!m)return N.droparea(y.current)},[d,m,y]);const E=V=>{const ne=new FormData;return ne.append("upload",V.file),fetch(c,{method:"POST",body:ne}).then(Q=>Q.json()).then(Q=>({id:V.id,...Q}),()=>({id:V.id,status:"error"})).catch(Q=>(console.log(Q),{id:V.id,status:"error"}))},R=(V,ne)=>{const Q=N.updateFile(V,ne),J={...Q,status:N.getState()};Q&&Q.uploaded&&Q.uploaded(J),g&&g(J),Q.temp&&N.deleteFile(Q.id)},$=V=>{if(!V)return;const ne=typeof c=="function"?c(V):E(V);N.setReady(ne.then(Q=>{Q.status=Q.status||"server",R(V.id,Q)}).catch(Q=>{R(V.id,{status:"error",error:Q})}))},F=(V,ne)=>{const Q={...ne||b,id:KC(),status:"client",name:V.name,file:V};Q.selected&&Q.selected(Q),v&&v(Q),N.addFile(Q,r),$(Q),w.current&&(w.current.value="")},q=(V,ne,Q)=>{V.isFile?V.file(J=>{F(J,Q)}):V.isDirectory&&V.createReader().readEntries(J=>{J.forEach(le=>{q(le,ne+le.name+"/",Q)})})},z=V=>{Array.from(V.target.files).forEach(ne=>F(ne))},L=(V,ne)=>{Array.from(V.dataTransfer.items).forEach(Q=>{const J=Q.webkitGetAsEntry();J&&q(J,"",ne)})},ie=()=>{w.current&&w.current.click()};return u.useEffect(()=>{if(N.signal){const[V,ne,Q]=N.signal;j(ne),V==="click"?ie():V==="drop"&&L(Q,ne),N.setSignal(null)}},[N.signal]),d?s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:z,accept:a,multiple:r,disabled:m}),p]}):s.jsxs("div",{className:`wx-at1A8tb8 wx-label ${N.drag?"wx-active":""} ${m?"wx-disabled":""}`,ref:y,children:[s.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:z,accept:a,multiple:r,disabled:m}),p||s.jsx("div",{className:"wx-at1A8tb8 wx-dropzone",children:s.jsxs("span",{children:[k("Drop files here or")," ",s.jsx("span",{className:"wx-at1A8tb8 wx-action",onClick:ie,children:k("select files")})]})})]})};new Date().valueOf();function XC(n,a){if(Object.keys(n).length!==Object.keys(a).length)return!1;for(const r in a){const l=n[r],c=a[r];if(!mf(l,c))return!1}return!0}function mf(n,a){if(typeof n=="number"||typeof n=="string"||typeof n=="boolean"||n===null)return n===a;if(typeof n!=typeof a||(n===null||a===null)&&n!==a||n instanceof Date&&a instanceof Date&&n.getTime()!==a.getTime())return!1;if(typeof n=="object")if(Array.isArray(n)&&Array.isArray(a)){if(n.length!==a.length)return!1;for(let r=n.length-1;r>=0;r--)if(!mf(n[r],a[r]))return!1;return!0}else return XC(n,a);return n===a}function _h(n){if(typeof n!="object"||n===null)return n;if(n instanceof Date)return new Date(n);if(n instanceof Array)return n.map(_h);const a={};for(const r in n)a[r]=_h(n[r]);return a}var Ow=2,ZC=class{constructor(n){n&&(this._writable=n.writable,this._async=n.async),this._values={},this._state={}}setState(n,a=0){const r={};return this._wrapProperties(n,this._state,this._values,"",r,a),r}getState(){return this._values}getReactive(){return this._state}_wrapProperties(n,a,r,l,c,d){for(const m in n){const p=a[m],v=r[m],g=n[m];if(p&&(v===g&&typeof g!="object"||g instanceof Date&&v instanceof Date&&v.getTime()===g.getTime()))continue;const w=l+(l?".":"")+m;p?(p.__parse(g,w,c,d)&&(r[m]=g),d&Ow?c[w]=p.__trigger:p.__trigger()):(g&&g.__reactive?a[m]=this._wrapNested(g,g,w,c):a[m]=this._wrapWritable(g),r[m]=g),c[w]=c[w]||null}}_wrapNested(n,a,r,l){const c=this._wrapWritable(n);return this._wrapProperties(n,c,a,r,l,0),c.__parse=(d,m,p,v)=>(this._wrapProperties(d,c,a,m,p,v),!1),c}_wrapWritable(n){const a=[],r=function(){for(let l=0;l<a.length;l++)a[l](n)};return{subscribe:l=>(a.push(l),this._async?setTimeout(l,1,n):l(n),()=>{const c=a.indexOf(l);c>=0&&a.splice(c,1)}),__trigger:()=>{a.length&&(this._async?setTimeout(r,1):r())},__parse:function(l){return n=l,!0}}}},JC=class{constructor(n,a,r,l){typeof n=="function"?this._setter=n:this._setter=n.setState.bind(n),this._routes=a,this._parsers=r,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(c=>{c.in.forEach(d=>{const m=this._triggers.get(d)||[];m.push(c),this._triggers.set(d,m)}),c.out.forEach(d=>{const m=this._sources.get(d)||{};c.in.forEach(p=>m[p]=!0),this._sources.set(d,m)})}),this._routes.forEach(c=>{c.length=Math.max(...c.in.map(d=>Bw(d,this._sources,1)))}),this._bus=l}init(n){const a={};for(const r in n)if(this._prev[r]!==n[r]){const l=this._parsers[r];a[r]=l?l(n[r]):n[r]}this._prev=this._prev?{...this._prev,...n}:{...n},this.setState(a),this._bus&&this._bus.exec("init-state",a)}setStateAsync(n){const a=this._setter(n,Ow);return this._async?Object.assign(this._async.signals,a):this._async={signals:a,timer:setTimeout(this._applyState.bind(this),1)},a}_applyState(){const n=this._async;if(n){this._async=null,this._triggerUpdates(n.signals,[]);for(const a in n.signals){const r=n.signals[a];r&&r()}}}setState(n,a=[]){const r=this._setter(n);return this._triggerUpdates(r,a),r}_triggerUpdates(n,a){const r=Object.keys(n),l=!a.length;a=a||[];for(let c=0;c<r.length;c++){const d=r[c],m=this._triggers.get(d);m&&m.forEach(p=>{a.indexOf(p)==-1&&a.push(p)})}l&&this._execNext(a)}_execNext(n){for(;n.length;){n.sort((r,l)=>r.length<l.length?1:-1);const a=n[n.length-1];n.splice(n.length-1),a.exec(n)}}};function Bw(n,a,r){const l=a.get(n);if(!l)return r;const c=Object.keys(l).map(d=>Bw(d,a,r+1));return Math.max(...c)}var ek=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(n,a,r){let l=this._handlers[n];l?r&&r.intercept?l.unshift(a):l.push(a):l=this._handlers[n]=[a],r&&r.tag&&this._tag.set(a,r.tag)}intercept(n,a,r){this.on(n,a,{...r,intercept:!0})}detach(n){for(const a in this._handlers){const r=this._handlers[a];for(let l=r.length-1;l>=0;l--)this._tag.get(r[l])===n&&r.splice(l,1)}}async exec(n,a){const r=this._handlers[n];if(r)for(let l=0;l<r.length;l++){const c=r[l](a);if(c===!1||c&&c.then&&await c===!1)return}return this._nextHandler&&await this._nextHandler.exec(n,a),a}setNext(n){return this._nextHandler=n}};function tk(n){return a=>a[n]}function nk(n){return(a,r)=>a[n]=r}function Ur(n,a){return(a.getter||tk(a.id))(n)}function nh(n,a,r){return(a.setter||nk(a.id))(n,r)}function ak(n,a){const r=document.createElement("a");r.href=URL.createObjectURL(n),r.download=a,document.body.appendChild(r),r.click(),document.body.removeChild(r)}function $r(n,a){let r=Ur(n,a)??"";return a.template?r=a.template(r,n,a):a.optionsMap&&(Array.isArray(r)?r=r.map(l=>a.optionsMap.get(l)).join(", "):r=a.optionsMap.get(r)),typeof r>"u"?"":r+""}function sk(n,a){const r=/\n|"|;|,/;let l="";const c=a.rows||`
12
+ `,d=a.cols||" ",m=n._columns,p=n.flatData;a.header!==!1&&m[0].header&&(l=Qx("header",m,l,d,c));for(let v=0;v<p.length;v++){const g=[];for(let w=0;w<m.length;w++){let y=$r(p[v],m[w]);r.test(y)&&(y='"'+y.replace(/"/g,'""')+'"'),g.push(y)}l+=(l?c:"")+g.join(d)}return a.footer!==!1&&m[0].footer&&(l=Qx("footer",m,l,d,c)),l}function Qx(n,a,r,l,c){const d=/\n|"|;|,/;for(let m=0;m<a[0][n].length;m++){const p=[];for(let v=0;v<a.length;v++){let g=(a[v][n][m].text||"")+"";d.test(g)&&(g='"'+g.replace(/"/g,'""')+'"'),p.push(g)}r+=(r?c:"")+p.join(l)}return r}const ik="portrait",rk=100,lk="a4",ok={a3:{width:11.7,height:16.5},a4:{width:8.27,height:11.7},letter:{width:8.5,height:11}};function ck(n,a){const r=[];let l=[],c=0;const d=n.filter(p=>!p.hidden),m=uk(a);return d.forEach((p,v)=>{c+p.width<=m?(c+=p.width,l.push(p)):(l.length&&r.push(l),l=[p],c=p.width),v===d.length-1&&l.length&&r.push(l)}),r}function Xx(n,a,r){const l=[];return n.forEach((c,d)=>{const m=c[a];for(let p=0;p<r.length;p++){l[p]||(l[p]=[]);const v={...m[p]};if(l[p][d]!==null){if(!d&&!v.rowspan&&!v.colspan){let g=1,w=n[d+g][a][p],y=v.width;for(;!w.rowspan&&!w.colspan;)g++,w=n[d+g][a][p],y+=w.width;v.colspan=g,v.width=y,v.height=r[p]}if(l[p].push(v),!v.collapsed&&v.colspan>1){let g=v.colspan-1;if(v.colspan+d>n.length){const w=v.colspan-(v.colspan+d-n.length);v.colspan=w,v.width=n.slice(d,d+g+1).reduce((y,b)=>y+b.width,0),w>1&&(g=w-1)}for(let w=0;w<g;w++)l[p].push(null)}if(v.rowspan>1){const g=v.rowspan;for(let w=1;w<g;w++)l[p+w]||(l[p+w]=[]),l[p+w].push(null)}}}if(c.collapsed)for(let p=0;p<l.length;p++){const v=l[p],g=v[d];if(g&&g.collapsed){if(v[d]=null,!p)break}else{const w=g||v.findLast(y=>y?.colspan>=1);w&&(w.colspan=w.colspan-1,w.width=w.width-c.width)}}}),l.map(c=>c.filter(d=>d&&d.colspan!==0))}function uk(n){const{mode:a,ppi:r,paper:l}=n,{width:c,height:d}=ok[l];return dk(a==="portrait"?c:d,r)}function dk(n,a){return n*a}function fk(n={}){const{mode:a,ppi:r,paper:l}=n;return{mode:a||ik,ppi:r||rk,paper:l||lk}}function Fw(n,a){return n.flexgrow?`min-width:${a}px;width:auto`:`width:${n.width}px; max-width:${n.width}px; height:${n.height}px`}function mk(n,a,r){let l=n[r.id];if(r.filter.type==="richselect"&&l){const c=r.filter.config?.options||a.find(({id:d})=>d==r.id).options;c&&(l=c.find(({id:d})=>d==l).label)}return l??""}const Zx=["resize-column","hide-column","update-cell"],hk=["delete-row","update-row","update-cell"],pk=["move-item"],gk=["resize-column","move-item"];class vk{undo=[];redo=[];progress={};in;getState;setState;_previousValues={};constructor(a,r,l){this.in=a,this.getState=r,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:r}=a,{data:l}=this.getPrev(),c=l.findIndex(d=>d.id===r);return{action:"add-row",data:{id:r,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:r,column:l}=a,c=this.getRow(r),d=this.getColumn(l),m=Ur(c,d);return mf(m,a.value)?null:{action:"update-cell",data:{id:r,column:l,value:m},source:{action:"update-cell",data:a}}}},"update-row":{handler:a=>{const{id:r,row:l}=a,c=this.getRow(r);for(const d in l)Object.keys(c).includes(d)||(c[d]=void 0);return{action:"update-row",data:{id:r,row:c},source:{action:"update-row",data:a}}}},"copy-row":{handler:a=>{const{id:r}=a,{data:l}=this.getState(),c=l.findIndex(m=>m.id===r),d=l[c];return{action:"delete-row",data:{id:r},source:{action:"add-row",data:{id:r,row:d,before:c<l.length-1?l[c+1].id:void 0}}}}},"resize-column":{handler:a=>{const{id:r,width:l}=a,c=this.getColumn(r),{_sizes:d}=this.getState();return{action:"resize-column",data:{id:r,width:c.width??d.columnWidth},source:{action:"resize-column",data:{id:r,width:l}}}}},"hide-column":{handler:a=>{const{id:r}=a,l=this.getColumn(r);return{action:"hide-column",data:{id:r,mode:l.hidden},source:{action:"hide-column",data:a}}}},"collapse-column":{handler:a=>{const{id:r,row:l,mode:c}=a;return{action:"collapse-column",data:{id:r,row:l,mode:typeof c=="boolean"?!c:c},source:{action:"collapse-column",data:a}}}},"move-item":{handler:a=>{const{id:r,target:l,mode:c}=a,{flatData:d}=this.getPrev(),m=d.findIndex(p=>p.id===r);return{action:"move-item",data:{id:r,target:d[m+(m?-1:1)].id,mode:m?"after":"before"},source:{action:"move-item",data:{id:r,target:l,mode:c}}}}},"open-row":{handler:a=>{const{id:r,nested:l}=a;return{action:"close-row",data:{id:r,nested:l},source:{action:"open-row",data:a}}}},"close-row":{handler:a=>{const{id:r,nested:l}=a;return{action:"open-row",data:{id:r,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 r in a)this.in.intercept(r,l=>{if(!(l.eventSource==="undo"||l.eventSource==="redo"||l.skipUndo)){if(gk.includes(r)){(l.inProgress&&!this.progress[r]||typeof l.inProgress!="boolean")&&(pk.includes(r)&&this.setPrev("flatData"),Zx.includes(r)&&this.setPrev("columns")),this.progress[r]=l.inProgress;return}hk.includes(r)&&this.setPrev("data"),Zx.includes(r)&&this.setPrev("columns")}}),this.in.on(r,l=>{if(l.eventSource==="undo"||l.eventSource==="redo"||l.skipUndo||l.inProgress)return;const c=a[r].handler(l);c&&this.addToHistory(c)})}setPrev(a){this._previousValues[a]=_h(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:r}=this.getPrev();return this.getState().tree?this.getTreeRow(r,a):r.find(l=>l.id===a)}getTreeRow(a,r){for(let l=0;l<a.length;l++){if(a[l].id===r)return a[l];if(a[l].data){const c=this.getTreeRow(a[l].data,r);if(c)return c}}return null}getColumn(a){const{columns:r}=this.getPrev();return r.find(l=>l.id===a)}}function Pw(n,a){return typeof n>"u"||n===null?-1:typeof a>"u"||a===null?1:n===a?0:n>a?1:-1}function xk(n,a){return-Pw(n,a)}function yk(n,a){if(typeof a.sort=="function")return function(l,c){const d=a.sort(l,c);return n==="asc"?d:-d};const r=n==="asc"?Pw:xk;return function(l,c){return r(Ur(l,a),Ur(c,a))}}function wk(n,a){if(!n||!n.length)return;const r=n.map(l=>{const c=a.find(d=>d.id==l.key);return yk(l.order,c)});return n.length===1?r[0]:function(l,c){for(let d=0;d<r.length;d++){const m=r[d](l,c);if(m!==0)return m}return 0}}const Rd=28,bk=20;function Sk(){if(typeof document>"u")return"willow";const n=document.querySelector('[class^="wx"][class$="theme"]');return n?n.className.substring(3,n.className.length-6):"willow"}function af(n,a,r,l,c){const d=document.createElement("div"),m=document.createElement("div"),p=document.body;c=c?`${c}px`:"auto";let v,g;m.className=a,d.classList.add(`wx-${r}-theme`),d.style.cssText=`height:auto;position:absolute;top:0px;left:100px;overflow:hidden;width=${c};white-space:nowrap;`,d.appendChild(m),p.appendChild(d),typeof n!="object"&&(n=[n]);for(let w=0;w<n.length;w++){m.innerText=n[w]+"";const y=d.getBoundingClientRect(),b=Math.ceil(y.width)+(l&&l.length?l[w]:0),j=Math.ceil(y.height);v=Math.max(v||0,b),g=Math.max(g||0,j)}return d.remove(),{width:v,height:g}}function Jx(n,a,r,l,c){const d=[];for(let m=0;m<n.length;m++){const p=n[m][a],v=p.length;for(let g=0;g<v;g++){const{text:w,vertical:y,collapsed:b,rowspan:j,css:C}=p[g];if(!w){d[g]=Math.max(d[g]||0,l);continue}let N=0;if(y&&!b){let T=`wx-measure-cell-${a}`;if(T+=C?` ${C}`:"",N=af(w,T,c).width,(j>1||!p[g+1])&&r>g+1){const k=j||r-g,E=d.slice(g,g+k).reduce((R,$)=>R+$,0);if(E<N){const R=Math.ceil((N-E)/k);for(let $=g;$<g+k;$++)d[$]=(d[$]||l)+R}continue}}d[g]=Math.max(d[g]||l,N)}}return d}function jk(n,a,r){const l=[],c=[];let d="wx-measure-cell-body";d+=n.css?` ${n.css}`:"";for(let m=0;m<a.length;m++){const p=a[m],v=$r(p,n);v&&(l.push(v),n.treetoggle?c.push(a[m].$level*Rd+(a[m].$count?Rd:0)+(n.draggable?Rd:0)):n.draggable&&c.push(Rd))}return af(l,d,r,c).width}function Ck(n,a){const r="wx-measure-cell-header",l=n.sort?bk:0;let c=n.header;if(typeof c=="string")return af(c,r,a).width+l;let d;Array.isArray(c)||(c=[c]);for(let m=0;m<c.length;m++){const p=c[m],v=typeof p=="string"?p:p.text,g=r+(typeof p=="string"?"":` ${p.css}`);let w=af(v,g,a).width;m===c.length-1&&(w+=l),d=Math.max(d||0,w)}return d}const kk={text:(n,a)=>n?n.toString().toLowerCase().indexOf(a.toLowerCase())!==-1:!a,richselect:(n,a)=>typeof a!="number"&&!a?!0:n==a,datepicker:(n,a)=>a?n&&Nk(n,a):!0,multiselect:(n,a)=>!a||a?.length===0?!0:Array.isArray(n)?n?.some(r=>a.includes(r)):n&&a.includes(n)};function Hw(n){return kk[n]}function Ak(n,a){const r=[];for(const l in n){const c=a.find(v=>v.id==l),{config:d,type:m}=c.header.find(v=>v.filter).filter,p=n[l];r.push(v=>{const g=Ur(v,c);return d?.handler?d.handler(g,p):Hw(m)(g,p)})}return l=>{for(let c=0;c<r.length;c++)if(!r[c](l))return!1;return!0}}function Nk(n,a){return n.getFullYear()===a.getFullYear()&&n.getMonth()===a.getMonth()&&n.getDate()===a.getDate()}let Mk=class extends ZC{in;_router;_branches;_xlsxWorker;_historyManager;constructor(a){super({writable:a,async:!1});const r={rowHeight:37,columnWidth:160,headerHeight:36,footerHeight:36};this._router=new JC(super.setState.bind(this),[{in:["columns","sizes","_skin"],out:["_columns","_sizes"],exec:c=>{const{columns:d,sizes:m,_skin:p}=this.getState(),v=this.copyColumns(d),g=v.reduce((b,j)=>Math.max(j.header.length,b),0),w=v.reduce((b,j)=>Math.max(j.footer.length,b),0);v.forEach(this.setCollapsibleColumns);const y=this.normalizeSizes(v,m,g,w,p);for(let b=0;b<v.length;b++)this.normalizeColumns(v,b,"header",g,y),this.normalizeColumns(v,b,"footer",w,y);this.setState({_columns:v,_sizes:y},c)}},{in:["data","tree","_filterIds"],out:["flatData","_rowHeightFromData"],exec:c=>{const{data:d,tree:m,dynamic:p,_filterIds:v}=this.getState(),g=v&&new Set(v),w=m?this.flattenRows(d,[],v):g?d.filter(b=>g.has(b.id)):d,y=!p&&w.some(b=>b.rowHeight);this.setState({flatData:w,_rowHeightFromData:y},c)}}],{sizes:c=>({...r,...c})});const l=this.in=new ek;l.on("close-editor",({ignore:c})=>{const{editor:d}=this.getState();d&&(c||l.exec("update-cell",d),this.setState({editor:null}))}),l.on("open-editor",({id:c,column:d})=>{let m=this.getState().editor;m&&l.exec("close-editor",{});const p=this.getRow(c),v=d?this.getColumn(d):this.getNextEditor(p);if(v?.editor){let g=v.editor;if(typeof g=="function"&&(g=g(p,v)),!g)return;m={column:v.id,id:c,value:Ur(p,v)??"",renderedValue:$r(p,v),type:g.type||g},typeof g=="object"&&g.config&&(m.config=g.config,g.config.options&&(m.options=g.config.options)),v.options&&!m.options&&(m.options=v.options),this.setState({editor:m})}}),l.on("editor",({value:c})=>{let d=this.getState().editor;if(d){d={...d},d.value=c;const m=this.getColumn(d.column),p={...this.getRow(d.id)};nh(p,m,c),d.renderedValue=$r(p,m),this.setState({editor:d})}}),l.on("add-row",c=>{const d=this.getState();let{data:m}=d;const{select:p,_filterIds:v}=d,{row:g,before:w,after:y,select:b}=c;if(c.id=g.id=c.id||g.id||Dd(),w||y){const C=w||y,N=m.findIndex(T=>T.id===C);m=[...m],m.splice(N+(y?1:0),0,c.row)}else m=[...m,c.row];const j={data:m};v&&(j._filterIds=[...v,c.id]),this.setState(j),!(typeof b=="boolean"&&!b)&&(b||p)&&l.exec("select-row",{id:g.id,show:!0})}),l.on("delete-row",c=>{const{data:d,selectedRows:m,focusCell:p,editor:v}=this.getState(),{id:g}=c,w={data:d.filter(y=>y.id!==g)};this.isSelected(g)&&(w.selectedRows=m.filter(y=>y!==g)),v?.id===g&&(w.editor=null),this.setState(w),p?.row===g&&this.in.exec("focus-cell",{eventSource:"delete-row"})}),l.on("update-cell",c=>{const d=this.getState();let{data:m}=d;m=[...m];const{tree:p}=d,{id:v,column:g,value:w}=c,y=this.getColumn(g);if(p){const b={...this._branches[v]};nh(b,y,w);const j=this.updateTreeRow(b);b.$parent===0&&(m=j)}else{const b=m.findIndex(C=>C.id===v),j={...m[b]};nh(j,y,w),m[b]=j}this.setState({data:m})}),l.on("update-row",c=>{let{data:d}=this.getState();const{id:m,row:p}=c,v=d.findIndex(g=>g.id===m);d=[...d],d[v]={...d[v],...p},this.setState({data:d})}),l.on("select-row",({id:c,toggle:d,range:m,mode:p,show:v,column:g})=>{const w=this.getState(),{focusCell:y}=w;let{selectedRows:b}=w;if(b.length||(m=d=!1),m){const{data:j}=this.getState();let C=j.findIndex(T=>T.id===b[b.length-1]),N=j.findIndex(T=>T.id===c);C>N&&([C,N]=[N,C]),j.slice(C,N+1).forEach(T=>{this.isSelected(T.id)||b.push(T.id)})}else if(d&&this.isSelected(c)){if(p===!0)return;b=b.filter(j=>j!==c)}else if(d){if(p===!1)return;b.push(c)}else b=[c];this.setState({selectedRows:[...b]}),y?.row!==c&&this.in.exec("focus-cell",{eventSource:"select-row"}),v&&this.in.exec("scroll",{row:c,column:g})}),this.in.on("focus-cell",c=>{const{row:d,column:m,eventSource:p}=c,{_columns:v,split:g}=this.getState();d&&m?(this.setState({focusCell:{row:d,column:m}}),p!=="click"&&((!g.left||v.findIndex(w=>w.id===c.column)>=g.left)&&(!g.right||v.findIndex(w=>w.id===c.column)<v.length-g.right)?this.in.exec("scroll",{row:d,column:m}):this.in.exec("scroll",{row:d}))):this.setState({focusCell:null})}),l.on("resize-column",c=>{const{id:d,auto:m,maxRows:p,inProgress:v}=c;if(v===!1)return;let g=c.width||0;const w=[...this.getState().columns],y=this.getColumn(d);if(m){if(m==="data"||m===!0){const{flatData:b,_skin:j}=this.getState();let C=b.length;p&&(C=Math.min(p,C));const N=b.slice(0,C);g=jk(y,N,j)}if(m==="header"||m===!0){const{_skin:b}=this.getState();g=Math.max(Ck(y,b),g)}}y.width=Math.max(17,g),delete y.flexgrow,this.setState({columns:w})}),l.on("hide-column",c=>{const{id:d,mode:m}=c,p=[...this.getState().columns],v=this.getColumn(d),g=p.reduce((w,y)=>w+(y.hidden?0:1),0);!m||g>1?(v.hidden=!v.hidden,this.setState({columns:p})):c.skipUndo=!0}),l.on("sort-rows",c=>{const{key:d,add:m,sort:p}=c,v=this.getState(),{columns:g,data:w,tree:y}=v;if(p){const E=[...w];E.sort(p),this.setState({data:E});return}const{order:b="asc"}=c;let j=v.sortMarks;const C=Object.keys(j),N=C.length;!m||!N||N===1&&j[d]?j={[d]:{order:b}}:(N===1&&(j[C[0]]={...j[C[0]],index:0}),j={...j,[d]:{order:b,index:typeof m=="number"?m:j[d]?.index??N}});const T=Object.keys(j).sort((E,R)=>j[E].index-j[R].index).map(E=>({key:E,order:j[E].order}));this.setState({sortMarks:j});const k=wk(T,g);if(k){const E=[...w];y?this.sortTree(E,k):E.sort(k),this.setState({data:E})}}),l.on("filter-rows",c=>{const{value:d,key:m,filter:p}=c;if(!Object.keys(c).length){this.setState({filterValues:{},_filterIds:null});return}const v=this.getState(),{data:g,tree:w,_columns:y}=v;let b=v.filterValues;const j={};m&&(b={...b,[m]:d},j.filterValues=b);const C=p??Ak(b,y);let N=[];w?N=this.filterTree(g,C,N):g.forEach(T=>{C(T)&&N.push(T.id)}),j._filterIds=N,this.setState(j)}),l.on("collapse-column",c=>{const{id:d,row:m,mode:p}=c,v=[...this.getState().columns],g=this.getColumn(d).header,w=Array.isArray(g)?g[m]:g;typeof w=="object"&&(w.collapsed=p??!w.collapsed,this.setState({columns:v}))}),l.on("move-item",c=>{const{id:d,inProgress:m}=c;let{target:p,mode:v="after"}=c;const{data:g,flatData:w,tree:y}=this.getState(),b=w.findIndex(N=>N.id===d);let j;if(v==="up"||v==="down"){if(v==="up"){if(b===0)return;j=b-1,v="before"}else if(v==="down"){if(b===w.length-1)return;j=b+1,v="after"}p=w[j]&&w[j].id}else j=w.findIndex(N=>N.id===p);if(b===-1||j===-1||m===!1)return;let C;y||(C=this.moveItem(d,p,g,v)),this.setState({data:y?this.normalizeTreeRows(C):C})}),l.on("copy-row",c=>{const{id:d,target:m,mode:p="after"}=c,v=this.getState(),{flatData:g,_filterIds:w}=v;let{data:y}=v;const b=this.getRow(d);if(!b)return;const j={...b,id:Dd()};c.id=j.id;const C=g.findIndex(T=>T.id===m);if(C===-1)return;y.splice(C+(p==="after"?1:0),0,j),y=[...y];const N={data:y};w&&(N._filterIds=[...w,j.id]),this.setState(N)}),l.on("open-row",c=>{const{id:d,nested:m}=c;this.toggleBranch(d,!0,m)}),l.on("close-row",c=>{const{id:d,nested:m}=c;this.toggleBranch(d,!1,m)}),l.on("export-data",c=>new Promise((d,m)=>{const p=c.format||"csv",v=`${c.fileName||"data"}.${p}`;if(p==="csv"){const g=sk(this.getState(),c.csv||{});c.download!==!1?ak(new Blob(["\uFEFF"+g],{type:"text/csv"}),v):c.result=g,d(!0)}else m()})),l.on("hotkey",({key:c,event:d,isInput:m})=>{switch(c){case"arrowup":{const{flatData:p,focusCell:v,select:g}=this.getState();if(d.preventDefault(),m)return;const w=v?v.column:this._getFirstVisibleColumn()?.id,y=v?this.getPrevRow(v.row)?.id:p[p.length-1]?.id;w&&y&&(this.in.exec("focus-cell",{row:y,column:w,eventSource:"key"}),g&&this.in.exec("select-row",{id:y}));break}case"arrowdown":{const{flatData:p,focusCell:v,select:g}=this.getState();if(d.preventDefault(),m)return;const w=v?v.column:this._getFirstVisibleColumn()?.id,y=v?this.getNextRow(v.row)?.id:p[0]?.id;w&&y&&(this.in.exec("focus-cell",{row:y,column:w,eventSource:"key"}),g&&this.in.exec("select-row",{id:y}));break}case"arrowright":{const{focusCell:p}=this.getState();if(m)return;if(d.preventDefault(),p){const v=this.getNextColumn(p.column,!0)?.id;v&&this.in.exec("focus-cell",{row:p.row,column:v,eventSource:"key"})}break}case"arrowleft":{const{focusCell:p}=this.getState();if(m)return;if(d.preventDefault(),p){const v=this.getPrevColumn(p.column,!0)?.id;v&&this.in.exec("focus-cell",{row:p.row,column:v,eventSource:"key"})}break}case"tab":{const{editor:p,focusCell:v,select:g}=this.getState();if(p){d.preventDefault();const w=p.column;let y=p.id,b=this.getNextEditor(this.getRow(y),this.getColumn(w));if(!b){const j=this.getNextRow(y);j&&(y=j.id,b=this.getNextEditor(j))}b&&(this.in.exec("open-editor",{id:y,column:b.id}),this.in.exec("focus-cell",{row:y,column:b.id,eventSource:"key"}),g&&!this.isSelected(y)&&this.in.exec("select-row",{id:y}))}else v&&this.in.exec("focus-cell",{eventSource:"key"});break}case"shift+tab":{const{editor:p,focusCell:v,select:g}=this.getState();if(p){d.preventDefault();const w=p.column;let y=p.id,b=this.getPrevEditor(this.getRow(y),this.getColumn(w));if(!b){const j=this.getPrevRow(y);j&&(y=j.id,b=this.getPrevEditor(j))}b&&(this.in.exec("open-editor",{id:y,column:b.id}),this.in.exec("focus-cell",{row:y,column:b.id,eventSource:"key"}),g&&!this.isSelected(y)&&this.in.exec("select-row",{id:y}))}else v&&this.in.exec("focus-cell",{eventSource:"key"});break}case"escape":{const{editor:p}=this.getState();p&&(this.in.exec("close-editor",{ignore:p.type!="multiselect"}),this.in.exec("focus-cell",{row:p.id,column:p.column,eventSource:"key"}));break}case"f2":{const{editor:p,focusCell:v}=this.getState();!p&&v&&this.in.exec("open-editor",{id:v.row,column:v.column});break}case"enter":{const{focusCell:p,tree:v}=this.getState();if(!m&&v&&p&&this.getColumn(p.column).treetoggle){const g=this.getRow(p.row);if(!g.data)return;this.in.exec(g.open?"close-row":"open-row",{id:p.row,nested:!0})}break}case"home":{const{editor:p,focusCell:v}=this.getState();if(!p&&v){d.preventDefault();const g=this._getFirstVisibleColumn()?.id;this.in.exec("focus-cell",{row:v.row,column:g,eventSource:"key"})}break}case"ctrl+home":{const{editor:p,focusCell:v,flatData:g,select:w}=this.getState();if(!p&&v){d.preventDefault();const y=g[0]?.id,b=this._getFirstVisibleColumn()?.id;y&&b&&(this.in.exec("focus-cell",{row:y,column:b,eventSource:"key"}),w&&!this.isSelected(y)&&this.in.exec("select-row",{id:y}))}break}case"end":{const{editor:p,focusCell:v}=this.getState();if(!p&&v){d.preventDefault();const g=this._getLastVisibleColumn()?.id,w=v.row;this.in.exec("focus-cell",{row:w,column:g,eventSource:"key"})}break}case"ctrl+end":{const{editor:p,focusCell:v,flatData:g,select:w}=this.getState();if(!p&&v){d.preventDefault();const y=g.at(-1).id,b=this._getLastVisibleColumn()?.id;y&&b&&(this.in.exec("focus-cell",{row:y,column:b,eventSource:"key"}),w&&!this.isSelected(y)&&this.in.exec("select-row",{id:y}))}break}case"ctrl+z":{this.in.exec("undo",{});break}case"ctrl+y":{this.in.exec("redo",{});break}}}),l.on("scroll",c=>{const{_columns:d,split:m,_sizes:p,flatData:v,dynamic:g,_rowHeightFromData:w}=this.getState();let y=-1,b=-1,j=0,C=0;if(c.column){y=0;const N=d.findIndex(T=>T.id===c.column);j=d[N].width;for(let T=m.left??0;T<N;T++){const k=d[T];k.hidden||(y+=k.width)}}if(c.row&&!g){const N=v.findIndex(T=>T.id===c.row);N>=0&&(w?(b=v.slice(0,N).reduce((T,k)=>T+(k.rowHeight||p.rowHeight),0),C=v[N].rowHeight):b=p.rowHeight*N)}this.setState({scroll:{top:b,left:y,width:j,height:C||p.rowHeight}})}),l.on("scroll-to",c=>{const d={};c.top!==void 0&&(d.scrollTop=c.top),c.left!==void 0&&(d.scrollLeft=c.left),Object.keys(d).length&&this.setState(d)}),l.on("print",c=>{const d=fk(c);this.setState({_print:d}),this.setStateAsync({_print:null})}),l.on("undo",()=>{this._historyManager?.handleUndo()}),l.on("redo",()=>{this._historyManager?.handleRedo()}),this.initOnce()}getXlsxWorker(a){if(!this._xlsxWorker){const r=window.URL.createObjectURL(new Blob([`importScripts('${a}');`],{type:"text/javascript"}));this._xlsxWorker=new Promise(l=>{const c=new Worker(r);c.addEventListener("message",d=>{d.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=Sk()),a.columns&&a.columns.forEach(r=>{r.options&&(r.optionsMap=new Map(r.options.map(l=>[l.id,l.label])))}),mf(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 vk(this.in,this.getState.bind(this),this.setState.bind(this))),this._router.init({...a})}setState(a,r){return this._router.setState(a,r)}setStateAsync(a){this._router.setStateAsync(a)}getRow(a){const{tree:r}=this.getState();return r?this._branches[a]:this.getState().data.find(l=>l.id===a)}getRowIndex(a,r){return r||(r=this.getState().flatData),r.findIndex(l=>l.id===a)}getNextRow(a){const r=this.getState().flatData,l=this.getRowIndex(a,r);return r[l+1]}getPrevRow(a){const r=this.getState().flatData,l=this.getRowIndex(a,r);return r[l-1]}getColumn(a){return this.getState().columns.find(r=>r.id===a)}getNextColumn(a,r){const l=this.getState()._columns,c=l.findIndex(d=>d.id===a);return r?this._getFirstVisibleColumn(c+1):l[c+1]}getPrevColumn(a,r){const l=this.getState()._columns,c=l.findIndex(d=>d.id===a);return r?this._getLastVisibleColumn(c-1):l[c-1]}_getFirstVisibleColumn(a){const r=this.getState()._columns;let l=a??0;for(;l<r.length&&(r[l]?.hidden||r[l]?.collapsed);)l++;return r[l]}_getLastVisibleColumn(a){const r=this.getState()._columns;let l=a??r.length-1;for(;l<r.length&&(r[l]?.hidden||r[l]?.collapsed);)l--;return r[l]}isCellEditable(a,r){const{editor:l,hidden:c}=r;return!l||c?!1:typeof l=="function"?l(a,r):!0}getNextEditor(a,r){let l=this.getState().columns;if(r){const c=l.findIndex(d=>d.id===r.id);l=l.slice(c+1)}return l.find(c=>this.isCellEditable(a,c))}getPrevEditor(a,r){let l=this.getState().columns;if(r){const c=l.findLastIndex(d=>d.id===r.id);l=l.slice(0,c)}return l.findLast(c=>this.isCellEditable(a,c))}toggleBranch(a,r,l){let c=this._branches[a],{data:d}=this.getState();if(d=[...d],a!==0){c={...c,open:r};const m=this.updateTreeRow(c);c.$parent===0&&(d=m)}l&&c.data?.length&&c.data.forEach(m=>{const p=this.toggleKids(m,r,l);a===0&&(d=p)}),this.setState({data:d})}toggleKids(a,r,l){a={...a,open:r};const c=this.updateTreeRow(a);return l&&a.data?.length&&a.data.forEach(d=>{this.toggleKids(d,r,l)}),c}updateTreeRow(a){const r=a.id;this._branches[r]=a;const l=this._branches[a.$parent],c=l.data.findIndex(d=>d.id===r);return l.data=[...l.data],l.data[c]=a,l.data}isSelected(a){return this.getState().selectedRows.indexOf(a)!==-1}findAndRemove(a,r){for(let l=0;l<a.length;l++){if(a[l].id===r)return a.splice(l,1)[0];if(a[l].data){const c=[...a[l].data],d=this.findAndRemove(c,r);if(d)return a[l]={...a[l],data:c},d}}return null}insertItem(a,r,l,c){for(let d=0;d<a.length;d++){if(a[d].id===r){const m=a[d],p=c==="before"?d:d+1;if(m.data){if(c==="before"){const v=d>0?a[d-1]:null;return v?.data&&v.open?a[d-1]={...v,data:[...v.data,l]}:a.splice(p,0,l),!0}else if(m.open)return a[d]={...m,data:[l,...m.data]},!0}return a.splice(p,0,l),!0}if(a[d].data&&(a[d]={...a[d],data:[...a[d].data]},this.insertItem(a[d].data,r,l,c)))return!0}return!1}moveItem(a,r,l,c){const d=[...l],m=this.findAndRemove(d,a);return this.insertItem(d,r,m,c),d}copyColumns(a){const r=[];for(let l=0;l<a.length;l++){const c={...a[l]};this.copyHeaderFooter(c,"header"),this.copyHeaderFooter(c,"footer"),r[l]=c}return r}copyHeaderFooter(a,r){let l=a[r];l=Array.isArray(l)?[...l]:[l],l.forEach((c,d)=>{l[d]=typeof c=="string"?{text:c}:{...c}}),a[r]=l}setCollapsibleColumns(a,r,l){let c=a.header;for(let d=0;d<c.length;d++){const m=c[d];if(m.collapsible&&m.collapsed){if(m.collapsible!=="first"){a.collapsed=!0,a.width=36,m.vertical=!0;const v=c.length-d;c=c.slice(0,d+1),c[d].rowspan=v}const p=m.colspan;if(p){const v=c[d+1];let g=1;v&&v.colspan&&!v.collapsed&&(g=v.colspan);for(let w=g;w<p;w++){const y=l[r+w];y&&(y.hidden=!0)}}}}}normalizeColumns(a,r,l,c,d){const m=a[r];m.width||(m.width=m.flexgrow?17:d.columnWidth),m._colindex=r+1;const p=m[l],v=d[`${l}RowHeights`];for(let g=0;g<c;g++){const w=p[g];w.id=m.id,g===p.length-1&&(w.rowspan=w.rowspan?Math.min(w.rowspan,c-g):c-g);for(let y=1;y<w.rowspan;y++){p.splice(g+y,0,{_hidden:!0});for(let b=1;b<w.colspan;b++)a[r+b][l].splice(g+y,0,{})}if(w.rowspan){const y=(w.rowspan===c?v:v.slice(g,w.rowspan+g)).reduce((b,j)=>b+j,0);w.height=y,g+w.rowspan!=c&&w.height--}if(w.colspan){let y=m.width,b=m.flexgrow||0;const j=w.colspan;for(let C=1;C<j;C++){const N=a[r+C];N&&(N.hidden?w.colspan-=1:N.flexgrow?b+=N.flexgrow:y+=N.width||d.columnWidth),b?w.flexgrow=b:w.width=y}}else w.width=m.width,w.flexgrow=m.flexgrow;l==="header"&&w.filter&&typeof w.filter=="string"&&(w.filter={type:w.filter})}p.length>c&&(p.length=c),m[l]=p}normalizeRows(a){for(let r=0;r<a.length;r++)a[r].id||(a[r].id=Dd());return a}normalizeTreeRows(a,r,l){return!r&&!l&&(this._branches={0:{data:a}}),a.forEach(c=>{c.id||(c.id=Dd()),c.$level=r||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,r){a.sort(r),a.forEach(l=>{l.data&&this.sortTree(l.data,r)})}filterTree(a,r,l){return a.forEach(c=>{r(c)&&l.push(c.id),c.data&&this.filterTree(c.data,r,l)}),l}flattenRows(a,r,l){const c=r;return a.forEach(d=>{(!l||l.includes(d.id))&&c.push(d),d.data?.length&&d.open!==!1&&this.flattenRows(d.data,c,l)}),c}createFilter(a){const{_columns:r}=this.getState(),l=[];for(const c in a){const d=r.find(g=>g.id==c),{config:m,type:p}=d.header.find(g=>g.filter).filter,v=a[c];l.push(g=>{const w=Ur(g,d);return m?.handler?m.handler(w,v):Hw(p)(w,v)})}return c=>{for(let d=0;d<l.length;d++)if(!l[d](c))return!1;return!0}}searchRows(a,r){a=a.trim().toLowerCase();const l={};if(!a)return l;const{flatData:c,columns:d}=this.getState(),m=r?d.filter(p=>r[p.id]):d;return c.forEach(p=>{const v={};m.forEach(g=>{const w=$r(p,g);String(w).toLowerCase().includes(a)&&(v[g.id]=!0)}),Object.keys(v).length&&(l[p.id]=v)}),l}normalizeSizes(a,r,l,c,d){const m=Jx(a,"header",l,r.headerHeight,d),p=Jx(a,"footer",c,r.footerHeight,d),v=m.reduce((w,y)=>w+y,0),g=p.reduce((w,y)=>w+y,0);return{...r,headerRowHeights:m,footerRowHeights:p,headerHeight:v,footerHeight:g}}},Tk=new Date().valueOf();function Dd(){return"temp://"+Tk++}function Ek(n,a="data-id"){let r=n;for(!r.tagName&&n.target&&(r=n.target);r;){if(r.getAttribute&&r.getAttribute(a))return r;r=r.parentNode}return null}new Date().valueOf();var Rk=class{constructor(){this.store=new Map}configure(n,a){this.node=a;for(const r in n)if(n[r]){const l=r.toLowerCase().replace(/[ ]/g,""),c=n[r];this.store.set(l,c)}}},To=[],Dk={subscribe:n=>{_k();const a=new Rk;return To.push(a),n(a),()=>{const r=To.findIndex(l=>l===a);r>=0&&To.splice(r,1)}}},ey=!1;function _k(){ey||(ey=!0,document.addEventListener("keydown",n=>{if(To.length&&(n.ctrlKey||n.altKey||n.metaKey||n.shiftKey||n.key.length>1||n.key===" ")){const a=[];n.ctrlKey&&a.push("ctrl"),n.altKey&&a.push("alt"),n.metaKey&&a.push("meta"),n.shiftKey&&a.push("shift");let r=n.code.replace("Key","").toLocaleLowerCase();n.key===" "&&(r="space"),a.push(r);const l=a.join("+");for(let c=To.length-1;c>=0;c--){const d=To[c],m=d.store.get(l)||d.store.get(r);m&&d.node.contains(n.target)&&m(n,{key:l,evKey:r})}}}))}const Lk={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 zk(n,{keys:a,exec:r}){if(!a)return;function l(m){const p=m.target;return p.tagName==="INPUT"||p.tagName==="TEXTAREA"||Ek(p,"data-header-id")?.classList.contains("wx-filter")||!!p.closest(".wx-cell.wx-editor")}const c={};for(const m in a){const p=a[m];typeof p<"u"&&(typeof p=="function"?c[m]=p:p&&(c[m]=v=>{const g=l(v);r({key:m,event:v,isInput:g})}))}const d=Dk.subscribe(m=>{m.configure(c,n)});return{destroy:()=>{d()}}}function Ik(n,a){let r=null;a.scroll.subscribe(l=>{if(!l||l===r)return;r=l;const{left:c,top:d,height:m,width:p}=l,v=a.getHeight(),g=a.getWidth(),w=a.getScrollMargin();if(d>=0){const y=n.scrollTop;d<y?n.scrollTop=d:d+m>y+v&&(n.scrollTop=d-v+m)}if(c>=0){const y=n.scrollLeft;c<y?n.scrollLeft=c:c+p>y+g-w&&(n.scrollLeft=c-g+p+w)}}),a.scrollLeft?.subscribe?.(l=>{requestAnimationFrame(()=>{Math.abs(n.scrollLeft-l)>1&&(n.scrollLeft=l)})}),a.scrollTop?.subscribe?.(l=>{requestAnimationFrame(()=>{Math.abs(n.scrollTop-l)>1&&(n.scrollTop=l)})})}const Wa=u.createContext(null);function Ok(n,a){const r=new ResizeObserver(l=>{requestAnimationFrame(()=>a(l[0].contentRect))});return r.observe(n.parentNode),{destroy(){r.disconnect()}}}const ty=5,Bk=700;function Ud(n){const a=n.getBoundingClientRect(),r=document.body,l=a.top+r.scrollTop-r.clientTop||0,c=a.left+r.scrollLeft-r.clientLeft||0;return{y:Math.round(l),x:Math.round(c),width:n.offsetWidth,height:n.offsetHeight}}function Lh(n,a){const r=Ud(a);return{x:n.clientX-r.x,y:n.clientY-r.y}}function Fk(n,a){const r=a.current;let l=null,c,d,m=!1,p=!1;const v=document.createElement("DIV");v.className="wx-drag-zone",v.setAttribute("tabindex",-1);function g(){clearTimeout(c),c=null}function w(z){const L=_o(z);L&&(l={container:v,sourceNode:z.target,from:uf(L),pos:Lh(z,n)},d=l.pos,y(z))}function y(z){if(!l)return;const L=l.pos=Lh(z,n);if(!m){if(!p&&!z?.target?.getAttribute("draggable-data")&&Math.abs(d.x-L.x)<ty&&Math.abs(d.y-L.y)<ty)return;if(F(z)===!1)return q()}if(p){const ie=window.scrollX||document.documentElement.scrollLeft||document.body.scrollLeft,V=window.scrollY||document.documentElement.scrollTop||document.body.scrollTop;l.targetNode=document.elementFromPoint(z.pageX-ie,z.pageY-V)}else l.targetNode=z.target;r.move&&r.move(z,l),v.style.left=-(l.offset?l.offset.x:0)+"px",v.style.top=l.pos.y+(l.offset?l.offset.y:0)+"px"}function b(z){v.parentNode&&v.parentNode.removeChild(v),v.innerHTML="",m&&r.end&&r.end(z,l),l=d=null,q()}function j(z){r.getReorder&&!r.getReorder()||z.button===0&&($(z),window.addEventListener("mousemove",C),window.addEventListener("mouseup",N),w(z))}function C(z){y(z)}function N(z){b(z)}function T(z){if(r.getReorder&&!r.getReorder())return;c=setTimeout(()=>{p=!0,w(z.touches[0])},Bk),$(z);function L(){c&&g(),z.target.removeEventListener("touchmove",k),z.target.removeEventListener("touchend",L),b(z)}z.target.addEventListener("touchmove",k),z.target.addEventListener("touchend",L),n.addEventListener("contextmenu",E)}function k(z){m?(z.preventDefault(),y(z.touches[0])):c&&g()}function E(z){if(m||c)return z.preventDefault(),!1}function R(z){z.preventDefault()}function $(z){if(!r.getDraggableInfo)return;const{hasDraggable:L}=r.getDraggableInfo();(!L||z.target.getAttribute("draggable-data"))&&(document.body.style.userSelect="none",document.body.style.webkitUserSelect="none")}function F(z){if(m=!0,r.start){if(r.start(z,l)===!1)return!1;n.appendChild(v),document.body.style.cursor="move"}}function q(z){m=p=!1,document.body.style.cursor="",document.body.style.userSelect="",document.body.style.webkitUserSelect="",window.removeEventListener("mousemove",C),window.removeEventListener("mouseup",N),z&&(n.removeEventListener("mousedown",j),n.removeEventListener("touchstart",T),n.removeEventListener("dragstart",R))}return n.addEventListener("mousedown",j),n.addEventListener("touchstart",T),n.addEventListener("dragstart",R),{destroy(){q(!0)}}}const Pk=.004;function Hk(){return{dirX:0,dirY:0,scrollSpeedFactor:1}}function $k(n,a,r,l){const{node:c,left:d,top:m,bottom:p,sense:v,xScroll:g,yScroll:w}=l,y=Lh(n,c);r.scrollState||(r.scrollState=Hk());let b=0,j=0;y.x<d+v?b=-1:y.x>a.width-v&&(b=1),y.y<m+Math.round(v/2)?j=-1:y.y>a.height-p-Math.round(v/2)&&(j=1),(r.scrollState.dirX!==b||r.scrollState.dirY!==j)&&($w(r),r.scrollState.dirX=b,r.scrollState.dirY=j),(g&&r.scrollState.dirX!==0||w&&r.scrollState.dirY!==0)&&Uk(r,l,{x:r.scrollState.dirX,y:r.scrollState.dirY})}function Uk(n,a,r){n.autoScrollTimer||(n.autoScrollTimer=setTimeout(()=>{n.activeAutoScroll=setInterval(qk,15,n,a,r)},250))}function $w(n){n.scrollSpeedFactor=1,n.autoScrollTimer&&(n.autoScrollTimer=clearTimeout(n.autoScrollTimer),n.activeAutoScroll=clearInterval(n.activeAutoScroll))}function qk(n,a,r){const{x:l,y:c}=r;n.scrollSpeedFactor+=Pk,l!==0&&Vk(n,a,l),c!==0&&Gk(n,a,c)}function Gk(n,a,r){const l=a.node.scrollTop;Uw(l+Math.round(a.sense/3)*n.scrollSpeedFactor*r,"scrollTop",a)}function Vk(n,a,r){const l=a.node.scrollLeft;Uw(l+Math.round(a.sense/3)*n.scrollSpeedFactor*r,"scrollLeft",a)}function Uw(n,a,r){r.node[a]=n}function hf(n,a,r,l,c,d){const m={};return n&&(m.width=`${n}px`,m.minWidth=`${n}px`),a&&(m.flexGrow=a),d&&(m.height=`${d}px`),r&&(m.position="sticky",r.left&&(m.left=`${l}px`),r.right&&(m.right=`${c}px`)),m}function qw(n,a,r){let l="";if(n.fixed)for(const c in n.fixed){let d=n.fixed[c]===-1;!d&&n.fixed.leftSize&&a.colspan&&(d=a.colspan+n._colindex-1===n.fixed.leftSize),l+=d?"wx-shadow ":"wx-fixed "}return l+=a.rowspan>1?"wx-rowspan ":"",l+=a.colspan>1?"wx-colspan ":"",l+=a.vertical?"wx-vertical ":"",l+=r?r(n)+" ":"",l}function Yk(n){const{row:a,column:r,cellStyle:l=null,columnStyle:c=null,children:d,focusable:m}=n,p=u.useContext(Wa),v=nt(p,"focusCell"),g=nt(p,"search"),w=nt(p,"reorder"),y=u.useMemo(()=>g?.rows[a.id]&&g.rows[a.id][r.id],[g,a.id,r.id]),b=u.useMemo(()=>hf(r.width,r.flexgrow,r.fixed,r.left,r.right),[r.width,r.flexgrow,r.fixed,r.left,r.right]);function j(F,q){let z="wx-cell";return z+=r.fixed?" "+(r.fixed===-1?"wx-shadow":"wx-fixed"):"",z+=F?" "+F(r):"",z+=q?" "+q(a,r):"",z+=r.treetoggle?" wx-tree-cell":"",z}const C=u.useMemo(()=>j(c,l),[c,l,r,a]),N=u.useMemo(()=>typeof r.draggable=="function"?r.draggable(a,r)!==!1:r.draggable,[r,a]),T=u.useRef(null);u.useEffect(()=>{T.current&&m&&v?.row===a.id&&v?.column===r.id&&T.current.focus()},[v,m,a.id,r.id]);const k=u.useCallback(()=>{m&&!v&&p.exec("focus-cell",{row:a.id,column:r.id,eventSource:"focus"})},[p,m,v,a.id,r.id]);function E(F){const q=new RegExp(`(${g.value.trim()})`,"gi");return String(F).split(q).map(z=>({text:z,highlight:q.test(z)}))}const R=u.useMemo(()=>{const F=r.fixed&&r.fixed.left===-1||r.fixed.right===-1,q=r.fixed&&r.fixed.right;return[C,F?"wx-shadow":"",q?"wx-fixed-right":""].filter(Boolean).join(" ")},[C,r]),$=r.cell;return s.jsxs("div",{className:"wx-TSCaXsGV "+R,ref:T,onFocus:k,style:b,"data-row-id":zn(a.id),"data-col-id":zn(r.id),tabIndex:m?"0":"-1",role:"gridcell","aria-colindex":r._colindex,"aria-readonly":r.editor?void 0:!0,children:[w&&r.draggable?N?s.jsx("i",{"draggable-data":"true",className:"wx-TSCaXsGV wx-draggable wxi-drag"}):s.jsx("i",{className:"wx-TSCaXsGV wx-draggable-stub"}):null,r.treetoggle?s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{marginLeft:`${a.$level*28}px`}}),a.$count?s.jsx("i",{"data-action":"toggle-row",className:`wx-TSCaXsGV wx-table-tree-toggle wxi-menu-${a.open!==!1?"down":"right"}`}):null]}):null,$?s.jsx($,{api:p,row:a,column:r,onAction:({action:F,data:q})=>p.exec(F,q)}):d?d():y?s.jsx("span",{children:E($r(a,r)).map(({highlight:F,text:q},z)=>F?s.jsx("mark",{className:"wx-TSCaXsGV wx-search",children:q},z):s.jsx("span",{children:q},z))}):$r(a,r)]})}function ny(n,a){let r,l;function c(p){r=p.clientX,n.style.opacity=1,document.body.style.cursor="ew-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",d),window.addEventListener("mouseup",m),a&&a.down&&a.down(n)}function d(p){l=p.clientX-r,a&&a.move&&a.move(l)}function m(){n.style.opacity="",document.body.style.cursor="",document.body.style.userSelect="",a&&a.up&&a.up(l),window.removeEventListener("mousemove",d),window.removeEventListener("mouseup",m)}return n.addEventListener("mousedown",c),{destroy(){n.removeEventListener("mousedown",c)}}}function Wk({filter:n,column:a,action:r,filterValue:l}){function c({value:d}){r({value:d,key:a.id})}return s.jsx(rp,{...n.config??{},value:l,onChange:c})}function Kk({filter:n,column:a,action:r,filterValue:l}){const c=u.useContext(Wa),d=nt(c,"flatData"),m=u.useMemo(()=>n?.config?.options||a?.options||v(),[n,a,d]),p=u.useMemo(()=>n?.config?.template,[n]);function v(){const y=[];return d.forEach(b=>{const j=Ur(b,a);y.includes(j)||y.push(j)}),y.map(b=>({id:b,label:b}))}function g({value:y}){r({value:y,key:a.id})}function w(y){y.key!=="Tab"&&y.preventDefault()}return s.jsx("div",{style:{width:"100%"},onKeyDown:w,children:s.jsx(cC,{placeholder:"",clear:!0,...n?.config??{},options:m,value:l,onChange:g,children:y=>p?p(y):y.label})})}function Qk({filter:n,column:a,action:r,filterValue:l}){function c({value:d}){r({value:d,key:a.id})}return s.jsx("div",{className:"wx-aaaK5VYO",style:{width:"100%"},children:s.jsx(oC,{placeholder:"",clear:!0,...n?.config??{},value:l,onChange:c})})}function Gw(n){const{value:a,options:r=[],placeholder:l="",clear:c=!1,text:d=null,template:m=null,cell:p=null,dropdown:v={},autoOpen:g=!1,onChange:w,onAction:y}=n,[b,j]=Tw(a||[]),C=u.useMemo(()=>(b||[]).map(V=>r.find(ne=>ne.id===V)).filter(Boolean),[b,r]),N=u.useRef(null),T=u.useRef(null),[k,E]=u.useState(null),R=()=>{const V=b||[];if(!V.length)return 0;const ne=r.find(Q=>V.includes(Q.id));return ne?r.indexOf(ne):0};function $(V){T.current=V.navigate,E(()=>V.keydown),g&&V.navigate(R())}u.useEffect(()=>{g&&(N.current?.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges())},[]);function F({id:V}){j(V),w&&w({value:V})}function q(V){V.stopPropagation(),j([]),w&&w({value:[]})}function z(){T.current?.(R())}function L(){T.current?.(null)}function ie(V){k?.(V,R())}return s.jsxs("div",{ref:N,className:"wx-multiselect wx-aadNNOwy",onClick:z,onKeyDown:ie,tabIndex:0,children:[s.jsx("div",{className:"wx-label wx-aadNNOwy",children:m?m(C):p?s.jsx(p,{data:C,onAction:y}):d?s.jsx("span",{className:"wx-text wx-aadNNOwy",children:d}):C.length?s.jsx("span",{className:"wx-text wx-aadNNOwy",children:C.map(V=>V.label).join(", ")}):l?s.jsx("span",{className:"wx-placeholder wx-aadNNOwy",children:l}):" "}),c&&b?.length?s.jsx("i",{className:"wx-icon wxi-close wx-aadNNOwy",onClick:q}):s.jsx("i",{className:"wx-icon wxi-angle-down wx-aadNNOwy"}),s.jsx(ff,{items:r,onReady:$,onSelect:F,multiselect:!0,checkboxes:!0,value:b||[],onCancel:L,...v,children:({option:V})=>s.jsx("div",{className:"wx-option wx-aadNNOwy",children:m?m(V):p?s.jsx(p,{data:V,onAction:y}):V.label})})]})}function Xk({filter:n,column:a,action:r,filterValue:l}){const c=u.useContext(On.i18n)?.getGroup("grid")||nu(cp).getGroup("grid"),d=u.useMemo(()=>({clear:!0,...n?.config||{}}),[n]),m=u.useMemo(()=>d.options||a.options,[d,a]),p=u.useMemo(()=>{const w=l?.length;return w?w<3?l.map(y=>a.optionsMap.get(y)).join(", "):w+" "+c("selected"):""},[l,a,c]);function v({value:w}){r({value:w,key:a.id})}function g(w){w.key!=="Tab"&&w.preventDefault()}return s.jsx("div",{style:{width:"100%"},onKeyDown:g,children:s.jsx(Gw,{placeholder:"",...d,options:m,value:l||[],text:p,onChange:v})})}const Zk={text:Wk,richselect:Kk,datepicker:Qk,multiselect:Xk};function Jk({filter:n,column:a}){const r=u.useContext(Wa),l=nt(r,"filterValues");function c(m){r.exec("filter-rows",m)}const d=u.useMemo(()=>Zk[n.type],[n.type]);return s.jsx(d,{filter:n,column:a,action:c,filterValue:l[a.id]})}function eA(n){const{cell:a,column:r,row:l,lastRow:c,sortRow:d,columnStyle:m,bodyHeight:p,hasSplit:v}=n,g=u.useContext(Wa),w=nt(g,"sortMarks"),y=u.useMemo(()=>w?w[r.id]:void 0,[w,r.id]),b=u.useRef(),j=u.useCallback(le=>{b.current=a.flexgrow?le.parentNode.clientWidth:a.width},[a.flexgrow,a.width]),C=u.useCallback((le,Y)=>{g.exec("resize-column",{id:a.id,width:Math.max(1,(b.current||0)+le),inProgress:Y})},[g,a.id]),N=u.useCallback(le=>C(le,!0),[C]),T=u.useCallback(le=>C(le,!1),[C]),k=u.useCallback(le=>{if(!r.sort||a.filter)return;let Y=y?.order;Y&&(Y=Y==="asc"?"desc":"asc"),g.exec("sort-rows",{key:a.id,add:le.ctrlKey||le.metaKey,order:Y})},[g,a.id,a.filter,r.sort,y?.order]),E=u.useCallback(le=>{le&&le.stopPropagation(),g.exec("collapse-column",{id:a.id,row:l})},[g,a.id,l]),R=u.useCallback(le=>{le.key==="Enter"&&E()},[E]),$=u.useCallback(le=>{le.key==="Enter"&&!a.filter&&k(le)},[k,a.filter]),F=u.useMemo(()=>a.collapsed&&r.collapsed,[a.collapsed,r.collapsed]),q=u.useMemo(()=>F&&!v&&a.collapsible!=="header",[F,v,a.collapsible]),z=u.useMemo(()=>q?{top:-p/2,position:"absolute"}:{},[q,p]),L=u.useMemo(()=>hf(a.width,a.flexgrow,r.fixed,r.left,a.right??r.right,a.height+(F&&q?p:0)),[a.width,a.flexgrow,r.fixed,r.left,a.right,r.right,a.height,F,q,p]),ie=u.useMemo(()=>qw(r,a,m),[r,a,m]),V=u.useCallback(()=>Object.fromEntries(Object.entries(a).filter(([le])=>le!=="cell")),[a]),ne=`wx-cell ${ie} ${a.css||""} wx-collapsed`,Q=["wx-cell",ie,a.css||"",a.filter?"wx-filter":"",r.fixed&&r.fixed.right?"wx-fixed-right":""].filter(Boolean).join(" "),J=u.useRef(null);return u.useEffect(()=>{const le=J.current;if(!le)return;const Y=ny(le,{down:j,move:N,up:T});return()=>{typeof Y=="function"&&Y()}},[j,N,T,ny]),F?s.jsx("div",{className:"wx-RsQD74qC "+ne,style:L,role:"button","aria-label":`Expand column ${a.text||""}`,"aria-expanded":!a.collapsed,tabIndex:0,onKeyDown:R,onClick:E,"data-header-id":zn(r.id),children:s.jsx("div",{className:"wx-RsQD74qC wx-text",style:z,children:a.text||""})}):s.jsxs("div",{className:"wx-RsQD74qC "+Q,style:L,onClick:k,"data-header-id":zn(r.id),tabIndex:!a._hidden&&r.sort&&!a.filter?0:void 0,role:"columnheader","aria-colindex":r._colindex,"aria-colspan":a.colspan>1?a.colspan:void 0,"aria-rowspan":a.rowspan>1?a.rowspan:void 0,"aria-sort":!y?.order||a.filter?"none":y?.order==="asc"?"ascending":"descending",onKeyDown:$,children:[a.collapsible?s.jsx("div",{className:"wx-RsQD74qC wx-collapse",role:"button","aria-label":a.collapsed?"Expand column":"Collapse column","aria-expanded":!a.collapsed,tabIndex:0,onKeyDown:R,onClick:E,children:s.jsx("i",{className:`wx-RsQD74qC wxi-angle-${a.collapsed?"down":"right"}`})}):null,a.cell?(()=>{const le=a.cell;return s.jsx(le,{api:g,cell:V(),column:r,row:l,onAction:({action:Y,data:O})=>g.exec(Y,O)})})():a.filter?s.jsx(Jk,{filter:a.filter,column:r}):s.jsx("div",{className:"wx-RsQD74qC wx-text",children:a.text||""}),r.resize&&c&&!a._hidden?s.jsx("div",{className:"wx-RsQD74qC wx-grip",role:"presentation","aria-label":"Resize column",ref:J,onClick:le=>le.stopPropagation(),children:s.jsx("div",{})}):null,d?s.jsx("div",{className:"wx-RsQD74qC wx-sort",children:y?s.jsxs(s.Fragment,{children:[typeof y.index<"u"?s.jsx("div",{className:"wx-RsQD74qC wx-order",children:y.index+1}):null,s.jsx("i",{className:`wx-RsQD74qC wxi-arrow-${y.order==="asc"?"up":"down"}`})]}):null}):null]})}function tA({cell:n,column:a,row:r,columnStyle:l}){const c=u.useContext(Wa),d=u.useMemo(()=>hf(n?.width,n?.flexgrow,a?.fixed,a?.left,n?.right??a?.right,n?.height),[n?.width,n?.flexgrow,a?.fixed,a?.left,n?.right,a?.right,n?.height]),m=u.useMemo(()=>qw(a,n,l),[a,n,l]),p=u.useCallback(()=>Object.fromEntries(Object.entries(n||{}).filter(([g])=>g!=="cell")),[n]),v=`wx-6Sdi3Dfd wx-cell ${m||""} ${n?.css||""}`+(a?.fixed&&a?.fixed.right?" wx-fixed-right":"");return s.jsx("div",{className:v,style:d,children:!a?.collapsed&&!n?.collapsed?n?.cell?Yh.createElement(n.cell,{api:c,cell:p(),column:a,row:r,onAction:({action:g,data:w})=>c.exec(g,w)}):s.jsx("div",{className:"wx-6Sdi3Dfd wx-text",children:n?.text||""}):null})}function ay({deltaLeft:n,contentWidth:a,columns:r,type:l="header",columnStyle:c,bodyHeight:d}){const m=u.useContext(Wa),p=nt(m,"_sizes"),v=nt(m,"split"),g=u.useMemo(()=>p?.[`${l}RowHeights`],[p,l]),w=u.useMemo(()=>{let N=[];if(r&&r.length){const T=r[0][l].length;for(let k=0;k<T;k++){let E=0;N.push([]),r.forEach((R,$)=>{const F={...R[l][k]};E||N[k].push(F),F.colspan>1?E=F.colspan-1:E&&E--})}}return N},[r,l]),y=u.useMemo(()=>v?.left||v?.right,[v]);function b(N){return r.find(T=>T.id===N)}function j(N,T){let k=T;return N.rowspan&&(k+=N.rowspan-1),k===w.length-1}function C(N,T,k){if(!k.sort)return!1;for(let E=w.length-1;E>=0;E--){const R=k.header[E];if(!R.filter&&!R._hidden)return T===E}return j(N,T)}return s.jsx("div",{className:`wx-sAsPVaUK wx-${l}`,style:{paddingLeft:`${n}px`,width:`${a}px`},role:"rowgroup",children:w.map((N,T)=>s.jsx("div",{className:l==="header"?"wx-sAsPVaUK wx-h-row":"wx-sAsPVaUK wx-f-row",style:{height:`${g?.[T]}px`,display:"flex"},role:"row",children:N.map(k=>{const E=b(k.id);return l==="header"?s.jsx(eA,{cell:k,columnStyle:c,column:E,row:T,lastRow:j(k,T),bodyHeight:d,sortRow:C(k,T,E),hasSplit:y},k.id):s.jsx(tA,{cell:k,columnStyle:c,column:b(k.id),row:T},k.id)})},T))})}function nA({overlay:n}){const a=u.useContext(Wa);function r(c){return typeof c=="function"}const l=n;return s.jsx("div",{className:"wx-1ty666CQ wx-overlay",children:r(n)?s.jsx(l,{onAction:({action:c,data:d})=>a.exec(c,d)}):n})}function aA(n){const{editor:a,onSave:r,onApply:l}=n,[c,d]=u.useState(a?.value||""),{type:m="text"}=u.useMemo(()=>a?.config||{},[a]),p=u.useRef(null);u.useEffect(()=>{p.current&&p.current.focus()},[]),u.useEffect(()=>{if(!p.current)return;const w=ii(p.current,()=>r(!0));return()=>w.destroy()},[r]);function v(){p.current&&(d(p.current.value),l(p.current.value))}function g({key:w}){w==="Enter"&&r()}return s.jsx("input",{className:"wx-e7Ao5ejY wx-text",onInput:v,onKeyDown:g,ref:p,type:m,value:c})}function sA({editor:n,onAction:a,onSave:r,onApply:l,onCancel:c}){const[d,m]=u.useState(n?.value),[p,v]=u.useState(n?.renderedValue),[g,w]=u.useState(n?.options||[]),y=u.useMemo(()=>n?.config?.template,[n]),b=u.useMemo(()=>n?.config?.cell,[n]),j=u.useMemo(()=>n?.config?.dropdown||{},[n]),C=u.useMemo(()=>({trackScroll:!0,...j}),[j]),N=u.useMemo(()=>(g||[]).findIndex(z=>z.id===d),[g,d]),T=u.useRef(null),k=u.useRef(null),E=u.useCallback(z=>{T.current=z.navigate,k.current=z.keydown,T.current(N)},[N,T]),R=u.useCallback(z=>{const L=z?.target?.value??"";v(L);const ie=L?(n?.options||[]).filter(V=>(V.label||"").toLowerCase().includes(L.toLowerCase())):n?.options||[];w(ie),ie.length?T.current(-1/0):T.current(null)},[n]),$=u.useRef(null);u.useEffect(()=>{$.current&&$.current.focus()},[]);const F=u.useRef(r);u.useEffect(()=>{F.current=r},[r]),u.useEffect(()=>{if(!$.current)return;const z=ii($.current,()=>F.current(!0));return()=>z.destroy()},[]),u.useEffect(()=>{m(n?.value),v(n?.renderedValue),w(n?.options||[])},[n]);const q=u.useCallback(({id:z})=>{l(z),r()},[l,r]);return s.jsxs(s.Fragment,{children:[s.jsx("input",{className:"wx-0UYfSd1x wx-input",ref:$,value:p??"",onChange:R,onKeyDown:z=>k.current?k.current(z,N):void 0}),s.jsx(ff,{items:g,onReady:E,onSelect:q,...C,onCancel:c,children:({option:z})=>y?y(z):b?s.jsx(b,{data:z,onAction:a}):z.label})]})}function iA({editor:n,onAction:a,onSave:r,onApply:l,onCancel:c}){const[d]=u.useState(()=>n.value||new Date),{template:m,cell:p,dropdown:v={}}=n?.config||{},g=u.useMemo(()=>({trackScroll:!0,width:"auto",...v}),[v]);function w({value:C}){l(C),r()}const y=u.useRef(null),[b,j]=u.useState(null);return u.useEffect(()=>{y.current&&y.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),u.useEffect(()=>{if(!b)return;const C=ii(b,()=>r(!0));return()=>C.destroy()},[b,r]),s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"wx-lNWNYUb6 wx-value",ref:y,tabIndex:0,onClick:c,onKeyDown:C=>C.preventDefault(),children:m?m(d):p?s.jsx(p,{data:n.value,onAction:a}):s.jsx("span",{className:"wx-lNWNYUb6 wx-text",children:n.renderedValue})}),s.jsx(ip,{...g,onCancel:c,children:s.jsx("div",{ref:j,className:"wx-lNWNYUb6",children:s.jsx(Cw,{value:d,onChange:w,buttons:n.config?.buttons})})})]})}function rA(n){const{editor:a}=n,r=n.onAction??n.onaction,l=n.onSave??n.onsave,c=n.onApply??n.onapply,d=n.onCancel??n.oncancel,m=a.config||{},{dropdown:p={}}=m,v=u.useMemo(()=>({trackScroll:!0,...p}),[p]),[g]=u.useState(a.options.find(R=>R.id===a.value)),[w]=u.useState(a.value),[y]=u.useState(a.options),b=u.useMemo(()=>y.findIndex(R=>R.id===w),[y,w]);function j({id:R}){c(R),l()}let C;const[N,T]=u.useState();function k(R){C=R.navigate,T(()=>R.keydown),C(b)}const E=u.useRef(null);return u.useEffect(()=>{E.current&&E.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),u.useEffect(()=>{if(!E.current)return;const R=ii(E.current,()=>l(!0));return()=>R.destroy()},[l]),s.jsxs(s.Fragment,{children:[s.jsx("div",{ref:E,className:"wx-ywGRk611 wx-value",tabIndex:0,onClick:d,onKeyDown:R=>{N(R,b),R.preventDefault()},children:m.template?m.template(g):m.cell?(()=>{const R=m.cell;return s.jsx(R,{data:g,onAction:r})})():s.jsx("span",{className:"wx-ywGRk611 wx-text",children:a.renderedValue})}),s.jsx(ff,{items:y,onReady:k,onSelect:j,...v,onCancel:d,children:({option:R})=>m.template?m.template(R):m.cell?(()=>{const $=m.cell;return s.jsx($,{data:R,onAction:r})})():R.label})]})}function lA(n){const{editor:a,onAction:r,onSave:l,onApply:c}=n,d=a?.config||{},m=a?.options??[],p=a?.value||[],v=a?.renderedValue,g=u.useMemo(()=>({trackScroll:!0,...d.dropdown||{}}),[d]);function w({value:b}){c(b)}const y=u.useRef(null);return u.useEffect(()=>{if(!y.current)return;const b=ii(y.current,()=>l(!0));return()=>b.destroy()},[l]),s.jsx("div",{ref:y,className:"wx-value wx-aacZ4gNU",onClick:()=>l(!0),children:s.jsx(Gw,{value:p,options:m,text:v,template:d.template,cell:d.cell,clear:d.clear,dropdown:g,autoOpen:!0,onChange:w,onAction:r})})}const oA={text:aA,combo:sA,datepicker:iA,richselect:rA,multiselect:lA};function cA({column:n,row:a}){const r=u.useContext(Wa),l=nt(r,"editor"),c=u.useCallback((C,N)=>{r.exec("close-editor",{ignore:C}),N&&r.exec("focus-cell",{...N,eventSource:"click"})},[r]),d=u.useCallback(C=>{const N=C?null:{row:l?.id,column:l?.column};c(!1,N)},[l,c]),m=u.useCallback(()=>{c(!0,{row:l?.id,column:l?.column})},[l,c]),p=u.useCallback(C=>{r.exec("editor",{value:C})},[r]),v=u.useCallback(C=>{C.key==="Enter"&&l&&(n.editor.type==="multiselect"?p(l.value):m())},[l,n.editor,m,p]),g=u.useMemo(()=>hf(n.width,n.flexgrow,n.fixed,n.left,n.right),[n.width,n.flexgrow,n.fixed,n.left,n.right]),w=u.useMemo(()=>{let C=n.editor;if(typeof C=="function"&&(C=C(a,n)),!C)return null;let N=typeof C=="string"?C:C.type;return oA[N]},[n,a]),y=u.useRef(null);u.useEffect(()=>{y.current&&typeof g=="string"&&y.current.setAttribute("style",g)},[g]);const b=typeof a.$parent<"u"?"gridcell":"cell",j=typeof a.$parent<"u"?!n.editor:void 0;return s.jsx("div",{className:"wx-8l724t2g wx-cell wx-editor",ref:y,style:typeof g=="object"&&g!==null?g:void 0,role:b,"aria-readonly":j,tabIndex:-1,onClick:C=>C.stopPropagation(),onDoubleClick:C=>C.stopPropagation(),onKeyDown:v,children:w?s.jsx(w,{editor:l,onSave:d,onApply:p,onCancel:m,onAction:({action:C,data:N})=>r.exec(C,N)}):null})}function sy(n){const{columns:a,type:r,columnStyle:l}=n,c=u.useContext(Wa),{filterValues:d,_columns:m,_sizes:p}=c.getState();function v(g){return l?" "+l(g):""}return s.jsx(s.Fragment,{children:a.map((g,w)=>s.jsx("tr",{children:g.map(y=>{const b=m.find(N=>N.id===y.id),j=`wx-print-cell-${r}${v(b)}${y.filter?" wx-print-cell-filter":""}${y.vertical?" wx-vertical":""}`,C=y.cell;return s.jsx("th",{style:Ew(Fw(y,p.columnWidth)),className:"wx-Gy81xq2u "+j,rowSpan:y.rowspan,colSpan:y.colspan,children:C?s.jsx(C,{api:c,cell:Object.fromEntries(Object.entries(y).filter(([N])=>N!=="cell")),column:b,row:w}):y.filter?s.jsx("div",{className:"wx-Gy81xq2u wx-print-filter",children:mk(d,m,y)}):s.jsx("div",{className:"wx-Gy81xq2u wx-text",children:y.text??""})},y.id)})},w))})}function uA(n){const{columns:a,rowStyle:r,columnStyle:l,cellStyle:c,header:d,footer:m,reorder:p}=n,v=u.useContext(Wa),{flatData:g,_sizes:w}=v.getState(),y=d&&Xx(a,"header",w.headerRowHeights),b=m&&Xx(a,"footer",w.footerRowHeights);function j(N,T){let k="";return k+=l?" "+l(T):"",k+=c?" "+c(N,T):"",k}function C(N,T){return typeof T.draggable=="function"?T.draggable(N,T)!==!1:T.draggable}return s.jsxs("table",{className:`wx-8NTMLH0z wx-print-grid ${a.some(N=>N.flexgrow)?"wx-flex-columns":""}`,children:[d?s.jsx("thead",{children:s.jsx(sy,{columns:y,type:"header",columnStyle:l})}):null,s.jsx("tbody",{children:g.map((N,T)=>s.jsx("tr",{className:"wx-8NTMLH0z wx-row"+(r?" "+r(N):""),style:{height:`${N.rowHeight||w.rowHeight}px`},children:a.map(k=>k.collapsed?null:s.jsxs("td",{className:`wx-8NTMLH0z wx-print-cell wx-cell ${j(N,k)}`,style:Ew(Fw(k,w.columnWidth)),children:[p&&k.draggable?s.jsx("span",{className:"wx-8NTMLH0z wx-print-draggable",children:C(N,k)?s.jsx("i",{className:"wx-8NTMLH0z wxi-drag"}):null}):null,k.treetoggle?s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{marginLeft:N.$level*28+"px"}}),N.$count?s.jsx("i",{className:`wx-8NTMLH0z wx-print-grid-tree-toggle wxi-menu-${N.open!==!1?"down":"right"}`}):null]}):null,k.cell?(()=>{const E=k.cell;return s.jsx(E,{api:v,row:N,column:k})})():s.jsx("span",{children:$r(N,k)})]},k.id))},T))}),m?s.jsx("tfoot",{children:s.jsx(sy,{columns:b,type:"footer",columnStyle:l})}):null]})}function dA(n){const{config:a,...r}=n,l=u.useContext(Wa),{_skin:c,_columns:d}=l.getState(),m=u.useMemo(()=>ck(d,a),[]),p=u.useRef(null);return u.useEffect(()=>{const v=document.body;v.classList.add("wx-print");const g=p.current;if(!g)return;const w=g.cloneNode(!0);v.appendChild(w);const y=`@media print { @page { size: ${a.paper} ${a.mode}; }`,b=document.createElement("style");b.setAttribute("type","text/css"),b.setAttribute("media","print"),document.getElementsByTagName("head")[0].appendChild(b),b.appendChild(document.createTextNode(y)),window.print(),b.remove(),v.classList.remove("wx-print"),w.remove()},[]),s.jsx("div",{className:`wx-4zwCKA7C wx-${c}-theme wx-print-container`,ref:p,children:m.map((v,g)=>s.jsx("div",{className:"wx-4zwCKA7C wx-print-grid-wrapper",children:s.jsx(uA,{columns:v,...r})},g))})}function fA(n){const{header:a,footer:r,overlay:l,multiselect:c,onreorder:d,rowStyle:m,columnStyle:p,cellStyle:v,autoRowHeight:g,resize:w,clientWidth:y,clientHeight:b,responsiveLevel:j,hotkeys:C}=n,N=u.useContext(Wa),T=nt(N,"dynamic"),k=nt(N,"_columns"),E=nt(N,"flatData"),R=nt(N,"split"),$=nt(N,"_sizes"),[F,q]=ps(N,"selectedRows"),z=nt(N,"select"),L=nt(N,"editor"),ie=nt(N,"scrollLeft"),V=nt(N,"scrollTop"),ne=nt(N,"tree"),Q=nt(N,"focusCell"),J=nt(N,"_print"),le=nt(N,"undo"),Y=nt(N,"reorder"),O=nt(N,"_rowHeightFromData"),[Z,X]=u.useState(0);u.useEffect(()=>{X(ut())},[]);const[D,K]=u.useState(0),ce=u.useMemo(()=>(k||[]).some(te=>!te.hidden&&te.flexgrow),[k]),W=u.useMemo(()=>$?.rowHeight||0,[$]),P=u.useRef(null),[me,pe]=u.useState(null),[ve,ke]=u.useState(null),_e=u.useMemo(()=>{let te=[],Me=0;return R&&R.left&&(te=(k||[]).slice(0,R.left).filter(Pe=>!Pe.hidden).map(Pe=>({...Pe})),te.forEach(Pe=>{Pe.fixed={left:1,leftSize:R.left},Pe.left=Me,Me+=Pe.width}),te.length&&(te[te.length-1].fixed.left=-1)),{columns:te,width:Me}},[R,k]),Le=u.useMemo(()=>{let te=[],Me=0;if(R&&R.right){te=(k||[]).slice(R.right*-1).filter(Pe=>!Pe.hidden).map(Pe=>({...Pe}));for(let Pe=te.length-1;Pe>=0;Pe--){const at=te[Pe];at.fixed={right:1},at.right=Me,Me+=at.width}te.length&&(te[0].fixed={right:-1})}return{columns:te,width:Me}},[R,k]),ue=u.useMemo(()=>{const te=(k||[]).slice(R?.left||0,(k||[]).length-(R?.right??0)).filter(Me=>!Me.hidden);return te.forEach(Me=>{Me.fixed=0}),te},[k,R]),Ve=u.useMemo(()=>(k||[]).reduce((te,Me)=>(Me.hidden||(te+=Me.width),te),0),[k]),Ye=1;function oe(te,Me,Pe){let at=Me,Wt=te;if(ue.length){let Mt=ue.length;for(let Qe=te;Qe>=0;Qe--)ue[Qe][Pe].forEach(rt=>{rt.colspan>1&&Qe>te-rt.colspan&&Qe<Mt&&(Mt=Qe)});if(Mt!==ue.length&&Mt<te){for(let Qe=Mt;Qe<te;Qe++)at-=ue[Qe].width;Wt=Mt}}return{index:Wt,delta:at}}const Ne=u.useMemo(()=>{let te,Me,Pe;const at=ie||0,Wt=(ie||0)+(y||0);let Mt=0,Qe=0,rt=0,Kt=0;ue.forEach((rn,Qt)=>{at>rt&&(Mt=Qt,Kt=rt),rt=rt+rn.width,Wt>rt&&(Qe=Qt+Ye)});const Pt={header:0,footer:0};for(let rn=Qe;rn>=Mt;rn--)["header","footer"].forEach(Qt=>{ue[rn]&&ue[rn][Qt].forEach(gs=>{const vs=gs.colspan;if(vs&&vs>1){const li=vs-(Qe-rn+1);li>0&&(Pt[Qt]=Math.max(Pt[Qt],li))}})});const Rt=oe(Mt,Kt,"header"),Ot=oe(Mt,Kt,"footer"),Ht=Rt.delta,Dt=Rt.index,Tn=Ot.delta,Za=Ot.index;return ce&&Ve>(y||0)?te=Me=Pe=[..._e.columns,...ue,...Le.columns]:(te=[..._e.columns,...ue.slice(Mt,Qe+1),...Le.columns],Me=[..._e.columns,...ue.slice(Dt,Qe+Pt.header+1),...Le.columns],Pe=[..._e.columns,...ue.slice(Za,Qe+Pt.footer+1),...Le.columns]),{data:te||[],header:Me||[],footer:Pe||[],d:Kt,df:Tn,dh:Ht}},[ue,_e,Le,ie,y,ce,Ve]),je=u.useMemo(()=>a&&$?.headerHeight||0,[a,$]),Ee=u.useMemo(()=>r&&$?.footerHeight||0,[r,$]),Re=u.useMemo(()=>y&&b?Ve>=y:!1,[y,b,Ve]),[Fe,he]=u.useState(!1),Ae=u.useMemo(()=>(b||0)-je-Ee-(Re?Z:0),[b,je,Ee,Re,Z]),de=u.useMemo(()=>Math.ceil((Ae||0)/(W||1))+1,[Ae,W]),ye=u.useRef([]),[qe,tt]=u.useState(0),[pn,Ke]=u.useState(void 0),ht=u.useMemo(()=>{let te=0,Me=0;const Pe=2,at=V||0;if(g){let Qe=at;for(;Qe>0;)Qe-=ye.current[te]||W,te++;Me=at-Qe;for(let rt=Math.max(0,te-Pe-1);rt<te;rt++)Me-=ye.current[te-rt]||W;te=Math.max(0,te-Pe)}else{if(O){let Qe=0,rt=0;for(let Ot=0;Ot<(E||[]).length;Ot++){const Ht=E[Ot].rowHeight||W;if(rt+Ht>at){Qe=Ot;break}rt+=Ht}te=Math.max(0,Qe-Pe);for(let Ot=0;Ot<te;Ot++)Me+=E[Ot].rowHeight||W;let Kt=0,Pt=0;for(let Ot=Qe+1;Ot<(E||[]).length;Ot++){const Ht=E[Ot].rowHeight||W;if(Kt++,Pt+Ht>Ae)break;Pt+=Ht}const Rt=Math.min(T?T.rowCount:(E||[]).length,Qe+Kt+Pe);return{d:Me,start:te,end:Rt}}te=Math.floor(at/(W||1)),te=Math.max(0,te-Pe),Me=te*(W||0)}const Wt=T?T.rowCount:(E||[]).length,Mt=Math.min(Wt,te+(de||0)+Pe);return{d:Me,start:te,end:Mt}},[g,O,V,W,T,E,de,Ae]),St=u.useMemo(()=>{const te=T?T.rowCount:(E||[]).length;if(g)return qe+ht.d+(te-(pn||0))*(W||0);if(!O)return te*(W||0);let Me=0;for(let Pe=0;Pe<te;Pe++)Me+=E[Pe]?.rowHeight||W;return Me},[T,E,W,g,O,qe,ht.d,pn]),An=u.useRef({});An.current={clientWidth:y,clientHeight:b,fullHeight:St,headerHeight:je,footerHeight:Ee,fullWidth:Ve,SCROLLSIZE:Z};const Oe=u.useCallback(()=>{const te=An.current;he(te.clientWidth&&te.clientHeight?te.fullHeight+te.headerHeight+te.footerHeight>=te.clientHeight-(te.fullWidth>=te.clientWidth?te.SCROLLSIZE:0):!1)},[]);u.useEffect(()=>{const te=requestAnimationFrame(Oe);return()=>window.cancelAnimationFrame(te)},[D,Oe]),u.useEffect(()=>{Oe()},[b,Oe]);const It=u.useMemo(()=>ce&&Ve<=(y||0)?(y||0)-0-(Fe?Z:0):Ve,[ce,Ve,y,Fe,Z,Re]),Ut=u.useMemo(()=>ce&&Ve<=(y||0)?y||0:It<(y||0)?Ve+(Fe?Z:0):-1,[ce,Ve,y,It,Fe,Z]),pt=u.useRef({});u.useEffect(()=>{if(T&&(pt.current.start!==ht.start||pt.current.end!==ht.end)){const{start:te,end:Me}=ht;pt.current={start:te,end:Me},N&&N.exec&&N.exec("request-data",{row:{start:te,end:Me}})}},[T,ht,N]);const st=u.useMemo(()=>T?E||[]:(E||[]).slice(ht.start,ht.end),[T,E,ht]),Jt=u.useMemo(()=>(F||[]).filter(te=>(st||[]).some(Me=>Me.id===te)),[q,st]),Nt=u.useMemo(()=>ht.start,[ht.start]),De=u.useRef({top:V,left:ie});De.current={top:V,left:ie};const Nn=u.useCallback(te=>{const Me=te.target.scrollTop,Pe=te.target.scrollLeft,at=De.current;(Me!==at.top||Pe!==at.left)&&N.exec("scroll-to",{top:Me,left:Pe})},[N]),Vi=u.useCallback(te=>{te.shiftKey&&te.preventDefault(),P.current&&P.current.focus&&P.current.focus()},[]),un=u.useCallback(()=>!!(k||[]).find(te=>!!te.draggable),[k]),Bn=u.useRef(null),ga=u.useRef(null),Ka=u.useRef({dblclick:(te,Me)=>{const Pe={id:te,column:eu(Me,"data-col-id")};N.exec("open-editor",Pe)},click:(te,Me)=>{if(Me.target.closest("input")||Bn.current)return;const Pe=eu(Me,"data-col-id");if(Q?.id!==te&&N.exec("focus-cell",{row:te,column:Pe,eventSource:"click"}),z===!1)return;const at=c&&(Me.ctrlKey||Me.metaKey),Wt=c&&Me.shiftKey;(at||F.length>1||!F.includes(te))&&N.exec("select-row",{id:te,toggle:at,range:Wt})},"toggle-row":te=>{const Me=N.getRow(te);N.exec(Me.open!==!1?"close-row":"open-row",{id:te})},"ignore-click":()=>!1}),Mn=u.useMemo(()=>({top:je,bottom:Ee,left:_e.width,xScroll:Re,yScroll:Fe,sense:g&&ve?ve.offsetHeight:Math.max($?.rowHeight||0,40),node:P.current&&P.current.firstElementChild}),[je,Ee,_e.width,Re,Fe,g,ve,$]);function Qa(te,Me){const{container:Pe,sourceNode:at,from:Wt}=Me;if(un()&&!at.getAttribute("draggable-data"))return!1;pe(Wt),ne&&N.getRow(Wt).open&&N.exec("close-row",{id:Wt,nested:!0});const Mt=_o(at),Qe=Mt.cloneNode(!0);Qe.classList.remove("wx-selected"),Qe.querySelectorAll("[tabindex]").forEach(Rt=>Rt.setAttribute("tabindex","-1")),Pe.appendChild(Qe),ke(Qe);const rt=(ie||0)-Ne.d,Kt=Fe?Z:0;Pe.style.width=Math.min((y||0)-Kt,ce&&Ve<=(y||0)?It:It-Kt)+rt+"px";const Pt=Ud(Mt);Me.offset={x:rt,y:-Math.round(Pt.height/2)},ga.current||(ga.current=te.clientY)}function Ie(te,Me){const{from:Pe}=Me,at=Me.pos,Wt=Ud(P.current);at.x=Wt.x;const Mt=Mn.top;if(at.y<Mt)at.y=Mt;else{const Qe=Wt.height-(Re&&Z>0?Z:Math.round(Mn.sense/2))-Mn.bottom;at.y>Qe&&(at.y=Qe)}if(P.current.contains(Me.targetNode)){const Qe=_o(Me.targetNode),rt=Qe&&uf(Qe);if(rt&&rt!==Pe){Me.to=rt;const Kt=g?ve?.offsetHeight:$?.rowHeight;if(ve&&((V||0)===0||at.y>Mt+Kt-1)){const Pt=Qe.getBoundingClientRect(),Rt=Ud(ve).y,Ot=Pt.y,Ht=Rt>Ot?-1:1,Dt=Ht===1?"after":"before",Tn=N.getState().flatData,Za=Math.abs(Tn.findIndex(Qt=>Qt.id===Pe)-Tn.findIndex(Qt=>Qt.id===rt)),rn=Za!==1?Dt==="before"?"after":"before":Dt;if(Za===1&&(Ht===-1&&te.clientY>ga.current||Ht===1&&te.clientY<ga.current))return;ga.current=te.clientY,N.exec("move-item",{id:Pe,target:rt,mode:rn,inProgress:!0})}}d&&d({event:te,context:Me})}$k(te,Wt,Me,Mn)}function ri(te,Me){const{from:Pe,to:at}=Me;N.exec("move-item",{id:Pe,target:at,inProgress:!1}),Bn.current=setTimeout(()=>{Bn.current=0},1),pe(null),ke(null),ga.current=null,$w(Me)}function ut(){const te=document.createElement("div");te.style.cssText="position:absolute;left:-1000px;width:100px;padding:0px;margin:0px;min-height:100px;overflow-y:scroll;",document.body.appendChild(te);const Me=te.offsetWidth-te.clientWidth;return document.body.removeChild(te),Me}const Xa=u.useMemo(()=>Ut>0?{width:`${Ut}px`}:void 0,[Ut]),qt=u.useRef(null);function zs(){Promise.resolve().then(()=>{let te=0,Me=Nt;const Pe=qt.current;Pe&&(Array.from(Pe.children).forEach((at,Wt)=>{ye.current[Nt+Wt]=at.offsetHeight,te+=at.offsetHeight,Me++}),tt(te),Ke(Me))})}u.useEffect(()=>{st&&g&&zs()},[st,g,Nt]);let[B,He]=u.useState();u.useEffect(()=>{if(Q&&(!z||!Jt.length||Jt.includes(Q.row)))He({...Q});else if(st.length&&Ne.data.length){if(!B||Jt.length&&!Jt.includes(B.row)||st.findIndex(te=>te.id===B.row)===-1||Ne.data.findIndex(te=>te.id===B.column&&!te.collapsed)===-1){const te=Jt[0]||st[0].id,Me=Ne.data.findIndex(Pe=>!Pe.collapsed);He(Me!==-1?{row:te,column:Ne.data[Me].id}:null)}}else He(null)},[Q]);const dt=u.useRef(null);u.useEffect(()=>{const te=P.current;if(!te)return;const Me=Ok(te,w);return()=>{typeof Me=="function"&&Me()}},[w]);const en=u.useRef({});Object.assign(en.current,{start:Qa,move:Ie,end:ri,getReorder:()=>Y,getDraggableInfo:()=>({hasDraggable:un()})}),u.useEffect(()=>{const te=P.current;return te?Fk(te,en).destroy:void 0},[Y,P.current]),u.useEffect(()=>{const te=P.current;return te?zk(te,{keys:C!==!1&&{...Lk,"ctrl+z":le,"ctrl+y":le,...C},exec:Me=>N.exec("hotkey",Me)}).destroy:void 0},[N,le,C]);const sn=u.useRef({scroll:N.getReactiveState().scroll,scrollLeft:N.getReactiveState().scrollLeft,scrollTop:N.getReactiveState().scrollTop});sn.current.getWidth=()=>(y||0)-(Fe?Z:0),sn.current.getHeight=()=>Ae,sn.current.getScrollMargin=()=>_e.width+Le.width,u.useEffect(()=>{Ik(dt.current,sn.current)},[]);const Is=u.useRef(null);u.useEffect(()=>{const te=Is.current;if(!te)return;const Me=[];Me.push(ii(te,()=>Q&&N.exec("focus-cell",{eventSource:"click"})).destroy),Me.push(FC(te,Ka.current)),K(te.clientHeight);const Pe=new ResizeObserver(()=>{K(te.clientHeight)});return Pe.observe(te),Me.push(()=>Pe.disconnect()),()=>Me.forEach(at=>at())},[]);const na=`wx-grid ${j?`wx-responsive-${j}`:""}`;return u.useEffect(()=>{Q&&(st.some(te=>te.id===Q.row)&&Ne.data.some(te=>te.id===Q.column&&!te.collapsed)||N.exec("focus-cell",{eventSource:"destroy"}))},[Q,st,Ne.data,N]),s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"wx-4VuBwK2D "+na,style:{"--header-height":`${je}px`,"--footer-height":`${Ee}px`,"--split-left-width":`${_e.width}px`,"--split-right-width":`${Le.width}px`},children:s.jsx("div",{ref:P,className:"wx-4VuBwK2D wx-table-box",style:Xa,role:ne?"treegrid":"grid","aria-colcount":Ne.data.length,"aria-rowcount":st.length,"aria-multiselectable":ne&&c?!0:void 0,tabIndex:-1,children:s.jsxs("div",{ref:dt,className:"wx-4VuBwK2D wx-scroll",style:{overflowX:Re?"scroll":"hidden",overflowY:Fe?"scroll":"hidden"},onScroll:Nn,children:[a?s.jsx("div",{className:"wx-4VuBwK2D wx-header-wrapper",children:s.jsx(ay,{contentWidth:It,deltaLeft:Ne.dh,columns:Ne.header,columnStyle:p,bodyHeight:Ae-+r})}):null,s.jsxs("div",{ref:Is,className:"wx-4VuBwK2D wx-body",style:{width:`${It}px`,height:`${St}px`},onMouseDown:te=>Vi(te),children:[l?s.jsx(nA,{overlay:l}):null,s.jsx("div",{ref:qt,className:"wx-4VuBwK2D wx-data",style:{paddingTop:`${ht.d}px`,paddingLeft:`${Ne.d}px`},children:st.map((te,Me)=>{const Pe=F.indexOf(te.id)!==-1,at=me===te.id,Wt="wx-row"+(g?" wx-autoheight":"")+(m?" "+m(te):"")+(Pe?" wx-selected":"")+(at?" wx-inactive":""),Mt=g?{minHeight:`${te.rowHeight||W}px`}:{height:`${te.rowHeight||W}px`};return s.jsx("div",{className:"wx-4VuBwK2D "+Wt,"data-id":zn(te.id),"data-context-id":zn(te.id),style:Mt,role:"row","aria-rowindex":Me,"aria-expanded":te.open,"aria-level":ne?te.$level+1:void 0,"aria-selected":ne?Pe:void 0,tabIndex:-1,children:Ne.data.map(Qe=>Qe.collapsed?s.jsx("div",{className:"wx-4VuBwK2D wx-cell wx-collapsed"},Qe.id):L?.id===te.id&&L.column===Qe.id?s.jsx(cA,{row:te,column:Qe},Qe.id):s.jsx(Yk,{row:te,column:Qe,columnStyle:p,cellStyle:v,reorder:Y,focusable:B?.row===te.id&&B?.column===Qe.id},Qe.id))},te.id)})})]}),r&&(E||[]).length?s.jsx(ay,{type:"footer",contentWidth:It,deltaLeft:Ne.df,columns:Ne.footer,columnStyle:p}):null]})})}),J?s.jsx(dA,{config:J,rowStyle:m,columnStyle:p,cellStyle:v,header:a,footer:r,reorder:Y}):null]})}const mA=n=>n.split("-").map(a=>a?a.charAt(0).toUpperCase()+a.slice(1):"").join(""),hA=u.forwardRef(function({data:n=[],columns:a=[],rowStyle:r=null,columnStyle:l=null,cellStyle:c=null,selectedRows:d,select:m=!0,multiselect:p=!1,header:v=!0,footer:g=!1,dynamic:w=null,overlay:y=null,reorder:b=!1,onReorder:j=null,autoRowHeight:C=!1,sizes:N,split:T,tree:k=!1,autoConfig:E=!1,init:R=null,responsive:$=null,sortMarks:F,undo:q=!1,hotkeys:z=null,filterValues:L,...ie},V){const ne=u.useRef();ne.current=ie;const Q=u.useMemo(()=>new Mk(Rw),[]),J=u.useMemo(()=>Q.in,[Q]),le=u.useRef(null);le.current===null&&(le.current=new kw((Le,ue)=>{const Ve="on"+mA(Le);ne.current&&ne.current[Ve]&&ne.current[Ve](ue)}),J.setNext(le.current));const Y=u.useMemo(()=>({getState:Q.getState.bind(Q),getReactiveState:Q.getReactive.bind(Q),getStores:()=>({data:Q}),exec:J.exec,setNext:Le=>(le.current=le.current.setNext(Le),le.current),intercept:J.intercept.bind(J),on:J.on.bind(J),detach:J.detach.bind(J),getRow:Q.getRow.bind(Q),getColumn:Q.getColumn.bind(Q)}),[Q,J]),[O,Z]=u.useState(0),[X,D]=u.useState(0),[K,ce]=u.useState(null),[W,P]=u.useState(null),me=u.useMemo(()=>{if(E&&!a.length&&n.length){const Le=n[0],ue=[];for(let Ve in Le)if(Ve!=="id"&&Ve[0]!=="$"){let Ye={id:Ve,header:Ve[0].toUpperCase()+Ve.slice(1)};typeof E=="object"&&(Ye={...Ye,...E}),ue.push(Ye)}return ue}return(W&&W.columns)??a},[E,a,n,W]),pe=u.useMemo(()=>(W&&W.sizes)??N,[W,N]),ve=u.useCallback(Le=>{if(Z(Le.width),D(Le.height),$){const ue=Object.keys($).map(Number).sort((Ve,Ye)=>Ve-Ye).find(Ve=>Le.width<=Ve)??null;ue!==K&&(P($[ue]),ce(ue))}},[$,K]),ke=u.useContext(On.theme),_e=u.useRef(0);return u.useEffect(()=>{if(!_e.current)R&&R(Y);else{const Le=Q.getState();Q.init({data:n,columns:me,split:T||Le.split,sizes:pe||Le.sizes,selectedRows:d||Le.selectedRows,dynamic:w,tree:k,sortMarks:F||Le.sortMarks,filterValues:L||Le.filterValues,undo:q,reorder:b,_skin:ke,_select:m})}_e.current++},[Q,n,me,T,pe,d,w,k,F,L,q,b,ke,m,R,Y]),_e.current===0&&Q.init({data:n,columns:me,split:T||{left:0},sizes:pe||{},selectedRows:d||[],dynamic:w,tree:k,sortMarks:F||{},filterValues:L||{},undo:q,reorder:b,_skin:ke,select:m}),u.useImperativeHandle(V,()=>({...Y}),[Y]),s.jsx(Wa.Provider,{value:Y,children:s.jsx(op,{words:cp,optional:!0,children:s.jsx(fA,{header:v,footer:g,overlay:y,rowStyle:r,columnStyle:l,cellStyle:c,onReorder:j,multiselect:p,autoRowHeight:C,clientWidth:O,clientHeight:X,responsiveLevel:K,resize:ve,hotkeys:z})})})});tp(_a);const In=u.createContext(null),fp=u.createContext(null),mp=u.createContext(null);function pA({children:n}){const a=u.useContext(On.i18n),r=u.useMemo(()=>a.getGroup("filemanager"),[a]),l=u.useContext(In),[c]=ps(l,"panels"),d=nt(l,"activePanel"),m=c[d].path,[p,v]=u.useState(null),[g,w]=u.useState(null),[y,b]=u.useState(""),[j,C]=u.useState(""),[N,T]=u.useState(!1);function k(){const F=y.trim();if(!F){T(!0);return}p.add?l.exec("create-file",{file:{...p.item,name:F},parent:m}):j!==F&&l.exec("rename-file",{id:p.item.id,name:F}),E()}function E(){v(null),T(null),C(""),b("")}function R(){l.exec("delete-files",{ids:g.selected}),w(null)}const $=u.useMemo(()=>({showPrompt(F){const q=F.item.name||(F.item.type==="folder"?r("New folder"):`${r("New file")}.txt`);C(q),b(q),v({...F})},showConfirm(F){w({...F})}}),[r]);return s.jsxs(fp.Provider,{value:$,children:[s.jsx(pC,{children:n}),p?s.jsx(Dh,{title:r(`Enter ${p.item.type} name`),onConfirm:k,onCancel:E,children:s.jsx(rp,{error:N,select:!0,focus:!0,value:y,onChange:({value:F})=>b(F)})}):null,g?s.jsx(Dh,{title:r("Are you sure you want to delete these items:"),onConfirm:R,onCancel:()=>w(null),children:g.selected?s.jsx("ul",{className:"wx-gq7BMzEP wx-list",children:g.selected.map((F,q)=>s.jsx("li",{children:F},q))}):null}):null]})}let iy={"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 gA(n){const a=n.lastIndexOf("."),r=a>0&&a<n.length-1?Math.min(10,n.length-a):Math.min(5,n.length),l=n.slice(0,-r),c=n.slice(-r);return[l,c]}function vA({item:n}){const a=u.useContext(In),r=u.useContext(On.i18n).getGroup("filemanager"),l=u.useContext(In).templates,[c]=ps(a,"panels"),d=nt(a,"activePanel"),m=nt(a,"mode"),p=c[d].selected,v=u.useMemo(()=>l.preview(n,214,163),[l,n]),g=u.useMemo(()=>l.icon(n,"big"),[l,n]),[w,y]=u.useMemo(()=>gA(n.name),[n.name]);return s.jsx(s.Fragment,{children:n.id==="/wx-filemanager-parent-link"?m!=="search"?s.jsx("div",{className:"wx-GAOa4kDV wx-back-item",children:s.jsxs("div",{className:`wx-GAOa4kDV wx-back ${n.navigation?"wx-selected":""}`,"data-id":zn("/wx-filemanager-parent-link"),children:[s.jsx("i",{className:"wx-GAOa4kDV wxi-arrow-left"}),s.jsx("span",{children:r("Back to parent folder")})]})}):null:s.jsxs("div",{className:`wx-GAOa4kDV wx-item ${p?.length&&p.indexOf(n.id)>=0?"wx-selected":""}`,"data-id":zn(n.id),children:[v?s.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-preview",children:s.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:r("A miniature file preview"),src:v})}):g?s.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-icon",children:s.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:"",src:g})}):s.jsx("div",{className:"wx-GAOa4kDV wx-preview",children:s.jsx("i",{className:`wx-GAOa4kDV wxi-${n.type}`})}),n.type==="folder"?s.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[s.jsxs("div",{className:"wx-GAOa4kDV wx-folder-name",children:[s.jsx("span",{className:"wx-GAOa4kDV wx-type",children:r("Folder")}),s.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[s.jsx("span",{children:w}),s.jsx("span",{children:y})]})]}),s.jsx("div",{"data-action-id":zn(n.id),className:"wx-GAOa4kDV wx-more",children:s.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]}):s.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[s.jsx("div",{className:"wx-GAOa4kDV wx-file-name",children:s.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[s.jsx("span",{children:w}),s.jsx("span",{children:y})]})}),s.jsx("div",{"data-action-id":zn(n.id),className:"wx-GAOa4kDV wx-more",children:s.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]})]})})}function Vw(){const n=u.useContext(In),a=u.useContext(On.i18n),r=u.useMemo(()=>a.getGroup("filemanager"),[a]),[l]=ps(n,"panels"),c=nt(n,"activePanel"),d=nt(n,"mode"),m=l[c]._files,p=l[c].selected,v=l[c].path,g=l[c]._crumbs,w=l[c]._selectNavigation,y=u.useCallback((E,R)=>{const $=R&&(R.ctrlKey||R.metaKey),F=R&&R.shiftKey;if(E==="/wx-filemanager-parent-link"){if(p.length&&($||F))return;n.exec("select-file",{type:"navigation"});return}let q=E==="body"&&R?null:E;const z=R.target.className.indexOf("wx-more")!==-1||R.target.className.indexOf("wxi-dots-v")!==-1;setTimeout(()=>{n.exec("select-file",{id:q,toggle:$&&!z,range:F&&!z,panel:c})},1)},[n,p,c]),b=u.useCallback(()=>{g.length>1&&n.exec("set-path",{id:g[g.length-2].id,panel:c,selected:[g[g.length-1].id]})},[n,g,c]),j=u.useCallback(E=>{if(E==="/wx-filemanager-parent-link")return b();d==="search"&&n.exec("filter-files",{text:""});const R=m.find($=>$.id===E);R&&(R.type=="folder"?n.exec("set-path",{id:R.id,panel:c}):n.exec("open-file",{id:R.id}))},[n,b,d,m,c]),C=u.useCallback((E,R)=>{(!p?.length||!p.filter($=>$?.id===E).length>0)&&y(E,R)},[p,y]),N=u.useMemo(()=>v!=="/"?[{id:"/wx-filemanager-parent-link",name:r("Back to parent folder"),navigation:w},...m]:m,[v,r,w,m]),T=u.useRef(null),k=u.useRef();return u.useEffect(()=>{T.current&&(k.current?(k.current.click=y,k.current._dblclick=j,k.current.context=C):(k.current={click:y,dblclick:E=>k.current._dblclick(E),_dblclick:j,context:C},Lo(T.current,k.current)))},[y,j,C]),d=="search"&&!N.length?s.jsx("div",{className:"wx-iyjASZCY wx-not-found",children:s.jsx("div",{className:"wx-iyjASZCY wx-not-found-text",children:r("Looks like nothing is here")})}):s.jsx("div",{tabIndex:0,className:"wx-iyjASZCY "+("wx-cards"+(v!=="/"&&d!=="search"?" wx-has-back-link":"")),"data-id":zn("body"),ref:T,children:N.map(E=>s.jsx(vA,{item:E},E.id))})}function Tl({name:n="",spin:a=!1,onClick:r}){return s.jsx("i",{"data-menu-ignore":"true",className:`wx-uwcvNSAG wx-icon wxi-${n} ${a?"wx-spin":""} ${r?"wx-clickable":""}`,onClick:()=>{r&&r()}})}function xA(){const n=u.useContext(On.i18n).getGroup("filemanager"),a=u.useContext(In),r=nt(a,"activePanel"),[l]=ps(a,"panels"),c=u.useMemo(()=>l[r]._crumbs,[l,r]);function d(){a.exec("filter-files",{text:""})}return s.jsxs("div",{className:"wx-GDJvtROw wx-search",children:[s.jsxs("div",{className:"wx-GDJvtROw wx-toolbar",children:[s.jsx("div",{className:"wx-GDJvtROw wx-back-icon",children:s.jsx(Tl,{name:"angle-left",onClick:d})}),s.jsxs("div",{className:"wx-GDJvtROw wx-text",children:[n("Search results in")," ",Array.isArray(c)&&c.map((m,p)=>s.jsxs(u.Fragment,{children:[p?"/":null,m.id=="/"?n(m.name):m.name]},p))]})]}),s.jsx(Vw,{})]})}function ah({narrowMode:n,extraInfo:a}){const r=u.useContext(In),{preview:l,icon:c}=r.templates,d=u.useContext(On.i18n),m=u.useMemo(()=>d.getGroup("filemanager"),[d]),p=u.useMemo(()=>Mo("%D, %d %F %Y, %H:%i",d.getRaw().calendar),[d]),[v,g]=ps(r,"panels"),w=nt(r,"activePanel"),y=nt(r,"preview"),b=nt(r,"search"),j=u.useMemo(()=>{const z=v&&w!=null&&v[w]?._selected?.length||0;return b&&!z},[b,g,w]),C=u.useMemo(()=>{const z=v&&w!=null?v[w]:null;return z?j?z._files:z._selected:[]},[j,g,w]),N=u.useCallback((z,L)=>(z?`${z} ${m(z>1?"folders":"folder")} `:"")+(L?`${L} ${m(L>1?"files":"file")}`:""),[m]),T=u.useCallback(()=>{r.exec("show-preview",{mode:!y})},[r,y]),k=u.useCallback(z=>z.type==="folder"?m("Folder"):z.ext||m("Unknown file"),[m]),E=u.useMemo(()=>{let z,L,ie,V,ne,Q,J,le;if(C.length===1&&!j){L=C[0],z=L.name;const Y=l(L,400,500);Y?(ie=Y,V=""):(V=c(L,"big"),ie=""),ne=L.type!=="folder"}else{if(L=ne=null,z="",C.length){let Y=0,O=0,Z=0,X=[],D;C.forEach(ce=>{typeof ce.size>"u"&&(D=!0,Y=void 0),D||(Y+=ce.size),X.push(k(ce)),ce.type==="folder"?O++:Z++});const K=new Set(X);Q=K.size>1?m("multiple"):[...K][0],J=N(O,Z),le=Y,j||(z=m("Multiple files"))}V=c({type:j?"search":C.length?"multiple":"none"},"big"),ie=""}return{name:z,item:L,previewSrc:ie,iconSrc:V,showDownloadIcon:ne,type:Q,totalCount:J,totalSize:le}},[C,j,l,c,m,k,N]),R=u.useCallback(()=>{r.exec("download-file",{id:C[0].id})},[r,C]),$=u.useCallback(async z=>{if(!a||!z)return null;try{return await a(z)}catch(L){return console.log(L),null}},[a]),[F,q]=u.useState(null);return u.useEffect(()=>{let z=!1;return q(null),Promise.resolve($(E.item)).then(L=>{z||q(L)}).catch(()=>{z||q(null)}),()=>{z=!0}},[$,E.item]),s.jsx("div",{className:"wx-O0BTtRrH wx-wrapper",children:C&&C.length?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"wx-O0BTtRrH wx-preview",children:[s.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[s.jsx("div",{className:"wx-O0BTtRrH wx-name",children:E.name}),s.jsxs("div",{className:"wx-O0BTtRrH wx-icons",children:[E.showDownloadIcon?s.jsx(Tl,{name:"download",onClick:R}):null,n?s.jsx(Tl,{name:"close",onClick:T}):null]})]}),E.previewSrc?s.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:s.jsx("img",{src:E.previewSrc,alt:m("A miniature file preview")})}):E.iconSrc?s.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:s.jsx("img",{src:E.iconSrc,alt:m("A miniature file preview")})}):s.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:E.item?s.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${E.item.type}`}):s.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${j?"search":"file-multiple-outline"}`})})]}),s.jsxs("div",{className:"wx-O0BTtRrH wx-info-panel",children:[s.jsx("div",{className:"wx-O0BTtRrH wx-title",children:m(j?"Found":"Information")}),s.jsxs("div",{className:"wx-O0BTtRrH wx-list",children:[E.item?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Type")}),s.jsx("span",{className:"wx-O0BTtRrH wx-value",children:k(E.item)}),typeof E.item.size<"u"?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Size")}),s.jsx("span",{className:"wx-O0BTtRrH wx-value",children:tu(E.item.size)})]}):null,s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Date")}),s.jsxs("span",{className:"wx-O0BTtRrH wx-value",children:[p(E.item.date)," "]})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Count")}),s.jsx("span",{className:"wx-O0BTtRrH wx-value",children:E.totalCount}),s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Type")}),s.jsx("span",{className:"wx-O0BTtRrH wx-value",children:E.type}),typeof E.totalSize<"u"?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Size")}),s.jsx("span",{className:"wx-O0BTtRrH wx-value",children:tu(E.totalSize)})]}):null]}),F?Object.entries(F).map(([z,L])=>s.jsxs(Yh.Fragment,{children:[s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:z}),s.jsx("span",{className:"wx-O0BTtRrH wx-value",children:L})]},z)):null]})]})]}):s.jsxs("div",{className:"wx-O0BTtRrH wx-no-info-panel",children:[s.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[s.jsx("div",{className:"wx-O0BTtRrH wx-name",children:E.name}),s.jsx("div",{className:"wx-O0BTtRrH wx-icons",children:n?s.jsx(Tl,{name:"close",onClick:T}):null})]}),s.jsx("div",{className:"wx-O0BTtRrH wx-no-info-wrapper",children:s.jsxs("div",{className:"wx-O0BTtRrH wx-no-info",children:[E.previewSrc?s.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:s.jsx("img",{src:E.previewSrc,alt:m("A miniature file preview")})}):E.iconSrc?s.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:s.jsx("img",{src:E.iconSrc,alt:m("A miniature file preview")})}):s.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:s.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${j?"search":"message-question-outline"}`})}),s.jsx("span",{className:"wx-O0BTtRrH wx-text",children:j?"":m("Select file or folder to view details")})]})})]})})}function Yw({panel:n}){const a=u.useContext(In),r=u.useContext(On.i18n),l=u.useMemo(()=>r.getGroup("filemanager"),[r]),[c,d]=ps(a,"panels"),m=u.useMemo(()=>c[n]._files,[d,n]),p=u.useMemo(()=>c[n]._crumbs||[],[d,n]);function v(C){const N=up(C,p);a.exec("set-path",{id:C,panel:n,...N&&{selected:[N]}})}const[g,w]=u.useState(null);u.useEffect(()=>{m&&w(null)},[m]);function y(){w(!0),a.exec("request-data",{id:p[p.length-1].id}),setTimeout(()=>{w(null)},5e3)}const b=u.useRef(null),j=u.useRef();return u.useEffect(()=>{j.current?j.current.click=v:(j.current={click:v},Lo(b.current,j.current))},[v]),s.jsxs("div",{className:"wx-SNY5LTYx wx-breadcrumbs","data-menu-ignore":"true",ref:b,children:[s.jsx("div",{className:"wx-SNY5LTYx wx-refresh-icon",children:s.jsx(Tl,{name:"refresh",spin:!!g,onClick:y})}),p.map((C,N)=>s.jsxs(Yh.Fragment,{children:[N?s.jsx(Tl,{name:"angle-right"}):null,s.jsx("div",{className:"wx-SNY5LTYx wx-item","data-id":zn(C.id),"data-menu-ignore":"true",children:C.id=="/"?l(C.name):C.name})]},N))]})}function yA({row:n}){const a=u.useContext(On.i18n),[r]=u.useState(()=>a.getGroup("filemanager")),l=u.useContext(In).templates,[c]=u.useState(()=>l.icon(n,"small"));return s.jsx("div",{className:"wx-qgAqG6sL wx-name-cell",children:n.id==="/wx-filemanager-parent-link"?s.jsxs(s.Fragment,{children:[s.jsx("i",{className:"wx-qgAqG6sL wxi-arrow-left"}),s.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",r("Back to parent folder")]})]}):s.jsxs(s.Fragment,{children:[c?s.jsx("img",{className:"wx-qgAqG6sL wx-icon",alt:"",src:c,height:"24px",width:"24px"}):s.jsx("i",{className:`wx-qgAqG6sL wxi-${n.type}`}),s.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",n.name," "]})]})})}function Ww({children:n}){const a=u.useContext(In),r=nt(a,"activePanel"),l=u.useContext(mp),c=u.useRef(null);let d=u.useRef({});return d.current.drop=()=>{const m=c.current,p=S1(m,"data-panel");p&&p!=r&&a.exec("set-active-panel",{panel:p*1})},d.current.dragEnter=()=>{const m=c.current;m&&m.classList.toggle("wx-active")},d.current.dragLeave=()=>{const m=c.current;m&&m.classList.toggle("wx-active")},u.useEffect(()=>{const m=c.current;return l.droparea(m,d.current)},[]),s.jsx("div",{className:"wx-LT9X7tb7 wx-upload-area",ref:c,children:n})}function zh({panel:n,active:a=!1,onClick:r,onContextMenu:l}){const c=u.useContext(In),d=u.useContext(On.i18n),m=u.useMemo(()=>d.getGroup("filemanager"),[d]),p=u.useMemo(()=>Mo("%d %M %Y",d.getRaw().calendar),[d]),[v]=ps(c,"panels"),g=v[n].selected,w=v[n].path,y=v[n]._crumbs,b=v[n]._sorts,j=v[n]._selectNavigation,C=v[n]._files,N=u.useMemo(()=>[{id:"name",header:m("Name"),flexgrow:3,sort:!0,resize:!0,cell:yA},{id:"size",header:m("Size"),width:100,sort:!0,resize:!0,template:Q=>typeof Q=="number"?tu(Q):""},{id:"date",header:m("Date"),width:120,sort:!0,resize:!0,template:Q=>Q?p(Q):""}],[m,p]),T=u.useRef(null),k=u.useRef(null),E=u.useMemo(()=>j?["/wx-filemanager-parent-link"]:[...g],[j,g]);function R(Q,J){if(J&&J.target&&J.target.className&&J.target.className.indexOf("wx-grip")!==-1)return;const le=J&&(J.ctrlKey||J.metaKey),Y=J&&J.shiftKey;if(Q==="/wx-filemanager-parent-link"){if(g.length&&(le||Y))return;c.exec("select-file",{type:"navigation"});return}let O=Q==="body"&&J?null:Q;!T.current&&!k.current?c.exec("select-file",{id:O,toggle:le,range:Y,panel:n}):(T.current=null,k.current=null)}function $(){y.length>1&&c.exec("set-path",{id:y[y.length-2].id,panel:n,selected:[y[y.length-1].id]})}function F(Q){if(Q==="/wx-filemanager-parent-link")return $();const J=C.find(le=>le.id===Q);J&&(J.type==="folder"?c.exec("set-path",{id:J.id,panel:n}):c.exec("open-file",{id:J.id}))}function q(Q){const J=Q.key,le=b[w];let Y=le?"asc":"desc";le&&le.key===J&&(Y=le.order==="asc"?"desc":"asc"),c.exec("sort-files",{key:J,order:Y,panel:n,path:w})}function z(Q){Q.intercept("sort-rows",J=>(T.current=!0,q(J),!1)),Q.intercept("select-row",()=>!1),Q.on("resize-column",()=>k.current=!0),Q.intercept("hotkey",()=>!1)}const L=u.useMemo(()=>w!=="/"?[{id:"/wx-filemanager-parent-link",name:m("Back to parent folder")},...C]:C,[w,C,m]),ie=u.useMemo(()=>{if(L&&b&&b[w]){const{key:Q,order:J}=b[w];return{[Q]:{order:J}}}},[L,b,w]),V=u.useRef(null),ne=u.useRef();return u.useEffect(()=>{ne.current?(ne.current.click=R,ne.current._dblclick=F):(ne.current={click:R,dblclick:Q=>ne.current._dblclick(Q),_dblclick:F},Lo(V.current,ne.current))},[R,F]),s.jsxs("div",{onClick:r,onContextMenu:l,className:"wx-SSaVhET7 wx-wrapper",children:[s.jsx(Yw,{panel:n}),s.jsx("div",{"data-id":zn("body"),className:`wx-SSaVhET7 wx-list ${a?"wx-active":""}`,ref:V,children:s.jsx(Ww,{children:s.jsx(hA,{init:z,data:L,columns:N,selectedRows:E,columnStyle:()=>"wx-SSaVhET7 wx-each-cell",sizes:{rowHeight:42,headerHeight:42},sortMarks:ie})})})]})}function wA(){const n=u.useContext(In),a=nt(n,"activePanel");function r(l){n.exec("set-active-panel",{panel:l})}return s.jsxs("div",{className:"wx-L55BfJa2 wx-panels","data-id":zn("body"),children:[s.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":0,children:s.jsx(zh,{panel:0,active:a==0,onClick:()=>r(0),onContextMenu:()=>r(0)})}),s.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":1,children:s.jsx(zh,{panel:1,active:a==1,onClick:()=>r(1),onContextMenu:()=>r(1)})})]})}function Kw({folderIcon:n=!1,folder:a={}}){const r=u.useContext(In),[l,c]=ps(r,"panels"),d=nt(r,"activePanel"),m=u.useMemo(()=>l[d].path,[c,d]),p=u.useContext(On.i18n),v=u.useMemo(()=>p.getGroup("filemanager"),[p]),g=u.useMemo(()=>!!a.data?.find(j=>j.type==="folder"),[a]),w=u.useMemo(()=>a.id=="/"?v(a.name):a.name,[a,v]),y=u.useMemo(()=>a.$level>1?(a.$level-1)*20:0,[a]),b=a.open;return s.jsxs(s.Fragment,{children:[s.jsxs("li",{"data-id":zn(a.id),className:`wx-NYfhvGIt wx-folder${m===a.id?" wx-selected":""}`,style:{paddingLeft:`${y}px`},children:[g?s.jsx("i",{className:`wx-NYfhvGIt wx-toggle wxi-${b?"angle-down":"angle-right"}`,"data-action":"toggle"}):s.jsx("span",{className:"wx-NYfhvGIt wx-toggle-placeholder"}),s.jsx("i",{className:"wx-NYfhvGIt "+(n||"wxi-folder")}),s.jsxs("span",{className:"wx-NYfhvGIt wx-name",children:[" ",w," "]})]}),b&&a.data&&a.data.length&&g?s.jsx(s.Fragment,{children:a.data.map(j=>j.type==="folder"?s.jsx(Kw,{folder:j},j.id):null)}):null]})}function bA(){const n=u.useContext(In),[a,r]=ps(n,"data"),[l,c]=ps(n,"panels"),d=nt(n,"activePanel"),m=u.useMemo(()=>l[d]._crumbs,[c,d]),p=u.useCallback(j=>{n.exec("open-tree-folder",{id:j,mode:!a.byId(j).open})},[n,r]),v=u.useCallback(j=>{const C=up(j,m);n.exec("set-path",{id:j,panel:d,...C&&{selected:[C]}})},[n,m,d]),[g,w]=u.useState([]);u.useEffect(()=>{w(a.byId(0).data)},[r]);const y=u.useRef(null),b=u.useRef();return u.useEffect(()=>{b.current?(b.current.click=v,b.current.toggle=p):(b.current={click:v,toggle:p},Lo(y.current,b.current))},[v,p]),s.jsx("ul",{ref:y,className:"wx-LyHJ6R6A",children:g.map(j=>j.type==="folder"?s.jsx(Kw,{folder:j},j.id):null)})}function SA(){const n=u.useContext(In),a=u.useContext(On.i18n),r=u.useMemo(()=>a.getGroup("filemanager"),[a]),l=nt(n,"drive"),c=l?l.used:"",d=l?l.total:"";return c&&d?s.jsxs("div",{className:"wx-DetSyKGG wx-drive",children:[s.jsx("progress",{value:c,max:d,className:"wx-DetSyKGG wx-progress"}),s.jsxs("p",{children:[tu(c)," ",r("of")," ",tu(d)," ",r("used")]})]}):null}function jA({option:n}){const a=u.useContext(On.i18n).getGroup("filemanager"),r=u.useContext(mp),l=u.useCallback(()=>{r.open({})},[r]);return s.jsx("div",{className:"wx-9XiKcxq5 wx-upload-button",onClick:l,children:s.jsx("span",{children:a(n.text)})})}function CA({readonly:n,menuOptions:a}){const r=u.useContext(On.i18n).getGroup("filemanager"),{showPrompt:l}=u.useContext(fp);u.useEffect(()=>{$C("upload",jA)},[]);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 d=u.useMemo(()=>a("add").map(m=>(m.text=r(m.text),m)),[a,r]);return s.jsxs("div",{className:"wx-FlucfALM wx-wrapper",children:[!n&&s.jsx("div",{className:"wx-FlucfALM wx-button",children:s.jsx(qC,{options:d,at:"bottom-fit",onClick:c,children:s.jsx(Kc,{type:"primary block",children:r("Add New")})})}),s.jsx("div",{className:"wx-FlucfALM wx-tree",children:s.jsx(bA,{})}),s.jsx(SA,{})]})}function kA({value:n="",onSearch:a}){const[r,l]=Tw(n),c=u.useContext(On.i18n).getGroup("filemanager"),d=u.useRef(null),m=u.useMemo(()=>r!==""?"wxi-close":"wxi-search",[r]);function p(g){const w=g.target.value;l(w),a&&a({value:w})}function v(){l(""),d.current&&d.current.focus(),a&&a({value:""})}return s.jsxs("div",{className:"wx-lUZMtgT1 wx-search-input",children:[s.jsx("i",{className:`wx-lUZMtgT1 wx-icon ${m}`,onClick:v}),s.jsx("input",{type:"text",className:"wx-lUZMtgT1 wx-text",ref:d,value:r,onInput:p,placeholder:c("Search")})]})}function AA({narrowMode:n=!1,onShowTree:a}){const r=u.useContext(In),l=u.useContext(On.i18n).getGroup("filemanager"),c=nt(r,"mode"),d=nt(r,"preview"),m=nt(r,"search"),p=[{icon:"wxi-view-sequential",id:"table"},{icon:"wxi-view-grid",id:"cards"},{icon:"wxi-view-column",id:"panels"}];function v({value:y}){r.exec("set-mode",{mode:y})}function g(y){y.preventDefault(),r.exec("show-preview",{mode:!d})}function w(y){r.exec("filter-files",{text:y.value})}return s.jsxs("div",{className:"wx-5PZQQztG wx-toolbar",children:[s.jsxs("div",{className:"wx-5PZQQztG wx-left "+(n?"wx-left-narrow":""),children:[n?c==="panels"||c==="search"?null:s.jsx("div",{className:"wx-5PZQQztG wx-sidebar-icon","data-id":zn("toggle-tree"),children:s.jsx(Tl,{onClick:()=>a&&a(),name:"subtask"})}):s.jsx("div",{className:"wx-5PZQQztG wx-name",children:l("Files")}),s.jsx(kA,{onSearch:w,value:m})]}),s.jsxs("div",{className:"wx-5PZQQztG wx-right",children:[n?null:s.jsx("div",{className:"wx-5PZQQztG wx-preview-icon",children:s.jsx(gC,{onClick:g,value:d,children:s.jsx("i",{className:"wx-5PZQQztG wxi-eye"})})}),s.jsx("div",{className:"wx-5PZQQztG wx-modes",children:s.jsx(uC,{value:c,options:p,onChange:v})})]})]})}function NA(){const n=u.useContext(In),a=nt(n,"activePanel");return s.jsxs("div",{className:"wx-NwohNJzN wx-wrapper",children:[s.jsx(Yw,{panel:a}),s.jsx(Ww,{children:s.jsx(Vw,{})})]})}function MA({readonly:n=!1,menuOptions:a,extraInfo:r}){const l=u.useRef(null),c=u.useRef(null),[d,m]=u.useState(void 0),[p,v]=u.useState(void 0),[g,w]=u.useState(!1),y=Iw(),b=u.useContext(In),{showPrompt:j,showConfirm:C}=u.useContext(fp),N=u.useContext(On.i18n),T=u.useMemo(()=>N.getGroup("filemanager"),[N]),k=nt(b,"mode"),E=nt(b,"preview"),R=nt(b,"activePanel"),[$,F]=ps(b,"panels"),q=u.useMemo(()=>($&&R!=null?$[R]:null)?.selected??[],[F,R]),z=u.useMemo(()=>($&&R!=null?$[R]:null)?.path,[F,R]),[L,ie]=u.useState([]);u.useEffect(()=>{const K=l.current;if(!K)return;const ce=new ResizeObserver(W=>{const P=W[0]?.borderBoxSize?.[0]?.inlineSize;typeof P=="number"&&v(P<768)});return ce.observe(K),()=>{ce.disconnect()}},[]);const V=u.useCallback(()=>{w(K=>!K)},[]),ne=u.useCallback(K=>{p&&eu(K)!=="toggle-tree"&&w(!1)},[p]);u.useEffect(()=>{const K=c.current;if(K)return ii(K,ne).destroy},[ne]),u.useEffect(()=>{const K=c.current;if(!K)return;const ce=new ResizeObserver(()=>{K&&m(K.clientWidth)});return ce.observe(K),K&&m(K.clientWidth),()=>{ce.disconnect()}},[]);const Q=u.useMemo(()=>({icon:"wxi-eye",text:"Preview",id:"preview"}),[]),J=u.useCallback(K=>{let ce=p?[Q]:[];return K==="file"&&(ce=[...ce,...a().filter(W=>W.id==="download")]),ce},[p,Q,a]),le=u.useRef(null),Y=u.useCallback((K,ce,W)=>{const P=W?[ce.id]:q;switch(K){case"download":b.exec("download-file",{id:ce.id});break;case"copy":case"move":le.current={action:K,ids:P};break;case"paste":le.current&&b.exec(le.current.action==="copy"?"copy-files":"move-files",{ids:le.current.ids,target:ce?.type==="folder"?ce.id:z});break;case"rename":j({item:ce});break;case"delete":C({selected:P});break;case"preview":b.exec("show-preview",{mode:!E});break}},[b,q,z,j,C,E]),O=u.useCallback(()=>$?.[R],[$,R]);u.useEffect(()=>{const K=l.current;if(!K)return;const ce=RC(K,{api:b,menuOptions:n?J:a,performAction:Y,getPanel:O});return()=>{typeof ce=="function"?ce():ce&&typeof ce.destroy=="function"&&ce.destroy()}},[b,n,J,a,Y,O]);const Z=u.useCallback((K,ce)=>{const W=K?b.getFile(K):null,P=ce.target.closest(".tree-item.folder");let me;if(n)me=J(W?.type);else{switch(K){case"body":me=a(K);break;default:if(W)if(!P&&q.length>1)me=p?[Q,...a("multiselect")]:a("multiselect");else if(K==="/")me=a("folder",W).filter(pe=>pe.id==="paste");else{const pe=a(W.type,W);pe&&(me=p?[Q,...pe]:pe)}}k==="search"&&(me=me?.filter(pe=>pe.id!=="paste"))}if(W?.id&&(!q.length||!q.some(pe=>pe===W.id))&&!P&&b.exec("select-file",{id:W.id}),me?.length)return me.forEach(pe=>{P&&(pe.hotkey=""),pe.text&&(pe.text=T(pe.text)),pe.hotkey&&(pe.subtext=pe.hotkey)}),ie(me),W||{}},[b,n,J,a,q,p,Q,k,T]),X=u.useCallback(K=>{const{action:ce,context:W}=K;ce&&Y(ce.id,W,!ce.hotkey)},[Y]);async function D(K){await Promise.resolve();const{name:ce,size:W}=K.file;b.exec("create-file",{file:{name:ce,size:W,date:new Date,file:K.file},parent:z})}return s.jsx("div",{className:"wx-RJbNonjJ wx-filemanager wx-flex",ref:l,"data-menu-ignore":"false",children:p&&E?s.jsx("div",{className:"wx-RJbNonjJ wx-info-narrow",children:s.jsx(ah,{narrowMode:p,extraInfo:r})}):s.jsxs(s.Fragment,{children:[s.jsx(AA,{narrowMode:p,onShowTree:V}),s.jsx(GC,{dataKey:"id",at:"point",options:L,resolver:Z,onClick:X,children:s.jsxs(zw,{dataKey:"actionId",options:L,resolver:Z,onClick:X,children:[s.jsx(QC,{data:y,apiOnly:!0,uploadURL:D}),s.jsx(mp.Provider,{value:y,children:s.jsx("div",{className:"wx-RJbNonjJ wx-content-wrapper wx-flex",children:k!=="panels"&&k!=="search"?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"wx-RJbNonjJ "+["wx-sidebar",p?"wx-sidebar-narrow":"",g?"wx-sidebar-visible":""].filter(Boolean).join(" "),ref:c,children:s.jsx(CA,{readonly:n,menuOptions:a})}),s.jsxs("div",{className:"wx-RJbNonjJ wx-content",style:{width:`calc(100% - ${d||0}px - 10px)`},children:[s.jsx("div",{className:`wx-RJbNonjJ wx-content-item${E?"":"-fit"}`,"data-id":zn("body"),children:k==="table"?s.jsx(zh,{panel:R}):s.jsx(NA,{})}),E?s.jsx("div",{className:"wx-RJbNonjJ wx-info",children:s.jsx(ah,{extraInfo:r})}):null]})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`wx-RJbNonjJ wx-content-item${E?"":"-fit"}`,children:k==="panels"?s.jsx(wA,{}):s.jsx(xA,{})}),E?s.jsx("div",{className:"wx-RJbNonjJ wx-info",children:s.jsx(ah,{extraInfo:r})}):null]})})})]})})]})})}const TA=n=>n.split("-").map(a=>a?a.charAt(0).toUpperCase()+a.slice(1):"").join("");function EA(n,a){const{type:r,ext:l}=n;if(r==="folder")return!1;let c;return r&&r!=="file"&&iy[r]?c=r:l?c=iy[l]?l:"file":c="unknown",`https://cdn.svar.dev/icons/filemanager/vivid/${a}/${c}.svg`}const RA=u.forwardRef(function(n,a){const{data:r=[],mode:l="cards",drive:c=null,preview:d=!1,panels:m=null,activePanel:p=0,readonly:v=!1,menuOptions:g=MC,extraInfo:w=null,init:y=null,icons:b=EA,previews:j=null,...C}=n,N=u.useRef();N.current=C;const T=u.useMemo(()=>new NC(Rw),[]),k=u.useMemo(()=>T.in,[T]),E=u.useRef(null);E.current===null&&(E.current=new kw((F,q)=>{const z="on"+TA(F);N.current&&N.current[z]&&N.current[z](q)}),k.setNext(E.current));const R=u.useMemo(()=>({getState:T.getState.bind(T),getReactiveState:T.getReactive.bind(T),getStores:()=>({data:T}),exec:k.exec,setNext:F=>(E.current=E.current.setNext(F),E.current),intercept:k.intercept.bind(k),on:k.on.bind(k),detach:k.detach.bind(k),getFile:T.getFile.bind(T),serialize:T.serialize.bind(T),templates:{preview:j||(()=>null),icon:b==="simple"?(()=>null):b}}),[T,k]),$=u.useRef(0);return u.useEffect(()=>{if(!$.current)y&&y(R);else{const F=T.getState();T.init({data:r,mode:l,drive:c,preview:d,panels:m||F.panels||[],activePanel:p})}$.current++},[T,r,l,c,d,m,p,y,R]),$.current===0&&T.init({data:r,mode:l,drive:c,preview:d,panels:m||[],activePanel:p}),u.useImperativeHandle(a,()=>({...R}),[R]),s.jsx(In.Provider,{value:R,children:s.jsx(op,{words:cp,optional:!0,children:s.jsx(pA,{children:s.jsx(MA,{readonly:v,menuOptions:g,extraInfo:w})})})})});function DA({fonts:n=!0,children:a}){return a?s.jsx(qx,{fonts:n,children:a}):s.jsx(qx,{fonts:n})}tp(_a);function hp(n,a){if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`Invalid Hub ${a} response.`);return n}function au(n,a,r){const l=hp(n,r);if(!Array.isArray(l[a]))throw new Error(`Invalid Hub ${r} response: ${a} must be an array.`);return l[a]}function _A(n,a,r){const l=hp(n,r);if(!l[a]||typeof l[a]!="object"||Array.isArray(l[a]))throw new Error(`Invalid Hub ${r} response: ${a} must be an object.`);return l[a]}async function LA(n,a=!1){return au(await $e(`/api/remote/filesystem/roots${a?"?refresh=1":""}`,void 0,n),"roots","filesystem roots")}async function sh(n,a){const r=await $e(`/api/remote/filesystem/entries?id=${encodeURIComponent(n)}`,void 0,a);return{folder:_A(r,"folder","filesystem entries"),entries:au(r,"entries","filesystem entries")}}async function zA(n,a){return $e("/api/remote/filesystem/selection/scan",{method:"POST",body:JSON.stringify({itemIds:n})},a)}async function IA(n,a,r,l){return $e("/api/remote/files/from-hub",{method:"POST",body:JSON.stringify({itemIds:n,deviceIds:a,remoteDirectory:r})},l)}async function OA(n,a=!1){const r=await $e(`/api/remote/files/jobs?active=${a?"1":"0"}`,void 0,n);return{jobs:au(r,"jobs","file transfer jobs")}}async function BA(n,a){return $e(`/api/remote/files/jobs/${encodeURIComponent(n)}`,void 0,a)}async function FA(n,a){return $e(`/api/remote/files/jobs/${encodeURIComponent(n)}/cancel`,{method:"POST"},a)}async function ry(n){return au(await $e("/api/remote/filesystem/shared-folders",void 0,n),"folders","shared folders")}async function PA(n,a){return $e("/api/remote/filesystem/shared-folders",{method:"POST",body:JSON.stringify({sourceId:n})},a)}async function HA(n,a,r){return $e(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)},r)}async function $A(n,a){return $e(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}`,{method:"DELETE"},a)}async function UA(n,a,r,l){const c=await $e(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}/sync`,{method:"POST",body:JSON.stringify({deviceIds:a,remoteDirectory:r})},l),d=hp(c,"shared folder sync");return{ok:d.ok===!0,jobs:au(c,"jobs","shared folder sync"),files:Number(d.files||0),totalBytes:Number(d.totalBytes||0)}}function qA(n){return{id:String(n.id),parentId:n.parent,name:n.name,type:n.type==="file"?"file":"folder",size:Number(n.size||0),modifiedAt:n.date?.toISOString()||null,displayPath:String(n.displayPath||n.name),hasChildren:n.lazy===!0||!!n.data?.length,locked:n.locked===!0}}function ly(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let r=n,l=0;for(;r>=1024&&l<a.length-1;)r/=1024,l+=1;return`${r.toFixed(l===0||r>=100?0:1)} ${a[l]}`}function qd(n){return n.driveType==="network"?"network":n.driveType==="removable"?"removable":"local"}function GA(n){const a=n.filter(r=>qd(r)==="local");return a.find(r=>/\bC:/i.test(`${r.name} ${r.displayPath||""}`))||a[0]||n[0]||null}function VA({hubUrl:n,roots:a,loading:r,error:l,onRefreshRoots:c,onImportFiles:d,onImportFolder:m,onSelectionChange:p,onShareItem:v,onAddSyncFolder:g,onNotice:w}){const y=u.useRef(null),b=u.useRef("/"),j=u.useRef(0),C=u.useRef([]),N=u.useRef(new Map),[T,k]=u.useState(null),[E,R]=u.useState([]),[$,F]=u.useState([]),[q,z]=u.useState(0),[L,ie]=u.useState(null),[V,ne]=u.useState(!1),[Q,J]=u.useState(""),[le,Y]=u.useState(new Set),O=a.find(oe=>oe.id===T)||null,Z=E[E.length-1]||null,X=O?Z?.svarPath||`/${O.name}`:null,D=X;u.useEffect(()=>{C.current=E,b.current=D||"/"},[D,E]);const K=u.useMemo(()=>(N.current.clear(),!O||!D||E.length===0?[]:(E.forEach(oe=>N.current.set(oe.svarPath,oe.hubId)),[...E.map((oe,Ne)=>({id:oe.svarPath,parent:Ne===0?"/":E[Ne-1].svarPath,type:"folder",name:oe.name,date:oe.modifiedAt?new Date(oe.modifiedAt):void 0,lazy:!1})),...$.map(oe=>{const Ne=`${D}/${oe.name}`;return N.current.set(Ne,oe.id),{id:Ne,parent:D,name:oe.name,type:oe.type==="file"?"file":"folder",...oe.type==="file"?{size:oe.size}:{},date:oe.modifiedAt?new Date(oe.modifiedAt):void 0,lazy:oe.type!=="file"&&oe.hasChildren===!0,displayPath:oe.displayPath,locked:oe.locked,driveType:oe.driveType,totalBytes:oe.totalBytes,freeBytes:oe.freeBytes}})])),[O,$,D,E]),ce=oe=>N.current.get(String(oe))||String(oe),W=oe=>qA({...oe,id:ce(String(oe.id)),parent:ce(String(oe.parent))}),P=async(oe,Ne)=>{const je=oe[oe.length-1];if(!je)return;const Ee=++j.current;ne(!0),J("");try{const Re=await sh(je.hubId,n);if(Ee!==j.current)return;if(!Array.isArray(Re.entries))throw new Error("Invalid Hub filesystem entries response.");const Fe={...je,displayPath:Re.folder.displayPath||je.displayPath,modifiedAt:Re.folder.modifiedAt||je.modifiedAt},he=[...oe.slice(0,-1),Fe];C.current=he,R(he),F(Re.entries),z(Ae=>Ae+1)}catch(Re){if(Ee!==j.current)return;console.error("[LiveDesk FS] folder navigation failed",{folderId:je.hubId,error:Re}),J(Re instanceof Error?`${Ne}: ${Re.message}`:`${Ne}: Unable to read this folder.`)}finally{Ee===j.current&&ne(!1)}},me=async oe=>{const Ne={svarPath:`/${oe.name}`,hubId:oe.id,name:oe.name,displayPath:oe.displayPath,modifiedAt:oe.modifiedAt},je=++j.current;k(oe.id),C.current=[Ne],R([Ne]),b.current=Ne.svarPath,F([]),J(""),ne(!0),ie(oe.id),Y(Ee=>{const Re=new Set(Ee);return Re.delete(oe.id),Re});try{const Ee=await sh(oe.id,n);if(je!==j.current)return;if(!Array.isArray(Ee.entries))throw new Error("Invalid Hub filesystem entries response.");const Re={...Ne,displayPath:Ee.folder.displayPath||Ne.displayPath,modifiedAt:Ee.folder.modifiedAt||Ne.modifiedAt};C.current=[Re],R([Re]),F(Ee.entries),z(Fe=>Fe+1)}catch(Ee){if(je!==j.current)return;console.error("[LiveDesk FS] getEntries failed",{rootId:oe.id,error:Ee}),Y(Re=>new Set(Re).add(oe.id)),J(Ee instanceof Error?`${oe.name}: ${Ee.message}`:`${oe.name}: Unable to read this drive.`),w(Ee instanceof Error?`${oe.name}: ${Ee.message}`:`${oe.name}: Unable to read this drive.`)}finally{je===j.current&&(ie(null),ne(!1))}},pe=oe=>{const Ne=C.current;oe<0||oe>=Ne.length||oe===Ne.length-1||P(Ne.slice(0,oe+1),Ne[oe].name)},ve=(oe,Ne)=>{if(oe.type!=="folder")return;const je=C.current,Ee=je.findIndex(Fe=>Fe.svarPath===Ne);if(Ee<0)return;const Re={svarPath:`${Ne}/${oe.name}`,hubId:oe.id,name:oe.name,displayPath:oe.displayPath,modifiedAt:oe.modifiedAt};P([...je.slice(0,Ee+1),Re],oe.name)},ke=()=>pe(C.current.length-2),_e=oe=>{if(oe.key!=="Enter"&&oe.code!=="Enter"&&oe.code!=="NumpadEnter"||oe.target?.closest('button, input, textarea, [contenteditable="true"]'))return;const je=y.current;if(!je)return;const Ee=je.getState().panels?.flatMap(Fe=>Fe.selected||[])||[];if(Ee.length!==1)return;const Re=je.getFile(String(Ee[0]));Re?.type==="folder"&&(oe.preventDefault(),oe.stopPropagation(),ve(W(Re),String(Re.parent||b.current)))};u.useEffect(()=>{const oe=a.find(Ne=>Ne.id===T)||GA(a);if(Y(Ne=>new Set([...Ne].filter(je=>a.some(Ee=>Ee.id===je)))),!oe){k(null),C.current=[],R([]),F([]);return}me(oe)},[a]);const Le=oe=>{y.current=oe,oe.on("request-data",async({id:Ne})=>{const je=String(Ne),Ee=ce(je);try{const Re=await sh(Ee,n);if(!Array.isArray(Re.entries))throw new Error("Invalid Hub filesystem entries response.");const Fe=Re.entries.map(he=>{const Ae=`${je}/${he.name}`;return N.current.set(Ae,he.id),{id:Ae,parent:je,name:he.name,type:he.type==="file"?"file":"folder",...he.type==="file"?{size:he.size}:{},date:he.modifiedAt?new Date(he.modifiedAt):void 0,lazy:he.type!=="file"&&he.hasChildren===!0,displayPath:he.displayPath,locked:he.locked,driveType:he.driveType,totalBytes:he.totalBytes,freeBytes:he.freeBytes}});await oe.exec("provide-data",{id:je,data:Fe})}catch(Re){console.error("[LiveDesk FS] nested getEntries failed",{id:Ee,error:Re}),w(Re instanceof Error?Re.message:"Unable to read this folder.")}}),oe.intercept("set-path",({id:Ne})=>{const je=String(Ne),Ee=C.current.findIndex(Fe=>Fe.svarPath===je);if(Ee>=0)return pe(Ee),!1;const Re=oe.getFile(je);if(Re?.type==="folder")return ve(W(Re),String(Re.parent||b.current)),!1}),oe.intercept("open-file",()=>!1),oe.on("select-file",()=>{window.setTimeout(()=>{const Ee=(oe.getState().panels?.flatMap(Re=>Re.selected||[])||[]).map(Re=>oe.getFile(Re)).filter(Boolean).map(Re=>W(Re));p(Ee.map(Re=>Re.id),Ee)},0)})},ue=(oe,Ne)=>{const je=Ne?W(Ne):null,Ee=()=>{const Re=je?.type==="file"?String(Ne?.parent||b.current):String(Ne?.id||b.current);y.current?.exec("request-data",{id:Re})};return oe==="body"?[{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Ee},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>w("Select a file or folder to view its properties.")}]:oe==="multiselect"?[{id:"share",text:"Share to workstations",icon:"mdi mdi-share-variant",handler:()=>{(y.current?.getState().panels?.flatMap(Fe=>Fe.selected||[])||[]).forEach(Fe=>{const he=y.current?.getFile(Fe);he&&v(W(he))})}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Ee}]:je?[{id:"share",text:"Share to workstations",icon:"mdi mdi-share-variant",handler:()=>v(je)},...je.type==="folder"?[{id:"sync",text:"Add folder to Sync",icon:"mdi mdi-folder-sync-outline",handler:()=>g(je)}]:[],{id:"copy-path",text:"Copy path",icon:"mdi mdi-content-copy",handler:()=>{Sl(je.displayPath||je.name)}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Ee},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>w(`${je.name}
13
+ ${je.displayPath||""}`)}]:[]},Ve=async()=>{try{await c()}catch(oe){w(oe instanceof Error?oe.message:"Unable to refresh Hub drives.")}},Ye=[{id:"local",label:"Local drives",icon:Cl,roots:a.filter(oe=>qd(oe)==="local")},{id:"removable",label:"Removable drives",icon:$S,roots:a.filter(oe=>qd(oe)==="removable")},{id:"network",label:"Network drives",icon:Wh,roots:a.filter(oe=>qd(oe)==="network")}];return s.jsxs("section",{className:"hub-file-explorer-panel","aria-label":"Hub file explorer",children:[s.jsxs("div",{className:"hub-file-explorer-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Hub file explorer"}),s.jsxs("strong",{children:[s.jsx(Cl,{size:16})," Browse files on this Hub"]})]}),s.jsxs("div",{className:"hub-file-explorer-heading-actions",children:[s.jsx("button",{className:"icon-button",onClick:d,title:"Import files from this browser",type:"button",children:s.jsx(Vy,{size:16})}),s.jsx("button",{className:"icon-button",onClick:m,title:"Import folder from this browser",type:"button",children:s.jsx(US,{size:16})}),s.jsx("button",{className:"icon-button",onClick:()=>{Ve()},title:"Refresh drives",type:"button",children:s.jsx(Ro,{size:16})})]})]}),r?s.jsxs("div",{className:"hub-file-explorer-state",children:[s.jsx(Cl,{size:24}),s.jsx("strong",{children:"Connecting to LiveDesk Hub file system..."})]}):l?s.jsxs("div",{className:"hub-file-explorer-state error",role:"alert",children:[s.jsx(Rs,{size:24}),s.jsx("strong",{children:l})]}):s.jsxs("div",{className:"hub-file-explorer-content",children:[s.jsxs("aside",{className:"hub-file-explorer-drive-sidebar","aria-label":"Hub drives",children:[s.jsxs("div",{className:"hub-drive-sidebar-title",children:[s.jsx(Cl,{size:15}),s.jsx("strong",{children:"This PC"})]}),Ye.map(oe=>oe.roots.length>0&&s.jsxs("section",{className:"hub-drive-group",children:[s.jsxs("h3",{children:[s.jsx(oe.icon,{size:13}),oe.label]}),s.jsx("div",{className:"hub-drive-list",children:oe.roots.map(Ne=>{const je=oe.icon,Ee=le.has(Ne.id)||Ne.locked===!0;return s.jsxs("button",{className:`hub-drive-item ${T===Ne.id?"active":""} ${Ee?"unavailable":""}`,onClick:()=>{me(Ne)},"aria-pressed":T===Ne.id,type:"button",children:[s.jsx("span",{className:"hub-drive-item-icon",children:s.jsx(je,{size:16})}),s.jsxs("span",{className:"hub-drive-item-copy",children:[s.jsx("strong",{children:Ne.name}),s.jsx("small",{children:Ne.displayPath||Ne.name}),s.jsxs("em",{children:[ly(Ne.freeBytes||0)," free / ",ly(Ne.totalBytes||0)]})]}),L===Ne.id?s.jsx(Hr,{className:"hub-drive-item-status spin",size:15}):Ee?s.jsx(ex,{className:"hub-drive-item-status",size:15}):null]},Ne.id)})})]},oe.id)),a.length===0&&s.jsxs("div",{className:"hub-drive-sidebar-empty",children:[s.jsx(Rs,{size:17}),s.jsx("span",{children:"No drives available."})]})]}),s.jsxs("div",{className:"hub-file-explorer-browser",children:[s.jsxs("div",{className:"hub-file-explorer-navigation",children:[s.jsx("nav",{className:"hub-file-explorer-breadcrumbs","aria-label":"Current Hub folder",children:E.map((oe,Ne)=>s.jsxs("span",{className:"hub-file-explorer-breadcrumb-item",children:[Ne>0&&s.jsx(Kh,{size:13,"aria-hidden":"true"}),s.jsx("button",{className:`hub-file-explorer-breadcrumb ${Ne===E.length-1?"current":""}`,onClick:()=>pe(Ne),"aria-current":Ne===E.length-1?"location":void 0,type:"button",children:oe.name})]},oe.svarPath))}),s.jsxs("div",{className:"hub-file-explorer-navigation-actions",children:[V&&s.jsx(Hr,{className:"hub-file-explorer-loading-icon spin",size:15,"aria-label":"Loading folder"}),s.jsx("button",{className:"icon-button",onClick:ke,disabled:E.length<=1||V,title:"Back to parent folder",type:"button",children:s.jsx(Fy,{size:16})})]})]}),Q&&s.jsxs("div",{className:"hub-file-explorer-folder-error",role:"alert",children:[s.jsx(ex,{size:15}),s.jsx("span",{children:Q})]}),s.jsx("div",{className:"hub-file-explorer-svar",onKeyDownCapture:_e,children:s.jsx(DA,{fonts:!1,children:s.jsx(RA,{data:K,panels:X?[{path:X,selected:[]}]:void 0,readonly:!0,mode:"table",preview:!1,init:Le,icons:"simple",menuOptions:ue},`${O?.id||"no-root"}:${q}`)})})]})]})]})}class YA extends u.Component{state={error:null};static getDerivedStateFromError(a){return{error:a}}componentDidCatch(a,r){console.error("[LiveDesk] Share Files runtime error",a,r.componentStack)}render(){return this.state.error?s.jsxs("section",{className:"file-share-error-boundary",role:"alert",children:[s.jsx(lf,{size:24}),s.jsx("strong",{children:"Share Files could not be opened."}),s.jsx("span",{children:this.state.error.message||"An unexpected file explorer error occurred."}),s.jsxs("button",{className:"text-button",onClick:this.props.onRetry,type:"button",children:[s.jsx(Ro,{size:15})," Retry"]})]}):this.props.children}}function WA(n){return n.deviceName||n.hostname||n.deviceId}function KA({devices:n,mode:a,selectedIds:r,onModeChange:l,onToggle:c}){const d=new Set(r);return s.jsxs("section",{className:"distribution-targets",children:[s.jsxs("div",{className:"file-share-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Target"}),s.jsx("strong",{children:a==="all"?`${n.length} connected`:`${r.length} selected`})]}),s.jsxs("div",{className:"file-share-tabs compact","aria-label":"File transfer targets",children:[s.jsxs("button",{className:a==="all"?"active":"",onClick:()=>l("all"),type:"button",children:[s.jsx(Yy,{size:14})," All connected"]}),s.jsxs("button",{className:a==="selected"?"active":"",onClick:()=>l("selected"),type:"button",children:[s.jsx(Zt,{size:14})," Selected"]})]})]}),s.jsx("div",{className:"file-share-device-list","aria-label":"Connected workstation targets",children:n.length===0?s.jsx("div",{className:"file-share-empty-inline",children:"No connected workstations."}):n.map(m=>{const p=a==="all"||d.has(m.deviceId);return s.jsxs("label",{className:`file-share-device-option ${p?"selected":""}`,children:[s.jsx("input",{type:"checkbox",checked:p,disabled:a==="all",onChange:()=>c(m.deviceId)}),s.jsx(Zt,{size:20,"aria-hidden":"true"}),s.jsxs("span",{children:[s.jsx("strong",{children:WA(m)}),s.jsxs("small",{children:["Slot ",m.slotNumber?String(m.slotNumber).padStart(3,"0"):"-"," / ",m.platform||"unknown OS"]})]}),s.jsx(Ln,{size:17,"aria-hidden":"true"})]},m.deviceId)})})]})}function QA(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let r=n,l=0;for(;r>=1024&&l<a.length-1;)r/=1024,l+=1;return`${r.toFixed(l===0||r>=100?0:1)} ${a[l]}`}function XA({folders:n,loading:a,busy:r,canSync:l,onSyncAll:c,onSync:d,onToggleAuto:m,onRemove:p,onAdd:v}){return s.jsxs("section",{className:"file-share-sync-panel",children:[s.jsxs("div",{className:"file-share-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Hub folders"}),s.jsx("strong",{children:"Continuous sync"})]}),s.jsxs("button",{className:"text-button compact",onClick:c,disabled:r||!l||n.length===0,type:"button",children:[s.jsx(Fd,{size:15})," ",r?"Syncing":"Sync all"]})]}),a?s.jsx("div",{className:"file-share-empty-state",children:"Loading Hub sync folders..."}):n.length===0?s.jsxs("button",{className:"file-share-empty-state interactive",onClick:v,type:"button",children:[s.jsx(Fd,{size:28}),s.jsx("strong",{children:"Add a selected Hub folder"}),s.jsx("span",{children:"Hub keeps the manifest and can sync while this browser is closed."})]}):s.jsx("div",{className:"file-share-sync-list",children:n.map(g=>s.jsxs("article",{className:`file-share-sync-row state-${g.status}`,children:[s.jsx("div",{className:"file-share-sync-icon",children:s.jsx(Fd,{size:19})}),s.jsxs("div",{className:"file-share-sync-info",children:[s.jsx("strong",{children:g.name}),s.jsx("span",{children:g.displayPath}),s.jsxs("small",{children:[g.fileCount," files / ",QA(g.totalBytes)," · ",g.lastSyncedAt?`Last sync ${jh(g.lastSyncedAt)} ago`:g.message||"Not synced yet"]})]}),s.jsxs("label",{className:"file-share-auto-sync",children:[s.jsx("input",{type:"checkbox",checked:g.autoSync,onChange:()=>m(g)}),s.jsx("span",{children:"Auto"})]}),s.jsxs("button",{className:"text-button compact",onClick:()=>d(g),disabled:r||!l||g.status==="syncing",type:"button",children:[s.jsx(Ro,{size:14})," Sync now"]}),s.jsx("button",{className:"icon-button",onClick:()=>p(g),title:"Remove sync folder",type:"button",children:s.jsx(Vh,{size:15})})]},g.id))})]})}function ZA(n){const r=(n.targetMode==="all"?n.devices.map(l=>l.deviceId):n.selectedTargetIds).length>0;return s.jsxs("aside",{className:"file-share-distribution-panel",children:[s.jsxs("div",{className:"file-share-distribution-head",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Distribution"}),s.jsx("strong",{children:"Hub → workstations"})]}),s.jsx(Do,{size:18})]}),s.jsxs("div",{className:"file-share-tabs",role:"tablist","aria-label":"Distribution mode",children:[s.jsx("button",{className:n.tab==="send"?"active":"",onClick:()=>n.onTabChange("send"),role:"tab","aria-selected":n.tab==="send",type:"button",children:"Send"}),s.jsx("button",{className:n.tab==="sync"?"active":"",onClick:()=>n.onTabChange("sync"),role:"tab","aria-selected":n.tab==="sync",type:"button",children:"Sync"})]}),n.tab==="send"?s.jsxs(s.Fragment,{children:[s.jsx(KA,{devices:n.devices,mode:n.targetMode,selectedIds:n.selectedTargetIds,onModeChange:n.onTargetModeChange,onToggle:n.onTargetToggle}),s.jsxs("label",{className:"file-share-destination",children:[s.jsx("span",{children:"Destination folder"}),s.jsxs("div",{children:[s.jsx(Ao,{size:15}),s.jsx("input",{value:n.remoteDirectory,onChange:l=>n.onRemoteDirectoryChange(l.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),s.jsx("small",{children:"Blank uses Desktop/LiveDeskFiles."})]}),s.jsxs("div",{className:"file-share-selection-summary",children:[s.jsx("span",{children:"Selected"}),s.jsx("strong",{children:n.selectedSummary})]}),s.jsxs("button",{className:"file-share-share-button",onClick:n.onShare,disabled:!n.canShare,type:"button",children:[s.jsx(Do,{size:17})," Share selected"]}),s.jsxs("button",{className:"file-share-secondary-button",onClick:n.onAddSync,disabled:!n.canAddSync,type:"button",children:[s.jsx(Ao,{size:16})," Add selected folder to Sync"]})]}):s.jsx(XA,{folders:n.folders,loading:n.foldersLoading,busy:n.syncBusy,canSync:r,onSyncAll:n.onSyncAll,onSync:n.onSync,onToggleAuto:n.onToggleAuto,onRemove:n.onRemove,onAdd:n.onAddFolder})]})}function JA(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let r=n,l=0;for(;r>=1024&&l<a.length-1;)r/=1024,l+=1;return`${r.toFixed(l===0||r>=100?0:1)} ${a[l]}`}function oy(n){return n.totalBytes>0?Math.max(0,Math.min(100,Math.round(n.sentBytes/n.totalBytes*100))):n.totalFiles>0?Math.max(0,Math.min(100,Math.round(n.completedFiles/n.totalFiles*100))):n.state==="completed"?100:0}function cy(n){return n.state==="scanning"?"Scanning selected Hub items":n.state==="queued"?"Preparing transfer":n.state==="sending"?`${n.completedFiles}/${n.totalFiles} · ${n.currentPath||"sending"}`:n.state==="completed"?`Sent ${n.totalFiles} file${n.totalFiles===1?"":"s"} to ${n.targetCount} workstation${n.targetCount===1?"":"s"}`:n.state==="partially-failed"?`${n.failedTargets.length} workstation${n.failedTargets.length===1?"":"s"} failed`:n.state==="cancelled"?"Transfer cancelled":n.error||"Transfer failed"}function uy(n){return["completed","partially-failed","failed","cancelled"].includes(n)}function eN({hubUrl:n,devices:a,localFeatureAccess:r,upgradeNotice:l,remoteDirectory:c,onRemoteDirectoryChange:d,targetMode:m,selectedTargetIds:p,onTargetModeChange:v,onTargetToggle:g,filePickerRef:w,folderPickerRef:y,onBrowserFileImport:b,onBrowserFolderImport:j,onNotice:C,onTransferChange:N}){const T=Array.isArray(a)?a:[],[k,E]=u.useState([]),[R,$]=u.useState(!0),[F,q]=u.useState(""),[z,L]=u.useState([]),[ie,V]=u.useState([]),[ne,Q]=u.useState(null),[J,le]=u.useState(!1),[Y,O]=u.useState([]),[Z,X]=u.useState(!0),[D,K]=u.useState(!1),[ce,W]=u.useState("send"),[P,me]=u.useState([]),pe=u.useRef(new Set),ve=u.useMemo(()=>m==="all"?T.map(de=>de.deviceId):p.filter(de=>T.some(ye=>ye.deviceId===de)),[T,p,m]),ke=P.find(de=>!uy(de.state)),_e=ie.length===1&&ie[0].type==="folder"?ie[0]:null,Le=ie.length===0?"Select files or folders from the Hub explorer.":J?"Calculating selection size...":ne?`${ne.files} files, ${ne.folders} folders · ${JA(ne.totalBytes)}`:`${ie.length} item${ie.length===1?"":"s"} selected`,ue=de=>{N({id:de.jobId,state:de.state,progress:oy(de),message:cy(de)})},Ve=u.useCallback(async()=>{const de=await LA(n,!0);return E(de),q(""),de},[n]),Ye=async()=>{try{const ye=(await OA(n,!0)).jobs||[],qe=await Promise.all([...pe.current].map(async Ke=>{try{return await BA(Ke,n)}catch{return null}})),tt=[...ye,...qe.filter(Boolean)],pn=[...new Map(tt.map(Ke=>[Ke.jobId,Ke])).values()];me(pn),pn.forEach(ue),pn.filter(Ke=>uy(Ke.state)).forEach(Ke=>pe.current.delete(Ke.jobId))}catch{}};u.useEffect(()=>{let de=!0;$(!0),q(""),Promise.all([Ve(),ry(n).then(qe=>{de&&O(qe)})]).catch(qe=>{de&&(q(qe instanceof Error?"Hub file system is unavailable. Make sure LiveDesk Hub is running on this computer.":"Hub file system is unavailable."),C(qe instanceof Error?qe.message:"Hub file system is unavailable."))}).finally(()=>{de&&($(!1),X(!1))}),Ye();const ye=window.setInterval(()=>{Ye()},800);return()=>{de=!1,window.clearInterval(ye)}},[n,Ve]),u.useEffect(()=>{if(z.length===0){Q(null);return}let de=!1;return le(!0),zA(z,n).then(ye=>{de||Q(ye)}).catch(ye=>{de||C(ye instanceof Error?ye.message:"Unable to calculate selected size.")}).finally(()=>{de||le(!1)}),()=>{de=!0}},[n,z.join("|")]);const oe=(de,ye)=>{L(de),V(ye)},Ne=de=>{de.forEach(ye=>pe.current.add(ye.jobId)),me(ye=>[...new Map([...ye,...de].map(qe=>[qe.jobId,qe])).values()]),de.forEach(ue)},je=async()=>{if(!r){C(l);return}if(z.length===0){C("Select files or folders from the Hub explorer.");return}if(ve.length===0){C("Choose at least one connected workstation.");return}if(ke){C("A Hub transfer is already running.");return}try{const de=await IA(z,ve,c.trim(),n);pe.current.add(de.jobId),C("Hub transfer queued."),await Ye()}catch(de){C(de instanceof Error?de.message:"Unable to start Hub transfer.")}},Ee=async de=>{const ye=de||_e;if(!ye||ye.type!=="folder"){C("Select one folder to add it to Sync.");return}try{const qe=await PA(ye.id,n);O(tt=>[...tt.filter(pn=>pn.id!==qe.folder.id),qe.folder]),W("sync"),C(`${ye.name} is ready for Hub sync.`)}catch(qe){C(qe instanceof Error?qe.message:"Unable to add the Hub folder to Sync.")}},Re=async de=>{if(ve.length===0){C("Choose at least one connected workstation.");return}K(!0),O(ye=>ye.map(qe=>qe.id===de.id?{...qe,status:"syncing"}:qe));try{const ye=await UA(de.id,ve,c.trim(),n);Ne(ye.jobs||[]),C(ye.jobs?.length?"Hub sync queued.":"No changed files to sync.");const qe=await ry(n);O(qe)}catch(ye){C(ye instanceof Error?ye.message:"Unable to sync the Hub folder."),O(qe=>qe.map(tt=>tt.id===de.id?{...tt,status:"error",message:"Sync failed"}:tt))}finally{K(!1)}},Fe=async()=>{K(!0);try{for(const de of Y)await Re(de)}finally{K(!1)}},he=async de=>{try{const ye=await HA(de.id,{autoSync:!de.autoSync},n);O(qe=>qe.map(tt=>tt.id===de.id?ye.folder:tt))}catch(ye){C(ye instanceof Error?ye.message:"Unable to update auto sync.")}},Ae=async de=>{try{await $A(de.id,n),O(ye=>ye.filter(qe=>qe.id!==de.id))}catch(ye){C(ye instanceof Error?ye.message:"Unable to remove the sync folder.")}};return s.jsxs("section",{className:"livedesk-file-explorer",children:[s.jsx("input",{ref:w,className:"hidden-file-input",type:"file",multiple:!0,onChange:de=>{de.currentTarget.files&&b(de.currentTarget.files),de.currentTarget.value=""}}),s.jsx("input",{ref:y,className:"hidden-file-input",type:"file",multiple:!0,webkitdirectory:"",directory:"",onChange:de=>{de.currentTarget.files&&j(de.currentTarget.files),de.currentTarget.value=""}}),s.jsx("div",{className:"file-share-workspace",children:s.jsxs(YA,{onRetry:()=>window.location.reload(),children:[s.jsx(VA,{hubUrl:n,roots:k,loading:R,error:F,onRefreshRoots:Ve,onImportFiles:()=>w.current?.click(),onImportFolder:()=>y.current?.click(),onSelectionChange:oe,onShareItem:de=>{L([de.id]),V([de]),W("send")},onAddSyncFolder:de=>{L([de.id]),V([de]),Ee(de)},onNotice:C}),s.jsx(ZA,{devices:T,targetMode:m,selectedTargetIds:p,onTargetModeChange:v,onTargetToggle:g,remoteDirectory:c,onRemoteDirectoryChange:d,selectedEntries:ie,selectedSummary:Le,canShare:r&&!ke&&z.length>0&&ve.length>0&&!J,onShare:()=>{je()},canAddSync:!!_e,onAddSync:()=>{Ee()},tab:ce,onTabChange:W,folders:Y,foldersLoading:Z,syncBusy:D,onSyncAll:()=>{Fe()},onSync:de=>{Re(de)},onToggleAuto:de=>{he(de)},onRemove:de=>{Ae(de)},onAddFolder:()=>{Ee()}})]})}),ke&&s.jsx("footer",{className:"file-share-workspace-footer",children:s.jsxs("span",{children:[cy(ke)," · ",oy(ke),"% ",s.jsx("button",{className:"icon-button",onClick:()=>{FA(ke.jobId,n).then(de=>{me(ye=>ye.map(qe=>qe.jobId===de.jobId?de:qe)),ue(de)})},title:"Cancel transfer",type:"button",children:s.jsx(Ds,{size:14})})]})})]})}const tN=u.forwardRef(function({value:a,onChange:r,onSubmit:l,onOpenSuggestedTasks:c,suggestedOpen:d=!1,suggestedTaskCount:m,disabled:p=!1},v){return s.jsxs("form",{className:"agents-composer",onSubmit:g=>{g.preventDefault(),l()},children:[s.jsxs("button",{className:`agents-suggested-trigger ${d?"active":""}`,type:"button","aria-label":m===void 0?"Open Suggested tasks":`Open Suggested tasks (${m} available)`,"aria-expanded":d,onClick:c,disabled:p,children:[s.jsx(qS,{size:17}),m!==void 0&&s.jsx("span",{className:"agents-suggested-count","aria-hidden":"true",children:m})]}),s.jsx("textarea",{ref:v,value:a,onChange:g=>r(g.target.value.slice(0,4e3)),placeholder:"Ask LiveDesk to work across your machines...","aria-label":"Ask LiveDesk",rows:2,disabled:p}),s.jsxs("button",{className:"agents-run-button",type:"submit",disabled:p||!a.trim(),children:[p?s.jsx(Hr,{className:"spin",size:16}):s.jsx(Do,{size:16}),p?"Running":"Run"]})]})}),nN=["read","processControl","serviceControl","applicationControl","fileRead","fileWrite","fileDelete","shell","script","softwareInstall","network","systemPower","systemConfiguration","userAccount"];function Qw(n){return n.deviceName?.trim()||n.hostname?.trim()||n.deviceId}function Ih(n){return n.connected!==!0?!1:n.synthetic===!0?!0:!n.channels||n.channels.control===!0}function aN(n){return n==="running"||n==="completed"||n==="failed"||n==="cancelled"?n:"queued"}function sN(n){switch(n){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 iN(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:null}function Ya(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function _d(n){const a=Ya(n);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 rN(n){const a=Ya(n);return a===null?"":`${Math.round((a<=1?a:a/100)*100)}%`}function lN(n){return!n||/^(?:[\w .-]+ )?collected(?:\.)?$/i.test(n.trim())?"":n.trim()}function sf(n,a){if(a.error)return a.error;const r=iN(a.data),l=lN(a.result||"");if(!r)return l||a.stage||a.status;if(n==="system.health"){const c=typeof r.machine=="string"?r.machine:"",d=_d(r.freeMemoryBytes),m=_d(r.totalMemoryBytes),p=Ya(r.totalMemoryBytes)&&Ya(r.freeMemoryBytes)!==null?`${Math.round(Ya(r.freeMemoryBytes)/Ya(r.totalMemoryBytes)*100)}% RAM free`:"";return[c,d&&m?`RAM ${d}/${m}`:"",p,typeof r.platform=="string"?r.platform:""].filter(Boolean).join(" · ")||l||a.status}if(n==="disk.status"){const c=typeof r.root=="string"?r.root:"",d=_d(r.freeBytes),m=Ya(r.totalBytes)&&Ya(r.freeBytes)!==null?`${Math.round(Ya(r.freeBytes)/Ya(r.totalBytes)*100)}% free`:"";return[c,d&&`${d} free`,m].filter(Boolean).join(" · ")||l||a.status}if(n==="gpu.status"){const c=typeof r.name=="string"&&r.name?r.name:"No GPU provider",d=rN(r.usageRatio),m=Ya(r.temperatureC)!==null?`${Math.round(Ya(r.temperatureC))}°C`:"",p=_d(r.freeMemoryBytes);return[c,d&&`GPU ${d}`,m,p&&`${p} free`].filter(Boolean).join(" · ")||l||a.status}if(n==="process.list"){const c=Ya(r.count);return c!==null?`${c} matching process${c===1?"":"es"}`:l||a.status}if(n==="network.status"){const c=Array.isArray(r.adapters)?r.adapters.length:null;return c!==null?`${c} active adapter${c===1?"":"s"}`:l||a.status}return l||a.stage||a.status}function dy(n,a){const r=sf(n,a);return a.status==="failed"||a.status==="cancelled"||/\b(?:warning|failed|error|offline|not running|low|timeout|timed out)\b/i.test(`${a.result||""} ${r}`)}function oN({state:n,operation:a}){const r=n.status==="completed"?Pr:n.status==="failed"||n.status==="cancelled"?Ds:n.status==="running"?Hr:Wy,l=n.status==="running"?n.stage||"Working":n.status==="completed"?a?sf(a,n):n.result||"Completed":n.status==="failed"?n.error||"Failed":n.status==="cancelled"?"Cancelled":"Queued";return s.jsxs("div",{className:`agent-target-row status-${n.status}`,"data-agent-target-id":n.deviceId,children:[s.jsx("span",{className:"agent-target-status","aria-hidden":"true",children:s.jsx(r,{size:15})}),s.jsx("strong",{children:n.deviceName}),s.jsx("span",{className:"agent-target-state",children:n.status[0].toUpperCase()+n.status.slice(1)}),s.jsx("small",{children:l})]})}function cN({operation:n,states:a,status:r,onCancel:l,onRetry:c,busy:d=!1}){const m=["running","queued"].includes(r),[p,v]=u.useState(!1),[g,w]=u.useState("all"),y=u.useMemo(()=>({total:a.length,completed:a.filter(R=>R.status==="completed").length,failed:a.filter(R=>R.status==="failed").length,running:a.filter(R=>R.status==="running").length,queued:a.filter(R=>R.status==="queued").length,cancelled:a.filter(R=>R.status==="cancelled").length}),[a]),b=a.filter(R=>dy(n,R)),j=b.filter(R=>R.status==="completed").length,C=y.failed>0,N=b.length>0,T=a.filter(R=>g==="issues"?dy(n,R):g==="running"?R.status==="running"||R.status==="queued":g==="completed"?R.status==="completed":g==="failed"?R.status==="failed":!0),k=N&&!m||r==="completed-with-failures"?"Completed with issues":r[0]?.toUpperCase()+r.slice(1),E=a.filter(R=>R.status==="completed").map(R=>sf(n,R)).filter(Boolean).filter((R,$,F)=>F.indexOf(R)===$).slice(0,2);return s.jsxs("section",{className:"agent-task-block","aria-label":"Task execution",children:[s.jsxs("div",{className:"agent-task-head",children:[s.jsxs("div",{children:[s.jsx("span",{children:"LiveDesk Agent"}),s.jsx("strong",{children:sN(n)})]}),s.jsx("span",{className:`agent-task-status status-${N?"completed-with-failures":r}`,children:k})]}),s.jsxs("div",{className:"agent-task-summary","aria-label":"Task summary",children:[s.jsxs("strong",{children:[y.total," targets"]}),s.jsxs("span",{className:"summary-completed",children:[y.completed," completed"]}),y.running>0&&s.jsxs("span",{className:"summary-running",children:[y.running," running"]}),y.queued>0&&s.jsxs("span",{children:[y.queued," queued"]}),C&&s.jsxs("span",{className:"summary-failed",children:[y.failed," failed"]}),j>0&&s.jsxs("span",{className:"summary-cancelled",children:[j," warning"]}),y.cancelled>0&&s.jsxs("span",{className:"summary-cancelled",children:[y.cancelled," cancelled"]})]}),E.length>0&&s.jsxs("div",{className:"agent-task-result-preview",title:E.join(" · "),children:[s.jsx("span",{children:"Result"}),E.join(" · ")]}),s.jsx("div",{className:"agent-target-chips","aria-label":"Target status overview",children:a.map((R,$)=>{const F=R.status==="completed"?"✓":R.status==="failed"?"×":R.status==="cancelled"?"!":R.status==="running"?"…":"·";return s.jsxs("span",{className:`agent-target-chip status-${R.status}`,title:`${R.deviceName}: ${sf(n,R)}`,"aria-label":`${$+1}. ${R.deviceName}: ${R.status}`,children:[s.jsx("b",{children:String($+1).padStart(2,"0")}),s.jsx("span",{children:F})]},R.deviceId)})}),a.length>0&&s.jsx("div",{className:"agent-task-details-toggle",children:s.jsxs("button",{type:"button",onClick:()=>v(R=>!R),"aria-expanded":p,children:[p?s.jsx(GS,{size:14}):s.jsx(Ky,{size:14}),p?"Hide details":"Show details"]})}),p&&s.jsxs("div",{className:"agent-task-details",children:[s.jsx("div",{className:"agent-task-filters",role:"tablist","aria-label":"Task result filter",children:["all","issues","running","completed","failed"].map(R=>s.jsx("button",{className:g===R?"active":"",onClick:()=>w(R),role:"tab","aria-selected":g===R,type:"button",children:R==="all"?"All":R==="issues"?"Issues only":R[0].toUpperCase()+R.slice(1)},R))}),s.jsx("div",{className:"agent-task-rows",children:T.length>0?T.map(R=>s.jsx(oN,{operation:n,state:R},R.deviceId)):s.jsx("small",{className:"agent-task-no-results",children:"No targets match this filter."})})]}),(m||C)&&s.jsxs("div",{className:"agent-task-actions",children:[m&&l&&s.jsxs("button",{onClick:l,disabled:d,type:"button",children:[s.jsx(VS,{size:14})," Cancel"]}),!m&&C&&c&&s.jsxs("button",{onClick:c,disabled:d,type:"button",children:[s.jsx(Gc,{size:14})," Retry failed"]})]})]})}function uN(n){try{return JSON.stringify(n,null,2).slice(0,6e3)}catch{return"{}"}}function dN({approval:n,busy:a=!1,onApprove:r,onReject:l}){return s.jsxs("article",{className:"agent-approval-card","aria-label":"Agent approval required",children:[s.jsxs("div",{className:"agent-approval-head",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Approval required"}),s.jsx("strong",{children:n.toolName})]}),s.jsx("span",{className:`agent-approval-risk risk-${n.risk}`,children:n.risk})]}),s.jsx("p",{children:n.description}),s.jsx("pre",{children:uN(n.arguments)}),s.jsxs("small",{children:["Permission: ",n.permissionMode," · Scope: selected devices only · Expires in 5 minutes"]}),s.jsxs("div",{className:"agent-approval-actions",children:[s.jsxs("button",{className:"reject",disabled:a,onClick:l,type:"button",children:[s.jsx(Ds,{size:14})," Reject"]}),s.jsxs("button",{disabled:a,onClick:()=>r("once"),type:"button",children:[s.jsx(Pr,{size:14})," Once"]}),s.jsx("button",{disabled:a,onClick:()=>r("same-action-this-run"),type:"button",children:"Allow same action"}),s.jsx("button",{disabled:a,onClick:()=>r("category-this-run"),type:"button",children:"Allow category"})]}),s.jsxs("div",{className:"agent-approval-scope",children:[s.jsx(lf,{size:13})," Approval is bound to this run, tool, arguments, selected devices, and policy hash."]})]})}function fN(n){return n==="queued"?"Request queued":n==="checking-codex"?"Checking Codex":n==="preparing-tools"?"Preparing tools":n==="thinking"?"Preparing answer":n==="tool-running"?"Working on computers":n==="recovering"?"Retrying safely":n==="waiting-approval"?"Waiting for approval":"Working"}function mN({items:n,onCancel:a,onRetry:r,busyBatchId:l,approvals:c,onApprove:d,onReject:m,busyApprovalId:p,progress:v}){const g=u.useRef(null),w=u.useRef(!0),y=u.useRef(""),b=n[n.length-1];return u.useLayoutEffect(()=>{const j=g.current;j&&(b?.type==="user"&&b.id!==y.current&&(w.current=!0),y.current=b?.id||"",w.current&&(j.scrollTop=j.scrollHeight))},[c,n,b?.id,b?.type,v?.message,v?.stage]),s.jsxs("section",{className:"agents-conversation","aria-live":"polite",ref:g,onScroll:j=>{const C=j.currentTarget;w.current=C.scrollHeight-C.scrollTop-C.clientHeight<72},children:[c.filter(j=>j.status==="pending").map(j=>s.jsx(dN,{approval:j,busy:p===j.approvalId,onApprove:C=>d(j,C),onReject:()=>m(j)},j.approvalId)),n.length===0&&s.jsxs("div",{className:"agents-empty-conversation",children:[s.jsx("strong",{children:"Ask LiveDesk to work across your machines."}),s.jsx("span",{children:"Start with a read-only request such as “모든 PC에서 ComfyUI가 실행 중인지 확인해줘”."})]}),n.map(j=>{if(j.type==="task"){const C=j;return s.jsx(cN,{operation:C.operation,states:C.states,status:C.status,onCancel:()=>a(C.batchId,C.agentRunId),onRetry:()=>r(C.batchId),busy:l===C.batchId},C.id)}return s.jsxs("article",{className:`agents-message ${j.type}`,children:[s.jsx("span",{children:j.type==="user"?"You":"LiveDesk Agent"}),s.jsx("p",{children:j.text})]},j.id)}),v&&s.jsxs("article",{className:"agents-message agent agents-progress-message",role:"status",children:[s.jsxs("span",{children:[s.jsx(Hr,{"aria-hidden":"true",size:15}),fN(v.stage)]}),s.jsx("p",{children:v.message})]})]})}const fy=["Recommended","Health & capacity","Processes & services","AI workloads","Files & configuration","Software & automation","Network & connectivity","Power & maintenance","Troubleshooting & recovery"],mn=["windows","macos","linux"],Br={"system.health":{label:"system health",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:mn},"gpu.status":{label:"GPU status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:mn},"disk.status":{label:"disk status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:mn},"process.list":{label:"process inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:mn},"service.status":{label:"service inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:mn},"diagnostics.collect":{label:"diagnostics collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:mn},"process.control":{label:"process control",permissionCategory:"processControl",readOnly:!1,risk:"high",supportedPlatforms:mn},"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:mn},"application.close":{label:"application close",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:mn},"file.read":{label:"file reading",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:mn},"file.write":{label:"file writing",permissionCategory:"fileWrite",readOnly:!1,risk:"high",supportedPlatforms:mn},"file.delete":{label:"file deletion",permissionCategory:"fileDelete",readOnly:!1,risk:"critical",supportedPlatforms:mn},"file.list":{label:"directory listing",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:mn},"command.run":{label:"command execution",permissionCategory:"shell",readOnly:!1,risk:"critical",supportedPlatforms:mn},"script.run":{label:"script execution",permissionCategory:"script",readOnly:!1,risk:"high",supportedPlatforms:mn},"software.install":{label:"software installation",permissionCategory:"softwareInstall",readOnly:!1,risk:"high",supportedPlatforms:mn},"network.status":{label:"network inspection",permissionCategory:"network",readOnly:!0,risk:"low",supportedPlatforms:mn},"system.power":{label:"power control",permissionCategory:"systemPower",readOnly:!1,risk:"critical",supportedPlatforms:mn},"system.configure":{label:"system configuration",permissionCategory:"systemConfiguration",readOnly:!1,risk:"critical",supportedPlatforms:mn},"logs.collect":{label:"log collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:mn}};new Set(Object.keys(Br));const hN={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","문제해결","복구","장애"]},my=["low","medium","high","critical"];function pN(n){return n.reduce((a,r)=>{const l=Br[r].risk;return my.indexOf(l)>my.indexOf(a)?l:a},"low")}function gN(n){return mn.filter(a=>n.every(r=>Br[r].supportedPlatforms.includes(a)))}function Be(n,a,r,l,c,d,m={}){const p=m.description||l,v=c.flatMap(w=>w.split(".")),g=[...new Set([...hN[a],...d,...v])];return{id:n,category:a,title:r,prompt:l,description:p,requiredOperations:c,risk:m.risk||pN(c),targetSupport:m.targetSupport||"single-or-multiple",supportedPlatforms:m.supportedPlatforms||gN(c),keywords:g,recommended:m.recommended??!1,enabled:!0}}const Xw=[Be("recommended-fleet-health","Recommended","Summarize current target health","Summarize system health, GPU, and disk capacity for the current target workstations.",["system.health","gpu.status","disk.status"],["summary","overview"],{recommended:!0}),Be("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}),Be("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}),Be("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}),Be("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}),Be("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}),Be("recommended-recover-ai","Recommended","Recover stopped AI workers","Find stopped AI workers and relaunch the registered worker application or service on the target workstation.",["process.list","application.launch","service.control"],["recover","start","ai worker"],{targetSupport:"single",recommended:!0}),Be("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}),Be("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","높은 사용량"]),Be("health-uptime","Health & capacity","Review workstation uptime","Show uptime, boot time, and current system health for the target workstations.",["system.health"],["uptime","boot","가동시간"]),Be("health-gpu-temperature","Health & capacity","Check GPU temperature","Check GPU temperature and thermal warnings on the current targets.",["gpu.status"],["thermal","temperature","발열"]),Be("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"]),Be("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","디스크"]),Be("health-gpu-compare","Health & capacity","Compare GPU capacity","Compare GPU model, memory, temperature, and utilization across the current targets.",["gpu.status"],["compare","graphics","capacity"]),Be("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","경고"]),Be("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"]),Be("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","실행 중"]),Be("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"]),Be("process-stop-named","Processes & services","Stop a named process","Stop process named [process name] on the target workstation after checking its current state.",["process.list","process.control"],["stop","terminate","종료"],{targetSupport:"single"}),Be("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"}),Be("process-launch-app","Processes & services","Launch a registered application","Launch the registered application [application] on the target workstation with [arguments].",["application.launch"],["launch","open","실행"],{targetSupport:"single"}),Be("process-close-app","Processes & services","Close an application","Close application [application] on the target workstation and report whether it exited cleanly.",["application.close","process.list"],["close","exit","앱 종료"],{targetSupport:"single"}),Be("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","서비스 상태"]),Be("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"}),Be("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"]),Be("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"}),Be("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"}),Be("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"]),Be("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"]),Be("ai-worker-logs","AI workloads","Collect AI worker logs","Collect recent logs and relevant log files for the AI worker on the target workstation.",["logs.collect","file.list","file.read"],["logs","diagnostics","worker"],{targetSupport:"single"}),Be("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"]),Be("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"}),Be("files-list-directory","Files & configuration","List a directory","List files and folders under [path] on the target workstation.",["file.list"],["directory","folder","list","목록"],{targetSupport:"single"}),Be("files-read-config","Files & configuration","Read a configuration file","Read the relevant settings from configuration file [path] on the target workstation.",["file.read"],["config","settings","read","구성"]),Be("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"]),Be("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"}),Be("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"}),Be("files-compare-config","Files & configuration","Compare configuration files","Read configuration file [path] on the target workstation and compare it with [reference path].",["file.read"],["compare","diff","configuration"]),Be("files-set-environment","Files & configuration","Set an environment variable","Set environment variable [name] to [value] for the target workstation and verify the resulting configuration.",["system.configure","file.read"],["environment","variable","env","환경변수"],{targetSupport:"single"}),Be("files-archive-diagnostics","Files & configuration","Write a diagnostic manifest","Collect selected diagnostics and write a manifest file to [path] on the target workstation.",["diagnostics.collect","file.write"],["manifest","export","diagnostic file"],{targetSupport:"single"}),Be("software-winget-install","Software & automation","Install software with winget","Install package [package name] with winget on the Windows target workstation, then verify it.",["software.install","process.list"],["winget","windows","install","설치"],{targetSupport:"single",supportedPlatforms:["windows"]}),Be("software-apt-install","Software & automation","Install software with apt","Install package [package name] with apt on the Linux target workstation, then verify it.",["software.install","process.list"],["apt","linux","package","설치"],{targetSupport:"single",supportedPlatforms:["linux"]}),Be("software-brew-install","Software & automation","Install software with Homebrew","Install package [package name] with brew on the macOS target workstation, then verify it.",["software.install","process.list"],["brew","homebrew","macos","설치"],{targetSupport:"single",supportedPlatforms:["macos"]}),Be("software-npm-install","Software & automation","Install an npm package","Install npm package [package name] on the target workstation and verify the installed version.",["software.install","command.run"],["npm","node","package"],{targetSupport:"single"}),Be("software-run-script","Software & automation","Run a registered script","Run the registered script [script path] on the target workstation and report its result.",["script.run"],["script","automation","registered"],{targetSupport:"single"}),Be("software-run-command","Software & automation","Run a command on one target","Run command [command] on the target workstation and return its exit status and output.",["command.run"],["command","shell","terminal"],{targetSupport:"single"}),Be("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"]),Be("software-toolchain-setup","Software & automation","Set up a toolchain","Install the requested package [package name], configure [change], and verify the toolchain on the target workstation.",["software.install","system.configure","process.list"],["toolchain","setup","developer"],{targetSupport:"single"}),Be("network-adapter-status","Network & connectivity","Check network adapters","Show adapter state, address, and link information for the current targets.",["network.status"],["adapter","ethernet","wifi","네트워크 상태"]),Be("network-disconnected","Network & connectivity","Find disconnected targets","Find current targets with disconnected or degraded network adapters.",["network.status"],["disconnected","offline","연결 끊김"]),Be("network-link-speed","Network & connectivity","Check link speed","Report network link speed and duplex information for the current targets.",["network.status"],["speed","bandwidth","duplex"]),Be("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"]),Be("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"]),Be("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"]),Be("network-compare","Network & connectivity","Compare target connectivity","Compare adapter state, addresses, and link speed across the current targets.",["network.status"],["compare","inventory","connectivity"]),Be("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"]),Be("power-lock","Power & maintenance","Lock the workstation","Lock the target workstation and report the resulting power action status.",["system.power"],["lock","security","잠금"],{targetSupport:"single",risk:"critical"}),Be("power-logoff","Power & maintenance","Log off the workstation","Log off the target workstation after warning that interactive sessions will close.",["system.power"],["logoff","session","로그오프"],{targetSupport:"single",risk:"critical"}),Be("power-sleep","Power & maintenance","Put the workstation to sleep","Put the target workstation to sleep after confirming the requested delay of [delay].",["system.power"],["sleep","suspend","절전"],{targetSupport:"single",risk:"critical"}),Be("power-restart","Power & maintenance","Restart the workstation","Restart the target workstation after confirming that active work may be interrupted.",["system.power"],["restart","reboot","재부팅"],{targetSupport:"single",risk:"critical"}),Be("power-shutdown","Power & maintenance","Shut down the workstation","Shut down the target workstation after confirming that active work may be interrupted.",["system.power"],["shutdown","power off","종료"],{targetSupport:"single",risk:"critical"}),Be("power-maintenance-restart","Power & maintenance","Restart after maintenance","Check the target workstation, restart it after maintenance, and verify that it returns online.",["system.health","system.power","network.status"],["maintenance","reboot","verify"],{targetSupport:"single",risk:"critical"}),Be("power-timezone","Power & maintenance","Set the workstation timezone","Set the target workstation timezone to [timezone] and verify the resulting system configuration.",["system.configure"],["timezone","clock","시간대"],{targetSupport:"single",risk:"critical"}),Be("power-persistent-environment","Power & maintenance","Persist an environment variable","Persist environment variable [name] with value [value] for the target workstation and verify it.",["system.configure"],["environment","persistent","환경변수"],{targetSupport:"single",risk:"critical"}),Be("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"}),Be("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"}),Be("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"}),Be("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"}),Be("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"}),Be("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"}),Be("recovery-network-instability","Troubleshooting & recovery","Recover network instability","Collect network diagnostics, inspect network services, and report the safest recovery action for the target workstation.",["network.status","service.status","diagnostics.collect"],["network","unstable","네트워크 복구"],{targetSupport:"single"}),Be("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","장애 보고서"])],ih={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 vN(n,a){return n==="safe-auto"?ih:n==="full-access"?{...ih,processControl:"allow",serviceControl:"allow",applicationControl:"allow",fileDelete:"allow",shell:"allow",script:"allow",softwareInstall:"allow",systemPower:"allow",systemConfiguration:"allow"}:n==="custom"&&a?a:{...ih,processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileWrite:"ask",network:"ask"}}function xN(n,a,r){const l=vN(a,r),c=n.requiredOperations.map(d=>l[Br[d].permissionCategory]);if(c.includes("deny")){const d=n.requiredOperations.find(m=>l[Br[m].permissionCategory]==="deny");return{state:"blocked",label:"Blocked",reason:`This task requires ${Br[d].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 workstation."}:n.requiredOperations.every(d=>Br[d].readOnly)?{state:"read-only",label:"Read only"}:a==="full-access"?{state:"full-access",label:"Full Access"}:{state:"auto",label:"Auto allowed"}}function yN(n){const a=String(n||"").trim().toLowerCase();return a==="windows"||a==="win32"||a==="win32nt"?"windows":a==="macos"||a==="macosx"||a==="darwin"||a==="osx"?"macos":a==="linux"?"linux":null}function wN(n,a,r){const l=new Set(r);return n.filter(c=>c.connected&&(a==="all"||l.has(c.deviceId)))}function bN(n,a){const r=yN(n.platform);if(!r||!a.supportedPlatforms.includes(r))return!1;const l=n.capabilities?.agentTools;return!Array.isArray(l)||l.length===0?a.requiredOperations.every(c=>Br[c].readOnly):a.requiredOperations.every(c=>l.includes(c))}function Zw(n,a,r,l,c,d){const m=xN(n,c,d),p=wN(a,r,l),v=p.map(j=>j.deviceId),g={...m,available:!1,availableDeviceIds:[],unsupportedDeviceIds:v,risk:n.risk,supportedPlatforms:n.supportedPlatforms};if(p.length===0)return{...g,reason:"Select at least one connected workstation."};if(n.targetSupport==="single"&&p.length!==1)return{...g,reason:"This task supports one workstation at a time."};if(m.state==="blocked")return g;const w=p.filter(j=>bN(j,n)),y=w.map(j=>j.deviceId),b=v.filter(j=>!y.includes(j));return w.length===0?{...g,unsupportedDeviceIds:b,reason:"No current target supports the required platform and client capabilities."}:{...g,available:!0,availableDeviceIds:y,unsupportedDeviceIds:b}}function SN(n,a,r,l,c,d){return n.filter(m=>m.enabled&&Zw(m,a,r,l,c,d).available).length}const rh="livedesk.agentPromptRecent",lh="livedesk.agentPromptFavorites",jN={Recommended:Nl,"Health & capacity":an,"Processes & services":XS,"AI workloads":Uy,"Files & configuration":QS,"Software & automation":Qd,"Network & connectivity":Wh,"Power & maintenance":zt,"Troubleshooting & recovery":KS};function hy(n){if(typeof window>"u")return[];try{const a=JSON.parse(window.localStorage.getItem(n)||"[]");return Array.isArray(a)?a.filter(r=>typeof r=="string"):[]}catch{return[]}}function Ld(n,a){try{window.localStorage.setItem(n,JSON.stringify(a))}catch{}}function oh(n){return n==="all"?"All tasks":n==="recent"?"Recent":n==="favorites"?"Favorites":n==="read-only"?"Read only":n==="auto"?"Auto allowed":n==="approval"?"Approval required":n==="full-access"?"Full Access":n==="available"?"Available":n==="unavailable"?"Unavailable":n}function CN(n){return n==="all"?"All":n==="recent"?"Recent":n==="favorites"?"Favorites":n==="read-only"?"Read only":n==="auto"?"Auto":n==="approval"?"Approval":n==="full-access"?"Full access":n==="available"?"Available":n==="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"}[n]}function kN(n,a,r){if(!r.trim())return!0;const l=r.trim().toLowerCase();return[n.title,n.prompt,n.description,n.category,n.risk,a.label,...n.keywords,...n.requiredOperations,...n.supportedPlatforms].join(" ").toLowerCase().includes(l)}function AN(n){return`permission-${n}`}function NN(n){return n==="low"?"Low risk":n==="medium"?"Medium risk":n==="high"?"High risk":"Critical risk"}function MN(n){return n==="windows"?"Windows":n==="macos"?"macOS":"Linux"}function TN({devices:n,targetMode:a,selectedIds:r,permissionMode:l,customCategories:c,onSelectPrompt:d,onClose:m}){const[p,v]=u.useState(""),[g,w]=u.useState("all"),[y,b]=u.useState(()=>hy(rh)),[j,C]=u.useState(()=>hy(lh)),[N,T]=u.useState(0),[k,E]=u.useState(""),R=u.useRef(null),$=u.useRef(null),F=u.useMemo(()=>Xw.filter(Y=>Y.enabled),[]),q=u.useMemo(()=>new Map(F.map(Y=>[Y.id,Zw(Y,n,a,r,l,c)])),[c,n,l,r,a,F]),z=u.useMemo(()=>[...q.values()].filter(Y=>Y.available).length,[q]),L=u.useMemo(()=>n.filter(Y=>Y.connected&&(a==="all"||r.includes(Y.deviceId))).length,[n,r,a]),ie=u.useMemo(()=>{const Y=F.filter(O=>kN(O,q.get(O.id),p));return g==="recent"?y.map(O=>Y.find(Z=>Z.id===O)).filter(O=>!!O):g==="favorites"?j.map(O=>Y.find(Z=>Z.id===O)).filter(O=>!!O):g==="all"?Y:Y.filter(O=>{const Z=q.get(O.id);return g==="read-only"?Z.state==="read-only":g==="auto"?Z.state==="auto":g==="approval"?Z.state==="approval":g==="full-access"?Z.state==="full-access":g==="available"?Z.available:g==="unavailable"?!Z.available:O.category===g})},[q,j,g,y,p,F]),V=u.useMemo(()=>g!=="all"?[{category:oh(g),templates:ie}]:fy.map(Y=>({category:Y,templates:ie.filter(O=>O.category===Y)})).filter(Y=>Y.templates.length>0),[g,ie]);u.useEffect(()=>{T(Y=>Math.min(Y,Math.max(0,ie.length-1)))},[ie.length]),u.useEffect(()=>{Ld(rh,y)},[y]),u.useEffect(()=>{Ld(lh,j)},[j]),u.useEffect(()=>{$.current?.focus();const Y=Z=>{Z.target instanceof Node&&!R.current?.contains(Z.target)&&m()},O=Z=>{Z.key==="Escape"&&(Z.preventDefault(),m())};return document.addEventListener("pointerdown",Y),document.addEventListener("keydown",O),()=>{document.removeEventListener("pointerdown",Y),document.removeEventListener("keydown",O)}},[m]);const ne=Y=>{const O=q.get(Y.id);if(!O.available){E(O.reason||"This task is not available for the current targets and permission policy.");return}const Z=[Y.id,...y.filter(X=>X!==Y.id)].slice(0,10);b(Z),Ld(rh,Z),d(Y.prompt),m()},Q=Y=>{C(O=>{const Z=O.includes(Y)?O.filter(X=>X!==Y):[Y,...O];return Ld(lh,Z),Z})},J=Y=>{Y.key==="ArrowDown"?(Y.preventDefault(),T(O=>Math.min(O+1,Math.max(0,ie.length-1)))):Y.key==="ArrowUp"?(Y.preventDefault(),T(O=>Math.max(O-1,0))):Y.key==="Enter"&&ie[N]&&(Y.preventDefault(),ne(ie[N]))};let le=-1;return s.jsxs("section",{className:"agents-suggested-tasks",ref:R,"aria-label":"Suggested tasks",children:[s.jsxs("header",{className:"agents-suggested-header",children:[s.jsxs("div",{children:[s.jsxs("span",{className:"agents-suggested-title",children:[s.jsx(Nl,{size:15})," Suggested tasks"]}),s.jsxs("small",{children:[z," available · ",F.length," total. Choose a task, edit it, then run it."]})]}),s.jsx("button",{className:"agents-suggested-close",type:"button","aria-label":"Close suggested tasks",onClick:m,children:s.jsx(Ds,{size:16})})]}),s.jsxs("label",{className:"agents-suggested-search",children:[s.jsx(YS,{size:15,"aria-hidden":"true"}),s.jsx("input",{ref:$,value:p,onChange:Y=>v(Y.target.value),onKeyDown:J,placeholder:"Search tasks...","aria-label":"Search suggested tasks"})]}),s.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",...fy].map(Y=>{const O=Y==="recent"?$y:Y==="favorites"?bh:Y==="all"?Nl:Y==="available"?Ln:Y==="unavailable"?WS:Y==="read-only"||Y==="auto"||Y==="approval"||Y==="full-access"?zt:jN[Y];return s.jsxs("button",{className:g===Y?"active":"",type:"button",title:oh(Y),"aria-label":oh(Y),"aria-pressed":g===Y,onClick:()=>{w(Y),T(0),E("")},children:[s.jsx(O,{size:12})," ",CN(Y)]},Y)})}),k&&s.jsx("div",{className:"agents-suggested-notice",role:"status",children:k}),s.jsxs("div",{className:"agents-suggested-list",role:"listbox","aria-label":"Suggested tasks",children:[V.map(Y=>s.jsxs("div",{className:"agents-suggested-group",children:[s.jsx("strong",{children:Y.category}),Y.templates.map(O=>{le+=1;const Z=le===N,X=j.includes(O.id),D=q.get(O.id),K=D.availableDeviceIds.length+D.unsupportedDeviceIds.length||L,ce=D.available?`Available on ${D.availableDeviceIds.length} of ${K} target${K===1?"":"s"}`:`Unavailable: ${D.reason||"not supported by the current targets"}`;return s.jsxs("div",{className:`agents-suggested-item ${Z?"active":""} ${D.available?"":"unavailable"}`,children:[s.jsxs("button",{className:"agents-suggested-prompt",type:"button",role:"option","aria-selected":Z,"aria-disabled":!D.available,onClick:()=>ne(O),children:[s.jsx("span",{children:O.title}),s.jsx("small",{className:"agents-suggested-description",children:O.description}),s.jsxs("span",{className:"agents-suggested-meta",children:[s.jsx("em",{children:O.category}),s.jsx("em",{className:AN(D.state),children:D.label}),s.jsx("em",{className:`risk-${O.risk}`,children:NN(O.risk)}),s.jsx("em",{children:O.supportedPlatforms.map(MN).join(" · ")}),s.jsx("em",{className:D.available?"availability-ok":"availability-unavailable",children:ce}),D.available&&D.unsupportedDeviceIds.length>0&&s.jsxs("em",{className:"availability-warning",children:["Unsupported on ",D.unsupportedDeviceIds.length]})]})]}),s.jsx("button",{className:`agents-suggested-favorite ${X?"favorite":""}`,type:"button","aria-label":X?`Remove ${O.title} from favorites`:`Add ${O.title} to favorites`,"aria-pressed":X,onClick:()=>Q(O.id),children:s.jsx(bh,{size:14,fill:X?"currentColor":"none"})})]},O.id)})]},Y.category)),ie.length===0&&s.jsx("p",{className:"agents-suggested-empty",children:"No tasks match this search or current filter."})]})]})}function EN({devices:n,mode:a,selectedIds:r,onModeChange:l,onToggle:c,permissionMode:d,onPermissionModeChange:m}){const p=n.filter(Ih),v=r.filter(g=>p.some(w=>w.deviceId===g)).length;return s.jsxs("section",{className:"agents-target-picker","aria-label":"Agent targets",children:[s.jsxs("div",{className:"agents-target-toolbar",children:[s.jsx("span",{className:"agents-section-label",children:"Targets"}),s.jsxs("div",{className:"agents-target-modes",children:[s.jsxs("button",{className:a==="all"?"active":"",onClick:()=>l("all"),type:"button",children:[s.jsx(Yy,{size:14})," All connected ",s.jsx("small",{children:p.length})]}),s.jsxs("button",{className:a==="selected"?"active":"",onClick:()=>l("selected"),type:"button",children:[s.jsx(Pr,{size:14})," Selected ",v]})]}),s.jsxs("label",{className:`agents-permission-picker permission-${d}`,children:[s.jsx(lf,{size:14}),s.jsx("span",{children:"Permission"}),s.jsxs("select",{value:d,onChange:g=>m(g.target.value),"aria-label":"Agent permission mode",children:[s.jsx("option",{value:"ask",children:"Ask"}),s.jsx("option",{value:"safe-auto",children:"Safe Auto"}),s.jsx("option",{value:"full-access",children:"Full Access"}),s.jsx("option",{value:"custom",children:"Custom"})]}),s.jsx(Ky,{size:13,"aria-hidden":"true"})]})]}),s.jsx("div",{className:"agents-target-list",children:n.length===0?s.jsx("span",{className:"agents-target-empty",children:"No workstations discovered."}):n.map(g=>{const w=Ih(g),y=a==="all"?w:r.includes(g.deviceId);return s.jsxs("label",{className:`agents-target-option ${y?"selected":""} ${w?"":"offline"}`,children:[s.jsx("input",{type:"checkbox",checked:y,disabled:!w||a==="all",onChange:()=>c(g.deviceId)}),s.jsx("span",{className:"agents-target-icon",children:s.jsx(Zt,{size:15})}),s.jsxs("span",{children:[s.jsx("strong",{children:Qw(g)}),s.jsx("small",{children:w?"Ready":g.connected?"Agent reconnecting":"Offline"})]}),y&&s.jsx(Pr,{className:"agents-target-check",size:15,"aria-hidden":"true"})]},g.deviceId)})})]})}async function RN(n,a){return $e("/api/settings/agent/plan",{method:"POST",body:JSON.stringify({instruction:a})},n)}async function DN(n,a){return $e("/api/settings/agent/run",{method:"POST",body:JSON.stringify(a)},n)}async function _N(n,a){return $e(`/api/settings/agent/runs/${encodeURIComponent(a)}`,void 0,n)}async function LN(n,a){return $e(`/api/settings/agent/runs/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})},n)}async function zN(n){return $e("/api/settings/agent/runs/cancel-all",{method:"POST",body:JSON.stringify({})},n)}async function IN(n,a,r,l){return $e(`/api/settings/agent/runs/${encodeURIComponent(a)}/approvals/${encodeURIComponent(r)}/approve`,{method:"POST",body:JSON.stringify({scope:l})},n)}async function ON(n,a,r,l="User rejected this action."){return $e(`/api/settings/agent/runs/${encodeURIComponent(a)}/approvals/${encodeURIComponent(r)}/reject`,{method:"POST",body:JSON.stringify({reason:l})},n)}async function BN(n,a,r){return $e(`/api/settings/agent/policies/${encodeURIComponent(a)}`,{method:"PUT",body:JSON.stringify({categories:r})},n)}async function FN(n,a){return $e("/api/settings/agent/summary",{method:"POST",body:JSON.stringify(a)},n)}async function PN(n,a){return $e("/api/remote/tasks",{method:"POST",body:JSON.stringify({instruction:a.instruction,deviceIds:a.deviceIds,operation:a.operation,targetQuery:a.targetQuery,approvalLevel:"read-only"})},n)}async function HN(n,a){return $e(`/api/remote/tasks/${encodeURIComponent(a)}`,void 0,n)}async function $N(n,a){return $e(`/api/remote/tasks/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})},n)}async function UN(n,a){return $e(`/api/remote/tasks/${encodeURIComponent(a)}/retry`,{method:"POST",body:JSON.stringify({failedOnly:!0})},n)}function xl(n){return`${n}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function zd(n,a){const r=new Map(a.map(l=>[l.deviceId,Qw(l)]));return n.results.map(l=>({deviceId:l.deviceId,deviceName:l.deviceName||r.get(l.deviceId)||l.deviceId,status:aN(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 qN(n,a){const r=new Map(a.map(l=>[l.deviceId,l]));return n.map(l=>{const c=r.get(l.deviceId);return!c||c.sequence<=l.sequence?l:c})}function GN(n,a){const r=a.filter(d=>d.status==="completed"),l=a.filter(d=>d.status==="failed");if(n.operation==="process.list"){const m=`${r.filter(p=>{const v=p.result||"";return!/not running|no process/i.test(v)&&/running|online|found/i.test(v)}).length}대에서 요청한 프로세스가 실행 중입니다.`;return l.length>0?`${m}
14
+ ${l.map(p=>`${p.deviceName}는 ${p.error||"응답하지 않았습니다."}`).join(`
15
+ `)}`:m}return l.length>0?`${r.length}대 완료, ${l.length}대 실패했습니다.`:`${r.length}대 작업이 완료되었습니다.`}const VN={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 YN(n){return n==="safe-auto"?"Safe Auto":n==="full-access"?"Full Access":n==="custom"?"Custom":"Ask"}function WN(n){return n.replace(/([A-Z])/g," $1").replace(/^./,a=>a.toUpperCase())}function KN(n){const a=n instanceof Error?n.message:String(n);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 workstation 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 QN({hubUrl:n,devices:a,launchRequest:r}){const[l,c]=u.useState("all"),[d,m]=u.useState([]),[p,v]=u.useState(""),[g,w]=u.useState([]),[y,b]=u.useState(""),[j,C]=u.useState(""),[N,T]=u.useState(""),[k,E]=u.useState("safe-auto"),[R]=u.useState("custom-default"),[$,F]=u.useState(VN),[q,z]=u.useState([]),[L,ie]=u.useState(""),[V,ne]=u.useState(!1),[Q,J]=u.useState(null),[le,Y]=u.useState(!1),[O,Z]=u.useState(""),[X,D]=u.useState(!1),[K,ce]=u.useState(null),W=u.useRef(null),P=u.useRef(new Set),me=u.useRef(new Set),pe=u.useRef(new Set),ve=u.useMemo(()=>a.filter(Ih).map(he=>he.deviceId),[a]),ke=u.useMemo(()=>SN(Xw,a,l,d,k,$),[$,a,k,d,l]);u.useEffect(()=>{r?.deviceId&&(c("selected"),m([r.deviceId]),v(r.instruction),D(!1),window.requestAnimationFrame(()=>{W.current?.focus(),W.current?.setSelectionRange(r.instruction.length,r.instruction.length)}))},[r]);const _e=u.useCallback(he=>{const Ae=zd(he,a);if(w(de=>de.map(ye=>ye.type==="task"&&ye.batchId===he.batchId?{...ye,states:qN(ye.states,Ae),status:he.status}:ye)),!["running","queued"].includes(he.status)&&!P.current.has(he.batchId)){P.current.add(he.batchId);const de=xl("agent-summary");w(ye=>[...ye,{type:"agent",id:de,text:GN(he,Ae)}]),he.operation&&FN(n,{instruction:he.instructionPreview,operation:he.operation,total:Ae.length,completed:Ae.filter(ye=>ye.status==="completed").length,failed:Ae.filter(ye=>ye.status==="failed").length,results:Ae.map(ye=>({deviceName:ye.deviceName,status:ye.status,result:ye.result,error:ye.error}))}).then(ye=>{!ye.ok||!ye.summary||w(qe=>qe.map(tt=>tt.type==="agent"&&tt.id===de?{...tt,text:ye.summary}:tt))}).catch(()=>{}),b(ye=>ye===he.batchId?"":ye)}},[a,n]),Le=u.useCallback(async he=>{const Ae=await HN(n,he);return _e(Ae),Ae},[n,_e]),ue=u.useCallback((he,Ae)=>{pe.current.has(he.batchId)||(pe.current.add(he.batchId),w(de=>[...de,{type:"task",id:xl("task"),batchId:he.batchId,agentRunId:Ae,operation:he.operation||"diagnostics.collect",instruction:he.instructionPreview,states:zd(he,a),status:he.status}])),_e(he)},[a,_e]),Ve=u.useCallback(async he=>{const Ae=await _N(n,he);for(const ye of Ae.taskBatches||[])ue(ye,he);z(Ae.approvals||[]);const de=["running","queued","waiting-approval"].includes(Ae.status);if(ce(de?{runId:he,stage:Ae.stage||Ae.status,message:Ae.progressMessage||(Ae.status==="waiting-approval"?"Review the requested action to continue.":"Codex is preparing the answer.")}:ye=>ye?.runId===he?null:ye),!de&&!me.current.has(he)){me.current.add(he);const ye=[Ae.error,Ae.errorMessage].filter(Boolean).join(" — "),qe=Ae.finalResponse?.trim()||(Ae.status==="cancelled"?"Codex 작업을 취소했습니다.":ye?`Codex 작업이 완료되지 않았습니다: ${ye}`:"Codex 작업이 완료되었습니다.");w(tt=>[...tt,{type:Ae.status==="failed"?"error":"agent",id:xl("agent-run-result"),text:qe}])}return Ae},[ue,n]);u.useEffect(()=>{if(!y)return;let he=!0;const Ae=async()=>{try{const ye=await Le(y);he&&!["running","queued"].includes(ye.status)&&b("")}catch(ye){he&&Z(ye instanceof Error?ye.message:String(ye))}};Ae();const de=window.setInterval(()=>{Ae()},800);return()=>{he=!1,window.clearInterval(de)}},[y,Le]),u.useEffect(()=>{if(!j)return;let he=!0;const Ae=async()=>{try{const ye=await Ve(j);he&&!["running","queued","waiting-approval"].includes(ye.status)&&(C(""),Y(!1))}catch(ye){he&&Z(ye instanceof Error?ye.message:String(ye))}};Ae();const de=window.setInterval(()=>{Ae()},800);return()=>{he=!1,window.clearInterval(de)}},[j,Ve]);const Ye=async(he="",Ae,de=!1)=>{const ye=(he||p).trim();if(!ye||y||j)return;let qe=null;const tt=Ae||(l==="all"?ve:d.filter(Ke=>ve.includes(Ke)));if(tt.length===0){Z("Select at least one connected workstation.");return}if(k==="full-access"&&!le&&!de){J({instruction:ye,targetIds:tt});return}if(w(Ke=>[...Ke,{type:"user",id:xl("user"),text:ye}]),v(""),D(!1),Z(""),tt.length===0){w(Ke=>[...Ke,{type:"error",id:xl("no-targets"),text:"연결된 대상 장비를 하나 이상 선택해 주세요."}]);return}if(!qe){try{if(k==="custom"){const ht=await BN(n,R,$);if(!ht.ok)throw new Error(ht.error||"Custom Agent policy could not be saved.")}const Ke=await DN(n,{instruction:ye,deviceIds:tt,permissionMode:k,customPolicyId:R});if(!Ke.ok||!Ke.runId)throw new Error(Ke.error||"Codex Agent run could not be started.");z(Ke.approvals||[]),ce({runId:Ke.runId,stage:Ke.stage||Ke.status||"queued",message:Ke.progressMessage||"Codex request queued on the Hub."}),C(Ke.runId);return}catch(Ke){try{const ht=await RN(n,ye);ht.ok&&ht.plan&&(qe={operation:ht.plan.operation,query:ht.plan.targetQuery})}catch{w(ht=>[...ht,{type:"error",id:xl("unsupported"),text:KN(Ke)}])}}if(!qe)return}try{const Ke=await PN(n,{instruction:ye,deviceIds:tt,operation:qe.operation,targetQuery:qe.query});if(!Ke.ok||!Ke.batch||!Ke.batchId)throw new Error(Ke.error||"작업을 만들지 못했습니다.");const ht={type:"task",id:xl("task"),batchId:Ke.batchId,operation:qe.operation,instruction:ye,states:zd(Ke.batch,a),status:Ke.batch.status};pe.current.add(Ke.batchId),w(St=>[...St,ht]),b(Ke.batchId)}catch(Ke){Z(Ke instanceof Error?Ke.message:String(Ke))}},oe=async(he,Ae)=>{ie(he.approvalId);try{const de=await IN(n,he.runId,he.approvalId,Ae);if(!de.ok)throw new Error(de.error||"Agent approval could not be applied.");await Ve(he.runId)}catch(de){Z(de instanceof Error?de.message:String(de))}finally{ie("")}},Ne=async he=>{ie(he.approvalId);try{const Ae=await ON(n,he.runId,he.approvalId);if(!Ae.ok)throw new Error(Ae.error||"Agent approval could not be rejected.");await Ve(he.runId)}catch(Ae){Z(Ae instanceof Error?Ae.message:String(Ae))}finally{ie("")}},je=async(he,Ae)=>{T(he);try{if(Ae){const ye=await LN(n,Ae);for(const qe of ye.taskBatches||[])_e(qe);C(qe=>qe===Ae?"":qe),ce(qe=>qe?.runId===Ae?null:qe);return}const de=await $N(n,he);_e(de),b(ye=>ye===he?"":ye)}catch(de){Z(de instanceof Error?de.message:String(de))}finally{T("")}},Ee=async()=>{if(!(V||!y&&!j)){ne(!0);try{const he=await zN(n);if(!he.ok)throw new Error(he.error||"모든 Agent 작업을 취소하지 못했습니다.");b(""),C(""),ce(null),z([]),w(Ae=>Ae.map(de=>de.type==="task"&&["queued","running"].includes(de.status)?{...de,status:"cancelled",states:de.states.map(ye=>["queued","running"].includes(ye.status)?{...ye,status:"cancelled",stage:"Cancelled",error:"Cancelled by user."}:ye)}:de))}catch(he){Z(he instanceof Error?he.message:String(he))}finally{ne(!1)}}},Re=async he=>{T(he);try{const Ae=await UN(n,he);if(!Ae.ok||!Ae.batch||!Ae.batchId)throw new Error(Ae.error||"재시도하지 못했습니다.");P.current.delete(Ae.batchId),w(de=>de.map(ye=>ye.type==="task"&&ye.batchId===he?{...ye,batchId:Ae.batchId,states:zd(Ae.batch,a),status:Ae.batch.status}:ye)),b(Ae.batchId)}catch(Ae){Z(Ae instanceof Error?Ae.message:String(Ae))}finally{T("")}},Fe=he=>{v(he),D(!1),window.requestAnimationFrame(()=>W.current?.focus())};return s.jsxs("section",{className:"agents-page",children:[s.jsxs("div",{className:"agents-workspace",children:[(y||j)&&s.jsxs("div",{className:"agents-page-status",children:[s.jsxs("span",{children:[ve.length," workstations · ",YN(k)]}),s.jsx("button",{type:"button",className:"agents-stop-all",onClick:()=>{Ee()},disabled:V,children:V?"Stopping…":"Stop all"})]}),Q&&s.jsx("div",{className:"agents-permission-modal-backdrop",role:"presentation",children:s.jsxs("section",{className:"agents-permission-modal",role:"dialog","aria-modal":"true","aria-labelledby":"full-access-title",children:[s.jsx("span",{className:"agents-permission-modal-icon",children:s.jsx(lf,{size:20})}),s.jsx("h3",{id:"full-access-title",children:"Confirm Full Access"}),s.jsx("p",{children:"Codex may change files, run commands, manage applications, and modify system state on the selected workstations. This run is still limited to the selected devices, the fixed policy, and the tool budget."}),s.jsxs("div",{className:"agents-permission-modal-actions",children:[s.jsx("button",{type:"button",onClick:()=>J(null),children:"Cancel"}),s.jsx("button",{type:"button",className:"danger",onClick:()=>{const he=Q;J(null),Y(!0),Ye(he.instruction,he.targetIds,!0)},children:"Run with Full Access"})]})]})}),O&&s.jsx("div",{className:"agents-error",role:"alert",children:O}),s.jsx(mN,{items:g,onCancel:je,onRetry:Re,busyBatchId:N,approvals:q,onApprove:oe,onReject:Ne,busyApprovalId:L,progress:K}),s.jsxs("div",{className:"agents-composer-shell",children:[X&&s.jsx(TN,{devices:a,targetMode:l,selectedIds:d,permissionMode:k,customCategories:$,onSelectPrompt:Fe,onClose:()=>D(!1)}),s.jsx(tN,{ref:W,value:p,onChange:v,onSubmit:()=>{Ye()},onOpenSuggestedTasks:()=>D(he=>!he),suggestedOpen:X,suggestedTaskCount:ke,disabled:!!y||!!j})]})]}),s.jsxs("aside",{className:"agents-target-sidebar","aria-label":"Agent targets and permissions",children:[s.jsx(EN,{devices:a,mode:l,selectedIds:d,onModeChange:c,onToggle:he=>m(Ae=>Ae.includes(he)?Ae.filter(de=>de!==he):[...Ae,he]),permissionMode:k,onPermissionModeChange:he=>{E(he),he!=="full-access"&&Y(!1)}}),k==="custom"&&s.jsxs("section",{className:"agents-custom-policy","aria-label":"Custom Agent permissions",children:[s.jsxs("div",{className:"agents-custom-policy-head",children:[s.jsxs("div",{children:[s.jsx("span",{className:"agents-section-label",children:"Custom policy"}),s.jsx("strong",{children:"Choose what Codex may do automatically."})]}),s.jsx("span",{children:"Denied actions never reach a device."})]}),s.jsx("div",{className:"agents-custom-policy-grid",children:nN.map(he=>s.jsxs("label",{children:[s.jsx("span",{children:WN(he)}),s.jsxs("select",{value:$[he],onChange:Ae=>F(de=>({...de,[he]:Ae.target.value})),children:[s.jsx("option",{value:"allow",children:"Allow automatically"}),s.jsx("option",{value:"ask",children:"Ask every time"}),s.jsx("option",{value:"deny",children:"Deny"})]})]},he))})]})]})]})}function Jw(n){return{type:n.type,deviceIds:n.deviceIds,monitorIndex:n.monitorIndex,label:n.label}}async function eb(n){try{return(await n.json()).error||`${n.status} ${n.statusText}`}catch{return`${n.status} ${n.statusText}`}}async function tb(n,a,r){const l=encodeURIComponent(JSON.stringify({kind:a.kind,fileName:a.fileName,mimeType:n.type||"application/octet-stream",durationMs:a.durationMs,target:Jw(a.target)})),c=await fetch(`${qr(r)}/api/captures?metadata=${l}`,{method:"POST",headers:{"Content-Type":n.type||"application/octet-stream"},body:n,cache:"no-store"});if(!c.ok)throw new Error(await eb(c));return await c.json()}async function XN(n,a){return await $e("/api/capture-sessions",{method:"POST",body:JSON.stringify({...n,target:Jw(n.target)})},a)}async function ZN(n,a,r,l){const c=await fetch(`${qr(l)}/api/capture-sessions/${encodeURIComponent(n)}/chunks/${a}`,{method:"PUT",headers:{"Content-Type":r.type||"application/octet-stream"},body:r,cache:"no-store"});if(!c.ok)throw new Error(await eb(c));return await c.json()}async function JN(n,a,r){return await $e(`/api/capture-sessions/${encodeURIComponent(n)}/finalize`,{method:"POST",body:JSON.stringify({durationMs:a})},r)}async function py(n,a){await $e(`/api/capture-sessions/${encodeURIComponent(n)}`,{method:"DELETE"},a)}async function eM(n){return await $e("/api/captures",void 0,n)}function gy(n,a){return`${qr(a)}/api/captures/${encodeURIComponent(n)}/content`}async function tM(n,a){return await $e(`/api/captures/${encodeURIComponent(n)}`,{method:"DELETE"},a)}function nM({hubUrl:n,onToast:a}){const[r,l]=u.useState([]),[c,d]=u.useState(!0),m=u.useCallback(async()=>{d(!0);try{l((await eM(n)).captures||[])}catch(v){a(v instanceof Error?v.message:String(v))}finally{d(!1)}},[n,a]);u.useEffect(()=>{m()},[m]);const p=async v=>{const g=gy(v.id,n);if(navigator.share)try{await navigator.share({title:v.fileName,url:g});return}catch{}window.open(g,"_blank","noopener,noreferrer")};return s.jsxs("section",{className:"capture-gallery",children:[s.jsxs("header",{children:[s.jsxs("div",{children:[s.jsx("span",{className:"settings-eyebrow",children:"Capture Gallery"}),s.jsx("h2",{children:"Saved captures"})]}),s.jsxs("button",{className:"text-button",onClick:()=>{m()},type:"button",children:[s.jsx(Ro,{size:15})," Refresh"]})]}),c?s.jsx("p",{className:"settings-help",children:"Loading captures..."}):r.length===0?s.jsx("p",{className:"settings-help",children:"No captures saved yet."}):s.jsx("div",{className:"capture-gallery-grid",children:r.map(v=>{const g=gy(v.id,n);return s.jsxs("article",{className:"capture-gallery-card",children:[v.mimeType.startsWith("image/")?s.jsx("img",{src:g,alt:v.target.label}):s.jsx("video",{src:g,controls:!0,preload:"metadata"}),s.jsxs("div",{className:"capture-gallery-card-body",children:[s.jsx("strong",{children:v.fileName}),s.jsxs("small",{children:[v.target.label," · ",new Date(v.createdAt).toLocaleString()," · ",Math.ceil(v.sizeBytes/1024)," KB"]}),s.jsxs("div",{children:[s.jsx("button",{className:"icon-button",title:"Open","aria-label":"Open",onClick:()=>window.open(g,"_blank","noopener,noreferrer"),type:"button",children:s.jsx(ZS,{size:15})}),s.jsx("a",{className:"icon-button",title:"Download","aria-label":"Download",href:`${g}?download=1`,download:v.fileName,children:s.jsx(Gh,{size:15})}),s.jsx("button",{className:"icon-button",title:"Share","aria-label":"Share",onClick:()=>{p(v)},type:"button",children:s.jsx(JS,{size:15})}),s.jsx("button",{className:"icon-button danger",title:"Delete","aria-label":"Delete",onClick:()=>{window.confirm(`Delete ${v.fileName}?`)&&tM(v.id,n).then(()=>m()).catch(w=>a(w instanceof Error?w.message:String(w)))},type:"button",children:s.jsx(Vh,{size:15})})]})]})]},v.id)})})]})}function Id(n){if(!n)return"";const a=Math.max(0,Math.floor((Date.now()-n)/1e3)),r=Math.floor(a/3600),l=Math.floor(a%3600/60),c=a%60;return r>0?`${String(r).padStart(2,"0")}:${String(l).padStart(2,"0")}:${String(c).padStart(2,"0")}`:`${String(l).padStart(2,"0")}:${String(c).padStart(2,"0")}`}function vy({controller:n,compact:a=!1,onFirstRollingUse:r,onError:l}){const{state:c,settings:d,videoSupported:m}=n,p=async y=>{try{await y()}catch(b){l?.(b instanceof Error?b.message:String(b))}},v=async()=>{if(d.rollingEnabled){n.setRollingEnabled(!1);return}(r?await r():window.confirm(`Keep the most recent 30 seconds in memory temporarily?
16
+ Nothing is saved until you press Save Last 30s.`))&&n.setRollingEnabled(!0)},g=c.recording?`Stop recording · ${Id(c.recordingStartedAt)}`:`Start recording · ${c.targetLabel}`,w=c.timelapse?`Stop timelapse · ${Id(c.timelapseStartedAt)}`:`Start timelapse · ${d.timelapseIntervalSeconds}s interval`;return s.jsxs("div",{className:`capture-toolbar ${a?"compact":""} ${c.recording?"recording-active":""}`,"aria-label":"Capture actions",children:[s.jsx("button",{className:"capture-action","aria-label":`Take screenshot · ${c.targetLabel}`,title:`Take screenshot · ${c.targetLabel}`,disabled:c.busy,onClick:()=>{p(n.takeScreenshot)},type:"button",children:s.jsx(e0,{size:17})}),s.jsx("button",{className:`capture-action ${c.recording?"active":""}`,"aria-label":g,title:g,disabled:!m||c.busy||c.timelapse,onClick:()=>{p(c.recording?n.stopRecording:n.startRecording)},type:"button",children:c.recording?s.jsxs(s.Fragment,{children:[s.jsx(tx,{size:14,fill:"currentColor"}),s.jsx("span",{children:Id(c.recordingStartedAt)})]}):s.jsx(Wy,{size:18})}),s.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 p(n.saveLast30Seconds):void v(),type:"button",children:[s.jsx(t0,{size:17}),s.jsx("small",{children:"30s"})]}),s.jsx("button",{className:`capture-action ${c.timelapse?"timelapse-active":""}`,"aria-label":w,title:w,disabled:!m||c.busy||c.recording,onClick:()=>{p(c.timelapse?n.stopTimelapse:n.startTimelapse)},type:"button",children:c.timelapse?s.jsxs(s.Fragment,{children:[s.jsx(tx,{size:14,fill:"currentColor"}),s.jsx("span",{children:Id(c.timelapseStartedAt)})]}):s.jsx(n0,{size:17})})]})}async function aM(n,a={}){const r=n.filter(y=>y.canvas&&y.canvas.width>0&&y.canvas.height>0),l=Math.max(320,a.maxWidth||1920),c=Math.max(180,a.maxHeight||1080),d=r.length<=1?1:r.length<=4?2:r.length<=9?3:4,m=Math.max(1,Math.ceil(Math.max(1,r.length)/d)),p=Math.floor(l/d),v=Math.floor(c/m),g=document.createElement("canvas");g.width=Math.max(320,p*d),g.height=Math.max(180,v*m);const w=g.getContext("2d",{alpha:!1});if(!w)return g;w.fillStyle="#0b1220",w.fillRect(0,0,g.width,g.height),w.font="600 14px system-ui, sans-serif",w.textBaseline="bottom";for(let y=0;y<r.length;y+=1){const b=r[y],j=y%d,C=Math.floor(y/d),N=j*p,T=C*v,k=b.canvas,E=Math.min(p/k.width,v/k.height),R=Math.max(1,Math.floor(k.width*E)),$=Math.max(1,Math.floor(k.height*E)),F=N+Math.floor((p-R)/2),q=T+Math.floor((v-$)/2);w.drawImage(k,F,q,R,$),a.includeLabels!==!1&&(w.fillStyle="rgba(4, 10, 20, .74)",w.fillRect(N,T+v-28,p,28),w.fillStyle="#f8fafc",w.fillText(b.label,N+9,T+v-9))}return g}function sM(n){return n?.signature||"none"}function iM(n){return n?.label||"No capture target"}function xy(n){return{...n,deviceIds:[...n.deviceIds],sourceCanvas:n.sourceCanvas||null}}function rM(){const n=new Date,a=r=>String(r).padStart(2,"0");return`${n.getFullYear()}${a(n.getMonth()+1)}${a(n.getDate())}_${a(n.getHours())}${a(n.getMinutes())}${a(n.getSeconds())}`}function lM(n){return n.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function oM(n){return`LiveDesk_${n.type==="wall"||n.type==="selection"?"Wall":`${lM(n.label)}_Monitor-${Number(n.monitorIndex||0)+1}`}_${rM()}.png`}async function cM(n,a,r){const l=await new Promise((d,m)=>n.toBlob(p=>p?d(p):m(new Error("Screenshot could not be encoded.")),"image/png")),c=await tb(l,{kind:"screenshot",fileName:oM(a),target:a},r);try{await navigator.clipboard.write([new ClipboardItem({"image/png":l})])}catch{}return c.capture}function nb(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(a=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(a))||""}function uM(n,a){const r=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 n==="timelapse"?`LiveDesk_Timelapse_${l}_${r}.webm`:`LiveDesk_Recording_${l}_${r}.webm`}async function ab(n){if(typeof MediaRecorder>"u"||typeof n.canvas.captureStream!="function")throw new Error("This browser does not support video recording.");const a=nb();if(!a)throw new Error("This browser does not support WebM recording.");const r=n.kind||"recording",l=await XN({kind:r,fileName:uM(r,n.target),mimeType:a,target:n.target},n.hubUrl),c=n.canvas.captureStream(n.frameRequests?0:n.fps),d=new MediaRecorder(c,{mimeType:a,videoBitsPerSecond:r==="timelapse"?2e6:4e6}),m=performance.now();let p=0,v=!1,g=null,w=Promise.resolve();return d.ondataavailable=y=>{if(!y.data||y.data.size===0)return;const b=p++;w=w.then(()=>ZN(l.sessionId,b,y.data,n.hubUrl).then(()=>{})).catch(j=>{g=g||(j instanceof Error?j:new Error(String(j))),n.onError?.(g)})},d.onerror=()=>{g=new Error("Video recording stopped unexpectedly."),n.onError?.(g)},d.start(1e3),{requestFrame:()=>{c.getVideoTracks()[0]?.requestFrame?.()},stop:async()=>{if(!v){if(v=!0,await new Promise(y=>{d.addEventListener("stop",()=>y(),{once:!0}),d.stop()}),c.getTracks().forEach(y=>y.stop()),await w,g)throw await py(l.sessionId,n.hubUrl).catch(()=>{}),g;await JN(l.sessionId,Math.max(0,performance.now()-m),n.hubUrl)}},cancel:async()=>{v||(v=!0,d.stop(),c.getTracks().forEach(y=>y.stop()),await py(l.sessionId,n.hubUrl).catch(()=>{}))}}}class dM{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,r){if(this.recorder&&this.targetSignature===r.signature)return;if(this.stop(),typeof MediaRecorder>"u"||typeof a.captureStream!="function")throw new Error("This browser does not support Last 30s.");const l=nb();if(!l)throw new Error("This browser does not support WebM recording.");this.targetSignature=r.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 d=performance.now();for(this.segments.push({blob:c.data,at:d}),this.totalBytes+=c.data.size;this.segments.length>1&&(d-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(r=>r.stop()),this.stream=null,this.segments=[],this.totalBytes=0,this.startedAt=0}async save(a,r){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"}),d=`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 tb(l,{kind:"last-30s",fileName:d,target:a,durationMs:Math.min(3e4,this.segments.length*1e3)},r)}}async function fM(n,a,r,l,c){const d=await ab({canvas:n,target:a,kind:"timelapse",fps:30,frameRequests:!0,hubUrl:l,onError:c});d.requestFrame?.();const m=window.setInterval(()=>d.requestFrame?.(),Math.max(5,r)*1e3);return{stop:async()=>{window.clearInterval(m),await d.stop()},cancel:async()=>{window.clearInterval(m),await d.cancel()}}}const sb="livedesk.captureSettings";function mM(){const n={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const a=JSON.parse(localStorage.getItem(sb)||"null");return{...n,...a&&typeof a=="object"?a:{}}}catch{return n}}function hM(n){const[a,r]=u.useState(mM),[l,c]=u.useState(0),[d,m]=u.useState(0),[p,v]=u.useState(0),[g,w]=u.useState(!1),y=u.useRef(void 0),b=u.useRef(!1),j=u.useRef(""),C=u.useRef(null),N=u.useRef(null),T=u.useRef(null),k=u.useRef(null),E=u.useRef(new dM),R=n.sourceRegistry.resolveCurrentTarget(),$=sM(R),F=iM(R),q=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;u.useEffect(()=>{if(localStorage.setItem(sb,JSON.stringify(a)),!b.current)return;const X=JSON.stringify(a);X!==j.current&&(j.current=X,$e("/api/settings",{method:"PATCH",body:JSON.stringify({revision:y.current,filesAudio:{rollingBufferEnabled:a.rollingEnabled,recordingQuality:a.recordingQuality,timelapseIntervalSeconds:a.timelapseIntervalSeconds,includeRemoteCursor:a.includeRemoteCursor}})},n.hubUrl).then(D=>{y.current=Number(D.revision||y.current||0)}).catch(()=>{}))},[n.hubUrl,a]),u.useEffect(()=>{let X=!0;return $e("/api/settings",void 0,n.hubUrl).then(D=>{if(!X)return;const K=D.settings?.filesAudio||{},ce=typeof K.rollingBufferEnabled=="boolean"?K.rollingBufferEnabled:a.rollingEnabled,W=K.recordingQuality==="high"?"high":"standard",P=[5,10,30,60].includes(Number(K.timelapseIntervalSeconds))?Number(K.timelapseIntervalSeconds):a.timelapseIntervalSeconds,me=typeof K.includeRemoteCursor=="boolean"?K.includeRemoteCursor:a.includeRemoteCursor,pe={rollingEnabled:ce,recordingQuality:W,timelapseIntervalSeconds:P,includeRemoteCursor:me};y.current=Number(D.revision||0),j.current=JSON.stringify(pe),b.current=!0,r(pe)}).catch(()=>{b.current=!0}),()=>{X=!1}},[n.hubUrl]);const z=u.useCallback(async X=>{if(X.sourceCanvas&&X.sourceCanvas.width>0&&X.sourceCanvas.height>0)return{target:xy(X),canvas:X.sourceCanvas,cleanup:()=>{}};const D=await n.sourceRegistry.composeWall(X.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let K=!1;const ce=window.setInterval(async()=>{if(K)return;const W=await n.sourceRegistry.composeWall(X.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0}).catch(()=>null);!W||K||((D.width!==W.width||D.height!==W.height)&&(D.width=W.width,D.height=W.height),D.getContext("2d")?.drawImage(W,0,0))},100);return{target:xy(X),canvas:D,cleanup:()=>{K=!0,window.clearInterval(ce)}}},[n.sourceRegistry]);u.useEffect(()=>{const X=E.current;if(!a.rollingEnabled||!R||!q){X.stop(),v(0);return}let D=!1,K=null;return(async()=>{try{if(K=await z(R),D)return;await X.start(K.canvas,K.target);const W=window.setInterval(()=>v(Math.round(X.seconds)),500),P=()=>{window.clearInterval(W),K?.cleanup()};X.__cleanup=P}catch(W){D||n.onToast(W instanceof Error?W.message:String(W))}})(),()=>{D=!0,X.stop(),X.__cleanup?.(),X.__cleanup=void 0,v(0)}},[z,n.onToast,a.rollingEnabled,$,q]);const L=u.useCallback(X=>r(D=>({...D,rollingEnabled:X})),[]),ie=u.useCallback(X=>r(D=>({...D,recordingQuality:X})),[]),V=u.useCallback(X=>r(D=>({...D,timelapseIntervalSeconds:X})),[]),ne=u.useCallback(async()=>{const X=n.sourceRegistry.resolveCurrentTarget();if(!X)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);let D=null;try{D=await z(X),await cM(D.canvas,D.target,n.hubUrl),n.onToast("Screenshot saved")}finally{D?.cleanup(),w(!1)}},[z,n.hubUrl,n.onToast,n.sourceRegistry]),Q=u.useCallback(async()=>{if(T.current)throw new Error("Stop the timelapse before recording.");const X=n.sourceRegistry.resolveCurrentTarget();if(!X)throw new Error("화면이 준비된 후 다시 시도하세요.");const D=await z(X),K=await ab({canvas:D.canvas,target:D.target,fps:X.type==="control"?30:15,hubUrl:n.hubUrl,onError:ce=>n.onToast(ce.message)});N.current=D.cleanup,C.current=K,c(Date.now()),n.onToast("Recording started")},[z,n.hubUrl,n.onToast,n.sourceRegistry]),J=u.useCallback(async()=>{const X=C.current;if(X){w(!0);try{await X.stop(),n.onToast("Recording saved")}finally{C.current=null,N.current?.(),N.current=null,c(0),w(!1)}}},[n.onToast]),le=u.useCallback(async()=>{if(C.current||T.current)throw new Error("Last 30s is unavailable during a recording.");const X=n.sourceRegistry.resolveCurrentTarget();if(!X)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);try{await E.current.save(X,n.hubUrl),n.onToast("Last 30 seconds saved")}finally{w(!1)}},[n.hubUrl,n.onToast,n.sourceRegistry]),Y=u.useCallback(async()=>{if(C.current)throw new Error("Stop the recording before starting a timelapse.");const X=n.sourceRegistry.resolveCurrentTarget();if(!X)throw new Error("화면이 준비된 후 다시 시도하세요.");const D=await z(X),K=await fM(D.canvas,D.target,a.timelapseIntervalSeconds,n.hubUrl,ce=>n.onToast(ce.message));k.current=D.cleanup,T.current=K,m(Date.now()),n.onToast("Timelapse started")},[z,n.hubUrl,n.onToast,n.sourceRegistry,a.timelapseIntervalSeconds]),O=u.useCallback(async()=>{const X=T.current;if(X){w(!0);try{await X.stop(),n.onToast("Timelapse saved")}finally{T.current=null,k.current?.(),k.current=null,m(0),w(!1)}}},[n.onToast]);return u.useEffect(()=>{const X=D=>{!C.current&&!T.current||(D.preventDefault(),D.returnValue="")};return window.addEventListener("beforeunload",X),()=>window.removeEventListener("beforeunload",X)},[]),u.useEffect(()=>()=>{E.current.stop(),C.current?.cancel(),T.current?.cancel(),N.current?.(),k.current?.()},[]),{state:u.useMemo(()=>({recording:!!C.current,recordingStartedAt:l,timelapse:!!T.current,timelapseStartedAt:d,bufferSeconds:p,bufferEnabled:a.rollingEnabled,busy:g,targetLabel:F}),[p,g,l,a.rollingEnabled,F,d]),settings:a,videoSupported:q,targetKey:$,setRollingEnabled:L,setRecordingQuality:ie,setTimelapseInterval:V,takeScreenshot:ne,startRecording:Q,stopRecording:J,saveLast30Seconds:le,startTimelapse:Y,stopTimelapse:O}}const pM=120,gM=999,Hc=5,$c=30,vM=Number.POSITIVE_INFINITY,ib="livedesk.remoteDirectory",Oh="livedesk.localHubAccessEnabled",rb="livedesk.streamSettings",Bh=16,lb="livedesk.controlStreamSettings",Fh=6,ob="livedesk.wallMonitorSelections",cb=1,ch=512*1024,Ph="".trim(),ub="".trim(),yy="livedesk-adsense-script",uh=!!Ph&&!!ub,xM=1e3/60,dh=1500,yM=650,wM=1800,bM=650,SM=2500,wy=1500,by=15e3,jM=6e4,Sy=240,CM=1024,kM=480,AM=270,jy="LiveDesk clients are updating. Hub will restart after every client reconnects.",fh="LiveDesk is restarting with the latest Hub.";function NM(n,a){if(a.deviceId!==n.deviceId)return!1;const r=Number(a.browserReceivedEpochMs);if(!Number.isFinite(r)||r<n.startedAtEpochMs)return!1;const l=Number(a.monitorIndex);if(Number.isFinite(l)&&Math.floor(l)!==n.monitorIndex)return!1;const c=String(a.frameMode||a.mode||"").trim().toLowerCase();return!c||c===n.frameMode}const yl={free:{name:"Free",price:"$0",limit:Hc,audience:"Personal trial",note:"5 devices with a standard ad banner."},ltd:{name:"Plus",price:"$79 LTD",ltd:"$79 LTD",limit:$c,audience:"Creators and homelabs",note:"30 devices, no ads, personal use."},pro:{name:"Pro",price:"$199 LTD",ltd:"$199 LTD",limit:vM,audience:"Business and studios",note:"Commercial use and larger workstation walls."}},pp={"mode1-jpeg":5,"mode3-h264-hw":30,"mode4-h264-atlas":20};function Ts(n,a){return`${n}:${a}`}const pa={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:pp["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},Ea={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-software",fps:30,maxWidth:1920,maxHeight:1080,quality:75,showScreenStatus:!1};function Gd(n,a){if(n.length===0)return 0;const r=[...n].sort((c,d)=>c-d),l=Math.max(0,Math.min(r.length-1,Math.ceil(r.length*a)-1));return r[l]}function gp(n,a){n.push(a),n.length>Sy&&n.splice(0,n.length-Sy)}function Cy(n,a){n.sampleFrames=0,n.sampleStartedAt=a,n.intervalCount=0,n.intervalSumMs=0,n.minIntervalMs=Number.POSITIVE_INFINITY,n.maxIntervalMs=0,n.intervalSamplesMs.length=0,n.seqGapCount=0,n.maxSeqGap=0}function ky(n,a,r){if(n.lastAt!==void 0){const l=Math.max(0,a-n.lastAt);n.intervalCount+=1,n.intervalSumMs+=l,n.minIntervalMs=Math.min(n.minIntervalMs,l),n.maxIntervalMs=Math.max(n.maxIntervalMs,l),gp(n.intervalSamplesMs,l)}if(n.lastFrameSeq!==void 0){const l=r-n.lastFrameSeq;l!==1&&(n.seqGapCount+=1,n.maxSeqGap=Math.max(n.maxSeqGap,Math.abs(l)))}n.lastAt=a,n.lastFrameSeq=r}function Ay(n){return!n||n.intervalCount<=0?"waiting":`${Math.round(n.averageIntervalMs)}ms avg / p95 ${Math.round(n.p95IntervalMs)}ms / max ${Math.round(n.maxIntervalMs)}ms`}function MM(){const[n,a]=u.useState({framesPerSecond:0,averageIntervalMs:0,p95IntervalMs:0,maxIntervalMs:0,longTaskCount:0,longTaskMs:0});return u.useEffect(()=>{let r=0,l=performance.now(),c=0,d=0,m=[],p=0,v=0,g=null;const w=b=>{document.visibilityState==="visible"?(c+=1,d>0&&gp(m,Math.max(0,b-d)),d=b):d=0,r=window.requestAnimationFrame(w)};try{g=new PerformanceObserver(b=>{for(const j of b.getEntries())p+=1,v+=j.duration}),g.observe({entryTypes:["longtask"]})}catch{g=null}r=window.requestAnimationFrame(w);const y=window.setInterval(()=>{const b=performance.now(),j=Math.max(1,b-l),C=m.reduce((N,T)=>N+T,0);a({framesPerSecond:c*1e3/j,averageIntervalMs:m.length>0?C/m.length:0,p95IntervalMs:Gd(m,.95),maxIntervalMs:m.length>0?Math.max(...m):0,longTaskCount:p,longTaskMs:v}),l=b,c=0,m=[],p=0,v=0},1e3);return()=>{window.cancelAnimationFrame(r),window.clearInterval(y),g?.disconnect()}},[]),n}function Ny(n){return!n||n.seqGapCount<=0?"none":`${n.seqGapCount} gaps / max ${n.maxSeqGap}`}function TM(n){return Number.isFinite(n)?String(n):"30+"}const Vd=[{id:"mode4-h264-atlas",label:"Mode 4",detail:"Hub H.264 Atlas"},{id:"mode3-h264-hw",label:"Mode 3",detail:"H.264 hardware"}],Hh=[{id:"prefer-software",label:"Software low latency"},{id:"prefer-hardware",label:"Hardware decode"},{id:"no-preference",label:"Browser auto"}],EM=[{id:"mode3-h264-hw",label:"Mode 3 - H.264 hardware"}],Yd=[{id:"640x360",label:"Compact",width:640,height:360},{id:"960x540",label:"Standard",width:960,height:540},{id:"1280x720",label:"HD",width:1280,height:720},{id:"1920x1080",label:"Full HD",width:1920,height:1080},{id:"2560x1440",label:"QHD",width:2560,height:1440},{id:"3840x2160",label:"4K",width:3840,height:2160}],mh=Yd.filter(n=>n.width>=1280),hh=[{id:"auto",label:"Auto by wall size"},{id:"320x180",label:"Standard 320x180",width:320,height:180},{id:"480x270",label:"Sharp 480x270",width:480,height:270}],vp=[1,2,5,8,12,20,30],RM=[20,30,60],My=[45,60,75,90],Ty={large:{maxWidth:1280,maxHeight:720},medium:{maxWidth:960,maxHeight:540},small:{maxWidth:640,maxHeight:360}},ta={preserveConfiguredFpsDeviceCount:12,visibleRootMargin:"520px 0px 760px 0px",fallbackVisibleCounts:{large:12,medium:18,small:32},maxWallFramesPerSecond:96,maxWallBytesPerSecond:80*1024*1024,maxFrameGapMs:280,lowLoadFrameRatio:.58,lowLoadByteRatio:.52,downshiftCooldownMs:1800,recoveryCooldownMs:14e3,minFps:5},Ey=2200,DM=8e3,_M=3500,LM=7e3,zM=2,IM=2600,OM=4200,BM=750,FM=2,Ry=4200;function Dy(n,a){return Math.min(3e4,n*2**Math.min(3,Math.max(0,a)))}function Qc(n,a){const r=n.capabilities?.[a];return typeof r=="boolean"?r:/^(1|true|yes|on)$/i.test(String(r||"").trim())}function ha(n){return n.deviceName||n.hostname||n.deviceId}function PM(){return"npx -y --prefer-online livedesk@latest client"}function HM(){return"npx -y --prefer-online livedesk@latest"}function $M(){try{return localStorage.getItem(ib)||""}catch{return""}}function UM(){try{return localStorage.getItem(Oh)==="1"}catch{return!1}}function bo(n){try{n?localStorage.setItem(Oh,"1"):localStorage.removeItem(Oh)}catch{}}function hs(n,a,r,l){const c=Number(n);return Number.isFinite(c)?Math.max(a,Math.min(r,Math.round(c))):l}function $h(n){const a=String(n||"").trim();return Vd.some(r=>r.id===a)?a:pa.frameMode}function rf(n){const a=String(n||"").trim();return Hh.some(r=>r.id===a)?a:pa.h264DecodeAcceleration}function Uh(n){return n==="mode3-h264-hw"?n:Ea.frameMode}function db(n){return pp[n]||12}function fb(n){return n==="mode3-h264-hw"?30:n==="mode4-h264-atlas"?20:30}function qh(n,a){return hs(n,1,fb(a),db(a))}function El(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function ma(n){const a=El(n.status),r=El(a.screens),l=El(n.capabilities),c=[a.monitorCount,a.screenCount,r.count,l.monitorCount,l.screenCount];for(const d of c){const m=Number(d);if(Number.isFinite(m)&&m>0)return Math.max(1,Math.min(64,Math.floor(m)))}return 1}function Fr(n){const a=Number(n);return Number.isFinite(a)&&a>0?Math.floor(a):0}function qM(n){const a=El(n.status),l=[El(a.screens).displays,a.displays,a.monitors];for(const c of l)if(!(!Array.isArray(c)||c.length===0))return c.map(d=>El(d));return[]}function mb(n,a){const r=qM(n),l=r.find(v=>Number(v.index)===a)||r[a]||r[0]||{},c=Fr(l.width),d=Fr(l.height),m=[l.name,l.displayName,l.deviceName,l.id].find(v=>typeof v=="string"&&v.trim()),p=typeof m=="string"?m.trim():`Display ${a+1}`;return{index:a,name:p,width:c,height:d,primary:l.primary===!0||l.isPrimary===!0}}function GM(n){const a=ma(n);return Array.from({length:a},(r,l)=>mb(n,l))}function VM(n){const a=[n.name||`Display ${n.index+1}`];return n.width>0&&n.height>0&&a.push(`${n.width}x${n.height}`),n.primary&&a.push("Primary"),a.join(" - ")}function hb(n,a){const r=mb(n,a);if(r.width>0&&r.height>0)return{width:r.width,height:r.height};const l=El(n.status),c=Fr(l.screenWidth||l.width),d=Fr(l.screenHeight||l.height);return c>0&&d>0?{width:c,height:d}:null}function pb(n){if(!n)return null;const a=Fr(n.sourceWidth)||Fr(n.width),r=Fr(n.sourceHeight)||Fr(n.height);return a>0&&r>0?{width:a,height:r}:null}function YM(n,a,r){const d=((typeof a?.monitorIndex=="number"?Ta(a.monitorIndex,Math.max(1,a.monitorCount||1)):r)===r?pb(a):null)||hb(n,r);return d?Math.max(.25,Math.min(4,d.width/d.height)):16/9}const Od=16/9;function Ta(n,a){const r=Math.max(1,Math.min(64,Math.floor(Number(a)||1))),l=Math.floor(Number(n));return Number.isFinite(l)?Math.max(0,Math.min(r-1,l)):0}function WM(){try{const n=localStorage.getItem(ob);if(!n)return{};const a=JSON.parse(n),r=a&&typeof a=="object"&&!Array.isArray(a)?a.selections:void 0;if(Number(a?.version)!==cb||!r||typeof r!="object"||Array.isArray(r))return{};const l={};for(const[c,d]of Object.entries(r)){const m=c.trim(),p=Math.floor(Number(d));!m||!Number.isFinite(p)||(l[m]=Math.max(0,Math.min(63,p)))}return l}catch{return{}}}function KM(n){try{localStorage.setItem(ob,JSON.stringify({version:cb,selections:n}))}catch{}}function QM(){try{const n=JSON.parse(localStorage.getItem(rb)||"{}"),a=Number(n.version);if(![Bh,15,14,13,12,11].includes(a))return pa;const r=$h(n.frameMode),l=hs(n.maxWidth,320,3840,pa.maxWidth),c=hs(n.maxHeight,180,2160,pa.maxHeight);return{frameMode:r,h264DecodeAcceleration:rf(n.h264DecodeAcceleration),fps:a<Bh&&r==="mode3-h264-hw"?pa.fps:qh(n.fps,r),maxWidth:l,maxHeight:c,atlasTileWidth:Number(n.atlasTileWidth)>=480?480:320,atlasTileHeight:Number(n.atlasTileHeight)>=270?270:180,atlasTileSizeMode:n.atlasTileSizeMode==="fixed"?"fixed":"auto",quality:hs(n.quality,20,95,pa.quality),autoStartLive:typeof n.autoStartLive=="boolean"?n.autoStartLive:pa.autoStartLive,showScreenStatus:typeof n.showScreenStatus=="boolean"?n.showScreenStatus:pa.showScreenStatus,visibleOnlyLive:typeof n.visibleOnlyLive=="boolean"?n.visibleOnlyLive:pa.visibleOnlyLive,adaptiveLoadShedding:typeof n.adaptiveLoadShedding=="boolean"?n.adaptiveLoadShedding:pa.adaptiveLoadShedding,adaptiveSizeByWall:typeof n.adaptiveSizeByWall=="boolean"?n.adaptiveSizeByWall:pa.adaptiveSizeByWall}}catch{return pa}}function XM(n){try{localStorage.setItem(rb,JSON.stringify({...n,version:Bh}))}catch{}}function ZM(){try{const n=JSON.parse(localStorage.getItem(lb)||"{}"),a=Number(n.version);if(![Fh,5,4,3,2,1].includes(a))return Ea;const r=hs(n.fps,20,60,Ea.fps),l=a<Fh;return{frameMode:l?Ea.frameMode:Uh(n.frameMode),h264DecodeAcceleration:l?Ea.h264DecodeAcceleration:rf(n.h264DecodeAcceleration),fps:l?Ea.fps:r,maxWidth:hs(n.maxWidth,1280,3840,Ea.maxWidth),maxHeight:hs(n.maxHeight,720,2160,Ea.maxHeight),quality:hs(n.quality,20,95,Ea.quality),showScreenStatus:typeof n.showScreenStatus=="boolean"?n.showScreenStatus:Ea.showScreenStatus}}catch{return Ea}}function JM(n){try{localStorage.setItem(lb,JSON.stringify({...n,version:Fh}))}catch{}}function ph(n,a){return n.length!==a.length?!1:n.every((r,l)=>r===a[l])}function gh(n){return[...new Set(n.filter(Boolean))].sort()}function eT(n){return ta.fallbackVisibleCounts[n]||ta.fallbackVisibleCounts.large}function tT(n,a,r){if(n.frameMode==="mode4-h264-atlas")return n.atlasTileSizeMode==="auto"?a==="large"?{maxWidth:480,maxHeight:270}:{maxWidth:320,maxHeight:180}:{maxWidth:n.atlasTileWidth,maxHeight:n.atlasTileHeight};if(!n.adaptiveSizeByWall)return{maxWidth:n.maxWidth,maxHeight:n.maxHeight};const l=Ty[a]||Ty.large;return{maxWidth:Math.min(n.maxWidth,l.maxWidth),maxHeight:Math.min(n.maxHeight,l.maxHeight)}}function nT(n,a=ta.minFps){const r=[...vp].sort((c,d)=>c-d),l=Math.max(a,Math.floor(n/2));return[...r].reverse().find(c=>c<n&&c>=a)||l}function aT(n,a){return[...vp].sort((l,c)=>l-c).find(l=>l>n&&l<=a)||a}function Uc(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let r=n,l=0;for(;r>=1024&&l<a.length-1;)r/=1024,l+=1;const c=l===0||r>=100?0:1;return`${r.toFixed(c)} ${a[l]}`}function _y(n){if(!Number.isFinite(n)||!n||n<=0)return"0GB";const a=1024**4,r=1024**3;return n>=a?`${Math.max(1,Math.round(n/a))}TB`:`${Math.max(1,Math.round(n/r))}GB`}function vh(n,a){if(!Number.isFinite(n)||!n||n<=0)return"not reported";const r=Math.max(0,n-Math.max(0,Number(a||0)));return`${_y(r)} / ${_y(n)}`}function sT(n){const a=new Uint8Array(n),r=32768;let l="";for(let c=0;c<a.length;c+=r){const d=a.subarray(c,c+r);l+=String.fromCharCode(...d)}return btoa(l)}function Ly(n){return Array.from(n).filter(a=>a.size>=0).map(a=>{const r=a.webkitRelativePath||a.name;return{file:a,relativePath:r,fingerprint:`${a.size}:${a.lastModified}`}})}function iT(n){return n===1?"middle":n===2?"right":"left"}function zy(n,...a){for(const r of a){const l=n?.[r];if(typeof l=="string"&&l.trim())return l.trim()}return""}function Iy(n){const a=Number(n);return Number.isInteger(a)&&a>=1&&a<=gM?a:0}const rT={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function lT(n,a,r){if(n==="online")return"Online";if(n==="busy")return"Busy";if(n==="stale")return"Stale";if(n==="offline")return"Offline";if(r==="failed")return"Task failed";const l=n==="critical"?"critical":"warn",c=a.find(m=>m.state===l)||a.find(m=>m.state==="critical"||m.state==="warn");if(!c)return n==="critical"?"Issue":"Check";const d=rT[c.id]||c.label;return c.value&&c.value!=="-"?`${d} ${c.value}`:d}function pf(n,a){const r=a.split(".");let l=n;for(const c of r){if(l==null)return;if(Array.isArray(l)){const d=Number(c);l=Number.isInteger(d)?l[d]:void 0;continue}if(typeof l=="object"){l=l[c];continue}return}return l}function tn(n,...a){for(const r of a){const l=pf(n,r),c=Number(l);if(Number.isFinite(c))return c}}function Ra(n,...a){for(const r of a){const l=pf(n,r);if(typeof l=="string"&&l.trim())return l.trim();if(typeof l=="number"&&Number.isFinite(l))return String(l)}return""}function oT(n,...a){for(const r of a){const l=pf(n,r);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 qi(n){const a=Number(n);if(Number.isFinite(a))return Math.max(0,Math.min(1,a>1?a/100:a))}function xh(n,a){if(!(typeof n!="number"||typeof a!="number"||!Number.isFinite(n)||!Number.isFinite(a)||n<=0))return qi((n-Math.max(0,a))/n)}function So(n){return n===void 0?"-":`${Math.round(n*100)}%`}function yh(n){return n===void 0||!Number.isFinite(n)?"":n>=1e3?`${(n/1e3).toFixed(n>=1e4?0:1)}Gb/s`:`${Math.round(n)}Mb/s`}function wl(n,a=.92,r=.78){return n===void 0?"unknown":n>=a?"critical":n>=r?"warn":"good"}function gb(n){return!Number.isFinite(n)||!n||n<=0?"-":n<3600?`${Math.round(n/60)}m`:n<86400?`${Math.round(n/3600)}h`:`${Math.round(n/86400)}d`}function Bd(n,a,r){const l=pf(n,`tools.${a}`),c=Ra(n,`tools.${a}.status`,`tooling.${a}.status`,`${a}.status`).toLowerCase(),d=oT(n,`tools.${a}.running`,`tooling.${a}.running`,`${a}.running`),m=Ra(n,`tools.${a}.version`,`tooling.${a}.version`,`${a}.version`),p=Ra(n,`tools.${a}.port`,`tooling.${a}.port`,`${a}.port`);let v="unknown";return c==="busy"?v="busy":["online","running","ready","active"].includes(c)||d===!0?v="online":(["offline","stopped","missing","not-found"].includes(c)||d===!1||l===!1)&&(v="offline"),{id:a,label:r,status:v,detail:v==="offline"?"offline":m||(p?`:${p}`:v==="unknown"?"not reported":v)}}function vb(n){const a=n.status||{},r=tn(a,"cpu.cores","cpuCores","processorCount"),l=tn(a,"loadavg.0","cpu.load1"),c=qi(tn(a,"cpu.usedRatio","cpu.usageRatio","cpu.ratio","cpu.usedPct","cpu.usagePct","cpu.percent")??(r&&l!==void 0?l/Math.max(1,r):void 0)),d=tn(a,"memory.totalBytes","totalMem"),m=tn(a,"memory.freeBytes","freeMem"),p=qi(tn(a,"memory.usedRatio","memory.usedPct","usedMemRatio"))??xh(d,m),v=tn(a,"disk.totalBytes","rootDisk.totalBytes","storage.totalBytes"),g=tn(a,"disk.freeBytes","rootDisk.freeBytes","storage.freeBytes"),w=qi(tn(a,"disk.usedRatio","disk.usedPct","rootDisk.usedRatio","storage.usedRatio"))??xh(v,g),y=tn(a,"thermal.cpuC","temperatureC","cpu.temperatureC","gpu.temperatureC"),b=qi(tn(a,"gpu.usedRatio","gpu.usageRatio","gpu.usedPct","gpu.usagePct","gpu.percent","accelerators.gpu.usageRatio")),j=Ra(a,"gpu.name","gpu.model","accelerators.gpu.name"),C=tn(a,"gpu.memory.totalBytes","gpu.totalMemoryBytes","gpu.vramTotalBytes"),N=tn(a,"gpu.memory.freeBytes","gpu.freeMemoryBytes","gpu.vramFreeBytes"),T=qi(tn(a,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??xh(C,N),k=tn(a,"gpu.temperatureC","thermal.gpuC"),E=qi(tn(a,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),R=Ra(a,"npu.name","npu.model","accelerators.npu.name"),$=tn(a,"npu.tops","npu.topsInt8","accelerators.npu.tops"),F=tn(a,"network.rxMbps","network.receiveMbps","network.downMbps"),q=tn(a,"network.txMbps","network.transmitMbps","network.upMbps"),z=tn(a,"network.latencyMs","network.rttMs"),L=qi(tn(a,"network.usedRatio","network.usageRatio","network.saturationRatio")),ie=Ra(a,"network.link","network.interface","network.name"),V=y===void 0?void 0:qi((y-35)/60),ne=Ra(a,"workload.role","role","lane")||(Qc(n,"aiAssist")?"Agent worker":Qc(n,"taskDispatch")?"Task worker":"Local machine"),Q=Ra(n.latestTask,"status")||Ra(a,"workload.status")||"idle",J=Ra(n.latestTask,"title","instructionPreview")||Ra(a,"workload.title"),le=Ra(n.latestTask,"resultSummary","error","instructionPreview")||Ra(a,"workload.summary"),Y=[Bd(a,"ollama","Ollama"),Bd(a,"lmStudio","LM Studio"),Bd(a,"comfyui","ComfyUI"),Bd(a,"stableDiffusion","Stable Diffusion")],O=Y.some(W=>W.status!=="unknown"),Z=Date.parse(n.lastSeenAt||n.connectedAt||""),X=Number.isFinite(Z)?Date.now()-Z:0;let D="online";n.connected?X>5*6e4?D="stale":(y??0)>=86||(k??0)>=88||(c??0)>=.94||(b??0)>=.96||(T??0)>=.96||(E??0)>=.96||(p??0)>=.94||(w??0)>=.94||(z??0)>=200||Q==="failed"?D="critical":(y??0)>=78||(k??0)>=80||(c??0)>=.82||(b??0)>=.86||(T??0)>=.88||(E??0)>=.86||(p??0)>=.82||(w??0)>=.86||(z??0)>=80?D="warn":(["queued","running","targeted"].includes(Q)||Y.some(W=>W.status==="busy"))&&(D="busy"):D="offline";const K=Y.filter(W=>W.status==="online"||W.status==="busy").length,ce=[{id:"cpu",label:"CPU",value:So(c),detail:r?`${r} cores`:l!==void 0?`load ${l.toFixed(1)}`:"not reported",ratio:c,state:wl(c,.92,.78)},{id:"memory",label:"RAM",value:So(p),detail:vh(d,m),ratio:p,state:wl(p,.92,.78)},{id:"disk",label:"DISK",value:So(w),detail:vh(v,g),ratio:w,state:wl(w,.92,.82)},{id:"gpu",label:"GPU",value:So(b),detail:j||(C&&N!==void 0?`${Uc(N)} VRAM free`:k!==void 0?`${Math.round(k)}C`:"not reported"),ratio:b,state:k!==void 0&&k>=88?"critical":k!==void 0&&k>=80?"warn":wl(b,.96,.86)},{id:"vram",label:"VRAM",value:So(T),detail:vh(C,N),ratio:T,state:wl(T,.96,.88)},{id:"npu",label:"NPU",value:E!==void 0?So(E):$!==void 0?`${Math.round($)} TOPS`:"-",detail:R||($!==void 0?"neural engine":"not reported"),ratio:E,state:wl(E,.96,.86)},{id:"temp",label:"TEMP",value:y===void 0?"-":`${Math.round(y)}C`,detail:K>0?`${K} local tools`:`uptime ${gb(tn(a,"uptimeSec"))}`,ratio:V,state:y===void 0?"unknown":y>=86?"critical":y>=78?"warn":"good"},{id:"network",label:"NET",value:yh(F)||(z!==void 0?`${Math.round(z)}ms`:ie||"-"),detail:yh(q)?`${yh(q)} up`:ie||"not reported",ratio:L,state:z!==void 0&&z>=200?"critical":z!==void 0&&z>=80?"warn":wl(L,.9,.75)}];return{state:D,label:lT(D,ce,Q),role:ne,taskLabel:J||(Q==="idle"?"idle":Q),taskStatus:Q,taskSummary:le,tools:O?Y:Y.map(W=>({...W,detail:"not reported"})),metrics:ce}}const cT=[{id:"small",label:"Small"},{id:"medium",label:"Medium"},{id:"large",label:"Large"}],uT=[{id:"wall",label:"Wall",icon:Xc,accent:"blue"},{id:"control",label:"Control",icon:Pd,accent:"red"},{id:"share-files",label:"Share Files",icon:Fd,accent:"green"},{id:"agents",label:"Agents",icon:Pc,accent:"violet"},{id:"sync-server",label:"Sync Server",icon:Hd,accent:"blue"}],dT=[{id:"doc",label:"Doc",icon:Wd,accent:"amber"},{id:"support",label:"Support",icon:qc,accent:"violet"},{id:"pricing",label:"Pricing",icon:Co,accent:"green"}];function fT(n){return n.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 nn(n){return fT(n).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 bl(n){return n.map(a=>nn(a))}function Jn(n){return{languageName:n.languageName,languageLabel:n.languageLabel,eyebrow:n.eyebrow,title:nn(n.title),intro:nn(n.intro),sections:[{title:nn(n.managerTitle),body:nn(n.managerBody),points:bl(n.managerPoints)},{title:nn(n.clientTitle),body:nn(n.clientBody),points:bl(n.clientPoints)},{title:nn(n.syncTitle),body:nn(n.syncBody),points:bl(n.syncPoints)},...n.agentTitle&&n.agentBody&&n.agentPoints?[{title:nn(n.agentTitle),body:nn(n.agentBody),points:bl(n.agentPoints)}]:[],{title:nn(n.platformTitle),body:nn(n.platformBody),points:bl(n.platformPoints)}],sync:{title:nn(n.syncTitle),body:nn(n.syncBody),points:bl(n.syncPoints)},firewall:{title:nn(n.firewallTitle),body:nn(n.firewallBody),points:bl(n.firewallPoints)},commands:{title:nn(n.commandsTitle),body:nn(n.commandsBody),manager:nn(n.managerCommandLabel),primary:nn(n.clientCommandLabel),slot:nn(n.slotCommandLabel),manual:nn(n.manualCommandLabel)}}}const Eo={ko:Jn({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은 Mode 3 H.264와 Mode 4 H.264 Atlas를 사용합니다. Mode 2는 Mode 4의 내부 Atlas 입력에만 한정되며 Wall/Control fallback으로 사용되지 않습니다.","원격 오디오는 선택한 장비가 capability를 광고할 때 사용할 수 있으며, 브라우저는 queue·drop·resync·automatic restart 상태를 진단합니다.","macOS: 화면 캡처와 제어에는 Screen Recording/Accessibility 권한이 필요합니다. RemoteFast 로그는 필요한 상태 중심으로 제한됩니다.","Linux: linux-x64 runtime, grim/gnome-screenshot/import/scrot 캡처, xdotool 입력 백엔드가 추가되었습니다. 오디오는 아직 비활성입니다."],firewallTitle:"방화벽과 외부 장소 연결",firewallBody:"같은 LAN 안에서는 보통 공유기 포트포워딩이 필요 없습니다. 다른 장소의 PC를 붙이려면 클라이언트가 매니저의 클라이언트 접속 포트에 도달할 수 있어야 합니다.",firewallPoints:["클라이언트 접속 포트는 TCP 5197입니다.","클라이언트 쪽은 나가는 연결이므로 보통 인바운드 포트 개방이 필요 없습니다.","다른 네트워크에서 붙일 때는 매니저 PC 방화벽에서 TCP 5197 인바운드를 허용하고, 공유기에서는 TCP 5197을 매니저 PC로 전달합니다.","Screen Wall/API 포트 5179는 매니저 UI용입니다. 외부 브라우저에서 Wall을 직접 열 필요가 있을 때만 별도로 노출을 검토합니다.","공개 인터넷에 바로 열기보다 VPN, Tailscale, ZeroTier, 고정 IP allowlist를 우선합니다."],commandsTitle:"현재 사용 명령",commandsBody:"웹사이트를 찾아가 설치 파일을 받는 방식보다 터미널 한 줄로 모든 운영체제에서 거의 같은 흐름을 쓰는 것이 LiveDesk의 기본 방향입니다.",managerCommandLabel:"매니저 시작",clientCommandLabel:"워크스테이션 연결",slotCommandLabel:"3번 슬롯에 고정",manualCommandLabel:"고급 수동 연결"}),en:Jn({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 workstations, 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 workstation",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-workstation tasks with Agent",agentBody:"The Agents page runs a Codex-based Agent in the Hub to inspect connected workstations 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:["Wall uses Mode 3 H.264 and Mode 4 H.264 Atlas. Mode 2 is restricted to internal Mode 4 Atlas input and is never used as a Wall or Control fallback.","Remote audio is available when the selected workstation 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, grim/gnome-screenshot/import/scrot capture, and xdotool input backend. Audio is still disabled."],firewallTitle:"Firewall and remote locations",firewallBody:"On the same LAN, router forwarding is usually unnecessary. For another office, building, or country, clients must be able to reach the manager client port.",firewallPoints:["Client connection port: TCP 5197.","Client machines normally only need outbound access.","For remote networks, allow inbound TCP 5197 on the manager firewall and forward TCP 5197 from the router to the manager PC.","Screen Wall/API port 5179 is for the manager UI. Expose it only if a remote browser must open the Wall directly.","Prefer VPN, Tailscale, ZeroTier, or fixed-IP allowlists over public internet exposure."],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 workstation",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ja:Jn({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. workstation を接続",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、xdotool input backend を追加済み。audio は未対応です。"],firewallTitle:"Firewall と外部拠点",firewallBody:"同じ LAN なら通常 router forwarding は不要です。外部拠点では client が manager の接続ポートへ到達できる必要があります。",firewallPoints:["client 接続ポートは TCP 5197 です。","client 側は通常 outbound だけで足ります。","外部 network では manager PC の firewall で TCP 5197 inbound を許可し、router から manager PC へ forward します。","5179 は manager UI 用なので、外部ブラウザで Wall を開く必要がある時だけ公開を検討します。","公開 internet より VPN、Tailscale、ZeroTier、IP allowlist を優先してください。"],commandsTitle:"現在のコマンド",commandsBody:"Web サイトから installer を探すより、OS をまたいで terminal 1行で動かす方向です。",managerCommandLabel:"manager 起動",clientCommandLabel:"workstation 接続",slotCommandLabel:"slot 3 に固定",manualCommandLabel:"高度な手動接続"}),"zh-CN":Jn({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. 连接 workstation",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 捕获、xdotool 输入后端。音频尚未启用。"],firewallTitle:"防火墙和外部地点",firewallBody:"同一 LAN 通常不需要路由端口转发。不同地点连接时,client 必须能访问 manager 的 client 连接端口。",firewallPoints:["client 连接端口是 TCP 5197。","client 机器通常只需要出站访问。","跨网络时,在 manager 防火墙放行 TCP 5197 入站,并在路由器转发到 manager PC。","5179 是 manager UI 端口,仅在需要远程浏览器直接打开 Wall 时考虑暴露。","优先使用 VPN、Tailscale、ZeroTier 或固定 IP allowlist。"],commandsTitle:"当前命令",commandsBody:"产品方向是跨操作系统使用一条终端命令,而不是先找网站、下载、安装。",managerCommandLabel:"启动 manager",clientCommandLabel:"连接 workstation",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"高级手动连接"}),"zh-TW":Jn({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. 連接 workstation",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、xdotool input backend。音訊尚未啟用。"],firewallTitle:"防火牆與外部地點",firewallBody:"同一 LAN 通常不需要路由器轉發。不同地點連線時,client 必須能到達 manager 的 client 連線埠。",firewallPoints:["client 連線埠是 TCP 5197。","client 電腦通常只需要對外連線。","跨網路時,請在 manager 防火牆允許 TCP 5197 inbound,並從路由器轉發到 manager PC。","5179 是 manager UI 連接埠,只在需要遠端瀏覽器直接打開 Wall 時才考慮公開。","優先使用 VPN、Tailscale、ZeroTier 或固定 IP allowlist。"],commandsTitle:"目前指令",commandsBody:"產品方向是跨作業系統用一行 terminal 指令,而不是先找網站、下載、安裝。",managerCommandLabel:"啟動 manager",clientCommandLabel:"連接 workstation",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"進階手動連線"}),es:Jn({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 workstation",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: agregado linux-x64 runtime, captura grim/gnome-screenshot/import/scrot y entrada xdotool. Audio aún desactivado."],firewallTitle:"Firewall y sedes remotas",firewallBody:"En la misma LAN normalmente no hace falta port forwarding. Para otra red, los clients deben llegar al puerto client del manager.",firewallPoints:["Puerto de conexión client: TCP 5197.","Los equipos client normalmente solo necesitan salida.","Para redes remotas, permite TCP 5197 inbound en el manager y reenvía TCP 5197 al PC manager.","El puerto 5179 es para la UI del manager; expónlo solo si un navegador remoto debe abrir el Wall.","Prefiere VPN, Tailscale, ZeroTier o allowlist de IP fijas."],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 workstation",slotCommandLabel:"Fijar al slot 3",manualCommandLabel:"Conexión manual avanzada"}),fr:Jn({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 workstation",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, capture grim/gnome-screenshot/import/scrot et entrée xdotool ajoutés. Audio désactivé."],firewallTitle:"Firewall et sites distants",firewallBody:"Sur le même LAN, le port forwarding est rarement nécessaire. Depuis un autre réseau, les clients doivent atteindre le port client du manager.",firewallPoints:["Port de connexion client: TCP 5197.","Les machines client ont normalement seulement besoin de sortie réseau.","Pour un réseau distant, autorisez TCP 5197 entrant sur le manager et redirigez TCP 5197 vers le PC manager.","Le port 5179 sert à l’UI manager; exposez-le seulement si un navigateur distant doit ouvrir le Wall.","Préférez VPN, Tailscale, ZeroTier ou allowlist IP fixes."],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 workstation",slotCommandLabel:"Fixer au slot 3",manualCommandLabel:"Connexion manuelle avancée"}),de:Jn({languageName:"Deutsch",languageLabel:"Dokumentsprache",eyebrow:"LiveDesk Manual",title:"Lokale Screen Wall mit einem Befehl öffnen",intro:"LiveDesk ist ein npm-first Arbeitsdeck, um viele Workstations, 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. Workstation 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, grim/gnome-screenshot/import/scrot Capture und xdotool Input Backend sind ergänzt. Audio ist deaktiviert."],firewallTitle:"Firewall und entfernte Standorte",firewallBody:"Im gleichen LAN ist Router-Forwarding meist unnötig. Aus anderen Netzwerken müssen Clients den Client-Port des Managers erreichen.",firewallPoints:["Client-Verbindungsport: TCP 5197.","Client-Rechner brauchen normalerweise nur ausgehenden Zugriff.","Für entfernte Netzwerke TCP 5197 inbound am Manager erlauben und vom Router zum Manager-PC forwarden.","Port 5179 ist für die Manager-UI; nur öffnen, wenn ein Remote-Browser die Wall direkt öffnen muss.","VPN, Tailscale, ZeroTier oder feste IP-Allowlists bevorzugen."],commandsTitle:"Aktuelle Befehle",commandsBody:"Die Produktlinie ist ein Terminalbefehl über Betriebssysteme hinweg, statt Website suchen, herunterladen und installieren.",managerCommandLabel:"Manager starten",clientCommandLabel:"Workstation verbinden",slotCommandLabel:"An Slot 3 fixieren",manualCommandLabel:"Erweiterte manuelle Verbindung"}),"pt-BR":Jn({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 workstation",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 xdotool adicionados. Áudio ainda desativado."],firewallTitle:"Firewall e locais remotos",firewallBody:"Na mesma LAN normalmente não é preciso port forwarding. Em outra rede, clients precisam alcançar a porta client do manager.",firewallPoints:["Porta client: TCP 5197.","Máquinas client normalmente só precisam de saída.","Para redes remotas, permita TCP 5197 inbound no manager e encaminhe TCP 5197 para o PC manager.","A porta 5179 é para a UI do manager; exponha apenas se um navegador remoto precisar abrir o Wall.","Prefira VPN, Tailscale, ZeroTier ou allowlist de IP fixo."],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 workstation",slotCommandLabel:"Fixar no slot 3",manualCommandLabel:"Conexão manual avançada"}),it:Jn({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 workstation, 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 workstation",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 xdotool. Audio disattivato."],firewallTitle:"Firewall e sedi remote",firewallBody:"Nella stessa LAN di solito non serve port forwarding. Da altre reti, i client devono raggiungere la porta client del manager.",firewallPoints:["Porta client: TCP 5197.","I client normalmente richiedono solo uscita.","Per reti remote, abilita TCP 5197 inbound sul manager e inoltra TCP 5197 al PC manager.","La porta 5179 è per la UI manager; esponila solo se un browser remoto deve aprire il Wall.","Preferisci VPN, Tailscale, ZeroTier o IP allowlist."],commandsTitle:"Comandi attuali",commandsBody:"La direzione è un comando terminale comune tra sistemi operativi, invece di download e install manuale.",managerCommandLabel:"Avvia manager",clientCommandLabel:"Connetti workstation",slotCommandLabel:"Fissa allo slot 3",manualCommandLabel:"Connessione manuale avanzata"}),id:Jn({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 workstation, 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 workstation",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 xdotool sudah ditambahkan. Audio belum aktif."],firewallTitle:"Firewall dan lokasi luar",firewallBody:"Di LAN yang sama biasanya tidak perlu port forwarding. Dari jaringan lain, client harus mencapai port client manager.",firewallPoints:["Port client: TCP 5197.","Mesin client biasanya hanya perlu akses keluar.","Untuk jaringan luar, izinkan TCP 5197 inbound di manager dan forward TCP 5197 ke PC manager.","Port 5179 untuk UI manager; buka hanya jika browser luar harus membuka Wall.","Utamakan VPN, Tailscale, ZeroTier, atau IP allowlist."],commandsTitle:"Perintah saat ini",commandsBody:"Arah produk adalah satu perintah terminal lintas OS, bukan download dan instal manual.",managerCommandLabel:"Mulai manager",clientCommandLabel:"Hubungkan workstation",slotCommandLabel:"Kunci ke slot 3",manualCommandLabel:"Koneksi manual lanjutan"}),vi:Jn({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 workstation, 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 workstation",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 xdotool. Audio chưa bật."],firewallTitle:"Firewall và địa điểm ngoài",firewallBody:"Trong cùng LAN thường không cần port forwarding. Từ mạng khác, client phải truy cập được port client của manager.",firewallPoints:["Port client: TCP 5197.","Máy client thường chỉ cần kết nối outbound.","Với mạng ngoài, cho phép TCP 5197 inbound trên manager và forward TCP 5197 tới PC manager.","Port 5179 dành cho UI manager; chỉ mở nếu trình duyệt từ xa cần mở Wall trực tiếp.","Ưu tiên VPN, Tailscale, ZeroTier hoặc allowlist IP cố định."],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 workstation",slotCommandLabel:"Ghim vào slot 3",manualCommandLabel:"Kết nối thủ công nâng cao"}),th:Jn({languageName:"ไทย",languageLabel:"ภาษาของเอกสาร",eyebrow:"LiveDesk Manual",title:"เปิด Screen Wall ภายในด้วยคำสั่งเดียว",intro:"LiveDesk คือ deck แบบ npm-first สำหรับดู workstation, กล่อง 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. เชื่อม workstation",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 และ xdotool input แล้ว audio ยังปิดอยู่"],firewallTitle:"Firewall และเครื่องต่างสถานที่",firewallBody:"ใน LAN เดียวกันปกติไม่ต้อง port forwarding ถ้าอยู่คนละ network client ต้องเข้าถึง client port ของ manager ได้",firewallPoints:["Client port คือ TCP 5197","เครื่อง client ปกติต้องการ outbound เท่านั้น","ถ้าอยู่นอก network ให้เปิด TCP 5197 inbound ที่ manager และ forward TCP 5197 ไปยัง manager PC","Port 5179 เป็น UI ของ manager เปิดเฉพาะเมื่อ browser ระยะไกลต้องเปิด Wall โดยตรง","ควรใช้ VPN, Tailscale, ZeroTier หรือ IP allowlist ก่อนเปิดสู่ public internet"],commandsTitle:"คำสั่งปัจจุบัน",commandsBody:"ทิศทาง product คือคำสั่ง terminal เดียวข้าม OS ไม่ใช่ download/install จากเว็บไซต์",managerCommandLabel:"เริ่ม manager",clientCommandLabel:"เชื่อม workstation",slotCommandLabel:"ตรึง slot 3",manualCommandLabel:"manual connection ขั้นสูง"}),hi:Jn({languageName:"हिन्दी",languageLabel:"दस्तावेज़ भाषा",eyebrow:"LiveDesk Manual",title:"एक कमांड से local Screen Wall खोलें",intro:"LiveDesk एक npm-first remote work deck है जिससे एक manager PC से कई workstation, 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. workstation जोड़ें",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, grim/gnome-screenshot/import/scrot capture और xdotool input backend जोड़े गए हैं। Audio अभी disabled है।"],firewallTitle:"Firewall और remote locations",firewallBody:"Same LAN में आम तौर पर router forwarding जरूरी नहीं। दूसरे network से clients को manager client port तक पहुंचना होगा।",firewallPoints:["Client connection port: TCP 5197.","Client machines को आम तौर पर सिर्फ outbound access चाहिए।","Remote network के लिए manager firewall में TCP 5197 inbound allow करें और router से TCP 5197 manager PC पर forward करें।","5179 manager UI port है; इसे तभी expose करें जब remote browser को Wall खोलना हो।","Public internet से पहले VPN, Tailscale, ZeroTier या fixed IP allowlist बेहतर है।"],commandsTitle:"Current commands",commandsBody:"Product direction है OS के बीच एक terminal command, website से download/install नहीं।",managerCommandLabel:"Start manager",clientCommandLabel:"Connect workstation",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ar:Jn({languageName:"العربية",languageLabel:"لغة المستند",eyebrow:"LiveDesk Manual",title:"افتح Screen Wall محلي بأمر واحد",intro:"LiveDesk هو deck بنمط npm-first لمراقبة عدة workstations وأجهزة 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. وصل workstation",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 وxdotool input. الصوت ما زال معطلا."],firewallTitle:"Firewall والمواقع البعيدة",firewallBody:"داخل نفس LAN غالبا لا تحتاج port forwarding. من شبكة أخرى يجب أن يصل client إلى منفذ manager client.",firewallPoints:["منفذ client: TCP 5197.","أجهزة client تحتاج عادة اتصال outbound فقط.","للشبكات البعيدة، اسمح TCP 5197 inbound على manager ووجه TCP 5197 من router إلى manager PC.","المنفذ 5179 مخصص لواجهة manager؛ اكشفه فقط إذا كان متصفح بعيد يحتاج فتح Wall مباشرة.","يفضل VPN أو Tailscale أو ZeroTier أو fixed IP allowlist بدل التعريض العام."],commandsTitle:"الأوامر الحالية",commandsBody:"اتجاه المنتج هو أمر terminal واحد عبر الأنظمة، وليس تحميل وتثبيت يدوي من موقع.",managerCommandLabel:"Start manager",clientCommandLabel:"Connect workstation",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),tr:Jn({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 workstation, 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. Workstation 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 xdotool input backend eklendi. Audio kapalı."],firewallTitle:"Firewall ve uzak konumlar",firewallBody:"Aynı LAN içinde genelde router forwarding gerekmez. Başka ağdan clients manager client portuna ulaşabilmelidir.",firewallPoints:["Client port: TCP 5197.","Client makineler normalde sadece outbound erişim ister.","Uzak ağ için manager firewall üzerinde TCP 5197 inbound aç ve routerdan TCP 5197yi manager PCye forward et.","5179 manager UI portudur; sadece uzak browser Wall açacaksa expose et.","Public internet yerine VPN, Tailscale, ZeroTier veya sabit IP allowlist tercih 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:"Workstation bağla",slotCommandLabel:"Slot 3’e sabitle",manualCommandLabel:"Gelişmiş manuel bağlantı"})},mT=Object.entries(Eo).map(([n,a])=>({id:n,label:a.languageName}));function hT(){if(typeof navigator>"u")return"en";const n=navigator.languages?.length?navigator.languages:[navigator.language];for(const a of n){const r=a.toLowerCase();if(Eo[a])return a;if(r.startsWith("zh-tw")||r.startsWith("zh-hk"))return"zh-TW";if(r.startsWith("pt"))return"pt-BR";const l=r.split("-")[0];if(Eo[l])return l}return"en"}function Oy({index:n}){const a=n+1;return s.jsx("article",{className:"device-tile placeholder-tile","aria-label":`Empty slot ${a}`,children:s.jsxs("div",{className:"tile-screen","aria-hidden":"true",children:[s.jsx("span",{className:"slot-grid","aria-hidden":"true"}),s.jsxs("span",{className:"empty-screen",children:[s.jsx(Zt,{size:24}),s.jsxs("strong",{children:["Slot ",String(a).padStart(3,"0")]})]})]})})}function pT(n){if(!n)return!1;const a=String(n.platform||"").trim().toLowerCase();return Es(a)&&n.capabilities?.screenRecordingPermission===!1}function Es(n){const a=String(n||"").trim().toLowerCase();return a==="macos"||a==="darwin"||a==="mac"||a==="macosx"}function By(n){if(!n)return!1;const a=String(n.capabilities?.liveCaptureConcurrency||"").trim().toLowerCase();return a==="exclusive"?!0:a==="parallel"?!1:Es(n.platform)}function wh({device:n,frame:a,selected:r,controlEnabled:l,showStatus:c,monitorIndex:d,monitorCount:m,onSelect:p,onFocusDevice:v,onOpenControl:g,onCycleMonitor:w,onCanvasReady:y,sendInput:b,updateIndicator:j,presentationReady:C,showPresentationSpinner:N=!1}){const T=u.useRef(null),k=u.useRef(null),E=u.useRef(0),R=u.useRef(null),$=vb(n),F=["cpu","gpu","memory","vram"].map(P=>$.metrics.find(me=>me.id===P)).filter(P=>!!P),q=Ta(d,m),z=m>1,L=C??!!a,ie=pT(n)&&!L,V=N&&n.connected&&!L&&!ie,ne=YM(n,a,q),Q=ne>=Od?100:ne/Od*100,J=ne>=Od?Od/ne*100:100,le={"--screen-aspect":ne.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,Q)).toFixed(3)}%`,"--screen-content-height":`${Math.max(1,Math.min(100,J)).toFixed(3)}%`},Y=u.useCallback(P=>{T.current=P,y(n.deviceId,P)},[n.deviceId,y]),O=P=>{const me=P.currentTarget.getBoundingClientRect();return p1(P.clientX,P.clientY,me)},Z=P=>({shiftKey:P.shiftKey,ctrlKey:P.ctrlKey,altKey:P.altKey,metaKey:P.metaKey}),X=u.useCallback(()=>{R.current!==null&&(window.cancelAnimationFrame(R.current),R.current=null)},[]),D=u.useCallback(()=>{const P=k.current;if(!P)return;k.current=null;const me=Number(P.input.normalizedX),pe=Number(P.input.normalizedY);if(!Number.isFinite(me)||!Number.isFinite(pe))return;b(n.deviceId,{...P.input,normalizedX:me,normalizedY:pe})&&(E.current=performance.now())},[n.deviceId,b]),K=u.useCallback(()=>{R.current===null&&(R.current=window.requestAnimationFrame(()=>{R.current=null,D()}))},[D]);u.useEffect(()=>()=>{X(),k.current=null},[X]);const ce=(P,me)=>{if(!l)return;const pe={type:me,monitorIndex:q,...O(P),button:iT(P.button),...Z(P)};if(me==="pointermove"){const ve=performance.now();k.current={input:pe},ve-E.current>=xM&&(X(),D()),K();return}k.current&&(X(),D()),b(n.deviceId,pe)},W=u.useCallback(P=>{const me=document.activeElement;me instanceof HTMLElement&&P.contains(me)&&me.classList.contains("monitor-cycle-button")&&me.blur()},[]);return s.jsx("article",{className:`device-tile ${r?"selected":""} ${n.connected?"online":"offline"}`,"data-live-device-id":n.deviceId,style:le,children:s.jsxs("div",{className:`tile-screen ${L?"has-frame":"is-empty"}`,role:"button",tabIndex:l?-1:0,"aria-pressed":r,onClick:P=>{P.target instanceof Element&&P.target.closest(".monitor-cycle")||l||p()},onKeyDown:P=>{P.target instanceof Element&&P.target.closest(".monitor-cycle")||l||(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),p())},onDoubleClick:P=>{P.target instanceof Element&&P.target.closest(".monitor-cycle")||(P.preventDefault(),g())},onPointerLeave:P=>W(P.currentTarget),children:[s.jsx("span",{className:`screen-content ${L?"has-frame":"is-empty"}`,children:s.jsx("canvas",{ref:Y,className:`remote-canvas ${L?"has-frame":"is-empty"}`,tabIndex:l?0:-1,onPointerDown:P=>{l&&(P.preventDefault(),P.stopPropagation(),v(),P.currentTarget.focus(),P.currentTarget.setPointerCapture(P.pointerId),ce(P,"pointerdown"))},onPointerMove:P=>{l&&P.preventDefault(),ce(P,"pointermove")},onPointerLeave:P=>{l&&(ce(P,"pointermove"),X(),D())},onPointerUp:P=>{l&&(P.preventDefault(),P.stopPropagation(),ce(P,"pointerup"),P.currentTarget.hasPointerCapture(P.pointerId)&&P.currentTarget.releasePointerCapture(P.pointerId))},onPointerCancel:P=>{P.currentTarget.hasPointerCapture(P.pointerId)&&P.currentTarget.releasePointerCapture(P.pointerId)},onWheel:P=>{l&&(P.preventDefault(),b(n.deviceId,{type:"wheel",monitorIndex:q,...O(P),deltaX:P.deltaX,deltaY:P.deltaY,...Z(P)}))},onKeyDown:P=>{l&&(P.preventDefault(),P.stopPropagation(),b(n.deviceId,{type:"keydown",monitorIndex:q,key:P.key,code:P.code,keyCode:P.keyCode||P.which||0,location:P.location,text:P.key.length===1?P.key:"",repeat:P.repeat,...Z(P)}))},onKeyUp:P=>{l&&(P.preventDefault(),P.stopPropagation(),b(n.deviceId,{type:"keyup",monitorIndex:q,key:P.key,code:P.code,keyCode:P.keyCode||P.which||0,location:P.location,text:P.key.length===1?P.key:"",repeat:!1,...Z(P)}))},onContextMenu:P=>l&&P.preventDefault()})}),!L&&s.jsx("span",{className:"empty-screen",children:s.jsx(Zt,{size:26})}),V&&s.jsxs("span",{className:"wall-presentation-loading",role:"status","aria-live":"polite",children:[s.jsx("span",{className:"wall-presentation-spinner","aria-hidden":"true"}),s.jsx("strong",{children:"Preparing video"})]}),ie&&s.jsxs("span",{className:"wall-presentation-loading permission-required",role:"status","aria-live":"polite",children:[s.jsx(zt,{size:24,"aria-hidden":"true"}),s.jsx("strong",{children:"Screen Recording permission required"}),s.jsx("small",{children:"Allow the terminal app on this Mac, then restart LiveDesk."})]}),j&&s.jsxs("span",{className:`wall-update-status ${j==="updated"?"updated":""}`,role:"status","aria-live":"polite",children:[j==="updating"?s.jsx("span",{className:"wall-update-spinner","aria-hidden":"true"}):s.jsx(Ln,{size:20,"aria-hidden":"true"}),s.jsx("strong",{children:j==="updating"?"Updating...":"Updated"})]}),c&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`tile-health-pill state-${$.state}`,children:$.label}),s.jsx("span",{className:"tile-metrics","aria-label":`${ha(n)} status`,children:F.map(P=>s.jsxs("span",{className:`tile-metric state-${P.state}`,children:[s.jsx("b",{children:P.label}),s.jsx("em",{children:P.value}),P.ratio!==void 0&&s.jsx("i",{style:{width:`${Math.round(P.ratio*100)}%`}})]},P.id))})]}),z&&s.jsxs("span",{className:"monitor-cycle","aria-label":`${ha(n)} display ${q+1} of ${m}`,onPointerDown:P=>P.stopPropagation(),onClick:P=>P.stopPropagation(),onDoubleClick:P=>P.stopPropagation(),children:[s.jsx("button",{className:"monitor-cycle-button previous",onClick:P=>{P.preventDefault(),P.stopPropagation(),w(-1),P.currentTarget.blur()},title:"Previous display",type:"button",children:s.jsx(Qy,{size:18})}),s.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",q+1,"/",m]}),s.jsx("button",{className:"monitor-cycle-button next",onClick:P=>{P.preventDefault(),P.stopPropagation(),w(1),P.currentTarget.blur()},title:"Next display",type:"button",children:s.jsx(Kh,{size:18})})]}),r&&s.jsx("span",{className:"device-selection-check","aria-hidden":"true",children:s.jsx(Pr,{size:23,strokeWidth:3.5})})]})})}function gT({visible:n}){return u.useEffect(()=>{if(!n||!uh)return;if(!document.getElementById(yy)){const r=document.createElement("script");r.id=yy,r.async=!0,r.crossOrigin="anonymous",r.src=`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${encodeURIComponent(Ph)}`,document.head.appendChild(r)}const a=window.setTimeout(()=>{try{window.adsbygoogle=window.adsbygoogle||[],window.adsbygoogle.push({})}catch{}},120);return()=>window.clearTimeout(a)},[n]),n?s.jsxs("aside",{className:`free-ad-banner ${uh?"adsense-ready":"house-ad"}`,"aria-label":"Advertisement",children:[s.jsx("span",{className:"ad-label",children:"Advertisement"}),uh?s.jsx("ins",{className:"adsbygoogle livedesk-ad-unit",style:{display:"block"},"data-ad-client":Ph,"data-ad-slot":ub,"data-ad-format":"auto","data-full-width-responsive":"true"}):s.jsxs("div",{className:"house-ad-copy",children:[s.jsx("strong",{children:"Sponsored placement"}),s.jsx("span",{children:"Local AI gear, mini PCs, GPUs, NAS, and developer tools."})]})]}):null}function vT(){const n=MM(),{session:a,loading:r}=Yj(),{target:l,error:c,refresh:d}=Kj(a),m=u.useMemo(()=>{if(!l?.active)return null;const x=l.expires_at?Date.parse(l.expires_at):Number.POSITIVE_INFINITY;return Number.isFinite(x)&&x<=Date.now()?null:l},[l]),p=u.useMemo(()=>gx(m),[m]),v=u.useMemo(()=>p.length>0?[...new Set([...p,hn])]:[hn],[p]),[g,w]=u.useState(UM),y=u.useMemo(()=>v.some(x=>!!Yc(x)),[v]),b=!y||g,{status:j,devices:C,error:N,refresh:T,hubBaseUrl:k}=Wj(v,b),{entitlement:E,licensed:R,loading:$,error:F,refresh:q}=Qj(a),[z,L]=u.useState([]),[ie,V]=u.useState(""),[ne,Q]=u.useState(""),[J,le]=u.useState(""),[Y,O]=u.useState(""),[Z,X]=u.useState(""),[D,K]=u.useState("idle"),[ce,W]=u.useState(!1),[P,me]=u.useState(null),[pe,ve]=u.useState(""),ke=u.useRef("");ke.current=Y;const[_e,Le]=u.useState(!1),[ue,Ve]=u.useState(!1),Ye=u.useRef(""),oe=u.useRef(new Map),Ne=u.useRef(0),[je,Ee]=u.useState(""),[Re,Fe]=u.useState(""),[he,Ae]=u.useState(!1),[de,ye]=u.useState(null);u.useEffect(()=>{je==="auth"&&a?.access_token&&Ee("")},[je,a?.access_token]);const[qe,tt]=u.useState(""),[pn,Ke]=u.useState(null),ht=u.useRef(null),St=u.useRef(0),An=u.useCallback((x,A,_)=>{const U=String(x||"").trim();if(tt(U),ht.current!==null&&(window.clearTimeout(ht.current),ht.current=null),!U){Ke(null);return}const I=++St.current;if(Ke({id:I,message:U,tone:A}),!_)return;const ge=window.setTimeout(()=>{Ke(we=>we?.id===I?null:we),ht.current===ge&&(ht.current=null)},5e3);ht.current=ge},[]),Oe=u.useCallback((x,A="info")=>{An(x,A,!0)},[An]),It=u.useCallback(x=>{An(x,"progress",!1)},[An]);u.useEffect(()=>()=>{ht.current!==null&&window.clearTimeout(ht.current)},[]);const[Ut,pt]=u.useState(()=>typeof window<"u"&&window.location.pathname.startsWith("/support")?"support":"wall");u.useEffect(()=>{const x=()=>{pt(window.location.pathname.startsWith("/support")?"support":A=>A==="support"?"wall":A)};return window.addEventListener("popstate",x),()=>window.removeEventListener("popstate",x)},[]);const[st,Jt]=u.useState("large"),[Nt,De]=u.useState(hT),[Nn,Vi]=u.useState(!1),[un,Bn]=u.useState(!1),[ga,Ka]=u.useState(!1),[Mn,Qa]=u.useState($M),[Ie,ri]=u.useState(QM),[ut,Xa]=u.useState(ZM),[qt,zs]=u.useState(WM),[B,He]=u.useState(null),[dt,en]=u.useState([]),[sn,Is]=u.useState(Ie.fps),[na,te]=u.useState(""),[Me,Pe]=u.useState(0),[at,Wt]=u.useState(0),[Mt,Qe]=u.useState(()=>new Set),rt=u.useRef(new Map),Kt=u.useRef(new Map),Pt=u.useRef(new Map),Rt=u.useRef(new Map),Ot=u.useRef(new Map),Ht=u.useRef(new Set),Dt=u.useRef(new Map),Tn=u.useRef(""),Za=u.useRef(""),rn=u.useRef(null),Qt=u.useRef(null),gs=u.useRef(new Map),vs=u.useRef(null),li=u.useRef(0),zo=u.useRef(new Map),[Yi,Rl]=u.useState({}),La=u.useRef(new Map),[Yn,su]=u.useState({}),[iu,Wn]=u.useState(!1),Dl=u.useRef(null),aa=u.useRef(null),za=u.useRef(0),gn=u.useRef(""),oi=u.useRef(new Map),Wi=u.useRef(new Map),Ki=u.useRef(performance.now()),Ja=u.useRef(new Map),ci=u.useRef(new Map),ui=u.useRef(new Map),Os=u.useRef(new Map),Gr=u.useRef(0),Vr=u.useRef(0),Yr=u.useRef(0),Qi=u.useRef(0),Io=u.useRef(0),ru=u.useRef(new Map),Ia=u.useRef(new Map),[Fn,es]=u.useState(null),[Oo,Bs]=u.useState(!1),[Wr,lu]=u.useState([]),[Fs,ou]=u.useState("all"),[ts,Oa]=u.useState([]),[cu,_l]=u.useState(!1),[di,Bo]=u.useState(!0),Kr=u.useRef(null),Fo=u.useRef(null),Ll=u.useRef(null),zl=u.useRef(null),uu=u.useRef(!1),En=u.useRef(!1),xs=u.useRef(!1),Ps=u.useRef(0),va=u.useRef(0),Il=Ut==="settings",Ol=Ut==="pricing",Bl=Ut==="doc",Xi=Ut==="support",Hs=Ut==="share-files",Fl=Ut==="agents",du=!Il&&!Ol&&!Bl&&!Xi&&!Hs&&!Fl,et=Ut==="control",gt=Ie.frameMode==="mode4-h264-atlas",Kn=Z||ut.frameMode,Po=Kn!=="mode3-h264-hw"?Math.min(30,ut.fps):ut.fps,$s=Kn!=="mode3-h264-hw"?{maxWidth:Math.min(1920,ut.maxWidth),maxHeight:Math.min(1080,ut.maxHeight)}:{maxWidth:ut.maxWidth,maxHeight:ut.maxHeight};u.useEffect(()=>{if(j?.started){if(!a?.access_token){$e("/api/remote/license",{method:"DELETE"},k).catch(()=>{});return}$e("/api/remote/license/sync",{method:"POST",headers:{Authorization:`Bearer ${a.access_token}`}},k).catch(x=>{console.warn("[LiveDesk] Hub license sync failed",x)})}},[E?.updated_at,k,a?.access_token,j?.started]),u.useEffect(()=>{!a?.access_token||!j?.started||j.runtimeRole!=="hub"||!j.deviceId||(async()=>{try{const{data:x,error:A}=await ot.rpc("register_livedesk_device",{p_device_id:j.deviceId,p_device_name:j.deviceName||j.deviceId,p_role:"hub",p_assigned_hub_id:null,p_platform:navigator.platform||navigator.userAgent,p_os_version:navigator.userAgent,p_app_version:j.managerVersion||j.managerPackage||""}),_=Array.isArray(x)?x[0]:x;(A||_?.ok===!1)&&console.warn("[LiveDesk] Hub device role registration failed",A||_?.reason||"unknown-error")}catch(x){console.warn("[LiveDesk] Hub device role registration failed",x)}})()},[a?.access_token,j?.deviceId,j?.deviceName,j?.managerPackage,j?.managerVersion,j?.runtimeRole,j?.started]),u.useEffect(()=>{!a?.access_token||!a.refresh_token||!j?.started||j.runtimeRole!=="hub"||xs.current||(xs.current=!0,$e("/api/auth/session",{method:"POST",body:JSON.stringify({accessToken:a.access_token,refreshToken:a.refresh_token,expiresAt:a.expires_at,user:{id:a.user.id,email:a.user.email}})},k||hn).then(x=>{x.hostTarget?.ok===!1&&console.warn("[LiveDesk] Hub host target publish is waiting for a valid Hub role:",x.hostTarget.error||"unknown-error"),T()}).catch(x=>{console.warn("[LiveDesk] Hub session sync failed:",x)}).finally(()=>{xs.current=!1}))},[k,T,a?.access_token,a?.expires_at,a?.refresh_token,a?.user?.email,a?.user?.id,j?.runtimeRole,j?.started]);const Je=u.useMemo(()=>C.filter(x=>x.connected),[C]),fu=Fs==="all"?Je.length:ts.filter(x=>Je.some(A=>A.deviceId===x)).length,gf=u.useMemo(()=>Je.reduce((x,A)=>Math.max(x,Iy(A.slotNumber)),0),[Je]),Qr=Math.max(pM,Je.length,gf),Xr=u.useMemo(()=>{const x=Array(Qr).fill(null),A=[];for(const _ of Je){const U=Iy(_.slotNumber);U>0&&U<=Qr&&!x[U-1]?x[U-1]=_:A.push(_)}for(const _ of A){const U=x.findIndex(I=>!I);U<0?x.push(_):x[U]=_}return x},[Je]),Ho=u.useMemo(()=>Je.map(x=>x.deviceId),[Je]),Zi=u.useMemo(()=>new Set(z),[z]),Ba=u.useMemo(()=>Je.filter(x=>Zi.has(x.deviceId)),[Je,Zi]),Us=u.useMemo(()=>C.find(x=>x.deviceId===ie)||Ba[0]||null,[C,ie,Ba]),Pn=u.useMemo(()=>C.find(x=>x.deviceId===ne)||null,[ne,C]),qs=Pn?Ta(qt[Pn.deviceId],ma(Pn)):0,Te=et?Pn:Us,$o=u.useMemo(()=>new Set(ts),[ts]),vf=u.useMemo(()=>Fs==="all"?Je.map(x=>x.deviceId):Je.filter(x=>$o.has(x.deviceId)).map(x=>x.deviceId),[Je,$o,Fs]),ns=u.useMemo(()=>Te?vb(Te):null,[Te]),xf=Te?Qc(Te,"control"):!1,Uo=Es(Te?.platform)&&(Te?.capabilities?.controlPermission===!1||Te?.capabilities?.accessibilityPermission===!1),Zr=Te?Qc(Te,"audio")||Qc(Te,"remoteAudio"):!1,mu=Array.isArray(Te?.capabilities?.agentTools)?Te.capabilities.agentTools.map(String):[],Pl=mu.includes("system.power"),hu=mu.includes("command.run"),$t=R?E?.plan==="pro"?"pro":"ltd":"free",Hl=yl[$t],Gs=Hl.limit,fi=u.useMemo(()=>{if(!Number.isFinite(Gs))return new Set(Je.map(A=>A.deviceId));const x=Te?[Te,...Je.filter(A=>A.deviceId!==Te.deviceId)]:Je;return new Set(x.slice(0,Gs).map(A=>A.deviceId))},[Gs,Je,Te]),pu=!Te||fi.has(Te.deviceId),gu=$t==="free",Gt=pu,mi=$t==="ltd"?`Plus includes up to ${$c} workstations. Upgrade to Pro for commercial use and larger walls.`:`Free includes up to ${Hc} workstations. Upgrade to Plus for ${$c} devices and no ads.`,vu=$t==="free",hi=Gt&&!!Te,ys=Gt&&!!Te&&xf,xu=Gt&&!!Te&&Zr;u.useEffect(()=>{Ae(!1)},[Ut,Te?.deviceId]);const $l=u.useMemo(()=>Xr.filter(x=>!!x?.connected).slice(0,eT(st)).map(x=>x.deviceId),[Xr,st]),Jr=u.useMemo(()=>gt?Ho:Ie.visibleOnlyLive?dt.length>0?dt:$l:Ho,[$l,gt,dt,Ie.visibleOnlyLive,Ho]),Fa=u.useMemo(()=>gh(Jr.filter(x=>fi.has(x))),[fi,Jr]),sa=u.useMemo(()=>Fa.filter(x=>x!==na),[Fa,na]),as=u.useMemo(()=>new Map(Je.map(x=>[x.deviceId,x.platform])),[Je]),ss=u.useMemo(()=>gt?sa.filter(x=>!Es(as.get(x))):[],[gt,as,sa]),Hn=u.useMemo(()=>gt?sa.filter(x=>Es(as.get(x))):sa,[gt,as,sa]);u.useEffect(()=>{const x=new Set(Fa);Qe(A=>{let _=!1;const U=new Set;for(const I of A)x.has(I)?U.add(I):_=!0;return _?U:A})},[Fa]);const yu=u.useMemo(()=>{const x=I=>Je.find(ge=>ge.deviceId===I)||null,A=I=>Ta(qt[I],x(I)?ma(x(I)):0),_=(I,ge=A(I))=>I===J&&(D==="connecting"||D==="active"||D==="warm")?Rt.current.get(I)||Kt.current.get(I)||null:gt?gs.current.get(I)||rt.current.get(I)||null:rt.current.get(I)||null,U=(I,ge=A(I))=>{const we=x(I);return`${we?ha(we):I} · Monitor ${ge+1}`};return{resolveCurrentTarget(){if(et&&Pn){const Xe=qs;return{type:"control",deviceIds:[Pn.deviceId],monitorIndex:Xe,label:`${ha(Pn)} · Monitor ${Xe+1}`,sourceCanvas:_(Pn.deviceId,Xe),signature:`control:${Pn.deviceId}:${Xe}:${ut.frameMode}`}}const I=Ba.map(Xe=>Xe.deviceId).filter(Xe=>sa.includes(Xe)),ge=Us&&sa.includes(Us.deviceId)?Us.deviceId:"",we=I.length>0?I:ge?[ge]:sa,ze=I.length===0&&!ge;if(we.length===0)return null;if(we.length===1){const Xe=we[0],mt=A(Xe);return{type:ze?"wall":I.length>1?"selection":"device",deviceIds:we,monitorIndex:mt,label:ze?"Wall":U(Xe,mt),sourceCanvas:ze?null:_(Xe,mt),signature:`${ze?"wall":"device"}:${Xe}:${mt}:${gt?"atlas":"direct"}`}}return{type:I.length>1?"selection":"wall",deviceIds:we,label:I.length>1?`${we.length} selected workstations`:"Wall",sourceCanvas:null,signature:`${I.length>1?"selection":"wall"}:${we.join(",")}:${st}`}},getDeviceCanvas:_,composeWall(I,ge={}){return aM(I.map(we=>{const ze=A(we);return{deviceId:we,label:U(we,ze),canvas:_(we,ze)}}),ge)}}},[Je,Pn,J,D,ut.frameMode,rt,gt,qt,qs,Ba,et,sa,Us,st]),qo=hM({hubUrl:k,sourceRegistry:yu,onToast:Oe}),Vs=u.useMemo(()=>Gt&&J&&fi.has(J)&&(D==="connecting"||D==="active"||D==="warm")?[J]:[],[J,D,Gt,fi]),Go=u.useMemo(()=>gh([...Fa,...Vs]),[Vs,Fa]),Qn=u.useMemo(()=>tT(Ie,st),[Ie,st]),pi=gt?Math.max(pp["mode3-h264-hw"],sn):sn,is=u.useCallback((x,A)=>{if(x.width<=0||x.height<=0)return!1;(A.width!==x.width||A.height!==x.height)&&(A.width=x.width,A.height=x.height);const _=A.getContext("2d",{alpha:!1});return _?(_.imageSmoothingEnabled=!0,_.imageSmoothingQuality="high",_.drawImage(x,0,0,x.width,x.height,0,0,A.width,A.height),!0):!1},[]),Ji=u.useCallback(x=>{x&&Qe(A=>{if(A.has(x))return A;const _=new Set(A);return _.add(x),_})},[]),Ul=u.useCallback(x=>{x&&Qe(A=>{if(!A.has(x))return A;const _=new Set(A);return _.delete(x),_})},[]),ql=u.useCallback((x,A)=>{if(!A||A.width<=0||A.height<=0)return!1;const _=document.createElement("canvas");return _.width=A.width,_.height=A.height,is(A,_)?(Pt.current.set(x,_),Ji(x),!0):!1},[Ji,is]),ws=u.useCallback((x,A=!1)=>{if(!Ht.current.has(x))return!1;const _=performance.now(),U=Dt.current.get(x)||0;if(!A&&_-U<150)return!1;const I=Rt.current.get(x)||Kt.current.get(x),ge=rt.current.get(x)||gs.current.get(x);return!I||!ge||!is(I,ge)?!1:(Dt.current.set(x,_),Ji(x),!0)},[Ji,is]);u.useEffect(()=>{Tn.current=na},[na]);const wu=u.useCallback((x,A)=>{const _=rt.current.get(x);if(_&&_!==A&&(ql(x,_),Oc(_)),A){rt.current.set(x,A),Pt.current.delete(x),ws(x,!0);return}rt.current.delete(x),Pt.current.has(x)||Ul(x)},[Ul,ws,ql]),ia=u.useCallback((x,A)=>{const _=Kt.current.get(x);if(_&&_!==A&&Oc(_),A){Kt.current.set(x,A);const U=Rt.current.get(x)||Pt.current.get(x)||rt.current.get(x)||gs.current.get(x);U&&is(U,A)&&x===ne&&Wn(!0);return}Kt.current.delete(x)},[ne,is]),Ys=u.useCallback((x,A,_)=>{const U=performance.now(),I=Ts(x,_.deviceId);let ge=_;if(x==="control"&&_.visualChanged){const ze=n1(_.deviceId),Xe=ru.current.get(_.deviceId)||0,mt=ze?U-ze.sentAt:Number.POSITIVE_INFINITY;ze&&ze.inputSeq>Xe&&mt<=wy&&(ge={..._,inputFeedbackSeq:ze.inputSeq,inputFeedbackMs:Math.max(0,mt),inputFeedbackAt:U},ru.current.set(_.deviceId,ze.inputSeq))}Wi.current.set(I,U);const we=zo.current.get(I)||{totalFrames:0,totalChangedFrames:0,sampleFrames:0,sampleChangedFrames:0,sampleStartedAt:U,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleDecoderInputBase:0,sampleDecoderOutputBase:0};x==="control"&&ge.inputFeedbackMs===void 0&&we.lastInfo?.inputFeedbackMs!==void 0&&we.lastInfo.inputFeedbackAt!==void 0&&U-we.lastInfo.inputFeedbackAt<=wy&&(ge={...ge,inputFeedbackSeq:we.lastInfo.inputFeedbackSeq,inputFeedbackMs:we.lastInfo.inputFeedbackMs,inputFeedbackAt:we.lastInfo.inputFeedbackAt}),we.totalFrames+=1,we.sampleFrames+=1,ky(we,U,ge.frameSeq),ge.visualChanged&&(we.totalChangedFrames+=1,we.sampleChangedFrames+=1),we.lastInfo=ge,zo.current.set(I,we)},[]),el=u.useCallback((x,A)=>{Ys("wall",x,A),x.kind==="live"&&Ji(x.deviceId);const _=ce&&J===x.deviceId;Tn.current!==x.deviceId&&!_&&(Ht.current.delete(x.deviceId),Dt.current.delete(x.deviceId))},[J,ce,Ji,Ys]),Vo=u.useCallback((x,A)=>{Ys("control",x,A),ve(ge=>ge&&"");const _=Rt.current.get(x.deviceId),U=Kt.current.get(x.deviceId);_&&_.width>0&&_.height>0&&(U&&is(_,U),Ot.current.set(x.deviceId,{...x,payload:new Uint8Array(0),byteLength:0}),Pt.current.delete(x.deviceId),Ht.current.add(x.deviceId),x.deviceId===J&&(W(!0),K(ge=>ge==="connecting"?"active":ge)),ws(x.deviceId));const I=Dl.current;!I||!NM(I,x)||Wn(!0)},[J,is,ws,Ys]);u.useEffect(()=>{const x=window.setInterval(()=>{const A=performance.now(),_={};for(const[U,I]of zo.current.entries()){const ge=Math.max(1,A-I.sampleStartedAt);_[U]={totalFrames:I.totalFrames,totalChangedFrames:I.totalChangedFrames,framesPerSecond:I.sampleFrames*1e3/ge,changedFramesPerSecond:I.sampleChangedFrames*1e3/ge,averageIntervalMs:I.intervalCount>0?I.intervalSumMs/I.intervalCount:0,minIntervalMs:Number.isFinite(I.minIntervalMs)?I.minIntervalMs:0,maxIntervalMs:I.maxIntervalMs,p95IntervalMs:Gd(I.intervalSamplesMs,.95),intervalCount:I.intervalCount,seqGapCount:I.seqGapCount,maxSeqGap:I.maxSeqGap,decoderInputFps:Math.max(0,(Number(I.lastInfo?.decoderInputCount||0)-I.sampleDecoderInputBase)*1e3/ge),decoderOutputFps:Math.max(0,(Number(I.lastInfo?.decoderOutputCount||0)-I.sampleDecoderOutputBase)*1e3/ge),sampleMs:ge,lastInfo:I.lastInfo},I.sampleDecoderInputBase=Number(I.lastInfo?.decoderInputCount||0),I.sampleDecoderOutputBase=Number(I.lastInfo?.decoderOutputCount||0),I.sampleChangedFrames=0,Cy(I,A)}Rl(_)},1e3);return()=>window.clearInterval(x)},[]);const gi=u.useCallback((x,A)=>{const _=performance.now(),U=Ts(x,A.deviceId);oi.current.set(U,_),Ia.current.delete(U),x==="control"&&ci.current.delete(U);const I=La.current.get(U)||{totalFrames:0,sampleFrames:0,sampleStartedAt:_,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(I.totalFrames+=1,I.sampleFrames+=1,I.sampleBytes+=Math.max(0,Number(A.byteLength||0)),String(A.frameMode||A.mode||A.codec||A.mimeType||"").toLowerCase().includes("h264")){I.sampleH264Frames+=1,Number(A.byteLength||0)<=CM&&(I.sampleTinyFrames+=1);const Xe=String(A.contentHash||"");Xe&&I.lastContentHash===Xe&&(I.sampleRepeatedFrames+=1),I.lastContentHash=Xe}const ze=Number(A.agentSendGapMs||0);ze>0&&ze<1e3&&gp(I.sourceSendIntervalsMs,ze),I.lastFrame=A,ky(I,_,A.frameSeq),La.current.set(U,I)},[]);u.useEffect(()=>{const x=window.setInterval(()=>{const A=performance.now(),_={};for(const[U,I]of La.current.entries()){const ge=Math.max(1,A-I.sampleStartedAt);_[U]={totalFrames:I.totalFrames,framesPerSecond:I.sampleFrames*1e3/ge,averageIntervalMs:I.intervalCount>0?I.intervalSumMs/I.intervalCount:0,minIntervalMs:Number.isFinite(I.minIntervalMs)?I.minIntervalMs:0,maxIntervalMs:I.maxIntervalMs,p95IntervalMs:Gd(I.intervalSamplesMs,.95),intervalCount:I.intervalCount,seqGapCount:I.seqGapCount,maxSeqGap:I.maxSeqGap,averageFrameBytes:I.sampleFrames>0?I.sampleBytes/I.sampleFrames:0,tinyFrameRatio:I.sampleH264Frames>0?I.sampleTinyFrames/I.sampleH264Frames:0,repeatedFrameRatio:I.sampleH264Frames>0?I.sampleRepeatedFrames/I.sampleH264Frames:0,sourceSendAverageMs:I.sourceSendIntervalsMs.length>0?I.sourceSendIntervalsMs.reduce((we,ze)=>we+ze,0)/I.sourceSendIntervalsMs.length:0,sourceSendP95Ms:Gd(I.sourceSendIntervalsMs,.95),sourceSendSampleCount:I.sourceSendIntervalsMs.length,sampleMs:ge,lastFrame:I.lastFrame},I.sampleBytes=0,I.sampleH264Frames=0,I.sampleTinyFrames=0,I.sampleRepeatedFrames=0,I.sourceSendIntervalsMs.length=0,Cy(I,A)}su(_)},1e3);return()=>window.clearInterval(x)},[]);const Yo=u.useCallback(x=>{gi("wall",x);const A=rt.current.get(x.deviceId);if(!A)return;const _=Es(as.get(x.deviceId));Xm(A,x,()=>rt.current.get(x.deviceId)!==A,el,_?"prefer-software":Ie.h264DecodeAcceleration,_?"interactive":"smooth").catch(()=>{})},[el,as,gi,Ie.h264DecodeAcceleration]),Gl=u.useCallback(x=>{gi("control",x);let A=Rt.current.get(x.deviceId);A||(A=document.createElement("canvas"),A.setAttribute("aria-hidden","true"),Rt.current.set(x.deviceId,A));const _=A,U=ke.current;Xm(_,x,()=>Rt.current.get(x.deviceId)!==_,Vo,ut.h264DecodeAcceleration,"interactive").catch(I=>{ke.current!==U||Rt.current.get(x.deviceId)!==_||J!==x.deviceId||ve(I instanceof Error?I.message:String(I||"Control H.264 decode failed"))})},[J,ut.h264DecodeAcceleration,Vo,gi]),yf=u.useCallback(x=>{const A=Qt.current;A&&A!==x&&Oc(A),Qt.current=x,Gr.current=0,Vr.current=0,Yr.current=0,Qi.current=0,Io.current=0,li.current=0},[]),Pa=u.useCallback(()=>{const x=Qt.current,A=vs.current;if(!(!x||!A||x.width<=0||x.height<=0||li.current!==A.layoutVersion))for(const _ of A.tiles){const U=gs.current.get(_.deviceId);if(!U||_.width<=0||_.height<=0)continue;const I=Math.max(1,Math.round(_.width)),ge=Math.max(1,Math.round(_.height)),we=kM,ze=AM;(U.width!==we||U.height!==ze)&&(U.width=we,U.height=ze);const Xe=U.getContext("2d",{alpha:!1});if(Xe){Xe.imageSmoothingEnabled=!0,Xe.imageSmoothingQuality="high";try{Xe.drawImage(x,Math.round(_.x),Math.round(_.y),I,ge,0,0,we,ze)}catch{}}}},[]),Wo=u.useCallback((x,A)=>{if(A){gs.current.set(x,A),Pt.current.delete(x),window.requestAnimationFrame(Pa),window.requestAnimationFrame(()=>ws(x,!0));return}const _=gs.current.get(x);ql(x,_),gs.current.delete(x),Pt.current.has(x)||Ul(x)},[Ul,Pa,ws,ql]),er=u.useCallback((x,A)=>{Yr.current=performance.now(),li.current=Number(x.layoutVersion||0),Pa();const _=vs.current?.tiles||[],U=_.length>0?Math.round(x.byteLength/_.length):x.byteLength;for(const I of _){const ge={...x,deviceId:I.deviceId,width:I.width,height:I.height,sourceWidth:I.width,sourceHeight:I.height,byteLength:U};el(ge,{...A,deviceId:I.deviceId,width:I.width,height:I.height,byteLength:U}),Tn.current===I.deviceId&&ws(I.deviceId,!0)}},[el,Pa,ws]),Ko=u.useCallback(x=>{const A=performance.now();Gr.current<=0&&(Gr.current=A),Vr.current=A;const _=Qt.current;if(!_)return;const U=vs.current?.tiles||[],I=U.length>0?Math.round(x.byteLength/U.length):x.byteLength;for(const ge of U)gi("wall",{...x,deviceId:ge.deviceId,width:ge.width,height:ge.height,sourceWidth:ge.width,sourceHeight:ge.height,byteLength:I});Xm(_,x,()=>Qt.current!==_,er).catch(()=>{})},[er,gi]),bu=u.useMemo(()=>({fps:pi,maxWidth:Qn.maxWidth,maxHeight:Qn.maxHeight,quality:Ie.quality,mode:gt?"mode3-h264-hw":Ie.frameMode,frameMode:gt?"mode3-h264-hw":Ie.frameMode,streamPurpose:"wall",monitorSelections:qt,onFrame:Yo}),[pi,Yo,Qn,gt,qt,Ie]),Ws=u.useCallback(x=>{if(x.deviceId!==J||x.streamPurpose!=="control"||x.monitorIndex!==qs)return;const A=Je.find(_=>_.deviceId===x.deviceId);!A?.sessionId||A.sessionId!==x.sessionId||(me(x),K(_=>_==="connecting"?"active":_))},[Je,J,qs]);u.useEffect(()=>{me(null)},[J,Y,Kn,qs]);const tr=u.useMemo(()=>({fps:Po,maxWidth:$s.maxWidth,maxHeight:$s.maxHeight,quality:ut.quality,mode:Kn,frameMode:Kn,streamPurpose:"control",forceRestart:Y!=="",forceRestartToken:Y,restartReason:Y?"control-session-start":"",monitorSelections:qt,onFrame:Gl,onStreamReady:Ws}),[Y,ut.quality,Gl,Po,Kn,$s.maxHeight,$s.maxWidth,Ws,qt]),{frames:Vl,state:nr,error:Ks,stats:bs,restartLive:tl}=Tx(Hn,Ie.autoStartLive&&Hn.length>0,k,bu),{frame:vi,layout:xi,state:Qo,stats:wf,refreshInputs:Xo}=a1(ss,gt&&Ie.autoStartLive&&ss.length>0,k,{fps:20,width:1920,height:1080,tileWidth:Qn.maxWidth,tileHeight:Qn.maxHeight,captureDeviceIds:ss,monitorSelections:qt,onFrame:Ko});u.useEffect(()=>{vs.current=xi,xi&&window.requestAnimationFrame(Pa)},[xi,Pa]),u.useEffect(()=>{if(!gt||Qo!=="open"){Gr.current=0,Vr.current=0,Yr.current=0;return}const x=window.setInterval(()=>{const A=Qt.current,_=performance.now();if(!A||document.visibilityState!=="visible"||_-Ki.current<dh)return;const U=Vr.current,I=Gr.current;if(U<=0||I<=0||_-U>500)return;const ge=Yr.current||I,we=_-ge;if(we>=wM&&_-Io.current>=SM){Km(A)&&(Io.current=_,Qi.current=_);return}we>=yM&&_-Qi.current>=bM&&Pj(A)&&(Qi.current=_)},250);return()=>window.clearInterval(x)},[Qo,gt]);const{frames:Yl,state:nl,error:$n,stats:Wl,restartLive:Un,reconnectLive:yi}=Tx(Vs,Vs.length>0,k,tr),ar=u.useMemo(()=>{const x=new Map(Vl);if(gt&&vi&&ss.length>0){const A=new Map((xi?.tiles||[]).map(U=>[U.deviceId,U])),_=Math.max(1,A.size);for(const U of ss){const I=A.get(U);I&&x.set(U,{...vi,deviceId:U,width:I.width,height:I.height,sourceWidth:I.width,sourceHeight:I.height,byteLength:Math.round(vi.byteLength/_)})}}for(const[A,_]of Yl.entries())x.set(A,_);for(const A of Jr){if(!Ht.current.has(A)||x.has(A))continue;const _=Ot.current.get(A);_&&x.set(A,_)}return x},[vi,xi,Yl,ss,gt,Vl,Jr,at]),sr=et&&Vs.length>0?nl:ss.length>0?Qo:nr,ir=et&&Vs.length>0?Wl:ss.length>0?wf:bs;u.useCallback((x,A="browser-stale")=>{const _=tl(x,A),U=Un(x,A);return _||U},[Un,tl]),u.useEffect(()=>{gt&&ss.length>0&&!et&&Xo()},[ss.length,gt,Xo,et]);const rr=u.useCallback((x,A,_)=>{const U=A==="control"?Rt.current.get(x)||null:rt.current.get(x)||null;if(!U||!Km(U))return!1;const I=performance.now();return Os.current.set(Ts(A,x),I),!0},[]),rs=u.useCallback(x=>{if(Kn!=="mode3-h264-hw"||!J||Z)return!1;const A=Je.find(ze=>ze.deviceId===J)||Pn,_=String(A?.platform||"").toLowerCase();if(!["win32","windows","win32nt"].includes(_))return!1;const U="mode5-lzo-delta",I=Ts("control",J),ge=performance.now();ui.current.set(I,ge),oi.current.delete(I),Wi.current.delete(I),Ja.current.delete(I),ci.current.delete(I),Ia.current.delete(I),Km(Rt.current.get(J)||null),yi([J],"control-decode-fallback"),X(U),O(`control-${U}-fallback-${J}-${Date.now()}`),W(!1),Wn(!1);const we=x==="no first frame"||x==="control-first-frame-timeout";return ve(ze=>ze||(we?`Control frame transport timeout; retrying Control with Mode 5 (${x})`:`H.264 decode failed; retrying Control with Mode 5 (${x})`)),K("connecting"),!0},[Je,Pn,J,Z,Kn,yi]);u.useEffect(()=>{const x=et?Pn:null;if(x){Dl.current={deviceId:x.deviceId,monitorIndex:qs,frameMode:Kn,startedAtEpochMs:Date.now()},Wn(J===x.deviceId&&ce||Mt.has(x.deviceId));return}Dl.current=null,Wn(!1)},[Pn?.sessionId,ne,J,ce,Kn,qs,et,Mt]);const al=u.useCallback(async x=>{const A=C.find(we=>we.deviceId===x),_=gt&&!Es(A?.platform),U=Ta(qt[x],A?ma(A):1),I=_?{fps:8,maxWidth:Qn.maxWidth,maxHeight:Qn.maxHeight,quality:60,mode:"mode2-lzo",frameMode:"mode2-lzo",streamPurpose:"atlas",monitorIndex:U}:{fps:gt&&Es(A?.platform)?pi:sn,maxWidth:Qn.maxWidth,maxHeight:Qn.maxHeight,quality:Ie.quality,mode:gt?"mode3-h264-hw":Ie.frameMode,frameMode:gt?"mode3-h264-hw":Ie.frameMode,streamPurpose:"wall",monitorIndex:U},ge=await $e(`/api/remote/devices/${encodeURIComponent(x)}/live/start`,{method:"POST",body:JSON.stringify(I)},k);if(ge?.ok===!1)throw new Error(ge.error||"wall-stream-start-failed");return ge},[sn,C,pi,Qn.maxHeight,Qn.maxWidth,k,gt,qt,Ie.frameMode,Ie.quality]),wi=u.useCallback(async x=>{const A=C.find(I=>I.deviceId===x),_=gt&&!Es(A?.platform),U=await $e(`/api/remote/devices/${encodeURIComponent(x)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:_?"atlas":"wall",reason:"control-active"})},k);if(U?.ok===!1)throw new Error(U.error||"wall-stream-stop-failed");return U},[C,k,gt]),Ha=u.useCallback(async(x,A="control-session-stop")=>{const _=await $e(`/api/remote/devices/${encodeURIComponent(x)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"control",reason:A})},k);if(_?.ok===!1)throw new Error(_.error||"control-stream-stop-failed");return _},[k]),lr=u.useCallback(x=>{const A=Rt.current.get(x);A&&(Oc(A),Rt.current.delete(x));const _=Kt.current.get(x);_&&Oc(_),Ot.current.delete(x),Ht.current.delete(x),Dt.current.delete(x)},[]);u.useEffect(()=>{const x=ne&&Je.find(I=>I.deviceId===ne)||null;if(!et||!Gt||!x){gn.current&&(++za.current,gn.current="");return}if(J===x.deviceId&&(D==="active"||D==="warm"||D==="connecting")){K(I=>I==="warm"?"active":I);return}if(gn.current===x.deviceId)return;const A=++za.current,_=J;gn.current=x.deviceId,(async()=>{if(_){if(K("stopping"),await Ha(_,"control-session-switch").catch(()=>{}),A!==za.current)return;lr(_)}if(A!==za.current)return;if(By(x)){try{await wi(x.deviceId)}catch(we){A===za.current&&(gn.current="",K("error"),Oe(we instanceof Error?we.message:String(we)));return}if(A!==za.current){await al(x.deviceId).catch(()=>{});return}Tn.current=x.deviceId,te(x.deviceId),Ht.current.add(x.deviceId)}const I=Ts("control",x.deviceId),ge=`control-session-${A}-${x.deviceId}`;ui.current.set(I,performance.now()),oi.current.delete(I),Wi.current.delete(I),Ia.current.delete(I),ci.current.delete(I),X(""),ve(""),O(ge),le(x.deviceId),W(!1),K("connecting"),za.current===A&&gn.current===x.deviceId&&(gn.current="")})()},[Je,ne,J,D,Gt,lr,et,al,Ha,wi]),u.useEffect(()=>{if(!J||Je.some(_=>_.deviceId===J))return;const x=J,A=++za.current;K("stopping"),Ha(x,"control-device-disconnected").catch(()=>{}).finally(()=>{A===za.current&&(lr(x),W(!1),O(""),X(""),ve(""),le(_=>_===x?"":_),K("idle"))})},[Je,J,lr,Ha]);const Xn=By(Je.find(x=>x.deviceId===J));u.useEffect(()=>{if(aa.current!==null&&(window.clearTimeout(aa.current),aa.current=null),!J||D==="idle"||D==="stopping"||D==="error"||et||Ut==="wall"){J&&!et&&Ut==="wall"&&K(_=>_==="warm"||_==="active"?"active":_);return}K(_=>_==="idle"||_==="stopping"?_:"warm");const x=J,A=++za.current;return aa.current=window.setTimeout(()=>{aa.current=null,K("stopping"),Ha(x,"control-session-warm-timeout").catch(()=>{}).finally(()=>{A===za.current&&(lr(x),W(!1),O(""),X(""),ve(""),le(_=>_===x?"":_),K("idle"))})},jM),()=>{aa.current!==null&&(window.clearTimeout(aa.current),aa.current=null)}},[Ut,J,D,lr,et,Ha]),u.useEffect(()=>()=>{aa.current!==null&&window.clearTimeout(aa.current)},[]),u.useEffect(()=>{const A=J&&(Xn&&(D==="connecting"||D==="active"||D==="warm"||D==="stopping")||ce&&(D==="active"||D==="warm"))?J:"";if(Za.current=A,rn.current)return;const _=async()=>{for(;;){const I=Za.current,ge=Tn.current;if(ge===I)return;if(ge){try{await al(ge)}catch(we){Oe(we instanceof Error?we.message:String(we))}finally{Tn.current===ge&&(Tn.current="",te(""))}continue}if(!I)return;try{await wi(I)}catch(we){Za.current=Tn.current,Oe(we instanceof Error?we.message:String(we));return}Tn.current=I,te(I),Ht.current.add(I)}};let U;U=_().finally(()=>{rn.current===U&&(rn.current=null),Tn.current!==Za.current&&Pe(I=>I+1)}),rn.current=U},[J,ce,D,Xn,gt,Oe,al,wi,Me]);const Ss=J&&Je.find(x=>x.deviceId===J)||null,xa=!!(et&&_e&&D==="active"&&Ss?.sessionId&&P?.deviceId===Ss.deviceId&&P.sessionId===Ss.sessionId&&P.streamPurpose==="control"&&P.commandId&&P.captureGeneration>0&&P.monitorIndex===qs),{state:sl,sendInput:il,stats:Rn,error:Kl}=s1(ys&&xa,k),or=u.useCallback((x,A)=>!xa||!Ss||!P||x!==Ss.deviceId?!1:il(x,{...A,controlSessionId:Ss.sessionId,controlCommandId:P.commandId,captureGeneration:P.captureGeneration}),[xa,Ss,P,il]),bi=xa&&sl==="open",{state:Su,lastFrame:ra,stats:ln,error:Si}=m1(Te?.deviceId||"",xu&&ue,k),cr=u.useRef(new Map);u.useEffect(()=>{const x=[["hub",N],["registry",c],["license",F],["wall-stream",Ks],["control-stream",$n],["control-decode",pe],["remote-input",Kl],["remote-audio",Si]];for(const[A,_]of x){const U=String(_||"").trim();if(!U){cr.current.delete(A);continue}cr.current.get(A)!==U&&(cr.current.set(A,U),Oe(U))}},[Si,pe,$n,N,Kl,F,c,Oe,Ks]),u.useEffect(()=>{if(!et||!_e||!ys||!bi||!Te)return;const x=(U,I)=>{const ge=U.target,we=ge?.tagName?.toLowerCase();ge?.isContentEditable||we==="input"||we==="textarea"||we==="select"||(U.preventDefault(),U.stopPropagation(),or(Te.deviceId,{type:I,monitorIndex:Ta(qt[Te.deviceId],ma(Te)),key:U.key,code:U.code,keyCode:U.keyCode||U.which||0,location:U.location,text:U.key.length===1?U.key:"",repeat:I==="keydown"?U.repeat:!1,shiftKey:U.shiftKey,ctrlKey:U.ctrlKey,altKey:U.altKey,metaKey:U.metaKey}))},A=U=>x(U,"keydown"),_=U=>x(U,"keyup");return window.addEventListener("keydown",A),window.addEventListener("keyup",_),()=>{window.removeEventListener("keydown",A),window.removeEventListener("keyup",_)}},[ys,bi,_e,qt,Te,or,et]),u.useEffect(()=>{const x=()=>{document.visibilityState==="visible"&&(Ki.current=performance.now())};return document.addEventListener("visibilitychange",x),window.addEventListener("pageshow",x),()=>{document.removeEventListener("visibilitychange",x),window.removeEventListener("pageshow",x)}},[]),u.useEffect(()=>{if(!J||D!=="connecting"&&D!=="active"&&D!=="warm"||nl!=="open")return;const x=J,A=Ts("control",x),_=window.setInterval(()=>{const U=performance.now();if(document.visibilityState!=="visible"||U-Ki.current<dh)return;const I=oi.current.get(A)||0,ge=Wi.current.get(A)||0,we=Ja.current.get(A)||0,ze=ui.current.get(A)||U;ui.current.has(A)||ui.current.set(A,ze);const Xe=I<=0,mt=Xe?U-ze>DM:U-I>Ey,it=I>0&&(ge<=0||U-ge>Ey);if(!mt&&it){const fl=Os.current.get(A)||0;U-fl>=Ry&&rr(x,"control","decoder-paint-stale");return}if(!mt)return;const yn=ci.current.get(A)||0;if(yn>0){if(U-yn<LM)return;ci.current.delete(A)}const da=Ia.current.get(A)||0;if(da>=zM){if(rs(Xe?"no first frame":"stale stream"))return;W(!1),Wn(!1),K("error");return}if(U-we<Dy(_M,da))return;Un([x],Xe?"control-first-frame-timeout":"control-receive-stale")&&(Ja.current.set(A,U),ci.current.set(A,U),ui.current.set(A,U),Ia.current.set(A,da+1))},650);return()=>window.clearInterval(_)},[nl,J,D,rs,rr,Un]),u.useEffect(()=>{!pe||Kn!=="mode3-h264-hw"||rs(pe)||(W(!1),Wn(!1),K("error"))},[pe,Kn,rs]),u.useEffect(()=>{!et||!J||!$n||K(x=>x==="error"?x:"error")},[$n,J,et]),u.useEffect(()=>{if(nr!=="open"||!Ie.autoStartLive||Hn.length===0)return;const x=window.setInterval(()=>{const A=performance.now();if(document.visibilityState!=="visible"||A-Ki.current<dh)return;const _=1e3/Math.max(1,pi||Ie.fps||1),U=Math.max(IM,Math.ceil(_*4)),I=[];for(const ge of Hn){if(I.length>=FM)break;const we=Ts("wall",ge),ze=oi.current.get(we)||0;if(ze<=0)continue;const Xe=Ja.current.get(we)||0,mt=Wi.current.get(we)||0,it=A-ze>U,yn=mt<=0||A-mt>U;if(!it&&yn){const dl=Os.current.get(we)||0;A-dl>=Ry&&rr(ge,"wall","decoder-paint-stale");continue}if(!it)continue;const da=Ia.current.get(we)||0;A-Xe>=Dy(OM,da)&&I.push(ge)}if(I.length>0&&tl(I,"wall-frame-stale"))for(const ge of I){const we=Ts("wall",ge);Ja.current.set(we,A),Ia.current.set(we,(Ia.current.get(we)||0)+1)}},BM);return()=>window.clearInterval(x)},[pi,Hn,rr,tl,Ie.autoStartLive,Ie.fps,nr]),u.useEffect(()=>{Is(Ie.fps),Ps.current=Date.now(),va.current=0},[Ie.fps,Ie.frameMode,Ie.adaptiveLoadShedding]),u.useEffect(()=>{Dj({h264DecodeAcceleration:Ie.h264DecodeAcceleration})},[Ie.h264DecodeAcceleration]),u.useEffect(()=>{if(!Gt||et||!Ie.visibleOnlyLive){en([]);return}const x=Kr.current;if(!x||typeof IntersectionObserver>"u"){en($l);return}const A=Array.from(x.querySelectorAll("[data-live-device-id]"));if(A.length===0){en([]);return}const _=new Map,U=()=>{const ge=gh(A.map(we=>String(we.dataset.liveDeviceId||"")).filter(we=>(_.get(we)||0)>0));en(we=>ph(we,ge)?we:ge)},I=new IntersectionObserver(ge=>{for(const we of ge){const ze=String(we.target.dataset.liveDeviceId||"");ze&&_.set(ze,we.isIntersecting?we.intersectionRatio||.01:0)}U()},{root:null,rootMargin:ta.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return A.forEach(ge=>I.observe(ge)),U(),()=>I.disconnect()},[$l,Gt,et,Xr,Ie.visibleOnlyLive,st]),u.useEffect(()=>{if(!Ie.adaptiveLoadShedding||!Ie.autoStartLive||Hn.length===0)return;const x=Ie.fps;if(Hn.length<=ta.preserveConfiguredFpsDeviceCount){sn!==x&&(Is(x),Ps.current=Date.now(),va.current=0);return}if(nr!=="open"||bs.sampleMs<500)return;const A=Date.now(),_=Hn.length*sn,U=bs.framesPerSecond,I=bs.bytesPerSecond,ge=Math.max(0,...Hn.map(it=>Yn[Ts("wall",it)]?.maxIntervalMs||0)),we=Math.max(0,...Hn.map(it=>Yi[Ts("wall",it)]?.maxIntervalMs||0)),ze=_>8&&U>0&&U<_*.72;if(U>ta.maxWallFramesPerSecond||I>ta.maxWallBytesPerSecond||ge>ta.maxFrameGapMs||we>ta.maxFrameGapMs||ze){va.current=0;const it=ta.minFps;if(A-Ps.current>=ta.downshiftCooldownMs&&sn>it){const yn=Math.max(it,nT(sn,it));yn<sn&&(Is(yn),Ps.current=A)}return}const mt=U<ta.maxWallFramesPerSecond*ta.lowLoadFrameRatio&&I<ta.maxWallBytesPerSecond*ta.lowLoadByteRatio;if(!mt||sn>=x){mt||(va.current=0);return}if(!va.current){va.current=A;return}if(A-va.current>=ta.recoveryCooldownMs){const it=Math.min(x,aT(sn,x));it>sn&&(Is(it),Ps.current=A,va.current=0)}},[sn,Hn.length,Hn,Yi,Yn,nr,bs.bytesPerSecond,bs.framesPerSecond,bs.lastUpdatedAt,bs.sampleMs,Ie.adaptiveLoadShedding,Ie.autoStartLive,Ie.frameMode,Ie.fps]),u.useEffect(()=>{const x=new URLSearchParams(window.location.search).get("checkout");if(x==="success"){Oe("Checkout returned. Waiting for Dodo confirmation."),q();const A=window.setInterval(()=>{q()},4e3),_=window.setTimeout(()=>{window.clearInterval(A)},45e3);return()=>{window.clearInterval(A),window.clearTimeout(_)}}x==="cancelled"&&Oe("Checkout cancelled.")},[q]),u.useEffect(()=>{!Gt&&_e&&Le(!1),!Gt&&ue&&Ve(!1)},[ue,_e,Gt]),u.useEffect(()=>{const x=Te?.deviceId||"",A=Ye.current;if(Ye.current=x,!A||A===x)return;const _=++Ne.current,U=x?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";x&&ue&&oe.current.set(x,U);let I=!0;return(async()=>{try{const we=oe.current.get(A);if(oe.current.delete(A),await $e(`/api/remote/devices/${encodeURIComponent(A)}/audio/stop`,{method:"POST",body:JSON.stringify(we?{streamId:we}:{})},k),!I||_!==Ne.current||!ue||!x||!Gt||!Zr)return;const ze=await $e(`/api/remote/devices/${encodeURIComponent(x)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:U,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},k);if(ze.ok===!1)throw new Error(ze.error||"Remote audio start failed.")}catch(we){I&&(oe.current.delete(x),Ve(!1),Oe(we instanceof Error?we.message:String(we)))}})(),()=>{I=!1}},[ue,Gt,k,Zr,Te?.deviceId]),u.useEffect(()=>{const x=Je.map(U=>U.deviceId),A=new Set(x),_=new Map(Je.map(U=>[U.deviceId,U]));L(U=>{const I=U.filter(ge=>A.has(ge));return ph(U,I)?U:I}),V(U=>U&&A.has(U)?U:""),Q(U=>U&&A.has(U)?U:""),zs(U=>{let I=!1;const ge={};for(const[we,ze]of Object.entries(U)){const Xe=_.get(we);if(!Xe){ge[we]=ze;continue}const mt=Ta(ze,Xe?ma(Xe):1);ge[we]=mt,mt!==ze&&(I=!0)}return I?ge:U}),Oa(U=>{const I=U.filter(ge=>A.has(ge));return ph(U,I)?U:I})},[Je,Qr]),u.useEffect(()=>{lu([]),Bo(!1)},[ws]),u.useEffect(()=>{!Hs||Fs!=="selected"||ts.length>0||Ba.length===0||Oa(Ba.map(x=>x.deviceId))},[Ba,ts.length,Fs,Hs]),u.useEffect(()=>{try{localStorage.setItem(ib,Mn)}catch{}},[Mn]),u.useEffect(()=>{XM(Ie)},[Ie]),u.useEffect(()=>{JM(ut)},[ut]),u.useEffect(()=>{KM(qt)},[qt]);const ji=u.useCallback(async()=>{const x=new Set(v);x.add(hn);try{const ge=await $e("/api/remote/status",void 0,hn);gx({endpoint:ge.agentEndpoint,endpoint_candidates:[...ge.agentEndpointCandidates||[],...ge.hostTargetEndpointCandidates||[]]}).forEach(we=>x.add(we))}catch{}const A=[...x].sort((ge,we)=>{const ze=Xe=>{const mt=Yc(Xe);return mt==="local"?0:mt==="loopback"?1:2};return ze(ge)-ze(we)||ge.localeCompare(we)});let _=!1,U="",I=!1;try{for(const ge of A){const we=Yc(ge);try{if(await $e("/api/health",void 0,ge),we==="local")return w(!0),bo(!0),ge;we==="loopback"&&(_=!0,U=ge)}catch{we==="local"&&(I=!0)}}return _?(I&&Oe("LiveDesk Hub is reachable on this PC, but not through the LAN address yet. Restart LiveDesk Hub to bind 5179 on the network."),w(!0),bo(!0),U||hn):(w(!1),bo(!1),"")}catch{return w(!1),bo(!1),""}},[v]),Dn=async()=>{if(Ee("auth"),Bn(!1),await ji(),window.liveDesk?.auth?.signInWithGoogle){const _=await window.liveDesk.auth.signInWithGoogle();_?.ok===!1&&(Oe(_.error||"LiveDesk could not open the system browser for Google sign-in."),Ee(""));return}const{data:x,error:A}=await ot.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}/callback`}});A&&(Oe(A.message),Ee(""))},ya=async()=>{Ee("auth"),Bn(!1),await ot.auth.signOut(),(await window.liveDesk?.auth?.persistSession?.(null))?.runtimeCleared===!1?Oe("Signed out locally. The LiveDesk runtime could not be reached to clear its session."):window.liveDesk?.auth?.persistSession||await $e("/api/auth/session",{method:"DELETE"},hn).catch(()=>{}),Ee("")};u.useEffect(()=>{if(!un)return;const x=_=>{_.target instanceof Element&&(_.target.closest(".account-popover, .rail-account")||Bn(!1))},A=_=>{_.key==="Escape"&&Bn(!1)};return window.addEventListener("pointerdown",x),window.addEventListener("keydown",A),()=>{window.removeEventListener("pointerdown",x),window.removeEventListener("keydown",A)}},[un]);const js=u.useCallback(async(x={})=>{const A=x.silent===!0,_=x.takeover===!0,U=x.requestLocalAccess===!0;if(!a?.user){A||Oe("Sign in before publishing this host.","error");return}if(!En.current){En.current=!0,A||(Ee("host"),It("Sync Server · 1/4 · Checking the local Hub…"));try{const ge=(U?await ji():"")||k||hn;if(!(j||await $e("/api/remote/status",void 0,ge)).started)throw new Error("Start LiveDesk on this computer before syncing the server.");A||It("Sync Server · 2/4 · Sending the signed-in session to the Hub…");const ze=await $e("/api/auth/session",{method:"POST",body:JSON.stringify({accessToken:a.access_token,refreshToken:a.refresh_token,expiresAt:a.expires_at,user:{id:a.user.id,email:a.user.email}})},ge);if(!ze.ok||!ze.authenticated)throw new Error(ze.error||"hub-session-sync-failed");A||It("Sync Server · 3/4 · Claiming the Hub role and publishing its endpoint…");const Xe=await $e("/api/hub/sync",{method:"POST",body:JSON.stringify({takeover:_})},ge);if(!Xe.ok)throw new Error(Xe.error||"host-target-failed");if(!A){It("Sync Server · 4/4 · Verifying the endpoint and lease renewal…");const mt=await $e("/api/hub/status",void 0,ge);if(!mt.hostTargetActive)throw new Error(mt.hostTargetLease?.lastError||"host-target-not-active-after-sync");const it=mt.hostTargetEndpoint||mt.agentEndpoint||"endpoint ready",yn=Number(mt.connectedDeviceCount||0),da=yn>0?`${yn} client${yn===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";Oe(`Sync Server ready · ${it} · lease auto-renewal active. ${da}`,"success"),(U||y)&&(w(!0),bo(!0)),T()}d()}catch(I){if(!A){const ge=I instanceof Error?I.message:String(I);ge.includes("local network access")&&(w(!1),bo(!1)),Oe(`Sync Server failed · ${ge}`,"error")}}finally{En.current=!1,A||Ee("")}}},[k,y,T,d,ji,a,Oe,It,j]),ls=u.useCallback(async()=>{if(!(!j?.update?.canApply||je==="update")){Ee("update");try{const x=await $e("/api/update/apply",{method:"POST",body:JSON.stringify({})},k||hn);if(!x.ok)throw new Error(x.error||"LiveDesk update could not be started.");const A=[...new Set((x.targets||[]).map(_=>String(_.deviceId||"").trim()).filter(Boolean))];A.length>0&&He({operationId:String(x.operationId||`wall-update-${Date.now()}`),targetIds:A,stage:x.state==="clients-updated"?"updated":"updating",requiresHubRestart:!!(x.managerUpdateAvailable||x.clientPackageUpdateAvailable),initialHostInstanceId:String(j.hostInstanceId||"")}),Oe(x.state==="hub-restart-requested"?fh:jy),T()}catch(x){Oe(x instanceof Error?x.message:String(x))}finally{Ee("")}}},[je,k,T,j]);u.useEffect(()=>{const x=B,A=j?.update;if(!x||x.stage==="updated"||!A)return;if(A.state==="failed"){He(I=>I?.operationId===x.operationId?null:I);return}if(A.operationId===x.operationId){!x.requiresHubRestart&&A.state==="clients-updated"&&He(I=>I?.operationId===x.operationId?{...I,stage:"updated"}:I);return}if(!x.requiresHubRestart)return;const _=j.started===!0&&(!x.initialHostInstanceId||j.hostInstanceId&&j.hostInstanceId!==x.initialHostInstanceId),U=A.state==="idle"&&A.updateAvailable===!1;_&&U&&He(I=>I?.operationId===x.operationId?{...I,stage:"updated"}:I)},[j,B]),u.useEffect(()=>{if(!B||B.stage!=="updated")return;const x=B.operationId,A=window.setTimeout(()=>{He(_=>_?.operationId===x?null:_)},8e3);return()=>window.clearTimeout(A)},[B]),u.useEffect(()=>{if(qe!==jy&&qe!==fh)return;const x=j?.update,A=String(x?.state||"");if(A==="failed"){Oe(x?.error||"LiveDesk update failed.");return}(A==="clients-updated"||A==="idle"&&x?.updateAvailable===!1||!j&&N&&qe===fh)&&Oe("")},[N,qe,j,j?.update?.error,j?.update?.state,j?.update?.updateAvailable]);const os=u.useCallback(async()=>{if(!je){Ee("pin");try{const A=await $e("/api/remote/pairing-pin",{method:"POST"},k||hn);if(!A.ok)throw new Error(A.error||"pin-rotation-failed");await T(),Oe("New PIN published.")}catch(x){Oe(x instanceof Error?x.message:String(x))}finally{Ee("")}}},[je,k,T]),$a=u.useCallback(x=>{x&&(V(x),L(A=>A.includes(x)?A:[...A,x]))},[]),Zo=u.useCallback(x=>{if(!x)return;const A=Zi.has(x);V(_=>A&&_===x?"":x),L(_=>A?_.filter(U=>U!==x):_.includes(x)?_:[..._,x])},[Zi]),Ci=u.useCallback(()=>{L([]),V("")},[is]),Ql=u.useCallback(()=>{L(Je.map(x=>x.deviceId)),V("")},[Je]),Xl=u.useCallback((x,A)=>{const _=Je.find(I=>I.deviceId===x);if(!_)return;const U=ma(_);U<=1||(zs(I=>{const we=(Ta(I[x],U)+A+U)%U;return{...I,[x]:we}}),et&&(Wn(!1),Q(x)))},[Je,et]);u.useEffect(()=>{const x=A=>{if(et&&_e&&ys)return;const _=A.target,U=_?.tagName?.toLowerCase();_?.isContentEditable||U==="input"||U==="textarea"||U==="select"||((A.ctrlKey||A.metaKey)&&A.key.toLowerCase()==="a"&&(A.preventDefault(),Ql()),A.key==="Escape"&&Ci())};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[ys,Ci,_e,Ql,et]);const vn=async()=>{if(!Te||Re)return;const x=Te;if(!fi.has(x.deviceId)){Oe(mi);return}Fe("view-screen"),Ae(!1),Le(!1),Wn(!1),Q(x.deviceId),pt("control");try{Oe(`Opening ${ha(x)} screen.`,"success")}finally{Fe("")}},Bt=(x,A)=>{const _=Je.find(I=>I.deviceId===x),U=Ta(A,_?ma(_):1);zs(I=>({...I,[x]:U})),et?(Wn(!1),Q(x)):$a(x)},ft=async x=>{if(Wn(!1),Q(x),pt("control"),!fi.has(x)){Le(!1),Oe(mi);return}const A=Je.find(U=>U.deviceId===x);if(Es(A?.platform)&&(A?.capabilities?.controlPermission===!1||A?.capabilities?.accessibilityPermission===!1)){Le(!1),Oe("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts LiveDesk, then restart the Mac client.","error");return}Le(!0),Oe(`Opening remote control${A?` for ${ha(A)}`:""}.`,"success")},Qs=async()=>{if(!Te){Oe("Select a workstation before playing audio.");return}if(!Gt){Oe(mi);return}if(!Zr){Oe("Selected workstation does not report remote audio support yet.");return}if(Re)return;const x=!ue,A=x?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:oe.current.get(Te.deviceId);x&&A?oe.current.set(Te.deviceId,A):x||oe.current.delete(Te.deviceId),Fe("audio"),Ve(x);try{await $e(`/api/remote/devices/${encodeURIComponent(Te.deviceId)}/audio/${x?"start":"stop"}`,{method:"POST",body:JSON.stringify({...A?{streamId:A}:{},mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},k),Oe(`${x?"Audio started":"Audio stopped"} for ${ha(Te)}.`,"success")}catch(_){x&&oe.current.delete(Te.deviceId),Ve(!1),Oe(_ instanceof Error?_.message:String(_),"error")}finally{Fe("")}},wa=x=>{const A=x instanceof Error?x.message:String(x);return/remote-actions-disabled|allowAgent-blocked-by-settings/i.test(A)?"Remote actions are off. Turn on Settings > Agent > Enable AI Agent first.":/power-actions-disabled/i.test(A)?"Power actions are off. Turn on Settings > Agent > Allow power actions first.":/agent-tool-capability-unavailable|unsupported-agent-operation/i.test(A)?"This workstation needs a newer LiveDesk Client for power actions.":/device-not-connected|404 device-not-found/i.test(A)?"The workstation disconnected before the action could be sent.":A},ur=async x=>{if(!Te||Re)return;const A=Te,U={lock:"Lock",sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[x];if(!(x!=="lock"&&!window.confirm(`${U} ${ha(A)}? Unsaved work on that computer may be lost.`))){Ae(!1),Fe(x),Oe(`Sending ${U.toLowerCase()} request to ${ha(A)}...`);try{const I=await $e(`/api/remote/devices/${encodeURIComponent(A.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:x})},k);if(!I.ok)throw new Error(I.error||"The remote action could not be sent.");Oe(`${U} request sent to ${ha(A)}.`,"success"),T()}catch(I){Oe(wa(I),"error")}finally{Fe("")}}},Xs=()=>{Te&&(Ae(!1),ye({id:Date.now(),deviceId:Te.deviceId,instruction:"Run command "}),Le(!1),pt("agents"),Oe(`Command runner opened for ${ha(Te)}.`))},Jo=async(x,A,_="files")=>{const U=x.filter(ze=>ze.file.size>=0);if(U.length===0)return{files:0,bytes:0};if(!Gt)throw new Error(mi);if(A.length===0)throw new Error("Select at least one connected workstation.");const I=crypto.randomUUID(),ge=U.reduce((ze,Xe)=>ze+Xe.file.size,0);let we=0;es({id:I,status:"reading",progress:1,message:`Preparing ${U.length} ${_}`});try{for(let ze=0;ze<U.length;ze+=1){const Xe=U[ze],mt=Xe.file,it=Math.max(1,Math.ceil(mt.size/ch));for(let yn=0;yn<it;yn+=1){const da=yn*ch,dl=Math.min(mt.size,da+ch),fl=mt.size===0?new ArrayBuffer(0):await mt.slice(da,dl).arrayBuffer(),Cf=yn===it-1;es({id:I,status:"sending",progress:Math.max(2,Math.min(98,Math.round(we/Math.max(1,ge)*96))),message:`${ze+1}/${U.length} ${Xe.relativePath}`});const Sr=await $e("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:I,deviceIds:A,remoteDirectory:Mn.trim(),name:mt.name,relativePath:Xe.relativePath,size:mt.size,type:mt.type,lastModified:mt.lastModified,offset:da,totalBytes:mt.size,final:Cf,dataBase64:sT(fl)})},k);if(!Sr.ok||Sr.queued!==A.length)throw new Error(Sr.error||`file-chunk-not-queued-${Sr.queued}/${A.length}`);we+=fl.byteLength,await new Promise(dc=>window.setTimeout(dc,0))}}return es({id:I,status:"queued",progress:100,message:`Sent ${U.length} file${U.length===1?"":"s"} to ${A.length} workstation${A.length===1?"":"s"}`}),window.setTimeout(()=>{es(ze=>ze?.id===I&&ze.status==="queued"?null:ze)},4500),{files:U.length,bytes:ge}}catch(ze){throw es({id:I,status:"failed",progress:100,message:ze instanceof Error?ze.message:String(ze)}),ze}},ec=async x=>{const A=Ba.length>0?Ba.map(_=>_.deviceId):Te?[Te.deviceId]:[];try{await Jo(Ly(x),A)}catch(_){Oe(_ instanceof Error?_.message:String(_))}},ki=async x=>{try{await Jo(Ly(x),vf)}catch(A){Oe(A instanceof Error?A.message:String(A))}};u.useEffect(()=>{uu.current=!1},[]);const Ai=x=>{x.preventDefault(),x.stopPropagation(),Bs(!1),ec(x.dataTransfer.files)},dr=async(x="ltd")=>{if(!a){Oe("Sign in with Google before checkout.");return}if(R&&x===$t){Oe("LiveDesk license is already active.");return}if(R&&$t==="pro"){Oe("LiveDesk Pro is already active.");return}Ee("checkout");try{const{data:A,error:_}=await ot.functions.invoke("dodo-checkout",{body:{plan:x}});if(_)throw _;if(!A?.checkout_url)throw new Error("Checkout function did not return a checkout URL.");window.location.assign(A.checkout_url)}catch(A){Oe(A instanceof Error?A.message:String(A)),Ee("")}},ba=PM(),fr=HM(),Ni=Je.length,Ua=Go.filter(x=>ar.has(x)).length,cs=sr==="open"&&ir.sampleMs>0?`${ir.framesPerSecond.toFixed(1)} fps`:sr,Ce=Te?et?Yl.get(Te.deviceId):ar.get(Te.deviceId):void 0,mr=Te?Ta(qt[Te.deviceId],ma(Te)):0,Zl=Te?GM(Te):[],hr=typeof Ce?.monitorIndex=="number"?Ta(Ce.monitorIndex,Math.max(1,Ce.monitorCount||1)):mr,Cs=(Ce&&hr===mr?pb(Ce):null)||(Te?hb(Te,mr):null),jn=Cs?`${Cs.width}x${Cs.height}`:"-",Mi=Te?Ts(et?"control":"wall",Te.deviceId):"",xn=Mi?Yn[Mi]:void 0,la=Mi?Yi[Mi]:void 0,vt=la?.lastInfo,bf=xn&&xn.sampleMs>0?`${xn.framesPerSecond.toFixed(1)} fps`:"waiting",on=xn?`#${xn.totalFrames} / ${bf}`:"waiting",nc=la&&la.sampleMs>0?`${la.framesPerSecond.toFixed(1)} fps`:"waiting",rl=la&&la.sampleMs>0?`${la.changedFramesPerSecond.toFixed(1)} fps`:"waiting",ll=vt?`#${vt.frameSeq} ${vt.decoderLabel} q${vt.queueSize} r${vt.renderQueueSize} d${vt.droppedForLatency} f${vt.decoderFlushCount} t${vt.decoderTimestampFallbacks} io${vt.decoderInputCount}/${vt.decoderOutputCount} ${vt.visualChanged?"changed":"same"}`:"waiting",ac=vt?`${Math.round(vt.queuedForMs)}ms total / ${Math.round(vt.decodedForMs)}ms decode / ${Math.round(vt.scheduledForMs)}ms pace / ${vt.drawMs.toFixed(1)}ms draw`:"-",pr=vt?.targetPaintIntervalMs?`${vt.targetPaintIntervalMs.toFixed(1)}ms / ${(1e3/vt.targetPaintIntervalMs).toFixed(1)} fps`:"-",gr=la?`${la.decoderInputFps.toFixed(1)} in / ${la.decoderOutputFps.toFixed(1)} out fps`:"waiting",Sf=vt?.canvasPresentation||"-",ju=vt?`${vt.interactiveBufferWaitCount} waits / ${Math.round(vt.interactiveBufferWaitMs)}ms / ${vt.interactiveQueueDrainCount} drains`:"waiting",jf=n.framesPerSecond>0?`${n.framesPerSecond.toFixed(1)} fps / p95 ${n.p95IntervalMs.toFixed(1)}ms / max ${n.maxIntervalMs.toFixed(1)}ms / long ${n.longTaskCount} (${Math.round(n.longTaskMs)}ms)`:"waiting",Cu=xn?Ce?.frameMode==="mode5-lzo-delta"?`${Uc(xn.averageFrameBytes)} avg / visual ${Ce.deltaVisualTileCount||0} + refresh ${Ce.deltaRefreshTileCount||0} / ${Ce.deltaTotalTiles||0}`:`${Uc(xn.averageFrameBytes)} avg / tiny ${Math.round(xn.tinyFrameRatio*100)}% / repeat ${Math.round(xn.repeatedFrameRatio*100)}%`:"waiting",Ti=xn&&xn.sourceSendSampleCount>0?`${xn.sourceSendAverageMs.toFixed(1)}ms avg / p95 ${xn.sourceSendP95Ms.toFixed(1)}ms`:"waiting",sc=Ay(xn),Jl=Ay(la),ku=xn&&la?`rx ${Ny(xn)} / paint ${Ny(la)}`:"waiting",Zs=Ce?Ce.frameMode||Ce.mode||Ce.codec||Ce.mimeType:et?ut.frameMode:Ie.frameMode,ol=et?ut.frameMode:Ie.frameMode,eo=Zs!==ol?`${ol} -> ${Zs}`:ol,to=Ce?`${Ce.width}x${Ce.height} ${Uc(Ce.byteLength)}`:et?`${$s.maxWidth}x${$s.maxHeight}`:`${Ie.maxWidth}x${Ie.maxHeight}`,Au=Ce?`${Ce.isKeyFrame?"key":String(Ce.chunkType||"delta")}`:"-",Nu=Ce&&Ce.monitorCount?`${(Ce.monitorIndex??0)+1}/${Ce.monitorCount}`:"-",Ei=Ce?[`src ${Math.round(Ce.sourceGapMs||0)}ms`,`gap ${Math.round(Ce.agentSendGapMs||0)}ms`,`tx ${Math.round(Ce.agentSendDurationMs||0)}ms`,`pace ${Math.round(Ce.agentPaceMs||0)}ms`,`queue ${Math.round(Ce.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(Ce.agentFrameAgeMs||0)}ms`,Ce.browserReceivedEpochMs&&Ce.receivedAt?`hub ${Math.max(0,Math.round(Ce.browserReceivedEpochMs-Date.parse(Ce.receivedAt)))}ms`:"",Ce.browserReceivedEpochMs&&Ce.hubPacketEpochMs?`sock ${Math.max(0,Math.round(Ce.browserReceivedEpochMs-Ce.hubPacketEpochMs))}ms`:"",Ce.droppedByAgent?`drop ${Ce.droppedByAgent}`:"",Ce.hubIngressDropped?`ingress-drop ${Ce.hubIngressDropped}`:"",Ce.hubClientDropped?`ws-drop ${Ce.hubClientDropped}`:"",Ce.captureStageMs?`capture ${Math.round(Ce.captureStageMs)}ms`:"",Ce.requestedFps?`req ${Math.round(Ce.requestedFps)}fps`:"",Ce.effectiveFps?`eff ${Math.round(Ce.effectiveFps)}fps`:"",Ce.captureAverageMs?`avg ${Math.round(Ce.captureAverageMs)}ms`:"",Ce.captureP95Ms?`p95 ${Math.round(Ce.captureP95Ms)}ms`:"",Ce.slowFrameCount?`slow ${Math.round(Ce.slowFrameCount)}`:"",Ce.captureHelperRestarts?`helper ${Math.round(Ce.captureHelperRestarts)}`:"",Ce.convertMs?`rgb565 ${Math.round(Ce.convertMs)}ms`:"",Ce.compressMs?`lzo ${Math.round(Ce.compressMs)}ms`:"",Ce.captureSourceSerial?`cap #${Ce.captureSourceSerial}`:"",Ce.captureSourceSkipped?`cap skip ${Ce.captureSourceSkipped}`:"",Ce.frameMode==="mode5-lzo-delta"?`tiles ${Ce.deltaVisualTileCount||0}+${Ce.deltaRefreshTileCount||0}/${Ce.deltaTotalTiles||0}@${Ce.deltaTileSize||0}`:"",Ce.platformProfile||Ce.hardwareEncoder||"-",Ce.atlasComposeMs?`atlas ${Ce.atlasComposeMs.toFixed(1)}ms`:"",Ce.atlasPoolStarved?`pool ${Ce.atlasPoolStarved}`:"",Ce.atlasTileCount?`tiles ${Ce.atlasReadyTiles||0}/${Ce.atlasTileCount}`:"",Ce.atlasInputRevision?`input #${Ce.atlasInputRevision}`:"",Ce.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(Ce.atlasSourceMaxAgeMs)}ms`:"",vt?.inputFeedbackMs!==void 0&&vt.inputFeedbackAt!==void 0&&performance.now()-vt.inputFeedbackAt<=by?`feedback ${Math.round(vt.inputFeedbackMs)}ms`:"",Ce.contentHash?`enc ${Ce.contentHash.slice(0,6)}`:"",vt?.visualHash?`pix ${vt.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "):"-",Ri=sl==="open"?[`${Rn.sentPerSecond.toFixed(1)} hz`,Rn.lastInputSeq>0?`rtt ${Math.round(Rn.lastRoundTripMs)}ms`:"",Rn.lastInputSeq>0?`apply ${Rn.lastAgentApplyMs.toFixed(1)}ms`:"",Rn.droppedPerSecond>0?`drop ${Rn.droppedPerSecond.toFixed(1)}/s`:"",Rn.bufferedAmount>0?`buf ${Uc(Rn.bufferedAmount)}`:"",Rn.lastInputType||"ready"].filter(Boolean).join(" / "):sl,Mu=vt?.inputFeedbackMs!==void 0&&vt.inputFeedbackAt!==void 0&&performance.now()-vt.inputFeedbackAt<=by?`${Math.round(vt.inputFeedbackMs)}ms / input #${vt.inputFeedbackSeq||0}`:"waiting for changed frame",Tu=ue?[Su,`context ${ln.audioContextState}`,`queue ${Math.round(ln.queuedMs)}ms`,`last ${Math.round(ln.lastPacketAgeMs)}ms`,`accepted ${Math.round(ln.lastAcceptedAgeMs)}ms`,`process ${Math.round(ln.localProcessingAgeMs)}ms`,`remote ${Math.round(ln.browserAgeMs)}/${Math.round(ln.captureAgeMs)}ms`,`heartbeat ${Math.round(ln.captureStatusAgeMs)}ms`,`capture ${ln.captureAlive&&ln.helperAlive?"alive":"down"}`,`drop ${ln.drops}`,`resync ${ln.resyncs}`,`restart ${ln.automaticRestarts}`,ln.pendingDecodes>0?`decode ${ln.pendingDecodes}`:"",ra?`#${ra.frameSeq}`:"waiting"].filter(Boolean).join(" / "):"off",vr=Ce?`#${Ce.frameSeq} ${jh(Ce.receivedAt||Ce.capturedAt)}`:"waiting",us=Math.max(0,ir.bytesPerSecond*8/1e6),cl=vi?.atlasReadyTiles??Ua,Di=vi?.atlasTileCount??Ua,no=cl===Di?`${Di} tiles`:`${cl}/${Di} tiles`,Eu=et?`1 stream / ${cs} / ${us.toFixed(us>=10?0:1)}Mbps`:gt?`1 stream / ${no} / ${cs} / ${us.toFixed(us>=10?0:1)}Mbps`:`${Ua} screens / ${cs} / ${us.toFixed(us>=10?0:1)}Mbps`,Js=N?"offline":j?.started?"online":"starting",ul=Ba.length,ks=et?Te?ha(Te):"No workstation":ul===0?"No workstation":ul>1?`${ul} selected`:Te?ha(Te):"No workstation",Cn=Eo[Nt]||Eo.en,xr=Cn.sync||Eo.en.sync,As=r||$?"checking":R?$t==="pro"?"Pro LTD active":`Plus LTD ${Je.length}/${$c}`:gu?`Free ${Je.length}/${Hc}`:`Upgrade ${Je.length}/${Hc}`,ei=$t==="pro"?"Pro active":je==="checkout"?"Opening":$t==="ltd"?"Pro $199":"Plus $79",ic=R?$t==="pro"?"Pro active":"Upgrade to Pro LTD":a?je==="checkout"?"Opening checkout":$t==="ltd"?"Buy Pro LTD":"Buy Plus LTD":je==="auth"?"Opening Google":"Sign in to buy",rc=$t==="pro"||je==="checkout"||je==="auth"||r||$,yr=a?.user?.user_metadata,ti=zy(yr,"avatar_url","picture"),wr=zy(yr,"full_name","name")||a?.user?.email||"Google",lc=wr.slice(0,1).toUpperCase(),br=j?.started?"Local app ready":"Start LiveDesk",so=l?.active?"Published":a?"Not published":"Sign in required",Ru=/^\d{6}$/.test(j?.pairingPin||"")?j?.pairingPin:"------",oc=Yd.find(x=>x.width===Ie.maxWidth&&x.height===Ie.maxHeight)?.id||`${Ie.maxWidth}x${Ie.maxHeight}`,cc=Ie.atlasTileSizeMode==="auto"?"auto":hh.find(x=>x.width===Ie.atlasTileWidth&&x.height===Ie.atlasTileHeight)?.id||"320x180",oa=mh.find(x=>x.width===ut.maxWidth&&x.height===ut.maxHeight)?.id||`${ut.maxWidth}x${ut.maxHeight}`,Sa=Vd.find(x=>x.id===Ie.frameMode)||Vd[0],dn=x=>{ri(A=>{const _=x.frameMode?$h(x.frameMode):A.frameMode,U=x.frameMode!==void 0&&_!==A.frameMode;return{...A,...x,frameMode:_,fps:qh(x.fps??(U?db(_):A.fps),_)}})},uc=x=>{const A=Yd.find(_=>_.id===x);A&&dn({maxWidth:A.width,maxHeight:A.height})},Du=x=>{if(x==="auto"){dn({atlasTileSizeMode:"auto"});return}const A=hh.find(_=>_.id===x);!A?.width||!A?.height||dn({atlasTileSizeMode:"fixed",atlasTileWidth:A.width,atlasTileHeight:A.height})},ca=x=>{x.frameMode!==void 0&&(X(""),ve("")),Xa(A=>{const _=x.frameMode?Uh(x.frameMode):A.frameMode,U=x.frameMode!==void 0&&_!==A.frameMode,I=x.fps??(U?30:A.fps),ge=x.maxWidth??A.maxWidth,we=x.maxHeight??A.maxHeight;return{...A,...x,frameMode:_,fps:hs(I,20,_==="mode3-h264-hw"?60:30,_==="mode3-h264-hw"?60:30),maxWidth:_==="mode3-h264-hw"?ge:Math.min(1920,ge),maxHeight:_==="mode3-h264-hw"?we:Math.min(1080,we)}})},ua=x=>{const A=mh.find(_=>_.id===x);A&&ca({maxWidth:A.width,maxHeight:A.height})},Vt=x=>{if(typeof window<"u"&&(x==="support"?window.history.pushState({},"","/support"):Ut==="support"&&window.history.pushState({},"","/")),x==="control"){const A=Pn||Us;if(A&&(Wn(!1),Q(A.deviceId)),pt(x),!Gt){Le(!1),Oe(mi);return}Le(!0);return}x==="agents"&&ye(null),x==="wall"&&Wt(A=>A+1),pt(x),Le(!1)},io=je==="update"||["dispatching","waiting-for-clients","hub-restart-requested"].includes(j?.update?.state||""),ds=u.useCallback(x=>{if(B?.targetIds.includes(x))return B.stage},[B]);return s.jsxs("main",{className:"app-shell",children:[s.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk tools",children:[s.jsx("div",{className:"rail-brand",title:"LiveDesk",children:s.jsx(tw,{size:25})}),s.jsx("nav",{className:"rail-tools",children:uT.map(x=>{const A=x.icon;return s.jsxs(u.Fragment,{children:[s.jsxs("button",{className:`rail-tool ${x.id==="sync-server"?"sync-server":""} ${Ut===x.id?"active":""} accent-${x.accent}`,onClick:()=>x.id==="sync-server"?void js({takeover:!0,requestLocalAccess:!0}):Vt(x.id),title:x.label,type:"button",disabled:x.id==="sync-server"&&je==="host","aria-busy":x.id==="sync-server"&&je==="host",children:[x.id==="sync-server"&&je==="host"?s.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):s.jsx(A,{size:19}),s.jsx("span",{children:x.id==="sync-server"&&je==="host"?"Syncing…":x.label})]}),x.id==="sync-server"&&j?.update?.updateAvailable&&j.update.canApply&&!io?s.jsxs("button",{className:"rail-update-button",onClick:()=>{ls()},title:`Update LiveDesk to ${j.update.latestVersion||"latest"}`,type:"button",children:[s.jsx(Gh,{size:16}),s.jsx("span",{children:"Update"})]}):null]},x.id)})}),s.jsxs("div",{className:"rail-footer",children:[dT.map(x=>{const A=x.icon;return s.jsxs("button",{className:`rail-tool compact ${Ut===x.id?"active":""} accent-${x.accent}`,onClick:()=>Vt(x.id),title:x.label,type:"button",children:[s.jsx(A,{size:18}),s.jsx("span",{children:x.label})]},x.id)}),s.jsxs("button",{className:`rail-tool compact local-settings ${Il?"active":""}`,onClick:()=>{pt("settings"),typeof window<"u"&&window.history.pushState({},"","/"),Bn(!1),Le(!1),Vi(!1)},title:"Settings",type:"button",children:[s.jsx(Py,{size:18}),s.jsx("span",{children:"Settings"})]}),s.jsxs("button",{className:`rail-account ${a?"signed-in":""}`,onClick:()=>{Bn(x=>!x)},disabled:r||je==="auth","aria-expanded":un,title:a?`Account: ${a.user?.email||wr}`:"Sign in with Google",type:"button",children:[a?ti?s.jsx("img",{src:ti,alt:wr,referrerPolicy:"no-referrer"}):s.jsx("span",{className:"avatar-fallback",children:lc}):s.jsx(Al,{size:18}),s.jsx("span",{children:a?"Account":"Google"})]}),un&&s.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[s.jsxs("div",{className:"account-popover-head",children:[s.jsx("div",{className:"account-popover-avatar",children:a&&ti?s.jsx("img",{src:ti,alt:wr,referrerPolicy:"no-referrer"}):a?s.jsx("span",{children:lc}):s.jsx(Al,{size:18})}),s.jsxs("div",{children:[s.jsx("strong",{children:a?wr:"Account"}),s.jsx("p",{children:a?.user?.email||"Not signed in"})]})]}),s.jsxs("dl",{className:"account-popover-facts",children:[s.jsx("dt",{children:"User"}),s.jsx("dd",{children:a?.user?.email||"Not signed in"}),s.jsx("dt",{children:"Network"}),s.jsx("dd",{children:br}),s.jsx("dt",{children:"Access"}),s.jsx("dd",{children:so}),s.jsx("dt",{children:"Plan"}),s.jsx("dd",{children:As}),s.jsx("dt",{children:"Ads"}),s.jsx("dd",{children:$t==="free"?"Standard banner":"Removed"})]}),a?s.jsxs("button",{className:"account-popover-action",onClick:ya,disabled:je==="auth",type:"button",children:[s.jsx(Hy,{size:16}),"Logout"]}):s.jsxs("button",{className:"account-popover-action primary",onClick:Dn,disabled:je==="auth",type:"button",children:[s.jsx(Al,{size:16}),"Sign in with Google"]})]})]})]}),s.jsxs("section",{className:`desk-stage ${du&&!Nn?"dock-open":""} ${et?"control-stage":""} ${Fl?"agents-stage":""}`,children:[s.jsxs("header",{className:"topbar",children:[s.jsxs("div",{className:"brand",children:[s.jsx("span",{className:"brand-mark",children:s.jsx(an,{size:18})}),s.jsxs("div",{children:[s.jsx("h1",{children:"LiveDesk"}),s.jsx("p",{children:"Control wall for local machines"})]})]}),Hs&&!et&&s.jsxs("div",{className:"file-share-top-route","aria-label":"File distribution route",children:[s.jsxs("div",{children:[s.jsx(Cl,{size:17}),s.jsxs("span",{children:[s.jsx("small",{children:"Source"}),s.jsx("strong",{children:"LiveDesk Hub"})]})]}),s.jsx(Wh,{size:15}),s.jsx(a0,{size:16}),s.jsxs("div",{children:[s.jsx("span",{className:"file-share-top-route-laptops",children:"▣ ▣ ▣"}),s.jsxs("span",{children:[s.jsx("small",{children:"Destination"}),s.jsxs("strong",{children:[fu," workstation",fu===1?"":"s"]}),s.jsx("em",{children:Mn.trim()||"Desktop/LiveDeskFiles"})]})]})]}),du&&!et&&s.jsxs("div",{className:"top-actions",children:[s.jsx(vy,{controller:qo,onError:Oe}),s.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),s.jsx("div",{className:"segmented-control","aria-label":"Screen size",children:cT.map(x=>s.jsx("button",{className:st===x.id?"active":"",onClick:()=>Jt(x.id),type:"button",children:x.label},x.id))})]}),et&&s.jsx("div",{className:"top-actions",children:s.jsx(vy,{controller:qo,onError:Oe})})]}),Bl?s.jsxs("section",{className:"doc-page",lang:Nt,dir:Nt==="ar"?"rtl":"ltr",children:[s.jsxs("section",{className:"doc-hero",children:[s.jsxs("div",{className:"doc-hero-copy",children:[s.jsxs("span",{className:"pricing-eyebrow",children:[s.jsx(Wd,{size:16}),Cn.eyebrow]}),s.jsx("h2",{children:Cn.title}),s.jsx("p",{children:Cn.intro})]}),s.jsxs("label",{className:"doc-language-picker",children:[s.jsxs("span",{children:[s.jsx(s0,{size:17}),Cn.languageLabel]}),s.jsx("select",{value:Nt,onChange:x=>De(x.target.value),children:mT.map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]})]}),s.jsx("section",{className:"doc-grid",children:Cn.sections.map((x,A)=>{const U=[Kd,Pc,Hd,zt,ko][A]||Wd;return s.jsxs("article",{className:"doc-card",children:[s.jsx("div",{className:"doc-card-icon",children:s.jsx(U,{size:19})}),s.jsxs("div",{children:[s.jsx("h3",{children:x.title}),s.jsx("p",{children:x.body}),s.jsx("ul",{children:x.points.map(I=>s.jsx("li",{children:I},I))})]})]},x.title)})}),xr&&s.jsxs("section",{className:"doc-sync",children:[s.jsxs("div",{className:"doc-sync-head",children:[s.jsx(Hd,{size:20}),s.jsxs("div",{children:[s.jsx("h3",{children:xr.title}),s.jsx("p",{children:xr.body})]})]}),s.jsx("ul",{children:xr.points.map(x=>s.jsx("li",{children:x},x))})]}),s.jsxs("section",{className:"doc-firewall",children:[s.jsxs("div",{className:"doc-firewall-head",children:[s.jsx(zt,{size:20}),s.jsxs("div",{children:[s.jsx("h3",{children:Cn.firewall.title}),s.jsx("p",{children:Cn.firewall.body})]})]}),s.jsx("ul",{children:Cn.firewall.points.map(x=>s.jsx("li",{children:x},x))})]}),s.jsxs("section",{className:"doc-command-panel",children:[s.jsxs("div",{className:"doc-command-head",children:[s.jsx(Pc,{size:20}),s.jsxs("div",{children:[s.jsx("h3",{children:Cn.commands.title}),s.jsx("p",{children:Cn.commands.body})]})]}),s.jsxs("div",{className:"doc-command-list",children:[Cn.commands.manager&&s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:Cn.commands.manager}),s.jsx("code",{children:fr}),s.jsx("button",{className:"icon-button",onClick:()=>Sl(fr),title:"Copy command",type:"button",children:s.jsx(gl,{size:16})})]}),s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:Cn.commands.primary}),s.jsx("code",{children:ba}),s.jsx("button",{className:"icon-button",onClick:()=>Sl(ba),title:"Copy command",type:"button",children:s.jsx(gl,{size:16})})]}),s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:Cn.commands.slot}),s.jsx("code",{children:`${ba} 3`}),s.jsx("button",{className:"icon-button",onClick:()=>Sl(`${ba} 3`),title:"Copy command",type:"button",children:s.jsx(gl,{size:16})})]})]})]})]}):Fl?s.jsx(QN,{hubUrl:k,devices:C,launchRequest:de}):Hs?s.jsx(eN,{hubUrl:k,devices:Je,localFeatureAccess:Gt,upgradeNotice:mi,remoteDirectory:Mn,onRemoteDirectoryChange:Qa,targetMode:Fs,selectedTargetIds:ts,onTargetModeChange:ou,onTargetToggle:x=>Oa(A=>A.includes(x)?A.filter(_=>_!==x):[...A,x]),filePickerRef:Ll,folderPickerRef:zl,onBrowserFileImport:x=>{ki(x)},onBrowserFolderImport:x=>{ki(x)},onNotice:Oe,onTransferChange:x=>{if(!x){es(null);return}const A=x.state==="failed"||x.state==="partially-failed"||x.state==="cancelled"?"failed":x.state==="completed"?"queued":x.state==="sending"?"sending":"reading";es({id:x.id,status:A,progress:x.progress,message:x.message}),["completed","partially-failed","failed","cancelled"].includes(x.state)&&window.setTimeout(()=>es(_=>_?.id===x.id?null:_),4500)}}):Xi?s.jsx(Zy,{session:a,currentProductKey:"livedesk",appVersion:"",onSignIn:Dn}):Il?s.jsx(v1,{hubUrl:k,runtimeRole:j?.runtimeRole||"hub",runtimeDeviceId:j?.deviceId||"",sessionAccessToken:a?.access_token||"",pin:s.jsxs(x1,{children:[s.jsxs("div",{className:"settings-section-grid",children:[s.jsxs("section",{className:"settings-section-card settings-pairing-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Pair a workstation"}),s.jsx("h3",{children:"Connect another local PC"})]}),s.jsx(Zt,{size:20})]}),s.jsxs("div",{className:"settings-pin-display",children:[s.jsx("span",{children:"Hub PIN"}),s.jsx("strong",{children:Ru}),s.jsxs("button",{className:"text-button ghost compact",onClick:os,disabled:!j?.started||je==="pin",type:"button",children:[s.jsx(Rs,{size:15}),je==="pin"?"Creating":"New PIN"]})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Hub status"}),s.jsx("h3",{children:Js})]}),s.jsx("span",{className:`settings-status-dot state-${Js}`})]}),s.jsxs("dl",{className:"settings-facts",children:[s.jsx("dt",{children:"Address"}),s.jsx("dd",{children:k||"-"}),s.jsx("dt",{children:"Connected workstations"}),s.jsxs("dd",{children:[Ni,"/",Qr]}),s.jsx("dt",{children:"Sync access"}),s.jsx("dd",{children:j?.started?"Local app ready":"Start Hub first"}),s.jsx("dt",{children:"Plan"}),s.jsx("dd",{children:As})]}),s.jsxs("div",{className:"settings-action-row",children:[s.jsxs("button",{className:"text-button primary",onClick:()=>js({takeover:!0,requestLocalAccess:!0}),disabled:!a||je==="host",type:"button",children:[je==="host"?s.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):s.jsx(Hd,{size:16}),je==="host"?"Syncing…":"Sync access"]}),s.jsxs("button",{className:"text-button buy",onClick:()=>dr($t==="ltd"?"pro":"ltd"),disabled:je==="checkout"||$t==="pro",type:"button",children:[s.jsx(Co,{size:16}),ei]})]})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"File transfer"}),s.jsx("h3",{children:"Client destination folder"})]}),s.jsx(Ao,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Remote folder"}),s.jsx("input",{value:Mn,onChange:x=>Qa(x.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),s.jsx("p",{className:"settings-help",children:"Blank uses Desktop/LiveDeskFiles on each workstation."})]})]}),wall:s.jsx(y1,{children:s.jsxs("div",{className:"settings-section-grid",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Wall stream"}),s.jsx("h3",{children:"Frame delivery"})]}),s.jsx(Xc,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Frame mode"}),s.jsx("select",{value:Ie.frameMode,onChange:x=>dn({frameMode:$h(x.target.value)}),children:Vd.map(x=>s.jsxs("option",{value:x.id,children:[x.label," - ",x.detail]},x.id))})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"H.264 decode"}),s.jsx("select",{value:Ie.h264DecodeAcceleration,onChange:x=>dn({h264DecodeAcceleration:rf(x.target.value)}),children:Hh.map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]}),s.jsxs("div",{className:"settings-field-grid",children:[s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"FPS"}),s.jsx("select",{value:Ie.fps,onChange:x=>dn({fps:qh(x.target.value,Ie.frameMode)}),children:vp.filter(x=>x<=fb(Ie.frameMode)).map(x=>s.jsx("option",{value:x,children:x},x))})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:gt?"Atlas tile":"Resolution"}),s.jsx("select",{value:gt?cc:oc,onChange:x=>gt?Du(x.target.value):uc(x.target.value),children:(gt?hh:Yd).map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Quality"}),s.jsx("select",{value:Ie.quality,onChange:x=>dn({quality:hs(x.target.value,20,95,pa.quality)}),children:My.map(x=>s.jsx("option",{value:x,children:x},x))})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Wall behavior"}),s.jsx("h3",{children:"Visibility and load"})]}),s.jsx(an,{size:20})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Ie.autoStartLive,onChange:x=>dn({autoStartLive:x.target.checked})}),s.jsx("span",{children:"Auto live on connected screens"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Ie.visibleOnlyLive,onChange:x=>dn({visibleOnlyLive:x.target.checked})}),s.jsx("span",{children:"Stream visible tiles first"})]}),!gt&&s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Ie.adaptiveSizeByWall,onChange:x=>dn({adaptiveSizeByWall:x.target.checked})}),s.jsx("span",{children:"Fit stream size to Wall"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Ie.adaptiveLoadShedding,onChange:x=>dn({adaptiveLoadShedding:x.target.checked})}),s.jsx("span",{children:"Reduce FPS under load"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Ie.showScreenStatus,onChange:x=>dn({showScreenStatus:x.target.checked})}),s.jsx("span",{children:"Screen status overlay"})]}),s.jsxs("div",{className:"settings-summary",children:[s.jsx("span",{children:Sa.label}),s.jsxs("strong",{children:[Qn.maxWidth,"x",Qn.maxHeight," / ",sn,"fps"]})]}),s.jsxs("button",{className:"settings-reset",onClick:()=>ri(pa),type:"button",children:[s.jsx(Gc,{size:15})," Reset Wall settings"]})]})]})}),control:s.jsx(w1,{children:s.jsxs("div",{className:"settings-section-grid",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Control stream"}),s.jsx("h3",{children:"Low-latency delivery"})]}),s.jsx(Pd,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Frame mode"}),s.jsx("select",{value:ut.frameMode,onChange:x=>ca({frameMode:Uh(x.target.value)}),children:EM.map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]}),ut.frameMode==="mode3-h264-hw"&&s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"H.264 decode"}),s.jsx("select",{value:ut.h264DecodeAcceleration,onChange:x=>ca({h264DecodeAcceleration:rf(x.target.value)}),children:Hh.map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]}),s.jsxs("div",{className:"settings-field-grid",children:[s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"FPS"}),s.jsx("select",{value:ut.fps,onChange:x=>ca({fps:hs(x.target.value,20,60,Ea.fps)}),children:RM.filter(x=>ut.frameMode==="mode3-h264-hw"||x<=30).map(x=>s.jsx("option",{value:x,children:x},x))})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Resolution"}),s.jsx("select",{value:oa,onChange:x=>ua(x.target.value),children:mh.filter(x=>ut.frameMode==="mode3-h264-hw"||x.width<=1920).map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]})]}),ut.frameMode==="mode3-h264-hw"&&s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Quality"}),s.jsx("select",{value:ut.quality,onChange:x=>ca({quality:hs(x.target.value,20,95,Ea.quality)}),children:My.map(x=>s.jsx("option",{value:x,children:x},x))})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Control behavior"}),s.jsx("h3",{children:"Session display"})]}),s.jsx(Zt,{size:20})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:ut.showScreenStatus,onChange:x=>ca({showScreenStatus:x.target.checked})}),s.jsx("span",{children:"Screen status overlay"})]}),s.jsxs("div",{className:"settings-summary control",children:[s.jsx("span",{children:ut.frameMode==="mode5-lzo-delta"?"Mode 5 tile delta":"Mode 3 H.264"}),s.jsxs("strong",{children:[$s.maxWidth,"x",$s.maxHeight," / ",Po,"fps"]})]}),s.jsxs("button",{className:"settings-reset",onClick:()=>Xa(Ea),type:"button",children:[s.jsx(Gc,{size:15})," Reset Control settings"]})]})]})}),agent:s.jsx(b1,{hubUrl:k}),captureGallery:s.jsx(nM,{hubUrl:k,onToast:Oe}),advancedExtras:s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Connection commands"}),s.jsx("h3",{children:"Developer setup"})]}),s.jsx(gl,{size:20})]}),s.jsxs("div",{className:"settings-command-list",children:[s.jsxs("div",{className:"settings-command-row",children:[s.jsx("span",{children:"Client"}),s.jsx("code",{children:ba}),s.jsx("button",{className:"icon-button",onClick:()=>Sl(ba),title:"Copy client command",type:"button",children:s.jsx(gl,{size:16})})]}),s.jsxs("div",{className:"settings-command-row",children:[s.jsx("span",{children:"Slot example"}),s.jsx("code",{children:`${ba} 3`}),s.jsx("button",{className:"icon-button",onClick:()=>Sl(`${ba} 3`),title:"Copy slot command",type:"button",children:s.jsx(gl,{size:16})})]}),s.jsxs("div",{className:"settings-command-row",children:[s.jsx("span",{children:"Hub"}),s.jsx("code",{children:fr}),s.jsx("button",{className:"icon-button",onClick:()=>Sl(fr),title:"Copy Hub command",type:"button",children:s.jsx(gl,{size:16})})]})]})]})}):Ol?s.jsxs("section",{className:"pricing-page",children:[s.jsxs("header",{className:"pricing-header",children:[s.jsxs("div",{children:[s.jsxs("span",{className:"pricing-eyebrow",children:[s.jsx(bh,{size:15})," LiveDesk plans"]}),s.jsx("h2",{children:"Choose the plan that fits your wall"}),s.jsx("p",{children:"Start free with a local screen wall. Upgrade when you need ad-free monitoring, more workstations, or commercial controls."})]}),s.jsx("button",{className:"pricing-close",onClick:()=>Vt("wall"),title:"Close pricing",type:"button",children:s.jsx(Ds,{size:18})})]}),s.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[s.jsx("span",{children:"Current plan"}),s.jsx("strong",{children:Hl.name}),s.jsxs("small",{children:[Je.length,"/",TM(Gs)," connected devices"]})]}),s.jsxs("div",{className:"pricing-cards","aria-label":"LiveDesk plans",children:[s.jsxs("article",{className:`pricing-plan-card ${$t==="free"?"current":""}`,children:[s.jsxs("div",{className:"pricing-plan-topline",children:[s.jsx("span",{className:"pricing-plan-badge free",children:"Free"}),s.jsx("strong",{children:"$0"})]}),s.jsx("p",{className:"pricing-plan-audience",children:yl.free.audience}),s.jsx("h3",{children:"Monitor your local wall"}),s.jsx("p",{children:yl.free.note}),s.jsxs("ul",{children:[s.jsxs("li",{children:[s.jsx(Ln,{size:16})," Up to ",Hc," devices"]}),s.jsxs("li",{children:[s.jsx(Ln,{size:16})," Live view and local control"]}),s.jsxs("li",{children:[s.jsx(Ln,{size:16})," Standard ad-supported banner"]})]}),s.jsx("span",{className:"pricing-current-label",children:$t==="free"?"Current plan":"Included for everyone"})]}),s.jsxs("article",{className:`pricing-plan-card featured ${$t==="ltd"?"current":""}`,children:[s.jsxs("div",{className:"pricing-plan-topline",children:[s.jsxs("span",{className:"pricing-plan-badge plus",children:[s.jsx(i0,{size:14})," Plus"]}),s.jsx("strong",{children:"$5"})]}),s.jsx("p",{className:"pricing-plan-audience",children:yl.ltd.audience}),s.jsx("h3",{children:"Ad-free monitoring"}),s.jsx("p",{children:"More room for personal AI workstations without the standard banner."}),s.jsxs("ul",{children:[s.jsxs("li",{children:[s.jsx(Ln,{size:16})," Up to ",$c," devices"]}),s.jsxs("li",{children:[s.jsx(Ln,{size:16})," No standard ad banner"]}),s.jsxs("li",{children:[s.jsx(Ln,{size:16})," ",yl.ltd.ltd]})]}),s.jsxs("button",{className:"pricing-plan-button",onClick:a?()=>dr("ltd"):Dn,disabled:$t!=="free"||je==="checkout"||je==="auth"||r||$,type:"button",children:[s.jsx(Co,{size:16}),$t==="free"?a?"Choose Plus":"Sign in for Plus":"Plus active"]})]}),s.jsxs("article",{className:`pricing-plan-card pro ${$t==="pro"?"current":""}`,children:[s.jsxs("div",{className:"pricing-plan-topline",children:[s.jsxs("span",{className:"pricing-plan-badge pro",children:[s.jsx(zt,{size:14})," Pro"]}),s.jsx("strong",{children:"$15"})]}),s.jsx("p",{className:"pricing-plan-audience",children:yl.pro.audience}),s.jsx("h3",{children:"For serious operations"}),s.jsx("p",{children:"Commercial-ready monitoring for larger AI labs, studios, and teams."}),s.jsxs("ul",{children:[s.jsxs("li",{children:[s.jsx(Ln,{size:16})," 30+ workstation walls"]}),s.jsxs("li",{children:[s.jsx(Ln,{size:16})," Commercial use included"]}),s.jsxs("li",{children:[s.jsx(Ln,{size:16})," ",yl.pro.ltd]})]}),s.jsxs("button",{className:"pricing-plan-button",onClick:a?()=>dr("pro"):Dn,disabled:$t==="pro"||je==="checkout"||je==="auth"||r||$,type:"button",children:[s.jsx(Co,{size:16}),$t==="pro"?"Pro active":a?"Choose Pro":"Sign in for Pro"]})]})]}),s.jsxs("section",{className:"pricing-includes",children:[s.jsxs("div",{children:[s.jsx(Zt,{size:17}),s.jsx("span",{children:"Screen wall"}),s.jsx("strong",{children:"120+ slots"})]}),s.jsxs("div",{children:[s.jsx(Pd,{size:17}),s.jsx("span",{children:"Focused control"}),s.jsx("strong",{children:"Local-first"})]}),s.jsxs("div",{children:[s.jsx(nx,{size:17}),s.jsx("span",{children:"Remote audio"}),s.jsx("strong",{children:"Available"})]}),s.jsxs("div",{children:[s.jsx(Ao,{size:17}),s.jsx("span",{children:"File transfer"}),s.jsx("strong",{children:"Included"})]})]}),s.jsxs("p",{className:"pricing-note",children:[s.jsx(Ln,{size:15})," Commercial use requires Pro. Plus LTD is for personal, creator, and homelab use."]}),s.jsxs("button",{className:"pricing-primary-cta",onClick:a?()=>dr($t==="ltd"?"pro":"ltd"):Dn,disabled:rc,type:"button",children:[s.jsx(Co,{size:18}),ic]})]}):s.jsx(s.Fragment,{children:s.jsxs("section",{className:`monitor-layout ${Nn?"dock-collapsed":""}`,children:[s.jsxs("section",{ref:Kr,className:`screen-wall-panel ${Oo?"drop-active":""}`,onClick:x=>{x.currentTarget===x.target&&Ci()},onDragEnter:x=>{x.preventDefault(),Bs(!0)},onDragOver:x=>{x.preventDefault(),x.dataTransfer.dropEffect="copy"},onDragLeave:x=>{x.currentTarget===x.target&&Bs(!1)},onDrop:Ai,children:[gt&&s.jsx("canvas",{ref:yf,className:"atlas-source-canvas",width:xi?.width||1920,height:xi?.height||1080,"aria-hidden":"true"}),et?s.jsx("section",{className:"control-focus",children:s.jsxs("div",{className:"control-wall",children:[Te&&Zl.length>1&&s.jsx("div",{className:"control-monitor-tabs","aria-label":"Select monitor",children:Zl.map(x=>s.jsxs("button",{className:x.index===mr?"active":"",onClick:()=>Bt(Te.deviceId,x.index),title:VM(x),type:"button",children:[s.jsx("span",{children:x.name||`Display ${x.index+1}`}),x.width>0&&x.height>0&&s.jsxs("small",{children:[x.width,"x",x.height]})]},x.index))}),Te?s.jsx(wh,{device:Te,frame:Ce,selected:!1,controlEnabled:ys&&_e&&bi,showStatus:ut.showScreenStatus,monitorIndex:Ta(qt[Te.deviceId],ma(Te)),monitorCount:ma(Te),onSelect:()=>{},onFocusDevice:()=>Q(Te.deviceId),onOpenControl:()=>ft(Te.deviceId),onCycleMonitor:x=>Xl(Te.deviceId,x),onCanvasReady:ia,sendInput:or,presentationReady:iu},Te.deviceId):s.jsxs("div",{className:"control-empty",children:[s.jsx(Zt,{size:30}),s.jsx("strong",{children:"No workstation"}),s.jsx("span",{children:"Open a workstation from the Wall."})]}),Te&&Uo&&s.jsxs("div",{className:"control-connection-overlay",role:"alert",children:[s.jsx(zt,{size:22,"aria-hidden":"true"}),s.jsx("strong",{children:"Accessibility permission required"}),s.jsx("small",{children:"On the Mac, allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client."})]}),Te&&!Uo&&!iu&&s.jsxs("div",{className:"control-connection-overlay",role:"status","aria-live":"polite",children:[D!=="error"&&s.jsx("span",{className:"control-connection-spinner","aria-hidden":"true"}),s.jsx("strong",{children:D==="error"?"Connection failed":"Connecting"}),s.jsx("small",{children:D==="error"?"See the notification for details. Reopen Control to retry.":$n||pe?"Control stream is recovering. See the notification for details.":sr==="open"?"Preparing the first control frame":"Opening the Control stream"})]})]})}):gt?s.jsx("div",{className:`screen-wall atlas-slot-wall size-${st}`,onClick:x=>{x.currentTarget===x.target&&Ci()},children:Xr.map((x,A)=>x?s.jsx(wh,{device:x,frame:ar.get(x.deviceId),selected:Zi.has(x.deviceId),controlEnabled:!1,showStatus:Ie.showScreenStatus,monitorIndex:Ta(qt[x.deviceId],ma(x)),monitorCount:ma(x),onSelect:()=>Zo(x.deviceId),onFocusDevice:()=>$a(x.deviceId),onOpenControl:()=>ft(x.deviceId),onCycleMonitor:_=>Xl(x.deviceId,_),onCanvasReady:Es(x.platform)?wu:Wo,sendInput:or,updateIndicator:ds(x.deviceId),presentationReady:Ie.autoStartLive&&Fa.includes(x.deviceId)?Mt.has(x.deviceId):void 0,showPresentationSpinner:Ie.autoStartLive&&Fa.includes(x.deviceId)},x.deviceId):s.jsx(Oy,{index:A},`slot-${A}`))}):s.jsx("div",{className:`screen-wall size-${st}`,onClick:x=>{x.currentTarget===x.target&&Ci()},children:Xr.map((x,A)=>x?s.jsx(wh,{device:x,frame:ar.get(x.deviceId),selected:Zi.has(x.deviceId),controlEnabled:ys&&_e&&bi&&Te?.deviceId===x.deviceId,showStatus:Ie.showScreenStatus,monitorIndex:Ta(qt[x.deviceId],ma(x)),monitorCount:ma(x),onSelect:()=>Zo(x.deviceId),onFocusDevice:()=>$a(x.deviceId),onOpenControl:()=>ft(x.deviceId),onCycleMonitor:_=>Xl(x.deviceId,_),onCanvasReady:wu,sendInput:or,updateIndicator:ds(x.deviceId),presentationReady:Ie.autoStartLive&&Fa.includes(x.deviceId)?Mt.has(x.deviceId):void 0,showPresentationSpinner:Ie.autoStartLive&&Fa.includes(x.deviceId)},x.deviceId):s.jsx(Oy,{index:A},`slot-${A}`))}),s.jsx(gT,{visible:vu&&!et})]}),!Il&&s.jsxs("aside",{className:`right-dock actions-mode ${Nn?"collapsed":""}`,"aria-label":"LiveDesk tools",children:[s.jsx("button",{className:"dock-toggle",onClick:()=>Vi(x=>!x),"aria-label":Nn?"Show control panel":"Hide control panel",title:Nn?"Show control panel":"Hide control panel",type:"button",children:Nn?s.jsx(Qy,{size:18}):s.jsx(Kh,{size:18})}),!Nn&&s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"action-dock",children:[s.jsxs("div",{className:"action-context",children:[s.jsx("span",{children:et?"Control target":ul>0?"Selection":"No selection"}),s.jsx("strong",{children:ks})]}),s.jsx("input",{ref:Fo,className:"hidden-file-input",type:"file",multiple:!0,onChange:x=>{x.currentTarget.files&&ec(x.currentTarget.files),x.currentTarget.value=""}}),s.jsxs("div",{className:"action-grid",children:[s.jsxs("button",{className:"action-tile primary",onClick:()=>{vn()},disabled:!hi||!!Re,type:"button",title:"Open this workstation's screen",children:[Re==="view-screen"?s.jsx(Hr,{className:"spin",size:21}):s.jsx(ax,{size:21}),s.jsx("span",{children:Re==="view-screen"?"Opening...":"View Screen"})]}),s.jsxs("button",{className:`action-tile ${_e?"active":""}`,onClick:()=>{if(Te){if(et&&_e){Le(!1),Oe("Remote control paused. Screen viewing stays on.");return}ft(Te.deviceId)}},disabled:!ys||!!Re,title:Uo?"Allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client.":ys?bi?"Keyboard and mouse control is ready":"Waiting for the current Control capture session":"Remote control is not available on this workstation",type:"button",children:[s.jsx(Pd,{size:21}),s.jsx("span",{children:_e&&sl==="connecting"?"Connecting...":"Remote Control"})]}),s.jsxs("button",{className:`action-tile ${ue?"active":""}`,onClick:()=>{Qs()},disabled:!xu||!!Re,type:"button",title:Zr?ue?"Stop hearing this workstation":"Hear this workstation":"Audio is not available on this workstation",children:[Re==="audio"?s.jsx(Hr,{className:"spin",size:21}):s.jsx(nx,{size:21}),s.jsx("span",{children:Re==="audio"?"Updating...":ue?"Mute Audio":"Hear Audio"})]}),s.jsxs("button",{className:"action-tile",onClick:()=>{Oe(`Choose files to send to ${ks}.`),Fo.current?.click()},disabled:!!Re||!Gt||(et?!Te:Ba.length===0),type:"button",title:"Choose files and send them to the selected workstation",children:[s.jsx(Ao,{size:21}),s.jsx("span",{children:"Send Files"})]}),s.jsxs("button",{className:"action-tile",onClick:()=>{ur("restart")},disabled:!Te||!Gt||!Pl||!!Re,type:"button",title:Pl?"Restart the selected workstation":"Restart requires a current LiveDesk Client",children:[Re==="restart"?s.jsx(Hr,{className:"spin",size:21}):s.jsx(Gc,{size:21}),s.jsx("span",{children:Re==="restart"?"Sending...":"Restart"})]}),s.jsxs("button",{className:`action-tile ${he?"active":""}`,onClick:()=>Ae(x=>!x),disabled:!Te||!Gt||!Pl||!!Re,type:"button",title:Pl?"Lock, sleep, or shut down this workstation":"Power options require a current LiveDesk Client","aria-expanded":he,children:[s.jsx(sx,{size:21}),s.jsx("span",{children:"Power Options"})]}),s.jsxs("button",{className:"action-tile",onClick:Xs,disabled:!Te||!Gt||!hu||!!Re,type:"button",title:hu?"Open the command runner for this workstation":"Command runner requires a current LiveDesk Client",children:[s.jsx(Pc,{size:21}),s.jsx("span",{children:"Run Command"})]})]}),he&&Te&&s.jsxs("div",{className:"power-action-menu",role:"group","aria-label":`Power options for ${ha(Te)}`,children:[s.jsxs("button",{type:"button",onClick:()=>{ur("lock")},children:[s.jsx(Rs,{size:16}),"Lock"]}),s.jsxs("button",{type:"button",onClick:()=>{ur("sleep")},children:[s.jsx(r0,{size:16}),"Sleep"]}),s.jsxs("button",{type:"button",className:"danger",onClick:()=>{ur("shutdown")},children:[s.jsx(sx,{size:16}),"Shut Down"]})]})]}),Te&&ns&&s.jsxs("section",{className:"side-panel selected-panel",children:[s.jsxs("div",{className:"machine-detail-head",children:[s.jsxs("div",{className:"panel-title",children:[s.jsx(Zt,{size:17}),s.jsx("h2",{children:"Machine detail"})]}),s.jsx("span",{className:`machine-health state-${ns.state}`,children:ns.label})]}),s.jsxs("div",{className:"machine-title",children:[s.jsx("strong",{children:ha(Te)}),s.jsx("span",{children:ns.role})]}),s.jsx("div",{className:"machine-metric-grid",children:ns.metrics.map(x=>s.jsxs("article",{className:`machine-metric state-${x.state}`,children:[s.jsx("span",{children:x.label}),s.jsx("strong",{children:x.value}),s.jsx("small",{children:x.detail}),x.ratio!==void 0&&s.jsx("i",{children:s.jsx("b",{style:{width:`${Math.round(x.ratio*100)}%`}})})]},x.id))}),s.jsxs("section",{className:"machine-section",children:[s.jsxs("div",{className:"machine-section-title",children:[s.jsx(an,{size:15}),s.jsx("span",{children:"Stream"})]}),s.jsxs("dl",{className:"facts compact",children:[s.jsx("dt",{children:"Frames"}),s.jsx("dd",{children:on}),s.jsx("dt",{children:et?"Control RX":gt?"Atlas RX":"Wall RX"}),s.jsx("dd",{children:Eu}),s.jsx("dt",{children:"Painted"}),s.jsx("dd",{children:nc}),s.jsx("dt",{children:et?"Encoded changes":"Visual samples"}),s.jsx("dd",{children:rl}),s.jsx("dt",{children:"Decoder"}),s.jsx("dd",{children:ll}),s.jsx("dt",{children:"Decoder IO"}),s.jsx("dd",{children:gr}),s.jsx("dt",{children:"Canvas"}),s.jsx("dd",{children:Sf}),s.jsx("dt",{children:"Control buffer"}),s.jsx("dd",{children:ju}),s.jsx("dt",{children:"Browser RAF"}),s.jsx("dd",{children:jf}),s.jsx("dt",{children:"Latency"}),s.jsx("dd",{children:ac}),s.jsx("dt",{children:"Cadence"}),s.jsx("dd",{children:pr}),s.jsx("dt",{children:"Source send"}),s.jsx("dd",{children:Ti}),s.jsx("dt",{children:"Packet mix"}),s.jsx("dd",{children:Cu}),s.jsx("dt",{children:"Receive gap"}),s.jsx("dd",{children:sc}),s.jsx("dt",{children:"Paint gap"}),s.jsx("dd",{children:Jl}),s.jsx("dt",{children:"Seq gap"}),s.jsx("dd",{children:ku}),s.jsx("dt",{children:"Selected"}),s.jsx("dd",{children:vr}),s.jsx("dt",{children:"Requested"}),s.jsx("dd",{children:eo}),s.jsx("dt",{children:"Mode"}),s.jsx("dd",{children:Zs}),s.jsx("dt",{children:"Chunk"}),s.jsx("dd",{children:Au}),s.jsx("dt",{children:"Size"}),s.jsx("dd",{children:to}),s.jsx("dt",{children:"Native"}),s.jsx("dd",{children:jn}),s.jsx("dt",{children:"Monitor"}),s.jsx("dd",{children:Nu}),s.jsx("dt",{children:"Source"}),s.jsx("dd",{children:Ei}),s.jsx("dt",{children:"Input"}),s.jsx("dd",{children:Ri}),s.jsx("dt",{children:"Audio"}),s.jsx("dd",{children:Tu}),et&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Visual feedback"}),s.jsx("dd",{children:Mu})]})]})]}),s.jsxs("section",{className:"machine-section",children:[s.jsxs("div",{className:"machine-section-title",children:[s.jsx(Pc,{size:15}),s.jsx("span",{children:"Local services"})]}),s.jsx("div",{className:"tool-probe-list",children:ns.tools.map(x=>s.jsxs("span",{className:`tool-probe state-${x.status}`,children:[s.jsx("b",{children:x.label}),s.jsx("em",{children:x.detail})]},x.id))})]}),s.jsxs("section",{className:"machine-section",children:[s.jsxs("div",{className:"machine-section-title",children:[s.jsx(Do,{size:15}),s.jsx("span",{children:"Workload"})]}),s.jsxs("div",{className:"workload-card",children:[s.jsx("strong",{children:ns.taskLabel}),s.jsx("span",{children:ns.taskStatus}),ns.taskSummary&&s.jsx("p",{children:ns.taskSummary})]})]}),s.jsxs("div",{className:"machine-section",children:[s.jsxs("div",{className:"machine-section-title",children:[s.jsx(Kd,{size:15}),s.jsx("span",{children:"System"})]}),s.jsxs("dl",{className:"facts compact",children:[s.jsx("dt",{children:"Platform"}),s.jsxs("dd",{children:[Te.platform||"-"," ",Te.arch||""]}),s.jsx("dt",{children:"Release"}),s.jsx("dd",{children:Ra(Te.status,"release")||"-"}),s.jsx("dt",{children:"Uptime"}),s.jsx("dd",{children:gb(tn(Te.status,"uptimeSec"))}),s.jsx("dt",{children:"Last seen"}),s.jsx("dd",{children:jh(Te.lastSeenAt||Te.connectedAt)}),s.jsx("dt",{children:"Agent"}),s.jsx("dd",{children:Te.agentVersion||"-"}),s.jsx("dt",{children:"Address"}),s.jsx("dd",{children:Te.remoteAddress||"-"})]})]}),s.jsxs("button",{className:"text-button full",onClick:()=>{vn()},disabled:!hi||!!Re,type:"button",children:[s.jsx(ax,{size:16}),"View screen"]})]})]})]})]})})]}),Fn&&s.jsxs("aside",{className:`transfer-bar state-${Fn.status}`,"aria-live":"polite",children:[s.jsx("span",{className:"transfer-bar-icon","aria-hidden":"true",children:Fn.status==="queued"?s.jsx(Ln,{size:18}):Fn.status==="failed"?s.jsx(Ds,{size:18}):s.jsx(Vy,{size:18})}),s.jsxs("div",{className:"transfer-bar-copy",children:[s.jsx("p",{children:Fn.message}),s.jsx("div",{className:"transfer-bar-track",children:s.jsx("span",{style:{width:`${Math.max(0,Math.min(100,Fn.progress))}%`}})})]}),s.jsxs("strong",{children:[Math.max(0,Math.min(100,Fn.progress)),"%"]})]}),pn&&s.jsxs("aside",{className:`livedesk-toast tone-${pn.tone}`,role:pn.tone==="error"?"alert":"status","aria-live":pn.tone==="error"?"assertive":"polite","aria-busy":pn.tone==="progress",children:[pn.tone==="progress"&&s.jsx("span",{className:"livedesk-toast-spinner","aria-hidden":"true"}),s.jsx("span",{children:pn.message}),s.jsx("button",{className:"livedesk-toast-close",onClick:()=>Oe(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:s.jsx(Ds,{size:15})})]})]})}function xT(){if(typeof window>"u")return[];const n=window.location.origin;return window.location.port==="5179"?[n]:["http://127.0.0.1:5179"]}function yT(){const[a,r]=u.useState(null);return u.useEffect(()=>{let l=!1,c=!1;const d=async()=>{for(const v of xT())try{const g=await fetch(`${v}/api/runtime`,{cache:"no-store"});if(!g.ok)continue;const y=(await g.json()).role==="hub"?"hub":"client";c=!0,l||r(y);return}catch{}};d();const m=window.setInterval(()=>{d()},1e3),p=window.setTimeout(()=>{!l&&!c&&r("client")},2500);return()=>{l=!0,window.clearInterval(m),window.clearTimeout(p)}},[null]),a?a==="client"?s.jsx(cj,{}):s.jsx(vT,{}):s.jsxs("main",{className:"runtime-role-boot","aria-busy":"true","aria-label":"Starting LiveDesk",children:[s.jsx("span",{className:"runtime-role-boot-mark","aria-hidden":"true"}),s.jsx("strong",{children:"Starting LiveDesk"}),s.jsx("p",{children:"Loading this computer's assigned role..."})]})}h0.createRoot(document.getElementById("root")).render(s.jsx(u.StrictMode,{children:s.jsx(yT,{})}));