livedesk 0.1.418 → 0.1.419

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,25 +0,0 @@
1
- import{r as zS,a as u,M as qc,S as Ht,R as Eo,B as IS,P as $m,X as Sa,b as Xc,C as ui,F as sy,L as Rs,A as Gx,c as OS,d as iy,E as ry,T as HS,D as Xh,e as _n,f as BS,g as FS,h as PS,i as $S,j as Vr,k as Zt,l as Gd,m as jo,n as Zh,o as Tl,p as Vx,q as bn,s as Jh,t as Wx,u as Ah,v as US,w as qS,H as Nl,W as El,x as GS,y as VS,z as ko,K as Ao,G as Yx,I as Vd,J as WS,N as Zc,O as Ds,Q as Co,U as YS,V as KS,Y as QS,Z as ep,_ as Gc,$ as tp,a0 as XS,a1 as np,a2 as Kx,a3 as ZS,a4 as ci,a5 as ly,a6 as ap,a7 as rf,a8 as Jc,a9 as Od,aa as JS,ab as Qx,ac as e0,ad as Xx,ae as t0,af as n0,ag as Nh,ah as a0,ai as s0,aj as i0,ak as r0,al as l0,am as o0,an as c0,ao as oy,ap as u0,aq as d0,ar as Hd,as as Bd,at as f0,au as m0,av as Um,aw as yl,ax as h0,ay as cy,az as Zx,aA as p0,aB as g0}from"./icons-grMviB7T.js";import{r as Jx}from"./react-BPvGG2Bl.js";import{c as v0}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 qm={exports:{}},zc={};var uy;function y0(){if(uy)return zc;uy=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 zc.Fragment=a,zc.jsx=r,zc.jsxs=r,zc}var dy;function x0(){return dy||(dy=1,qm.exports=y0()),qm.exports}var s=x0(),Gm={exports:{}},Ic={},Vm={exports:{}},Wm={};var fy;function b0(){return fy||(fy=1,(function(n){function a(I,ee){var G=I.length;I.push(ee);e:for(;0<G;){var q=G-1>>>1,oe=I[q];if(0<c(oe,ee))I[q]=ee,I[G]=oe,G=q;else break e}}function r(I){return I.length===0?null:I[0]}function l(I){if(I.length===0)return null;var ee=I[0],G=I.pop();if(G!==ee){I[0]=G;e:for(var q=0,oe=I.length,we=oe>>>1;q<we;){var Q=2*(q+1)-1,$=I[Q],he=Q+1,fe=I[he];if(0>c($,G))he<oe&&0>c(fe,$)?(I[q]=fe,I[he]=G,q=he):(I[q]=$,I[Q]=G,q=Q);else if(he<oe&&0>c(fe,G))I[q]=fe,I[he]=G,q=he;else break e}}return ee}function c(I,ee){var G=I.sortIndex-ee.sortIndex;return G!==0?G:I.id-ee.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,x=null,b=3,j=!1,C=!1,k=!1,M=!1,A=typeof setTimeout=="function"?setTimeout:null,T=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function P(I){for(var ee=r(g);ee!==null;){if(ee.callback===null)l(g);else if(ee.startTime<=I)l(g),ee.sortIndex=ee.expirationTime,a(v,ee);else break;ee=r(g)}}function F(I){if(k=!1,P(I),!C)if(r(v)!==null)C=!0,V||(V=!0,O());else{var ee=r(g);ee!==null&&K(F,ee.startTime-I)}}var V=!1,_=-1,L=5,ne=-1;function W(){return M?!0:!(n.unstable_now()-ne<L)}function J(){if(M=!1,V){var I=n.unstable_now();ne=I;var ee=!0;try{e:{C=!1,k&&(k=!1,T(_),_=-1),j=!0;var G=b;try{t:{for(P(I),x=r(v);x!==null&&!(x.expirationTime>I&&W());){var q=x.callback;if(typeof q=="function"){x.callback=null,b=x.priorityLevel;var oe=q(x.expirationTime<=I);if(I=n.unstable_now(),typeof oe=="function"){x.callback=oe,P(I),ee=!0;break t}x===r(v)&&l(v),P(I)}else l(v);x=r(v)}if(x!==null)ee=!0;else{var we=r(g);we!==null&&K(F,we.startTime-I),ee=!1}}break e}finally{x=null,b=G,j=!1}ee=void 0}}finally{ee?O():V=!1}}}var O;if(typeof R=="function")O=function(){R(J)};else if(typeof MessageChannel<"u"){var be=new MessageChannel,re=be.port2;be.port1.onmessage=J,O=function(){re.postMessage(null)}}else O=function(){A(J,0)};function K(I,ee){_=A(function(){I(n.unstable_now())},ee)}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(I){I.callback=null},n.unstable_forceFrameRate=function(I){0>I||125<I?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):L=0<I?Math.floor(1e3/I):5},n.unstable_getCurrentPriorityLevel=function(){return b},n.unstable_next=function(I){switch(b){case 1:case 2:case 3:var ee=3;break;default:ee=b}var G=b;b=ee;try{return I()}finally{b=G}},n.unstable_requestPaint=function(){M=!0},n.unstable_runWithPriority=function(I,ee){switch(I){case 1:case 2:case 3:case 4:case 5:break;default:I=3}var G=b;b=I;try{return ee()}finally{b=G}},n.unstable_scheduleCallback=function(I,ee,G){var q=n.unstable_now();switch(typeof G=="object"&&G!==null?(G=G.delay,G=typeof G=="number"&&0<G?q+G:q):G=q,I){case 1:var oe=-1;break;case 2:oe=250;break;case 5:oe=1073741823;break;case 4:oe=1e4;break;default:oe=5e3}return oe=G+oe,I={id:w++,callback:ee,priorityLevel:I,startTime:G,expirationTime:oe,sortIndex:-1},G>q?(I.sortIndex=G,a(g,I),r(v)===null&&I===r(g)&&(k?(T(_),_=-1):k=!0,K(F,G-q))):(I.sortIndex=oe,a(v,I),C||j||(C=!0,V||(V=!0,O()))),I},n.unstable_shouldYield=W,n.unstable_wrapCallback=function(I){var ee=b;return function(){var G=b;b=ee;try{return I.apply(this,arguments)}finally{b=G}}}})(Wm)),Wm}var my;function w0(){return my||(my=1,Vm.exports=b0()),Vm.exports}var hy;function S0(){if(hy)return Ic;hy=1;var n=w0(),a=zS(),r=Jx();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,E=f.child;E;){if(E===i){S=!0,i=f,o=h;break}if(E===o){S=!0,o=f,i=h;break}E=E.sibling}if(!S){for(E=h.child;E;){if(E===i){S=!0,i=h,o=f;break}if(E===o){S=!0,o=h,i=f;break}E=E.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 x=Object.assign,b=Symbol.for("react.element"),j=Symbol.for("react.transitional.element"),C=Symbol.for("react.portal"),k=Symbol.for("react.fragment"),M=Symbol.for("react.strict_mode"),A=Symbol.for("react.profiler"),T=Symbol.for("react.consumer"),R=Symbol.for("react.context"),P=Symbol.for("react.forward_ref"),F=Symbol.for("react.suspense"),V=Symbol.for("react.suspense_list"),_=Symbol.for("react.memo"),L=Symbol.for("react.lazy"),ne=Symbol.for("react.activity"),W=Symbol.for("react.memo_cache_sentinel"),J=Symbol.iterator;function O(e){return e===null||typeof e!="object"?null:(e=J&&e[J]||e["@@iterator"],typeof e=="function"?e:null)}var be=Symbol.for("react.client.reference");function re(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===be?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case k:return"Fragment";case A:return"Profiler";case M:return"StrictMode";case F:return"Suspense";case V:return"SuspenseList";case ne:return"Activity"}if(typeof e=="object")switch(e.$$typeof){case C:return"Portal";case R:return e.displayName||"Context";case T:return(e._context.displayName||"Context")+".Consumer";case P:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case _:return t=e.displayName||null,t!==null?t:re(e.type)||"Memo";case L:t=e._payload,e=e._init;try{return re(e(t))}catch{}}return null}var K=Array.isArray,I=a.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ee=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,G={pending:!1,data:null,method:null,action:null},q=[],oe=-1;function we(e){return{current:e}}function Q(e){0>oe||(e.current=q[oe],q[oe]=null,oe--)}function $(e,t){oe++,q[oe]=e.current,e.current=t}var he=we(null),fe=we(null),me=we(null),Se=we(null);function Be(e,t){switch($(me,t),$(fe,e),$(he,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?Nv(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Nv(t),e=Mv(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}Q(he),$(he,e)}function Oe(){Q(he),Q(fe),Q(me)}function ge(e){e.memoizedState!==null&&$(Se,e);var t=he.current,i=Mv(t,e.type);t!==i&&($(fe,e),$(he,i))}function Ze(e){fe.current===e&&(Q(he),Q(fe)),Se.current===e&&(Q(Se),Rc._currentValue=G)}var Ke,ce;function ve(e){if(Ke===void 0)try{throw Error()}catch(i){var t=i.stack.trim().match(/\n( *(at )?)/);Ke=t&&t[1]||"",ce=-1<i.stack.indexOf(`
2
- at`)?" (<anonymous>)":-1<i.stack.indexOf("@")?"@unknown:0:0":""}return`
3
- `+Ke+e+ce}var ke=!1;function Ne(e,t){if(!e||ke)return"";ke=!0;var i=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var o={DetermineComponentFrameRoot:function(){try{if(t){var je=function(){throw Error()};if(Object.defineProperty(je.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(je,[])}catch(pe){var le=pe}Reflect.construct(e,[],je)}else{try{je.call()}catch(pe){le=pe}e.call(je.prototype)}}else{try{throw Error()}catch(pe){le=pe}(je=e())&&typeof je.catch=="function"&&je.catch(function(){})}}catch(pe){if(pe&&le&&typeof pe.stack=="string")return[pe.stack,le.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],E=h[1];if(S&&E){var U=S.split(`
4
- `),ie=E.split(`
5
- `);for(f=o=0;o<U.length&&!U[o].includes("DetermineComponentFrameRoot");)o++;for(;f<ie.length&&!ie[f].includes("DetermineComponentFrameRoot");)f++;if(o===U.length||f===ie.length)for(o=U.length-1,f=ie.length-1;1<=o&&0<=f&&U[o]!==ie[f];)f--;for(;1<=o&&0<=f;o--,f--)if(U[o]!==ie[f]){if(o!==1||f!==1)do if(o--,f--,0>f||U[o]!==ie[f]){var xe=`
6
- `+U[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{ke=!1,Error.prepareStackTrace=i}return(i=e?e.displayName||e.name:"")?ve(i):""}function He(e,t){switch(e.tag){case 26:case 27:case 5:return ve(e.type);case 16:return ve("Lazy");case 13:return e.child!==t&&t!==null?ve("Suspense Fallback"):ve("Suspense");case 19:return ve("SuspenseList");case 0:case 15:return Ne(e.type,!1);case 11:return Ne(e.type.render,!1);case 1:return Ne(e.type,!0);case 31:return ve("Activity");default:return""}}function $e(e){try{var t="",i=null;do t+=He(e,i),i=e,e=e.return;while(e);return t}catch(o){return`
7
- Error generating stack: `+o.message+`
8
- `+o.stack}}var Xe=Object.prototype.hasOwnProperty,ye=n.unstable_scheduleCallback,ae=n.unstable_cancelCallback,Te=n.unstable_shouldYield,Pe=n.unstable_requestPaint,Je=n.unstable_now,Mt=n.unstable_getCurrentPriorityLevel,It=n.unstable_ImmediatePriority,an=n.unstable_UserBlockingPriority,mt=n.unstable_NormalPriority,Pn=n.unstable_LowPriority,Kt=n.unstable_IdlePriority,X=n.log,De=n.unstable_setDisableYieldValue,ze=null,Ae=null;function et(e){if(typeof X=="function"&&De(e),Ae&&typeof Ae.setStrictMode=="function")try{Ae.setStrictMode(ze,e)}catch{}}var gt=Math.clz32?Math.clz32:$n,Re=Math.log,fa=Math.LN2;function $n(e){return e>>>=0,e===0?32:31-(Re(e)/fa|0)|0}var at=256,qt=262144,un=4194304;function ns(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 as(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 E=o&134217727;return E!==0?(o=E&~h,o!==0?f=ns(o):(S&=E,S!==0?f=ns(S):i||(i=E&~e,i!==0&&(f=ns(i))))):(E=o&~h,E!==0?f=ns(E):S!==0?f=ns(S):i||(i=o&~e,i!==0&&(f=ns(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 Zn(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function nr(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 Fe(){var e=un;return un<<=1,(un&62914560)===0&&(un=4194304),e}function zs(e){for(var t=[],i=0;31>i;i++)t.push(e);return t}function vt(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function hi(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 E=e.entanglements,U=e.expirationTimes,ie=e.hiddenUpdates;for(i=S&~i;0<i;){var xe=31-gt(i),je=1<<xe;E[xe]=0,U[xe]=-1;var le=ie[xe];if(le!==null)for(ie[xe]=null,xe=0;xe<le.length;xe++){var pe=le[xe];pe!==null&&(pe.lane&=-536870913)}i&=~je}o!==0&&Jt(e,o,0),h!==0&&f===0&&e.tag!==0&&(e.suspendedLanes|=h&~(S&~t))}function Jt(e,t,i){e.pendingLanes|=t,e.suspendedLanes&=~t;var o=31-gt(t);e.entangledLanes|=t,e.entanglements[o]=e.entanglements[o]|1073741824|i&261930}function H(e,t){var i=e.entangledLanes|=t;for(e=e.entanglements;i;){var o=31-gt(i),f=1<<o;f&t|e[o]&t&&(e[o]|=t),i&=~f}}function Le(e,t){var i=t&-t;return i=(i&42)!==0?1:lt(i),(i&(e.suspendedLanes|t))!==0?0:i}function lt(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 hn(e){return e&=-e,2<e?8<e?(e&134217727)!==0?32:268435456:8:2}function ss(){var e=ee.p;return e!==0?e:(e=window.event,e===void 0?32:Xv(e.type))}function Dn(e,t){var i=ee.p;try{return ee.p=e,t()}finally{ee.p=i}}var ma=Math.random().toString(36).slice(2),te="__reactFiber$"+ma,Me="__reactProps$"+ma,Ge="__reactContainer$"+ma,ut="__reactEvents$"+ma,sn="__reactListeners$"+ma,Gt="__reactHandles$"+ma,nt="__reactResources$"+ma,kt="__reactMarker$"+ma;function Bt(e){delete e[te],delete e[Me],delete e[ut],delete e[sn],delete e[Gt]}function Qt(e){var t=e[te];if(t)return t;for(var i=e.parentNode;i;){if(t=i[Ge]||i[te]){if(i=t.alternate,t.child!==null||i!==null&&i.child!==null)for(e=zv(e);e!==null;){if(i=e[te])return i;e=zv(e)}return t}e=i,i=e.parentNode}return null}function rn(e){if(e=e[te]||e[Ge]){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 Dt(e){var t=e[nt];return t||(t=e[nt]={hoistableStyles:new Map,hoistableScripts:new Map}),t}function Vt(e){e[kt]=!0}var ha=new Set,is={};function Lt(e,t){pn(e,t),pn(e+"Capture",t)}function pn(e,t){for(is[e]=t,e=0;e<t.length;e++)ha.add(t[e])}var ar=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]*$"),Pa={},Ca={};function _l(e){return Xe.call(Ca,e)?!0:Xe.call(Pa,e)?!1:ar.test(e)?Ca[e]=!0:(Pa[e]=!0,!1)}function sr(e,t,i){if(_l(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 ir(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 $a(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 ja(e){switch(typeof e){case"bigint":case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function zl(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Lo(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 _o(e){if(!e._valueTracker){var t=zl(e)?"checked":"value";e._valueTracker=Lo(e,t,""+e[t])}}function zo(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var i=t.getValue(),o="";return e&&(o=zl(e)?e.checked?"true":"false":e.value),e=o,e!==i?(t.setValue(e),!0):!1}function Jn(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 Io=/[\n"\\]/g;function dn(e){return e.replace(Io,function(t){return"\\"+t.charCodeAt(0).toString(16)+" "})}function ea(e,t,i,o,f,h,S,E){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=""+ja(t)):e.value!==""+ja(t)&&(e.value=""+ja(t)):S!=="submit"&&S!=="reset"||e.removeAttribute("value"),t!=null?Ss(e,S,ja(t)):i!=null?Ss(e,S,ja(i)):o!=null&&e.removeAttribute("value"),f==null&&h!=null&&(e.defaultChecked=!!h),f!=null&&(e.checked=f&&typeof f!="function"&&typeof f!="symbol"),E!=null&&typeof E!="function"&&typeof E!="symbol"&&typeof E!="boolean"?e.name=""+ja(E):e.removeAttribute("name")}function Is(e,t,i,o,f,h,S,E){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)){_o(e);return}i=i!=null?""+ja(i):"",t=t!=null?""+ja(t):i,E||t===e.value||(e.value=t),e.defaultValue=t}o=o??f,o=typeof o!="function"&&typeof o!="symbol"&&!!o,e.checked=E?e.checked:!!o,e.defaultChecked=!!o,S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"&&(e.name=S),_o(e)}function Ss(e,t,i){t==="number"&&Jn(e.ownerDocument)===e||e.defaultValue===""+i||(e.defaultValue=""+i)}function Ua(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=""+ja(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 Qr(e,t,i){if(t!=null&&(t=""+ja(t),t!==e.value&&(e.value=t),i==null)){e.defaultValue!==t&&(e.defaultValue=t);return}e.defaultValue=i!=null?""+ja(i):""}function rr(e,t,i,o){if(t==null){if(o!=null){if(i!=null)throw Error(l(92));if(K(o)){if(1<o.length)throw Error(l(93));o=o[0]}i=o}i==null&&(i=""),t=i}i=ja(t),e.defaultValue=i,o=e.textContent,o===i&&o!==""&&o!==null&&(e.value=o),_o(e)}function qa(e,t){if(t){var i=e.firstChild;if(i&&i===e.lastChild&&i.nodeType===3){i.nodeValue=t;return}}e.textContent=t}var lr=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 or(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||lr.has(t)?t==="float"?e.cssFloat=i:e[t]=(""+i).trim():e[t]=i+"px"}function Il(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&&or(e,f,o)}else for(var h in t)t.hasOwnProperty(h)&&or(e,h,t[h])}function pi(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 Ol=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"]]),Hl=/^[\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 gi(e){return Hl.test(""+e)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":e}function Ga(){}var Bl=null;function rs(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ka=null,pa=null;function ru(e){var t=rn(e);if(t&&(e=t.stateNode)){var i=e[Me]||null;e:switch(e=t.stateNode,t.type){case"input":if(ea(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="'+dn(""+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));ea(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&&zo(o)}break e;case"textarea":Qr(e,i.value,i.defaultValue);break e;case"select":t=i.value,t!=null&&Ua(e,!!i.multiple,t,!1)}}}var Xr=!1;function gf(e,t,i){if(Xr)return e(t,i);Xr=!0;try{var o=e(t);return o}finally{if(Xr=!1,(ka!==null||pa!==null)&&(Vu(),ka&&(t=ka,e=pa,pa=ka=null,ru(t),e)))for(t=0;t<e.length;t++)ru(e[t])}}function Zr(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 ta=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Oo=!1;if(ta)try{var ls={};Object.defineProperty(ls,"passive",{get:function(){Oo=!0}}),window.addEventListener("test",ls,ls),window.removeEventListener("test",ls,ls)}catch{Oo=!1}var os=null,lu=null,Ho=null;function vf(){if(Ho)return Ho;var e,t=lu,i=t.length,o,f="value"in os?os.value:os.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 Ho=f.slice(e,1<o?1-o:void 0)}function Fl(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 Jr(){return!0}function Bo(){return!1}function na(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 E in e)e.hasOwnProperty(E)&&(i=e[E],this[E]=i?i(h):h[E]);return this.isDefaultPrevented=(h.defaultPrevented!=null?h.defaultPrevented:h.returnValue===!1)?Jr:Bo,this.isPropagationStopped=Bo,this}return x(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=Jr)},stopPropagation:function(){var i=this.nativeEvent;i&&(i.stopPropagation?i.stopPropagation():typeof i.cancelBubble!="unknown"&&(i.cancelBubble=!0),this.isPropagationStopped=Jr)},persist:function(){},isPersistent:Jr}),t}var vi={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Pl=na(vi),yi=x({},vi,{view:0,detail:0}),Fo=na(yi),xi,cs,Os,el=x({},yi,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:ur,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!==Os&&(Os&&e.type==="mousemove"?(xi=e.screenX-Os.screenX,cs=e.screenY-Os.screenY):cs=xi=0,Os=e),xi)},movementY:function(e){return"movementY"in e?e.movementY:cs}}),Po=na(el),ou=x({},el,{dataTransfer:0}),tl=na(ou),$o=x({},yi,{relatedTarget:0}),$l=na($o),ot=x({},vi,{animationName:0,elapsedTime:0,pseudoElement:0}),ht=na(ot),ga=x({},vi,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),cr=na(ga),yf=x({},vi,{data:0}),Uo=na(yf),Hs={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},it={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"},cu={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function xf(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):(e=cu[e])?!!t[e]:!1}function ur(){return xf}var bi=x({},yi,{key:function(e){if(e.key){var t=Hs[e.key]||e.key;if(t!=="Unidentified")return t}return e.type==="keypress"?(e=Fl(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?it[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:ur,charCode:function(e){return e.type==="keypress"?Fl(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?Fl(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),uu=na(bi),qo=x({},el,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Bs=na(qo),va=x({},yi,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:ur}),dr=na(va),Un=x({},vi,{propertyName:0,elapsedTime:0,pseudoElement:0}),Fs=na(Un),_e=x({},el,{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}),du=na(_e),bf=x({},vi,{newState:0,oldState:0}),wf=na(bf),Go=[9,13,27,32],wi=ta&&"CompositionEvent"in window,fr=null;ta&&"documentMode"in document&&(fr=document.documentMode);var fu=ta&&"TextEvent"in window&&!fr,Vo=ta&&(!wi||fr&&8<fr&&11>=fr),Wt=" ",Wo=!1;function nl(e,t){switch(e){case"keyup":return Go.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Si(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var mr=!1;function Sf(e,t){switch(e){case"compositionend":return Si(t);case"keypress":return t.which!==32?null:(Wo=!0,Wt);case"textInput":return e=t.data,e===Wt&&Wo?null:e;default:return null}}function en(e,t){if(mr)return e==="compositionend"||!wi&&nl(e,t)?(e=vf(),Ho=lu=os=null,mr=!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 Vo&&t.locale!=="ko"?null:t.data;default:return null}}var al={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 mu(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t==="input"?!!al[e.type]:t==="textarea"}function us(e,t,i,o){ka?pa?pa.push(o):pa=[o]:ka=o,t=Ju(t,"onChange"),0<t.length&&(i=new Pl("onChange","change",null,i,o),e.push({event:i,listeners:t}))}var hr=null,Ps=null;function Ul(e){wv(e,0)}function aa(e){var t=Ot(e);if(zo(t))return e}function Cs(e,t){if(e==="change")return t}var sl=!1;if(ta){var Aa;if(ta){var sa="oninput"in document;if(!sa){var ia=document.createElement("div");ia.setAttribute("oninput","return;"),sa=typeof ia.oninput=="function"}Aa=sa}else Aa=!1;sl=Aa&&(!document.documentMode||9<document.documentMode)}function hu(){hr&&(hr.detachEvent("onpropertychange",Yo),Ps=hr=null)}function Yo(e){if(e.propertyName==="value"&&aa(Ps)){var t=[];us(t,Ps,e,rs(e)),gf(Ul,t)}}function pr(e,t,i){e==="focusin"?(hu(),hr=t,Ps=i,hr.attachEvent("onpropertychange",Yo)):e==="focusout"&&hu()}function Cf(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return aa(Ps)}function qn(e,t){if(e==="click")return aa(t)}function gr(e,t){if(e==="input"||e==="change")return aa(t)}function Gn(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var ln=typeof Object.is=="function"?Object.is:Gn;function $s(e,t){if(ln(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(!Xe.call(t,f)||!ln(e[f],t[f]))return!1}return!0}function Ci(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function js(e,t){var i=Ci(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=Ci(i)}}function ji(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?ji(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function il(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Jn(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=Jn(e.document)}return t}function Va(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 pu=ta&&"documentMode"in document&&11>=document.documentMode,vr=null,yr=null,Us=null,ql=!1;function ki(e,t,i){var o=i.window===i?i.document:i.nodeType===9?i:i.ownerDocument;ql||vr==null||vr!==Jn(o)||(o=vr,"selectionStart"in o&&Va(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}),Us&&$s(Us,o)||(Us=o,o=Ju(yr,"onSelect"),0<o.length&&(t=new Pl("onSelect","select",null,t,i),e.push({event:t,listeners:o}),t.target=vr)))}function qs(e,t){var i={};return i[e.toLowerCase()]=t.toLowerCase(),i["Webkit"+e]="webkit"+t,i["Moz"+e]="moz"+t,i}var Ai={animationend:qs("Animation","AnimationEnd"),animationiteration:qs("Animation","AnimationIteration"),animationstart:qs("Animation","AnimationStart"),transitionrun:qs("Transition","TransitionRun"),transitionstart:qs("Transition","TransitionStart"),transitioncancel:qs("Transition","TransitionCancel"),transitionend:qs("Transition","TransitionEnd")},Ko={},Ni={};ta&&(Ni=document.createElement("div").style,"AnimationEvent"in window||(delete Ai.animationend.animation,delete Ai.animationiteration.animation,delete Ai.animationstart.animation),"TransitionEvent"in window||delete Ai.transitionend.transition);function Mi(e){if(Ko[e])return Ko[e];if(!Ai[e])return e;var t=Ai[e],i;for(i in t)if(t.hasOwnProperty(i)&&i in Ni)return Ko[e]=t[i];return e}var Qo=Mi("animationend"),gu=Mi("animationiteration"),vu=Mi("animationstart"),yu=Mi("transitionrun"),jf=Mi("transitionstart"),xu=Mi("transitioncancel"),xr=Mi("transitionend"),Xo=new Map,ds="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(" ");ds.push("scrollEnd");function ra(e,t){Xo.set(e,t),Lt(t,[e])}var ks=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)},An=[],Gs=0,Zo=0;function rl(){for(var e=Gs,t=Zo=Gs=0;t<e;){var i=An[t];An[t++]=null;var o=An[t];An[t++]=null;var f=An[t];An[t++]=null;var h=An[t];if(An[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&&bu(i,f,h)}}function br(e,t,i,o){An[Gs++]=e,An[Gs++]=t,An[Gs++]=i,An[Gs++]=o,Zo|=o,e.lanes|=o,e=e.alternate,e!==null&&(e.lanes|=o)}function ll(e,t,i,o){return br(e,t,i,o),Ti(e)}function Wa(e,t){return br(e,null,null,t),Ti(e)}function bu(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-gt(i),e=h.hiddenUpdates,o=e[f],o===null?e[f]=[t]:o.push(t),t.lane=i|536870912),h):null}function Ti(e){if(50<jc)throw jc=0,fm=null,Error(l(185));for(var t=e.return;t!==null;)e=t,t=e.return;return e.tag===3?e.stateNode:null}var Ei={};function Gl(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 Vn(e,t,i,o){return new Gl(e,t,i,o)}function ol(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Na(e,t){var i=e.alternate;return i===null?(i=Vn(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 cl(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 Vs(e,t,i,o,f,h){var S=0;if(o=e,typeof e=="function")ol(e)&&(S=1);else if(typeof e=="string")S=CS(e,i,he.current)?26:e==="html"||e==="head"||e==="body"?27:5;else e:switch(e){case ne:return e=Vn(31,i,t,f),e.elementType=ne,e.lanes=h,e;case k:return fs(i.children,f,h,t);case M:S=8,f|=24;break;case A:return e=Vn(12,i,t,f|2),e.elementType=A,e.lanes=h,e;case F:return e=Vn(13,i,t,f),e.elementType=F,e.lanes=h,e;case V:return e=Vn(19,i,t,f),e.elementType=V,e.lanes=h,e;default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case R:S=10;break e;case T:S=9;break e;case P:S=11;break e;case _: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=Vn(S,i,t,f),t.elementType=e,t.type=o,t.lanes=h,t}function fs(e,t,i,o){return e=Vn(7,e,o,t),e.lanes=i,e}function Ws(e,t,i){return e=Vn(6,e,null,t),e.lanes=i,e}function Ri(e){var t=Vn(18,null,null,0);return t.stateNode=e,t}function Vl(e,t,i){return t=Vn(4,e.children!==null?e.children:[],e.key,t),t.lanes=i,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}var Ys=new WeakMap;function Wn(e,t){if(typeof e=="object"&&e!==null){var i=Ys.get(e);return i!==void 0?i:(t={value:e,source:t,stack:$e(t)},Ys.set(e,t),t)}return{value:e,source:t,stack:$e(t)}}var Ks=[],Di=0,ya=null,wr=0,zn=[],In=0,Qs=null,Ya=1,Xt="";function ms(e,t){Ks[Di++]=wr,Ks[Di++]=ya,ya=e,wr=t}function ul(e,t,i){zn[In++]=Ya,zn[In++]=Xt,zn[In++]=Qs,Qs=e;var o=Ya;e=Xt;var f=32-gt(o)-1;o&=~(1<<f),i+=1;var h=32-gt(t)+f;if(30<h){var S=f-f%5;h=(o&(1<<S)-1).toString(32),o>>=S,f-=S,Ya=1<<32-gt(t)+f|i<<f|o,Xt=h+e}else Ya=1<<h|i<<f|o,Xt=e}function dl(e){e.return!==null&&(ms(e,1),ul(e,1,0))}function Li(e){for(;e===ya;)ya=Ks[--Di],Ks[Di]=null,wr=Ks[--Di],Ks[Di]=null;for(;e===Qs;)Qs=zn[--In],zn[In]=null,Xt=zn[--In],zn[In]=null,Ya=zn[--In],zn[In]=null}function wu(e,t){zn[In++]=Ya,zn[In++]=Xt,zn[In++]=Qs,Ya=t.id,Xt=t.overflow,Qs=e}var wn=null,_t=null,xt=!1,Xs=null,Ma=!1,Jo=Error(l(519));function hs(e){var t=Error(l(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw Ns(Wn(t,e)),Jo}function Wl(e){var t=e.stateNode,i=e.type,o=e.memoizedProps;switch(t[te]=e,t[Me]=o,i){case"dialog":St("cancel",t),St("close",t);break;case"iframe":case"object":case"embed":St("load",t);break;case"video":case"audio":for(i=0;i<Ac.length;i++)St(Ac[i],t);break;case"source":St("error",t);break;case"img":case"image":case"link":St("error",t),St("load",t);break;case"details":St("toggle",t);break;case"input":St("invalid",t),Is(t,o.value,o.defaultValue,o.checked,o.defaultChecked,o.type,o.name,!0);break;case"select":St("invalid",t);break;case"textarea":St("invalid",t),rr(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||kv(t.textContent,i)?(o.popover!=null&&(St("beforetoggle",t),St("toggle",t)),o.onScroll!=null&&St("scroll",t),o.onScrollEnd!=null&&St("scrollend",t),o.onClick!=null&&(t.onclick=Ga),t=!0):t=!1,t||hs(e,!0)}function Sr(e){for(wn=e.return;wn;)switch(wn.tag){case 5:case 31:case 13:Ma=!1;return;case 27:case 3:Ma=!0;return;default:wn=wn.return}}function _i(e){if(e!==wn)return!1;if(!xt)return Sr(e),xt=!0,!1;var t=e.tag,i;if((i=t!==3&&t!==27)&&((i=t===5)&&(i=e.type,i=!(i!=="form"&&i!=="button")||Nm(e.type,e.memoizedProps)),i=!i),i&&_t&&hs(e),Sr(e),t===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(l(317));_t=_v(e)}else if(t===31){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(l(317));_t=_v(e)}else t===27?(t=_t,zr(e.type)?(e=Dm,Dm=null,_t=e):_t=t):_t=wn?vs(e.stateNode.nextSibling):null;return!0}function As(){_t=wn=null,xt=!1}function ec(){var e=Xs;return e!==null&&(_a===null?_a=e:_a.push.apply(_a,e),Xs=null),e}function Ns(e){Xs===null?Xs=[e]:Xs.push(e)}var tc=we(null),zi=null,Ta=null;function Zs(e,t,i){$(tc,t._currentValue),t._currentValue=i}function ps(e){e._currentValue=tc.current,Q(tc)}function Yl(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 Kl(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 E=h;h=f;for(var U=0;U<t.length;U++)if(E.context===t[U]){h.lanes|=i,E=h.alternate,E!==null&&(E.lanes|=i),Yl(h.return,i,e),o||(S=null);break e}h=E.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),Yl(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 Cr(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 E=f.type;ln(f.pendingProps.value,S.value)||(e!==null?e.push(E):e=[E])}}else if(f===Se.current){if(S=f.alternate,S===null)throw Error(l(387));S.memoizedState.memoizedState!==f.memoizedState.memoizedState&&(e!==null?e.push(Rc):e=[Rc])}f=f.return}e!==null&&Kl(t,e,i,o),t.flags|=262144}function Ii(e){for(e=e.firstContext;e!==null;){if(!ln(e.context._currentValue,e.memoizedValue))return!0;e=e.next}return!1}function la(e){zi=e,Ta=null,e=e.dependencies,e!==null&&(e.firstContext=null)}function gn(e){return Xl(zi,e)}function Ql(e,t){return zi===null&&la(e),Xl(e,t)}function Xl(e,t){var i=t._currentValue;if(t={context:t,memoizedValue:i,next:null},Ta===null){if(e===null)throw Error(l(308));Ta=t,e.dependencies={lanes:0,firstContext:t},e.flags|=524288}else Ta=Ta.next=t;return i}var nc=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()})}},Ee=n.unstable_scheduleCallback,Zl=n.unstable_NormalPriority,fn={$$typeof:R,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function ac(){return{controller:new nc,data:new Map,refCount:0}}function Jl(e){e.refCount--,e.refCount===0&&Ee(Zl,function(){e.controller.abort()})}var Oi=null,jr=0,on=0,Nn=null;function bt(e,t){if(Oi===null){var i=Oi=[];jr=0,on=ym(),Nn={status:"pending",value:void 0,then:function(o){i.push(o)}}}return jr++,t.then(Su,Su),t}function Su(){if(--jr===0&&Oi!==null){Nn!==null&&(Nn.status="fulfilled");var e=Oi;Oi=null,on=0,Nn=null;for(var t=0;t<e.length;t++)(0,e[t])()}}function kr(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 sc=I.S;I.S=function(e,t){Kg=Je(),typeof t=="object"&&t!==null&&typeof t.then=="function"&&bt(e,t),sc!==null&&sc(e,t)};var Ms=we(null);function ic(){var e=Ms.current;return e!==null?e:Yt.pooledCache}function eo(e,t){t===null?$(Ms,Ms.current):$(Ms,t.pool)}function rc(){var e=ic();return e===null?null:{parent:fn._currentValue,pool:e}}var Js=Error(l(460)),lc=Error(l(474)),to=Error(l(542)),Mn={then:function(){}};function fl(e){return e=e.status,e==="fulfilled"||e==="rejected"}function oc(e,t,i){switch(i=e[i],i===void 0?e.push(t):i!==t&&(t.then(Ga,Ga),t=i),t.status){case"fulfilled":return t.value;case"rejected":throw e=t.reason,ju(e),e;default:if(typeof t.status=="string")t.then(Ga,Ga);else{if(e=Yt,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,ju(e),e}throw Ar=t,Js}}function Hi(e){try{var t=e._init;return t(e._payload)}catch(i){throw i!==null&&typeof i=="object"&&typeof i.then=="function"?(Ar=i,Js):i}}var Ar=null;function Cu(){if(Ar===null)throw Error(l(459));var e=Ar;return Ar=null,e}function ju(e){if(e===Js||e===to)throw Error(l(483))}var Bi=null,ei=0;function ti(e){var t=ei;return ei+=1,Bi===null&&(Bi=[]),oc(Bi,e,t)}function Nr(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 ku(e){function t(Z,Y){if(e){var se=Z.deletions;se===null?(Z.deletions=[Y],Z.flags|=16):se.push(Y)}}function i(Z,Y){if(!e)return null;for(;Y!==null;)t(Z,Y),Y=Y.sibling;return null}function o(Z){for(var Y=new Map;Z!==null;)Z.key!==null?Y.set(Z.key,Z):Y.set(Z.index,Z),Z=Z.sibling;return Y}function f(Z,Y){return Z=Na(Z,Y),Z.index=0,Z.sibling=null,Z}function h(Z,Y,se){return Z.index=se,e?(se=Z.alternate,se!==null?(se=se.index,se<Y?(Z.flags|=67108866,Y):se):(Z.flags|=67108866,Y)):(Z.flags|=1048576,Y)}function S(Z){return e&&Z.alternate===null&&(Z.flags|=67108866),Z}function E(Z,Y,se,Ce){return Y===null||Y.tag!==6?(Y=Ws(se,Z.mode,Ce),Y.return=Z,Y):(Y=f(Y,se),Y.return=Z,Y)}function U(Z,Y,se,Ce){var tt=se.type;return tt===k?xe(Z,Y,se.props.children,Ce,se.key):Y!==null&&(Y.elementType===tt||typeof tt=="object"&&tt!==null&&tt.$$typeof===L&&Hi(tt)===Y.type)?(Y=f(Y,se.props),Nr(Y,se),Y.return=Z,Y):(Y=Vs(se.type,se.key,se.props,null,Z.mode,Ce),Nr(Y,se),Y.return=Z,Y)}function ie(Z,Y,se,Ce){return Y===null||Y.tag!==4||Y.stateNode.containerInfo!==se.containerInfo||Y.stateNode.implementation!==se.implementation?(Y=Vl(se,Z.mode,Ce),Y.return=Z,Y):(Y=f(Y,se.children||[]),Y.return=Z,Y)}function xe(Z,Y,se,Ce,tt){return Y===null||Y.tag!==7?(Y=fs(se,Z.mode,Ce,tt),Y.return=Z,Y):(Y=f(Y,se),Y.return=Z,Y)}function je(Z,Y,se){if(typeof Y=="string"&&Y!==""||typeof Y=="number"||typeof Y=="bigint")return Y=Ws(""+Y,Z.mode,se),Y.return=Z,Y;if(typeof Y=="object"&&Y!==null){switch(Y.$$typeof){case j:return se=Vs(Y.type,Y.key,Y.props,null,Z.mode,se),Nr(se,Y),se.return=Z,se;case C:return Y=Vl(Y,Z.mode,se),Y.return=Z,Y;case L:return Y=Hi(Y),je(Z,Y,se)}if(K(Y)||O(Y))return Y=fs(Y,Z.mode,se,null),Y.return=Z,Y;if(typeof Y.then=="function")return je(Z,ti(Y),se);if(Y.$$typeof===R)return je(Z,Ql(Z,Y),se);no(Z,Y)}return null}function le(Z,Y,se,Ce){var tt=Y!==null?Y.key:null;if(typeof se=="string"&&se!==""||typeof se=="number"||typeof se=="bigint")return tt!==null?null:E(Z,Y,""+se,Ce);if(typeof se=="object"&&se!==null){switch(se.$$typeof){case j:return se.key===tt?U(Z,Y,se,Ce):null;case C:return se.key===tt?ie(Z,Y,se,Ce):null;case L:return se=Hi(se),le(Z,Y,se,Ce)}if(K(se)||O(se))return tt!==null?null:xe(Z,Y,se,Ce,null);if(typeof se.then=="function")return le(Z,Y,ti(se),Ce);if(se.$$typeof===R)return le(Z,Y,Ql(Z,se),Ce);no(Z,se)}return null}function pe(Z,Y,se,Ce,tt){if(typeof Ce=="string"&&Ce!==""||typeof Ce=="number"||typeof Ce=="bigint")return Z=Z.get(se)||null,E(Y,Z,""+Ce,tt);if(typeof Ce=="object"&&Ce!==null){switch(Ce.$$typeof){case j:return Z=Z.get(Ce.key===null?se:Ce.key)||null,U(Y,Z,Ce,tt);case C:return Z=Z.get(Ce.key===null?se:Ce.key)||null,ie(Y,Z,Ce,tt);case L:return Ce=Hi(Ce),pe(Z,Y,se,Ce,tt)}if(K(Ce)||O(Ce))return Z=Z.get(se)||null,xe(Y,Z,Ce,tt,null);if(typeof Ce.then=="function")return pe(Z,Y,se,ti(Ce),tt);if(Ce.$$typeof===R)return pe(Z,Y,se,Ql(Y,Ce),tt);no(Y,Ce)}return null}function Ye(Z,Y,se,Ce){for(var tt=null,Et=null,Qe=Y,pt=Y=0,jt=null;Qe!==null&&pt<se.length;pt++){Qe.index>pt?(jt=Qe,Qe=null):jt=Qe.sibling;var Rt=le(Z,Qe,se[pt],Ce);if(Rt===null){Qe===null&&(Qe=jt);break}e&&Qe&&Rt.alternate===null&&t(Z,Qe),Y=h(Rt,Y,pt),Et===null?tt=Rt:Et.sibling=Rt,Et=Rt,Qe=jt}if(pt===se.length)return i(Z,Qe),xt&&ms(Z,pt),tt;if(Qe===null){for(;pt<se.length;pt++)Qe=je(Z,se[pt],Ce),Qe!==null&&(Y=h(Qe,Y,pt),Et===null?tt=Qe:Et.sibling=Qe,Et=Qe);return xt&&ms(Z,pt),tt}for(Qe=o(Qe);pt<se.length;pt++)jt=pe(Qe,Z,pt,se[pt],Ce),jt!==null&&(e&&jt.alternate!==null&&Qe.delete(jt.key===null?pt:jt.key),Y=h(jt,Y,pt),Et===null?tt=jt:Et.sibling=jt,Et=jt);return e&&Qe.forEach(function(Fr){return t(Z,Fr)}),xt&&ms(Z,pt),tt}function st(Z,Y,se,Ce){if(se==null)throw Error(l(151));for(var tt=null,Et=null,Qe=Y,pt=Y=0,jt=null,Rt=se.next();Qe!==null&&!Rt.done;pt++,Rt=se.next()){Qe.index>pt?(jt=Qe,Qe=null):jt=Qe.sibling;var Fr=le(Z,Qe,Rt.value,Ce);if(Fr===null){Qe===null&&(Qe=jt);break}e&&Qe&&Fr.alternate===null&&t(Z,Qe),Y=h(Fr,Y,pt),Et===null?tt=Fr:Et.sibling=Fr,Et=Fr,Qe=jt}if(Rt.done)return i(Z,Qe),xt&&ms(Z,pt),tt;if(Qe===null){for(;!Rt.done;pt++,Rt=se.next())Rt=je(Z,Rt.value,Ce),Rt!==null&&(Y=h(Rt,Y,pt),Et===null?tt=Rt:Et.sibling=Rt,Et=Rt);return xt&&ms(Z,pt),tt}for(Qe=o(Qe);!Rt.done;pt++,Rt=se.next())Rt=pe(Qe,Z,pt,Rt.value,Ce),Rt!==null&&(e&&Rt.alternate!==null&&Qe.delete(Rt.key===null?pt:Rt.key),Y=h(Rt,Y,pt),Et===null?tt=Rt:Et.sibling=Rt,Et=Rt);return e&&Qe.forEach(function(_S){return t(Z,_S)}),xt&&ms(Z,pt),tt}function Ut(Z,Y,se,Ce){if(typeof se=="object"&&se!==null&&se.type===k&&se.key===null&&(se=se.props.children),typeof se=="object"&&se!==null){switch(se.$$typeof){case j:e:{for(var tt=se.key;Y!==null;){if(Y.key===tt){if(tt=se.type,tt===k){if(Y.tag===7){i(Z,Y.sibling),Ce=f(Y,se.props.children),Ce.return=Z,Z=Ce;break e}}else if(Y.elementType===tt||typeof tt=="object"&&tt!==null&&tt.$$typeof===L&&Hi(tt)===Y.type){i(Z,Y.sibling),Ce=f(Y,se.props),Nr(Ce,se),Ce.return=Z,Z=Ce;break e}i(Z,Y);break}else t(Z,Y);Y=Y.sibling}se.type===k?(Ce=fs(se.props.children,Z.mode,Ce,se.key),Ce.return=Z,Z=Ce):(Ce=Vs(se.type,se.key,se.props,null,Z.mode,Ce),Nr(Ce,se),Ce.return=Z,Z=Ce)}return S(Z);case C:e:{for(tt=se.key;Y!==null;){if(Y.key===tt)if(Y.tag===4&&Y.stateNode.containerInfo===se.containerInfo&&Y.stateNode.implementation===se.implementation){i(Z,Y.sibling),Ce=f(Y,se.children||[]),Ce.return=Z,Z=Ce;break e}else{i(Z,Y);break}else t(Z,Y);Y=Y.sibling}Ce=Vl(se,Z.mode,Ce),Ce.return=Z,Z=Ce}return S(Z);case L:return se=Hi(se),Ut(Z,Y,se,Ce)}if(K(se))return Ye(Z,Y,se,Ce);if(O(se)){if(tt=O(se),typeof tt!="function")throw Error(l(150));return se=tt.call(se),st(Z,Y,se,Ce)}if(typeof se.then=="function")return Ut(Z,Y,ti(se),Ce);if(se.$$typeof===R)return Ut(Z,Y,Ql(Z,se),Ce);no(Z,se)}return typeof se=="string"&&se!==""||typeof se=="number"||typeof se=="bigint"?(se=""+se,Y!==null&&Y.tag===6?(i(Z,Y.sibling),Ce=f(Y,se),Ce.return=Z,Z=Ce):(i(Z,Y),Ce=Ws(se,Z.mode,Ce),Ce.return=Z,Z=Ce),S(Z)):i(Z,Y)}return function(Z,Y,se,Ce){try{ei=0;var tt=Ut(Z,Y,se,Ce);return Bi=null,tt}catch(Qe){if(Qe===Js||Qe===to)throw Qe;var Et=Vn(29,Qe,null,Z.mode);return Et.lanes=Ce,Et.return=Z,Et}}}var Fi=ku(!0),Au=ku(!1),ni=!1;function cc(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function uc(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 Sn(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function ai(e,t,i){var o=e.updateQueue;if(o===null)return null;if(o=o.shared,(zt&2)!==0){var f=o.pending;return f===null?t.next=t:(t.next=f.next,f.next=t),o.pending=t,t=Ti(e),bu(e,null,i),t}return br(e,o,t,i),Ti(e)}function ml(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,H(e,i)}}function si(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 dc=!1;function Pi(){if(dc){var e=Nn;if(e!==null)throw e}}function gs(e,t,i,o){dc=!1;var f=e.updateQueue;ni=!1;var h=f.firstBaseUpdate,S=f.lastBaseUpdate,E=f.shared.pending;if(E!==null){f.shared.pending=null;var U=E,ie=U.next;U.next=null,S===null?h=ie:S.next=ie,S=U;var xe=e.alternate;xe!==null&&(xe=xe.updateQueue,E=xe.lastBaseUpdate,E!==S&&(E===null?xe.firstBaseUpdate=ie:E.next=ie,xe.lastBaseUpdate=U))}if(h!==null){var je=f.baseState;S=0,xe=ie=U=null,E=h;do{var le=E.lane&-536870913,pe=le!==E.lane;if(pe?(Ct&le)===le:(o&le)===le){le!==0&&le===on&&(dc=!0),xe!==null&&(xe=xe.next={lane:0,tag:E.tag,payload:E.payload,callback:null,next:null});e:{var Ye=e,st=E;le=t;var Ut=i;switch(st.tag){case 1:if(Ye=st.payload,typeof Ye=="function"){je=Ye.call(Ut,je,le);break e}je=Ye;break e;case 3:Ye.flags=Ye.flags&-65537|128;case 0:if(Ye=st.payload,le=typeof Ye=="function"?Ye.call(Ut,je,le):Ye,le==null)break e;je=x({},je,le);break e;case 2:ni=!0}}le=E.callback,le!==null&&(e.flags|=64,pe&&(e.flags|=8192),pe=f.callbacks,pe===null?f.callbacks=[le]:pe.push(le))}else pe={lane:le,tag:E.tag,payload:E.payload,callback:E.callback,next:null},xe===null?(ie=xe=pe,U=je):xe=xe.next=pe,S|=le;if(E=E.next,E===null){if(E=f.shared.pending,E===null)break;pe=E,E=pe.next,pe.next=null,f.lastBaseUpdate=pe,f.shared.pending=null}}while(!0);xe===null&&(U=je),f.baseState=U,f.firstBaseUpdate=ie,f.lastBaseUpdate=xe,h===null&&(f.shared.lanes=0),Er|=S,e.lanes=S,e.memoizedState=je}}function Nu(e,t){if(typeof e!="function")throw Error(l(191,e));e.call(t)}function ii(e,t){var i=e.callbacks;if(i!==null)for(e.callbacks=null,e=0;e<i.length;e++)Nu(i[e],t)}var ri=we(null),y=we(0);function N(e,t){e=Ki,$(y,e),$(ri,t),Ki=e|t.baseLanes}function z(){$(y,Ki),$(ri,ri.current)}function B(){Ki=y.current,Q(ri),Q(y)}var D=we(null),ue=null;function de(e){var t=e.alternate;$(yt,yt.current&1),$(D,e),ue===null&&(t===null||ri.current!==null||t.memoizedState!==null)&&(ue=e)}function Ie(e){$(yt,yt.current),$(D,e),ue===null&&(ue=e)}function qe(e){e.tag===22?($(yt,yt.current),$(D,e),ue===null&&(ue=e)):Ve()}function Ve(){$(yt,yt.current),$(D,D.current)}function At(e){Q(D),ue===e&&(ue=null),Q(yt)}var yt=we(0);function Yn(e){for(var t=e;t!==null;){if(t.tag===13){var i=t.memoizedState;if(i!==null&&(i=i.dehydrated,i===null||Em(i)||Rm(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 Ea=0,rt=null,Tt=null,tn=null,ao=!1,so=!1,hl=!1,Mu=0,fc=0,io=null,jw=0;function vn(){throw Error(l(321))}function kf(e,t){if(t===null)return!1;for(var i=0;i<t.length&&i<e.length;i++)if(!ln(e[i],t[i]))return!1;return!0}function Af(e,t,i,o,f,h){return Ea=h,rt=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,I.H=e===null||e.memoizedState===null?rg:Pf,hl=!1,h=i(o,f),hl=!1,so&&(h=kp(t,i,o,f)),jp(e),h}function jp(e){I.H=pc;var t=Tt!==null&&Tt.next!==null;if(Ea=0,tn=Tt=rt=null,ao=!1,fc=0,io=null,t)throw Error(l(300));e===null||Tn||(e=e.dependencies,e!==null&&Ii(e)&&(Tn=!0))}function kp(e,t,i,o){rt=e;var f=0;do{if(so&&(io=null),fc=0,so=!1,25<=f)throw Error(l(301));if(f+=1,tn=Tt=null,e.updateQueue!=null){var h=e.updateQueue;h.lastEffect=null,h.events=null,h.stores=null,h.memoCache!=null&&(h.memoCache.index=0)}I.H=lg,h=t(i,o)}while(so);return h}function kw(){var e=I.H,t=e.useState()[0];return t=typeof t.then=="function"?mc(t):t,e=e.useState()[0],(Tt!==null?Tt.memoizedState:null)!==e&&(rt.flags|=1024),t}function Nf(){var e=Mu!==0;return Mu=0,e}function Mf(e,t,i){t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i}function Tf(e){if(ao){for(e=e.memoizedState;e!==null;){var t=e.queue;t!==null&&(t.pending=null),e=e.next}ao=!1}Ea=0,tn=Tt=rt=null,so=!1,fc=Mu=0,io=null}function xa(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return tn===null?rt.memoizedState=tn=e:tn=tn.next=e,tn}function Cn(){if(Tt===null){var e=rt.alternate;e=e!==null?e.memoizedState:null}else e=Tt.next;var t=tn===null?rt.memoizedState:tn.next;if(t!==null)tn=t,Tt=e;else{if(e===null)throw rt.alternate===null?Error(l(467)):Error(l(310));Tt=e,e={memoizedState:Tt.memoizedState,baseState:Tt.baseState,baseQueue:Tt.baseQueue,queue:Tt.queue,next:null},tn===null?rt.memoizedState=tn=e:tn=tn.next=e}return tn}function Tu(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function mc(e){var t=fc;return fc+=1,io===null&&(io=[]),e=oc(io,e,t),t=rt,(tn===null?t.memoizedState:tn.next)===null&&(t=t.alternate,I.H=t===null||t.memoizedState===null?rg:Pf),e}function Eu(e){if(e!==null&&typeof e=="object"){if(typeof e.then=="function")return mc(e);if(e.$$typeof===R)return gn(e)}throw Error(l(438,String(e)))}function Ef(e){var t=null,i=rt.updateQueue;if(i!==null&&(t=i.memoCache),t==null){var o=rt.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=Tu(),rt.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]=W;return t.index++,i}function $i(e,t){return typeof t=="function"?t(e):t}function Ru(e){var t=Cn();return Rf(t,Tt,e)}function Rf(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 E=S=null,U=null,ie=t,xe=!1;do{var je=ie.lane&-536870913;if(je!==ie.lane?(Ct&je)===je:(Ea&je)===je){var le=ie.revertLane;if(le===0)U!==null&&(U=U.next={lane:0,revertLane:0,gesture:null,action:ie.action,hasEagerState:ie.hasEagerState,eagerState:ie.eagerState,next:null}),je===on&&(xe=!0);else if((Ea&le)===le){ie=ie.next,le===on&&(xe=!0);continue}else je={lane:0,revertLane:ie.revertLane,gesture:null,action:ie.action,hasEagerState:ie.hasEagerState,eagerState:ie.eagerState,next:null},U===null?(E=U=je,S=h):U=U.next=je,rt.lanes|=le,Er|=le;je=ie.action,hl&&i(h,je),h=ie.hasEagerState?ie.eagerState:i(h,je)}else le={lane:je,revertLane:ie.revertLane,gesture:ie.gesture,action:ie.action,hasEagerState:ie.hasEagerState,eagerState:ie.eagerState,next:null},U===null?(E=U=le,S=h):U=U.next=le,rt.lanes|=je,Er|=je;ie=ie.next}while(ie!==null&&ie!==t);if(U===null?S=h:U.next=E,!ln(h,e.memoizedState)&&(Tn=!0,xe&&(i=Nn,i!==null)))throw i;e.memoizedState=h,e.baseState=S,e.baseQueue=U,o.lastRenderedState=h}return f===null&&(o.lanes=0),[e.memoizedState,o.dispatch]}function Df(e){var t=Cn(),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);ln(h,t.memoizedState)||(Tn=!0),t.memoizedState=h,t.baseQueue===null&&(t.baseState=h),i.lastRenderedState=h}return[h,o]}function Ap(e,t,i){var o=rt,f=Cn(),h=xt;if(h){if(i===void 0)throw Error(l(407));i=i()}else i=t();var S=!ln((Tt||f).memoizedState,i);if(S&&(f.memoizedState=i,Tn=!0),f=f.queue,zf(Tp.bind(null,o,f,e),[e]),f.getSnapshot!==t||S||tn!==null&&tn.memoizedState.tag&1){if(o.flags|=2048,ro(9,{destroy:void 0},Mp.bind(null,o,f,i,t),null),Yt===null)throw Error(l(349));h||(Ea&127)!==0||Np(o,t,i)}return i}function Np(e,t,i){e.flags|=16384,e={getSnapshot:t,value:i},t=rt.updateQueue,t===null?(t=Tu(),rt.updateQueue=t,t.stores=[e]):(i=t.stores,i===null?t.stores=[e]:i.push(e))}function Mp(e,t,i,o){t.value=i,t.getSnapshot=o,Ep(t)&&Rp(e)}function Tp(e,t,i){return i(function(){Ep(t)&&Rp(e)})}function Ep(e){var t=e.getSnapshot;e=e.value;try{var i=t();return!ln(e,i)}catch{return!0}}function Rp(e){var t=Wa(e,2);t!==null&&za(t,e,2)}function Lf(e){var t=xa();if(typeof e=="function"){var i=e;if(e=i(),hl){et(!0);try{i()}finally{et(!1)}}}return t.memoizedState=t.baseState=e,t.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:$i,lastRenderedState:e},t}function Dp(e,t,i,o){return e.baseState=i,Rf(e,Tt,typeof o=="function"?o:$i)}function Aw(e,t,i,o,f){if(_u(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)}};I.T!==null?i(!0):h.isTransition=!1,o(h),i=t.pending,i===null?(h.next=t.pending=h,Lp(t,h)):(h.next=i.next,t.pending=i.next=h)}}function Lp(e,t){var i=t.action,o=t.payload,f=e.state;if(t.isTransition){var h=I.T,S={};I.T=S;try{var E=i(f,o),U=I.S;U!==null&&U(S,E),_p(e,t,E)}catch(ie){_f(e,t,ie)}finally{h!==null&&S.types!==null&&(h.types=S.types),I.T=h}}else try{h=i(f,o),_p(e,t,h)}catch(ie){_f(e,t,ie)}}function _p(e,t,i){i!==null&&typeof i=="object"&&typeof i.then=="function"?i.then(function(o){zp(e,t,o)},function(o){return _f(e,t,o)}):zp(e,t,i)}function zp(e,t,i){t.status="fulfilled",t.value=i,Ip(t),e.state=i,t=e.pending,t!==null&&(i=t.next,i===t?e.pending=null:(i=i.next,t.next=i,Lp(e,i)))}function _f(e,t,i){var o=e.pending;if(e.pending=null,o!==null){o=o.next;do t.status="rejected",t.reason=i,Ip(t),t=t.next;while(t!==o)}e.action=null}function Ip(e){e=e.listeners;for(var t=0;t<e.length;t++)(0,e[t])()}function Op(e,t){return t}function Hp(e,t){if(xt){var i=Yt.formState;if(i!==null){e:{var o=rt;if(xt){if(_t){t:{for(var f=_t,h=Ma;f.nodeType!==8;){if(!h){f=null;break t}if(f=vs(f.nextSibling),f===null){f=null;break t}}h=f.data,f=h==="F!"||h==="F"?f:null}if(f){_t=vs(f.nextSibling),o=f.data==="F!";break e}}hs(o)}o=!1}o&&(t=i[0])}}return i=xa(),i.memoizedState=i.baseState=t,o={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Op,lastRenderedState:t},i.queue=o,i=ag.bind(null,rt,o),o.dispatch=i,o=Lf(!1),h=Ff.bind(null,rt,!1,o.queue),o=xa(),f={state:t,dispatch:null,action:e,pending:null},o.queue=f,i=Aw.bind(null,rt,f,h,i),f.dispatch=i,o.memoizedState=e,[t,i,!1]}function Bp(e){var t=Cn();return Fp(t,Tt,e)}function Fp(e,t,i){if(t=Rf(e,t,Op)[0],e=Ru($i)[0],typeof t=="object"&&t!==null&&typeof t.then=="function")try{var o=mc(t)}catch(S){throw S===Js?to:S}else o=t;t=Cn();var f=t.queue,h=f.dispatch;return i!==t.memoizedState&&(rt.flags|=2048,ro(9,{destroy:void 0},Nw.bind(null,f,i),null)),[o,h,e]}function Nw(e,t){e.action=t}function Pp(e){var t=Cn(),i=Tt;if(i!==null)return Fp(t,i,e);Cn(),t=t.memoizedState,i=Cn();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=rt.updateQueue,t===null&&(t=Tu(),rt.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 $p(){return Cn().memoizedState}function Du(e,t,i,o){var f=xa();rt.flags|=e,f.memoizedState=ro(1|t,{destroy:void 0},i,o===void 0?null:o)}function Lu(e,t,i,o){var f=Cn();o=o===void 0?null:o;var h=f.memoizedState.inst;Tt!==null&&o!==null&&kf(o,Tt.memoizedState.deps)?f.memoizedState=ro(t,h,i,o):(rt.flags|=e,f.memoizedState=ro(1|t,h,i,o))}function Up(e,t){Du(8390656,8,e,t)}function zf(e,t){Lu(2048,8,e,t)}function Mw(e){rt.flags|=4;var t=rt.updateQueue;if(t===null)t=Tu(),rt.updateQueue=t,t.events=[e];else{var i=t.events;i===null?t.events=[e]:i.push(e)}}function qp(e){var t=Cn().memoizedState;return Mw({ref:t,nextImpl:e}),function(){if((zt&2)!==0)throw Error(l(440));return t.impl.apply(void 0,arguments)}}function Gp(e,t){return Lu(4,2,e,t)}function Vp(e,t){return Lu(4,4,e,t)}function Wp(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 Yp(e,t,i){i=i!=null?i.concat([e]):null,Lu(4,4,Wp.bind(null,t,e),i)}function If(){}function Kp(e,t){var i=Cn();t=t===void 0?null:t;var o=i.memoizedState;return t!==null&&kf(t,o[1])?o[0]:(i.memoizedState=[e,t],e)}function Qp(e,t){var i=Cn();t=t===void 0?null:t;var o=i.memoizedState;if(t!==null&&kf(t,o[1]))return o[0];if(o=e(),hl){et(!0);try{e()}finally{et(!1)}}return i.memoizedState=[o,t],o}function Of(e,t,i){return i===void 0||(Ea&1073741824)!==0&&(Ct&261930)===0?e.memoizedState=t:(e.memoizedState=i,e=Xg(),rt.lanes|=e,Er|=e,i)}function Xp(e,t,i,o){return ln(i,t)?i:ri.current!==null?(e=Of(e,i,o),ln(e,t)||(Tn=!0),e):(Ea&42)===0||(Ea&1073741824)!==0&&(Ct&261930)===0?(Tn=!0,e.memoizedState=i):(e=Xg(),rt.lanes|=e,Er|=e,t)}function Zp(e,t,i,o,f){var h=ee.p;ee.p=h!==0&&8>h?h:8;var S=I.T,E={};I.T=E,Ff(e,!1,t,i);try{var U=f(),ie=I.S;if(ie!==null&&ie(E,U),U!==null&&typeof U=="object"&&typeof U.then=="function"){var xe=kr(U,o);hc(e,t,xe,Xa(e))}else hc(e,t,o,Xa(e))}catch(je){hc(e,t,{then:function(){},status:"rejected",reason:je},Xa())}finally{ee.p=h,S!==null&&E.types!==null&&(S.types=E.types),I.T=S}}function Tw(){}function Hf(e,t,i,o){if(e.tag!==5)throw Error(l(476));var f=Jp(e).queue;Zp(e,f,t,G,i===null?Tw:function(){return eg(e),i(o)})}function Jp(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:G,baseState:G,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:$i,lastRenderedState:G},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 eg(e){var t=Jp(e);t.next===null&&(t=e.alternate.memoizedState),hc(e,t.next.queue,{},Xa())}function Bf(){return gn(Rc)}function tg(){return Cn().memoizedState}function ng(){return Cn().memoizedState}function Ew(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var i=Xa();e=Sn(i);var o=ai(t,e,i);o!==null&&(za(o,t,i),ml(o,t,i)),t={cache:ac()},e.payload=t;return}t=t.return}}function Rw(e,t,i){var o=Xa();i={lane:o,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null},_u(e)?sg(t,i):(i=ll(e,t,i,o),i!==null&&(za(i,e,o),ig(i,t,o)))}function ag(e,t,i){var o=Xa();hc(e,t,i,o)}function hc(e,t,i,o){var f={lane:o,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null};if(_u(e))sg(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,E=h(S,i);if(f.hasEagerState=!0,f.eagerState=E,ln(E,S))return br(e,t,f,0),Yt===null&&rl(),!1}catch{}if(i=ll(e,t,f,o),i!==null)return za(i,e,o),ig(i,t,o),!0}return!1}function Ff(e,t,i,o){if(o={lane:2,revertLane:ym(),gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null},_u(e)){if(t)throw Error(l(479))}else t=ll(e,i,o,2),t!==null&&za(t,e,2)}function _u(e){var t=e.alternate;return e===rt||t!==null&&t===rt}function sg(e,t){so=ao=!0;var i=e.pending;i===null?t.next=t:(t.next=i.next,i.next=t),e.pending=t}function ig(e,t,i){if((i&4194048)!==0){var o=t.lanes;o&=e.pendingLanes,i|=o,t.lanes=i,H(e,i)}}var pc={readContext:gn,use:Eu,useCallback:vn,useContext:vn,useEffect:vn,useImperativeHandle:vn,useLayoutEffect:vn,useInsertionEffect:vn,useMemo:vn,useReducer:vn,useRef:vn,useState:vn,useDebugValue:vn,useDeferredValue:vn,useTransition:vn,useSyncExternalStore:vn,useId:vn,useHostTransitionStatus:vn,useFormState:vn,useActionState:vn,useOptimistic:vn,useMemoCache:vn,useCacheRefresh:vn};pc.useEffectEvent=vn;var rg={readContext:gn,use:Eu,useCallback:function(e,t){return xa().memoizedState=[e,t===void 0?null:t],e},useContext:gn,useEffect:Up,useImperativeHandle:function(e,t,i){i=i!=null?i.concat([e]):null,Du(4194308,4,Wp.bind(null,t,e),i)},useLayoutEffect:function(e,t){return Du(4194308,4,e,t)},useInsertionEffect:function(e,t){Du(4,2,e,t)},useMemo:function(e,t){var i=xa();t=t===void 0?null:t;var o=e();if(hl){et(!0);try{e()}finally{et(!1)}}return i.memoizedState=[o,t],o},useReducer:function(e,t,i){var o=xa();if(i!==void 0){var f=i(t);if(hl){et(!0);try{i(t)}finally{et(!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=Rw.bind(null,rt,e),[o.memoizedState,e]},useRef:function(e){var t=xa();return e={current:e},t.memoizedState=e},useState:function(e){e=Lf(e);var t=e.queue,i=ag.bind(null,rt,t);return t.dispatch=i,[e.memoizedState,i]},useDebugValue:If,useDeferredValue:function(e,t){var i=xa();return Of(i,e,t)},useTransition:function(){var e=Lf(!1);return e=Zp.bind(null,rt,e.queue,!0,!1),xa().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,i){var o=rt,f=xa();if(xt){if(i===void 0)throw Error(l(407));i=i()}else{if(i=t(),Yt===null)throw Error(l(349));(Ct&127)!==0||Np(o,t,i)}f.memoizedState=i;var h={value:i,getSnapshot:t};return f.queue=h,Up(Tp.bind(null,o,h,e),[e]),o.flags|=2048,ro(9,{destroy:void 0},Mp.bind(null,o,h,i,t),null),i},useId:function(){var e=xa(),t=Yt.identifierPrefix;if(xt){var i=Xt,o=Ya;i=(o&~(1<<32-gt(o)-1)).toString(32)+i,t="_"+t+"R_"+i,i=Mu++,0<i&&(t+="H"+i.toString(32)),t+="_"}else i=jw++,t="_"+t+"r_"+i.toString(32)+"_";return e.memoizedState=t},useHostTransitionStatus:Bf,useFormState:Hp,useActionState:Hp,useOptimistic:function(e){var t=xa();t.memoizedState=t.baseState=e;var i={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return t.queue=i,t=Ff.bind(null,rt,!0,i),i.dispatch=t,[e,t]},useMemoCache:Ef,useCacheRefresh:function(){return xa().memoizedState=Ew.bind(null,rt)},useEffectEvent:function(e){var t=xa(),i={impl:e};return t.memoizedState=i,function(){if((zt&2)!==0)throw Error(l(440));return i.impl.apply(void 0,arguments)}}},Pf={readContext:gn,use:Eu,useCallback:Kp,useContext:gn,useEffect:zf,useImperativeHandle:Yp,useInsertionEffect:Gp,useLayoutEffect:Vp,useMemo:Qp,useReducer:Ru,useRef:$p,useState:function(){return Ru($i)},useDebugValue:If,useDeferredValue:function(e,t){var i=Cn();return Xp(i,Tt.memoizedState,e,t)},useTransition:function(){var e=Ru($i)[0],t=Cn().memoizedState;return[typeof e=="boolean"?e:mc(e),t]},useSyncExternalStore:Ap,useId:tg,useHostTransitionStatus:Bf,useFormState:Bp,useActionState:Bp,useOptimistic:function(e,t){var i=Cn();return Dp(i,Tt,e,t)},useMemoCache:Ef,useCacheRefresh:ng};Pf.useEffectEvent=qp;var lg={readContext:gn,use:Eu,useCallback:Kp,useContext:gn,useEffect:zf,useImperativeHandle:Yp,useInsertionEffect:Gp,useLayoutEffect:Vp,useMemo:Qp,useReducer:Df,useRef:$p,useState:function(){return Df($i)},useDebugValue:If,useDeferredValue:function(e,t){var i=Cn();return Tt===null?Of(i,e,t):Xp(i,Tt.memoizedState,e,t)},useTransition:function(){var e=Df($i)[0],t=Cn().memoizedState;return[typeof e=="boolean"?e:mc(e),t]},useSyncExternalStore:Ap,useId:tg,useHostTransitionStatus:Bf,useFormState:Pp,useActionState:Pp,useOptimistic:function(e,t){var i=Cn();return Tt!==null?Dp(i,Tt,e,t):(i.baseState=e,[e,i.queue.dispatch])},useMemoCache:Ef,useCacheRefresh:ng};lg.useEffectEvent=qp;function $f(e,t,i,o){t=e.memoizedState,i=i(o,t),i=i==null?t:x({},t,i),e.memoizedState=i,e.lanes===0&&(e.updateQueue.baseState=i)}var Uf={enqueueSetState:function(e,t,i){e=e._reactInternals;var o=Xa(),f=Sn(o);f.payload=t,i!=null&&(f.callback=i),t=ai(e,f,o),t!==null&&(za(t,e,o),ml(t,e,o))},enqueueReplaceState:function(e,t,i){e=e._reactInternals;var o=Xa(),f=Sn(o);f.tag=1,f.payload=t,i!=null&&(f.callback=i),t=ai(e,f,o),t!==null&&(za(t,e,o),ml(t,e,o))},enqueueForceUpdate:function(e,t){e=e._reactInternals;var i=Xa(),o=Sn(i);o.tag=2,t!=null&&(o.callback=t),t=ai(e,o,i),t!==null&&(za(t,e,i),ml(t,e,i))}};function og(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?!$s(i,o)||!$s(f,h):!0}function cg(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&&Uf.enqueueReplaceState(t,t.state,null)}function pl(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=x({},i));for(var f in e)i[f]===void 0&&(i[f]=e[f])}return i}function ug(e){ks(e)}function dg(e){console.error(e)}function fg(e){ks(e)}function zu(e,t){try{var i=e.onUncaughtError;i(t.value,{componentStack:t.stack})}catch(o){setTimeout(function(){throw o})}}function mg(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 qf(e,t,i){return i=Sn(i),i.tag=3,i.payload={element:null},i.callback=function(){zu(e,t)},i}function hg(e){return e=Sn(e),e.tag=3,e}function pg(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(){mg(t,i,o)}}var S=i.stateNode;S!==null&&typeof S.componentDidCatch=="function"&&(e.callback=function(){mg(t,i,o),typeof f!="function"&&(Rr===null?Rr=new Set([this]):Rr.add(this));var E=o.stack;this.componentDidCatch(o.value,{componentStack:E!==null?E:""})})}function Dw(e,t,i,o,f){if(i.flags|=32768,o!==null&&typeof o=="object"&&typeof o.then=="function"){if(t=i.alternate,t!==null&&Cr(t,i,f,!0),i=D.current,i!==null){switch(i.tag){case 31:case 13:return ue===null?Wu():i.alternate===null&&yn===0&&(yn=3),i.flags&=-257,i.flags|=65536,i.lanes=f,o===Mn?i.flags|=16384:(t=i.updateQueue,t===null?i.updateQueue=new Set([o]):t.add(o),pm(e,o,f)),!1;case 22:return i.flags|=65536,o===Mn?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)),pm(e,o,f)),!1}throw Error(l(435,i.tag))}return pm(e,o,f),Wu(),!1}if(xt)return t=D.current,t!==null?((t.flags&65536)===0&&(t.flags|=256),t.flags|=65536,t.lanes=f,o!==Jo&&(e=Error(l(422),{cause:o}),Ns(Wn(e,i)))):(o!==Jo&&(t=Error(l(423),{cause:o}),Ns(Wn(t,i))),e=e.current.alternate,e.flags|=65536,f&=-f,e.lanes|=f,o=Wn(o,i),f=qf(e.stateNode,o,f),si(e,f),yn!==4&&(yn=2)),!1;var h=Error(l(520),{cause:o});if(h=Wn(h,i),Cc===null?Cc=[h]:Cc.push(h),yn!==4&&(yn=2),t===null)return!0;o=Wn(o,i),i=t;do{switch(i.tag){case 3:return i.flags|=65536,e=f&-f,i.lanes|=e,e=qf(i.stateNode,o,e),si(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"&&(Rr===null||!Rr.has(h))))return i.flags|=65536,f&=-f,i.lanes|=f,f=hg(f),pg(f,e,i,o),si(i,f),!1}i=i.return}while(i!==null);return!1}var Gf=Error(l(461)),Tn=!1;function Kn(e,t,i,o){t.child=e===null?Au(t,null,i,o):Fi(t,e.child,i,o)}function gg(e,t,i,o,f){i=i.render;var h=t.ref;if("ref"in o){var S={};for(var E in o)E!=="ref"&&(S[E]=o[E])}else S=o;return la(t),o=Af(e,t,i,S,h,f),E=Nf(),e!==null&&!Tn?(Mf(e,t,f),Ui(e,t,f)):(xt&&E&&dl(t),t.flags|=1,Kn(e,t,o,f),t.child)}function vg(e,t,i,o,f){if(e===null){var h=i.type;return typeof h=="function"&&!ol(h)&&h.defaultProps===void 0&&i.compare===null?(t.tag=15,t.type=h,yg(e,t,h,o,f)):(e=Vs(i.type,null,o,t,t.mode,f),e.ref=t.ref,e.return=t,t.child=e)}if(h=e.child,!Jf(e,f)){var S=h.memoizedProps;if(i=i.compare,i=i!==null?i:$s,i(S,o)&&e.ref===t.ref)return Ui(e,t,f)}return t.flags|=1,e=Na(h,o),e.ref=t.ref,e.return=t,t.child=e}function yg(e,t,i,o,f){if(e!==null){var h=e.memoizedProps;if($s(h,o)&&e.ref===t.ref)if(Tn=!1,t.pendingProps=o=h,Jf(e,f))(e.flags&131072)!==0&&(Tn=!0);else return t.lanes=e.lanes,Ui(e,t,f)}return Vf(e,t,i,o,f)}function xg(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 bg(e,t,h,i,o)}if((i&536870912)!==0)t.memoizedState={baseLanes:0,cachePool:null},e!==null&&eo(t,h!==null?h.cachePool:null),h!==null?N(t,h):z(),qe(t);else return o=t.lanes=536870912,bg(e,t,h!==null?h.baseLanes|i:i,i,o)}else h!==null?(eo(t,h.cachePool),N(t,h),Ve(),t.memoizedState=null):(e!==null&&eo(t,null),z(),Ve());return Kn(e,t,f,i),t.child}function gc(e,t){return e!==null&&e.tag===22||t.stateNode!==null||(t.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),t.sibling}function bg(e,t,i,o,f){var h=ic();return h=h===null?null:{parent:fn._currentValue,pool:h},t.memoizedState={baseLanes:i,cachePool:h},e!==null&&eo(t,null),z(),qe(t),e!==null&&Cr(e,t,o,!0),t.childLanes=f,null}function Iu(e,t){return t=Hu({mode:t.mode,children:t.children},e.mode),t.ref=e.ref,e.child=t,t.return=e,t}function wg(e,t,i){return Fi(t,e.child,null,i),e=Iu(t,t.pendingProps),e.flags|=2,At(t),t.memoizedState=null,e}function Lw(e,t,i){var o=t.pendingProps,f=(t.flags&128)!==0;if(t.flags&=-129,e===null){if(xt){if(o.mode==="hidden")return e=Iu(t,o),t.lanes=536870912,gc(null,e);if(Ie(t),(e=_t)?(e=Lv(e,Ma),e=e!==null&&e.data==="&"?e:null,e!==null&&(t.memoizedState={dehydrated:e,treeContext:Qs!==null?{id:Ya,overflow:Xt}:null,retryLane:536870912,hydrationErrors:null},i=Ri(e),i.return=t,t.child=i,wn=t,_t=null)):e=null,e===null)throw hs(t);return t.lanes=536870912,null}return Iu(t,o)}var h=e.memoizedState;if(h!==null){var S=h.dehydrated;if(Ie(t),f)if(t.flags&256)t.flags&=-257,t=wg(e,t,i);else if(t.memoizedState!==null)t.child=e.child,t.flags|=128,t=null;else throw Error(l(558));else if(Tn||Cr(e,t,i,!1),f=(i&e.childLanes)!==0,Tn||f){if(o=Yt,o!==null&&(S=Le(o,i),S!==0&&S!==h.retryLane))throw h.retryLane=S,Wa(e,S),za(o,e,S),Gf;Wu(),t=wg(e,t,i)}else e=h.treeContext,_t=vs(S.nextSibling),wn=t,xt=!0,Xs=null,Ma=!1,e!==null&&wu(t,e),t=Iu(t,o),t.flags|=4096;return t}return e=Na(e.child,{mode:o.mode,children:o.children}),e.ref=t.ref,t.child=e,e.return=t,e}function Ou(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 Vf(e,t,i,o,f){return la(t),i=Af(e,t,i,o,void 0,f),o=Nf(),e!==null&&!Tn?(Mf(e,t,f),Ui(e,t,f)):(xt&&o&&dl(t),t.flags|=1,Kn(e,t,i,f),t.child)}function Sg(e,t,i,o,f,h){return la(t),t.updateQueue=null,i=kp(t,o,i,f),jp(e),o=Nf(),e!==null&&!Tn?(Mf(e,t,h),Ui(e,t,h)):(xt&&o&&dl(t),t.flags|=1,Kn(e,t,i,h),t.child)}function Cg(e,t,i,o,f){if(la(t),t.stateNode===null){var h=Ei,S=i.contextType;typeof S=="object"&&S!==null&&(h=gn(S)),h=new i(o,h),t.memoizedState=h.state!==null&&h.state!==void 0?h.state:null,h.updater=Uf,t.stateNode=h,h._reactInternals=t,h=t.stateNode,h.props=o,h.state=t.memoizedState,h.refs={},cc(t),S=i.contextType,h.context=typeof S=="object"&&S!==null?gn(S):Ei,h.state=t.memoizedState,S=i.getDerivedStateFromProps,typeof S=="function"&&($f(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&&Uf.enqueueReplaceState(h,h.state,null),gs(t,o,h,f),Pi(),h.state=t.memoizedState),typeof h.componentDidMount=="function"&&(t.flags|=4194308),o=!0}else if(e===null){h=t.stateNode;var E=t.memoizedProps,U=pl(i,E);h.props=U;var ie=h.context,xe=i.contextType;S=Ei,typeof xe=="object"&&xe!==null&&(S=gn(xe));var je=i.getDerivedStateFromProps;xe=typeof je=="function"||typeof h.getSnapshotBeforeUpdate=="function",E=t.pendingProps!==E,xe||typeof h.UNSAFE_componentWillReceiveProps!="function"&&typeof h.componentWillReceiveProps!="function"||(E||ie!==S)&&cg(t,h,o,S),ni=!1;var le=t.memoizedState;h.state=le,gs(t,o,h,f),Pi(),ie=t.memoizedState,E||le!==ie||ni?(typeof je=="function"&&($f(t,i,je,o),ie=t.memoizedState),(U=ni||og(t,i,U,o,le,ie,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=ie),h.props=o,h.state=ie,h.context=S,o=U):(typeof h.componentDidMount=="function"&&(t.flags|=4194308),o=!1)}else{h=t.stateNode,uc(e,t),S=t.memoizedProps,xe=pl(i,S),h.props=xe,je=t.pendingProps,le=h.context,ie=i.contextType,U=Ei,typeof ie=="object"&&ie!==null&&(U=gn(ie)),E=i.getDerivedStateFromProps,(ie=typeof E=="function"||typeof h.getSnapshotBeforeUpdate=="function")||typeof h.UNSAFE_componentWillReceiveProps!="function"&&typeof h.componentWillReceiveProps!="function"||(S!==je||le!==U)&&cg(t,h,o,U),ni=!1,le=t.memoizedState,h.state=le,gs(t,o,h,f),Pi();var pe=t.memoizedState;S!==je||le!==pe||ni||e!==null&&e.dependencies!==null&&Ii(e.dependencies)?(typeof E=="function"&&($f(t,i,E,o),pe=t.memoizedState),(xe=ni||og(t,i,xe,o,le,pe,U)||e!==null&&e.dependencies!==null&&Ii(e.dependencies))?(ie||typeof h.UNSAFE_componentWillUpdate!="function"&&typeof h.componentWillUpdate!="function"||(typeof h.componentWillUpdate=="function"&&h.componentWillUpdate(o,pe,U),typeof h.UNSAFE_componentWillUpdate=="function"&&h.UNSAFE_componentWillUpdate(o,pe,U)),typeof h.componentDidUpdate=="function"&&(t.flags|=4),typeof h.getSnapshotBeforeUpdate=="function"&&(t.flags|=1024)):(typeof h.componentDidUpdate!="function"||S===e.memoizedProps&&le===e.memoizedState||(t.flags|=4),typeof h.getSnapshotBeforeUpdate!="function"||S===e.memoizedProps&&le===e.memoizedState||(t.flags|=1024),t.memoizedProps=o,t.memoizedState=pe),h.props=o,h.state=pe,h.context=U,o=xe):(typeof h.componentDidUpdate!="function"||S===e.memoizedProps&&le===e.memoizedState||(t.flags|=4),typeof h.getSnapshotBeforeUpdate!="function"||S===e.memoizedProps&&le===e.memoizedState||(t.flags|=1024),o=!1)}return h=o,Ou(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=Fi(t,e.child,null,f),t.child=Fi(t,null,i,f)):Kn(e,t,i,f),t.memoizedState=h.state,e=t.child):e=Ui(e,t,f),e}function jg(e,t,i,o){return As(),t.flags|=256,Kn(e,t,i,o),t.child}var Wf={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function Yf(e){return{baseLanes:e,cachePool:rc()}}function Kf(e,t,i){return e=e!==null?e.childLanes&~i:0,t&&(e|=Qa),e}function kg(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:(yt.current&2)!==0),S&&(f=!0,t.flags&=-129),S=(t.flags&32)!==0,t.flags&=-33,e===null){if(xt){if(f?de(t):Ve(),(e=_t)?(e=Lv(e,Ma),e=e!==null&&e.data!=="&"?e:null,e!==null&&(t.memoizedState={dehydrated:e,treeContext:Qs!==null?{id:Ya,overflow:Xt}:null,retryLane:536870912,hydrationErrors:null},i=Ri(e),i.return=t,t.child=i,wn=t,_t=null)):e=null,e===null)throw hs(t);return Rm(e)?t.lanes=32:t.lanes=536870912,null}var E=o.children;return o=o.fallback,f?(Ve(),f=t.mode,E=Hu({mode:"hidden",children:E},f),o=fs(o,f,i,null),E.return=t,o.return=t,E.sibling=o,t.child=E,o=t.child,o.memoizedState=Yf(i),o.childLanes=Kf(e,S,i),t.memoizedState=Wf,gc(null,o)):(de(t),Qf(t,E))}var U=e.memoizedState;if(U!==null&&(E=U.dehydrated,E!==null)){if(h)t.flags&256?(de(t),t.flags&=-257,t=Xf(e,t,i)):t.memoizedState!==null?(Ve(),t.child=e.child,t.flags|=128,t=null):(Ve(),E=o.fallback,f=t.mode,o=Hu({mode:"visible",children:o.children},f),E=fs(E,f,i,null),E.flags|=2,o.return=t,E.return=t,o.sibling=E,t.child=o,Fi(t,e.child,null,i),o=t.child,o.memoizedState=Yf(i),o.childLanes=Kf(e,S,i),t.memoizedState=Wf,t=gc(null,o));else if(de(t),Rm(E)){if(S=E.nextSibling&&E.nextSibling.dataset,S)var ie=S.dgst;S=ie,o=Error(l(419)),o.stack="",o.digest=S,Ns({value:o,source:null,stack:null}),t=Xf(e,t,i)}else if(Tn||Cr(e,t,i,!1),S=(i&e.childLanes)!==0,Tn||S){if(S=Yt,S!==null&&(o=Le(S,i),o!==0&&o!==U.retryLane))throw U.retryLane=o,Wa(e,o),za(S,e,o),Gf;Em(E)||Wu(),t=Xf(e,t,i)}else Em(E)?(t.flags|=192,t.child=e.child,t=null):(e=U.treeContext,_t=vs(E.nextSibling),wn=t,xt=!0,Xs=null,Ma=!1,e!==null&&wu(t,e),t=Qf(t,o.children),t.flags|=4096);return t}return f?(Ve(),E=o.fallback,f=t.mode,U=e.child,ie=U.sibling,o=Na(U,{mode:"hidden",children:o.children}),o.subtreeFlags=U.subtreeFlags&65011712,ie!==null?E=Na(ie,E):(E=fs(E,f,i,null),E.flags|=2),E.return=t,o.return=t,o.sibling=E,t.child=o,gc(null,o),o=t.child,E=e.child.memoizedState,E===null?E=Yf(i):(f=E.cachePool,f!==null?(U=fn._currentValue,f=f.parent!==U?{parent:U,pool:U}:f):f=rc(),E={baseLanes:E.baseLanes|i,cachePool:f}),o.memoizedState=E,o.childLanes=Kf(e,S,i),t.memoizedState=Wf,gc(e.child,o)):(de(t),i=e.child,e=i.sibling,i=Na(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 Qf(e,t){return t=Hu({mode:"visible",children:t},e.mode),t.return=e,e.child=t}function Hu(e,t){return e=Vn(22,e,null,t),e.lanes=0,e}function Xf(e,t,i){return Fi(t,e.child,null,i),e=Qf(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function Ag(e,t,i){e.lanes|=t;var o=e.alternate;o!==null&&(o.lanes|=t),Yl(e.return,t,i)}function Zf(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 Ng(e,t,i){var o=t.pendingProps,f=o.revealOrder,h=o.tail;o=o.children;var S=yt.current,E=(S&2)!==0;if(E?(S=S&1|2,t.flags|=128):S&=1,$(yt,S),Kn(e,t,o,i),o=xt?wr:0,!E&&e!==null&&(e.flags&128)!==0)e:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&Ag(e,i,t);else if(e.tag===19)Ag(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&&Yn(e)===null&&(f=i),i=i.sibling;i=f,i===null?(f=t.child,t.child=null):(f=i.sibling,i.sibling=null),Zf(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&&Yn(e)===null){t.child=f;break}e=f.sibling,f.sibling=i,i=f,f=e}Zf(t,!0,i,null,h,o);break;case"together":Zf(t,!1,null,null,void 0,o);break;default:t.memoizedState=null}return t.child}function Ui(e,t,i){if(e!==null&&(t.dependencies=e.dependencies),Er|=t.lanes,(i&t.childLanes)===0)if(e!==null){if(Cr(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=Na(e,e.pendingProps),t.child=i,i.return=t;e.sibling!==null;)e=e.sibling,i=i.sibling=Na(e,e.pendingProps),i.return=t;i.sibling=null}return t.child}function Jf(e,t){return(e.lanes&t)!==0?!0:(e=e.dependencies,!!(e!==null&&Ii(e)))}function _w(e,t,i){switch(t.tag){case 3:Be(t,t.stateNode.containerInfo),Zs(t,fn,e.memoizedState.cache),As();break;case 27:case 5:ge(t);break;case 4:Be(t,t.stateNode.containerInfo);break;case 10:Zs(t,t.type,t.memoizedProps.value);break;case 31:if(t.memoizedState!==null)return t.flags|=128,Ie(t),null;break;case 13:var o=t.memoizedState;if(o!==null)return o.dehydrated!==null?(de(t),t.flags|=128,null):(i&t.child.childLanes)!==0?kg(e,t,i):(de(t),e=Ui(e,t,i),e!==null?e.sibling:null);de(t);break;case 19:var f=(e.flags&128)!==0;if(o=(i&t.childLanes)!==0,o||(Cr(e,t,i,!1),o=(i&t.childLanes)!==0),f){if(o)return Ng(e,t,i);t.flags|=128}if(f=t.memoizedState,f!==null&&(f.rendering=null,f.tail=null,f.lastEffect=null),$(yt,yt.current),o)break;return null;case 22:return t.lanes=0,xg(e,t,i,t.pendingProps);case 24:Zs(t,fn,e.memoizedState.cache)}return Ui(e,t,i)}function Mg(e,t,i){if(e!==null)if(e.memoizedProps!==t.pendingProps)Tn=!0;else{if(!Jf(e,i)&&(t.flags&128)===0)return Tn=!1,_w(e,t,i);Tn=(e.flags&131072)!==0}else Tn=!1,xt&&(t.flags&1048576)!==0&&ul(t,wr,t.index);switch(t.lanes=0,t.tag){case 16:e:{var o=t.pendingProps;if(e=Hi(t.elementType),t.type=e,typeof e=="function")ol(e)?(o=pl(e,o),t.tag=1,t=Cg(null,t,e,o,i)):(t.tag=0,t=Vf(null,t,e,o,i));else{if(e!=null){var f=e.$$typeof;if(f===P){t.tag=11,t=gg(null,t,e,o,i);break e}else if(f===_){t.tag=14,t=vg(null,t,e,o,i);break e}}throw t=re(e)||e,Error(l(306,t,""))}}return t;case 0:return Vf(e,t,t.type,t.pendingProps,i);case 1:return o=t.type,f=pl(o,t.pendingProps),Cg(e,t,o,f,i);case 3:e:{if(Be(t,t.stateNode.containerInfo),e===null)throw Error(l(387));o=t.pendingProps;var h=t.memoizedState;f=h.element,uc(e,t),gs(t,o,null,i);var S=t.memoizedState;if(o=S.cache,Zs(t,fn,o),o!==h.cache&&Kl(t,[fn],i,!0),Pi(),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=jg(e,t,o,i);break e}else if(o!==f){f=Wn(Error(l(424)),t),Ns(f),t=jg(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,_t=vs(e.firstChild),wn=t,xt=!0,Xs=null,Ma=!0,i=Au(t,null,o,i),t.child=i;i;)i.flags=i.flags&-3|4096,i=i.sibling;else{if(As(),o===f){t=Ui(e,t,i);break e}Kn(e,t,o,i)}t=t.child}return t;case 26:return Ou(e,t),e===null?(i=Bv(t.type,null,t.pendingProps,null))?t.memoizedState=i:xt||(i=t.type,e=t.pendingProps,o=ed(me.current).createElement(i),o[te]=t,o[Me]=e,Qn(o,i,e),Vt(o),t.stateNode=o):t.memoizedState=Bv(t.type,e.memoizedProps,t.pendingProps,e.memoizedState),null;case 27:return ge(t),e===null&&xt&&(o=t.stateNode=Iv(t.type,t.pendingProps,me.current),wn=t,Ma=!0,f=_t,zr(t.type)?(Dm=f,_t=vs(o.firstChild)):_t=f),Kn(e,t,t.pendingProps.children,i),Ou(e,t),e===null&&(t.flags|=4194304),t.child;case 5:return e===null&&xt&&((f=o=_t)&&(o=uS(o,t.type,t.pendingProps,Ma),o!==null?(t.stateNode=o,wn=t,_t=vs(o.firstChild),Ma=!1,f=!0):f=!1),f||hs(t)),ge(t),f=t.type,h=t.pendingProps,S=e!==null?e.memoizedProps:null,o=h.children,Nm(f,h)?o=null:S!==null&&Nm(f,S)&&(t.flags|=32),t.memoizedState!==null&&(f=Af(e,t,kw,null,null,i),Rc._currentValue=f),Ou(e,t),Kn(e,t,o,i),t.child;case 6:return e===null&&xt&&((e=i=_t)&&(i=dS(i,t.pendingProps,Ma),i!==null?(t.stateNode=i,wn=t,_t=null,e=!0):e=!1),e||hs(t)),null;case 13:return kg(e,t,i);case 4:return Be(t,t.stateNode.containerInfo),o=t.pendingProps,e===null?t.child=Fi(t,null,o,i):Kn(e,t,o,i),t.child;case 11:return gg(e,t,t.type,t.pendingProps,i);case 7:return Kn(e,t,t.pendingProps,i),t.child;case 8:return Kn(e,t,t.pendingProps.children,i),t.child;case 12:return Kn(e,t,t.pendingProps.children,i),t.child;case 10:return o=t.pendingProps,Zs(t,t.type,o.value),Kn(e,t,o.children,i),t.child;case 9:return f=t.type._context,o=t.pendingProps.children,la(t),f=gn(f),o=o(f),t.flags|=1,Kn(e,t,o,i),t.child;case 14:return vg(e,t,t.type,t.pendingProps,i);case 15:return yg(e,t,t.type,t.pendingProps,i);case 19:return Ng(e,t,i);case 31:return Lw(e,t,i);case 22:return xg(e,t,i,t.pendingProps);case 24:return la(t),o=gn(fn),e===null?(f=ic(),f===null&&(f=Yt,h=ac(),f.pooledCache=h,h.refCount++,h!==null&&(f.pooledCacheLanes|=i),f=h),t.memoizedState={parent:o,cache:f},cc(t),Zs(t,fn,f)):((e.lanes&i)!==0&&(uc(e,t),gs(t,null,null,i),Pi()),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),Zs(t,fn,o)):(o=h.cache,Zs(t,fn,o),o!==f.cache&&Kl(t,[fn],i,!0))),Kn(e,t,t.pendingProps.children,i),t.child;case 29:throw t.pendingProps}throw Error(l(156,t.tag))}function qi(e){e.flags|=4}function em(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(tv())e.flags|=8192;else throw Ar=Mn,lc}else e.flags&=-16777217}function Tg(e,t){if(t.type!=="stylesheet"||(t.state.loading&4)!==0)e.flags&=-16777217;else if(e.flags|=16777216,!qv(t))if(tv())e.flags|=8192;else throw Ar=Mn,lc}function Bu(e,t){t!==null&&(e.flags|=4),e.flags&16384&&(t=e.tag!==22?Fe():536870912,e.lanes|=t,uo|=t)}function vc(e,t){if(!xt)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 nn(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 zw(e,t,i){var o=t.pendingProps;switch(Li(t),t.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return nn(t),null;case 1:return nn(t),null;case 3:return i=t.stateNode,o=null,e!==null&&(o=e.memoizedState.cache),t.memoizedState.cache!==o&&(t.flags|=2048),ps(fn),Oe(),i.pendingContext&&(i.context=i.pendingContext,i.pendingContext=null),(e===null||e.child===null)&&(_i(t)?qi(t):e===null||e.memoizedState.isDehydrated&&(t.flags&256)===0||(t.flags|=1024,ec())),nn(t),null;case 26:var f=t.type,h=t.memoizedState;return e===null?(qi(t),h!==null?(nn(t),Tg(t,h)):(nn(t),em(t,f,null,o,i))):h?h!==e.memoizedState?(qi(t),nn(t),Tg(t,h)):(nn(t),t.flags&=-16777217):(e=e.memoizedProps,e!==o&&qi(t),nn(t),em(t,f,e,o,i)),null;case 27:if(Ze(t),i=me.current,f=t.type,e!==null&&t.stateNode!=null)e.memoizedProps!==o&&qi(t);else{if(!o){if(t.stateNode===null)throw Error(l(166));return nn(t),null}e=he.current,_i(t)?Wl(t):(e=Iv(f,o,i),t.stateNode=e,qi(t))}return nn(t),null;case 5:if(Ze(t),f=t.type,e!==null&&t.stateNode!=null)e.memoizedProps!==o&&qi(t);else{if(!o){if(t.stateNode===null)throw Error(l(166));return nn(t),null}if(h=he.current,_i(t))Wl(t);else{var S=ed(me.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(Qn(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&&qi(t)}}return nn(t),em(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,i),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==o&&qi(t);else{if(typeof o!="string"&&t.stateNode===null)throw Error(l(166));if(e=me.current,_i(t)){if(e=t.stateNode,i=t.memoizedProps,o=null,f=wn,f!==null)switch(f.tag){case 27:case 5:o=f.memoizedProps}e[te]=t,e=!!(e.nodeValue===i||o!==null&&o.suppressHydrationWarning===!0||kv(e.nodeValue,i)),e||hs(t,!0)}else e=ed(e).createTextNode(o),e[te]=t,t.stateNode=e}return nn(t),null;case 31:if(i=t.memoizedState,e===null||e.memoizedState!==null){if(o=_i(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 As(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;nn(t),e=!1}else i=ec(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=i),e=!0;if(!e)return t.flags&256?(At(t),t):(At(t),null);if((t.flags&128)!==0)throw Error(l(558))}return nn(t),null;case 13:if(o=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(f=_i(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 As(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;nn(t),f=!1}else f=ec(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=f),f=!0;if(!f)return t.flags&256?(At(t),t):(At(t),null)}return At(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),Bu(t,t.updateQueue),nn(t),null);case 4:return Oe(),e===null&&Sm(t.stateNode.containerInfo),nn(t),null;case 10:return ps(t.type),nn(t),null;case 19:if(Q(yt),o=t.memoizedState,o===null)return nn(t),null;if(f=(t.flags&128)!==0,h=o.rendering,h===null)if(f)vc(o,!1);else{if(yn!==0||e!==null&&(e.flags&128)!==0)for(e=t.child;e!==null;){if(h=Yn(e),h!==null){for(t.flags|=128,vc(o,!1),e=h.updateQueue,t.updateQueue=e,Bu(t,e),t.subtreeFlags=0,e=i,i=t.child;i!==null;)cl(i,e),i=i.sibling;return $(yt,yt.current&1|2),xt&&ms(t,o.treeForkCount),t.child}e=e.sibling}o.tail!==null&&Je()>qu&&(t.flags|=128,f=!0,vc(o,!1),t.lanes=4194304)}else{if(!f)if(e=Yn(h),e!==null){if(t.flags|=128,f=!0,e=e.updateQueue,t.updateQueue=e,Bu(t,e),vc(o,!0),o.tail===null&&o.tailMode==="hidden"&&!h.alternate&&!xt)return nn(t),null}else 2*Je()-o.renderingStartTime>qu&&i!==536870912&&(t.flags|=128,f=!0,vc(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=Je(),e.sibling=null,i=yt.current,$(yt,f?i&1|2:i&1),xt&&ms(t,o.treeForkCount),e):(nn(t),null);case 22:case 23:return At(t),B(),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&&(nn(t),t.subtreeFlags&6&&(t.flags|=8192)):nn(t),i=t.updateQueue,i!==null&&Bu(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&&Q(Ms),null;case 24:return i=null,e!==null&&(i=e.memoizedState.cache),t.memoizedState.cache!==i&&(t.flags|=2048),ps(fn),nn(t),null;case 25:return null;case 30:return null}throw Error(l(156,t.tag))}function Iw(e,t){switch(Li(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return ps(fn),Oe(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return Ze(t),null;case 31:if(t.memoizedState!==null){if(At(t),t.alternate===null)throw Error(l(340));As()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(At(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(l(340));As()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Q(yt),null;case 4:return Oe(),null;case 10:return ps(t.type),null;case 22:case 23:return At(t),B(),e!==null&&Q(Ms),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return ps(fn),null;case 25:return null;default:return null}}function Eg(e,t){switch(Li(t),t.tag){case 3:ps(fn),Oe();break;case 26:case 27:case 5:Ze(t);break;case 4:Oe();break;case 31:t.memoizedState!==null&&At(t);break;case 13:At(t);break;case 19:Q(yt);break;case 10:ps(t.type);break;case 22:case 23:At(t),B(),e!==null&&Q(Ms);break;case 24:ps(fn)}}function yc(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(E){Pt(t,t.return,E)}}function Mr(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,E=S.destroy;if(E!==void 0){S.destroy=void 0,f=t;var U=i,ie=E;try{ie()}catch(xe){Pt(f,U,xe)}}}o=o.next}while(o!==h)}}catch(xe){Pt(t,t.return,xe)}}function Rg(e){var t=e.updateQueue;if(t!==null){var i=e.stateNode;try{ii(t,i)}catch(o){Pt(e,e.return,o)}}}function Dg(e,t,i){i.props=pl(e.type,e.memoizedProps),i.state=e.memoizedState;try{i.componentWillUnmount()}catch(o){Pt(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){Pt(e,t,f)}}function li(e,t){var i=e.ref,o=e.refCleanup;if(i!==null)if(typeof o=="function")try{o()}catch(f){Pt(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){Pt(e,t,f)}else i.current=null}function Lg(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){Pt(e,e.return,f)}}function tm(e,t,i){try{var o=e.stateNode;sS(o,e.type,i,t),o[Me]=t}catch(f){Pt(e,e.return,f)}}function _g(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&zr(e.type)||e.tag===4}function nm(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||_g(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&&zr(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 am(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=Ga));else if(o!==4&&(o===27&&zr(e.type)&&(i=e.stateNode,t=null),e=e.child,e!==null))for(am(e,t,i),e=e.sibling;e!==null;)am(e,t,i),e=e.sibling}function Fu(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&&zr(e.type)&&(i=e.stateNode),e=e.child,e!==null))for(Fu(e,t,i),e=e.sibling;e!==null;)Fu(e,t,i),e=e.sibling}function zg(e){var t=e.stateNode,i=e.memoizedProps;try{for(var o=e.type,f=t.attributes;f.length;)t.removeAttributeNode(f[0]);Qn(t,o,i),t[te]=e,t[Me]=i}catch(h){Pt(e,e.return,h)}}var Gi=!1,En=!1,sm=!1,Ig=typeof WeakSet=="function"?WeakSet:Set,On=null;function Ow(e,t){if(e=e.containerInfo,km=ld,e=il(e),Va(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,E=-1,U=-1,ie=0,xe=0,je=e,le=null;t:for(;;){for(var pe;je!==i||f!==0&&je.nodeType!==3||(E=S+f),je!==h||o!==0&&je.nodeType!==3||(U=S+o),je.nodeType===3&&(S+=je.nodeValue.length),(pe=je.firstChild)!==null;)le=je,je=pe;for(;;){if(je===e)break t;if(le===i&&++ie===f&&(E=S),le===h&&++xe===o&&(U=S),(pe=je.nextSibling)!==null)break;je=le,le=je.parentNode}je=pe}i=E===-1||U===-1?null:{start:E,end:U}}else i=null}i=i||{start:0,end:0}}else i=null;for(Am={focusedElem:e,selectionRange:i},ld=!1,On=t;On!==null;)if(t=On,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,On=e;else for(;On!==null;){switch(t=On,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 Ye=pl(i.type,f);e=o.getSnapshotBeforeUpdate(Ye,h),o.__reactInternalSnapshotBeforeUpdate=e}catch(st){Pt(i,i.return,st)}}break;case 3:if((e&1024)!==0){if(e=t.stateNode.containerInfo,i=e.nodeType,i===9)Tm(e);else if(i===1)switch(e.nodeName){case"HEAD":case"HTML":case"BODY":Tm(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,On=e;break}On=t.return}}function Og(e,t,i){var o=i.flags;switch(i.tag){case 0:case 11:case 15:Wi(e,i),o&4&&yc(5,i);break;case 1:if(Wi(e,i),o&4)if(e=i.stateNode,t===null)try{e.componentDidMount()}catch(S){Pt(i,i.return,S)}else{var f=pl(i.type,t.memoizedProps);t=t.memoizedState;try{e.componentDidUpdate(f,t,e.__reactInternalSnapshotBeforeUpdate)}catch(S){Pt(i,i.return,S)}}o&64&&Rg(i),o&512&&xc(i,i.return);break;case 3:if(Wi(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{ii(e,t)}catch(S){Pt(i,i.return,S)}}break;case 27:t===null&&o&4&&zg(i);case 26:case 5:Wi(e,i),t===null&&o&4&&Lg(i),o&512&&xc(i,i.return);break;case 12:Wi(e,i);break;case 31:Wi(e,i),o&4&&Fg(e,i);break;case 13:Wi(e,i),o&4&&Pg(e,i),o&64&&(e=i.memoizedState,e!==null&&(e=e.dehydrated,e!==null&&(i=Vw.bind(null,i),fS(e,i))));break;case 22:if(o=i.memoizedState!==null||Gi,!o){t=t!==null&&t.memoizedState!==null||En,f=Gi;var h=En;Gi=o,(En=t)&&!h?Yi(e,i,(i.subtreeFlags&8772)!==0):Wi(e,i),Gi=f,En=h}break;case 30:break;default:Wi(e,i)}}function Hg(e){var t=e.alternate;t!==null&&(e.alternate=null,Hg(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&Bt(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 cn=null,Ra=!1;function Vi(e,t,i){for(i=i.child;i!==null;)Bg(e,t,i),i=i.sibling}function Bg(e,t,i){if(Ae&&typeof Ae.onCommitFiberUnmount=="function")try{Ae.onCommitFiberUnmount(ze,i)}catch{}switch(i.tag){case 26:En||li(i,t),Vi(e,t,i),i.memoizedState?i.memoizedState.count--:i.stateNode&&(i=i.stateNode,i.parentNode.removeChild(i));break;case 27:En||li(i,t);var o=cn,f=Ra;zr(i.type)&&(cn=i.stateNode,Ra=!1),Vi(e,t,i),Mc(i.stateNode),cn=o,Ra=f;break;case 5:En||li(i,t);case 6:if(o=cn,f=Ra,cn=null,Vi(e,t,i),cn=o,Ra=f,cn!==null)if(Ra)try{(cn.nodeType===9?cn.body:cn.nodeName==="HTML"?cn.ownerDocument.body:cn).removeChild(i.stateNode)}catch(h){Pt(i,t,h)}else try{cn.removeChild(i.stateNode)}catch(h){Pt(i,t,h)}break;case 18:cn!==null&&(Ra?(e=cn,Rv(e.nodeType===9?e.body:e.nodeName==="HTML"?e.ownerDocument.body:e,i.stateNode),xo(e)):Rv(cn,i.stateNode));break;case 4:o=cn,f=Ra,cn=i.stateNode.containerInfo,Ra=!0,Vi(e,t,i),cn=o,Ra=f;break;case 0:case 11:case 14:case 15:Mr(2,i,t),En||Mr(4,i,t),Vi(e,t,i);break;case 1:En||(li(i,t),o=i.stateNode,typeof o.componentWillUnmount=="function"&&Dg(i,t,o)),Vi(e,t,i);break;case 21:Vi(e,t,i);break;case 22:En=(o=En)||i.memoizedState!==null,Vi(e,t,i),En=o;break;default:Vi(e,t,i)}}function Fg(e,t){if(t.memoizedState===null&&(e=t.alternate,e!==null&&(e=e.memoizedState,e!==null))){e=e.dehydrated;try{xo(e)}catch(i){Pt(t,t.return,i)}}}function Pg(e,t){if(t.memoizedState===null&&(e=t.alternate,e!==null&&(e=e.memoizedState,e!==null&&(e=e.dehydrated,e!==null))))try{xo(e)}catch(i){Pt(t,t.return,i)}}function Hw(e){switch(e.tag){case 31:case 13:case 19:var t=e.stateNode;return t===null&&(t=e.stateNode=new Ig),t;case 22:return e=e.stateNode,t=e._retryCache,t===null&&(t=e._retryCache=new Ig),t;default:throw Error(l(435,e.tag))}}function Pu(e,t){var i=Hw(e);t.forEach(function(o){if(!i.has(o)){i.add(o);var f=Ww.bind(null,e,o);o.then(f,f)}})}function Da(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,E=S;e:for(;E!==null;){switch(E.tag){case 27:if(zr(E.type)){cn=E.stateNode,Ra=!1;break e}break;case 5:cn=E.stateNode,Ra=!1;break e;case 3:case 4:cn=E.stateNode.containerInfo,Ra=!0;break e}E=E.return}if(cn===null)throw Error(l(160));Bg(h,S,f),cn=null,Ra=!1,h=f.alternate,h!==null&&(h.return=null),f.return=null}if(t.subtreeFlags&13886)for(t=t.child;t!==null;)$g(t,e),t=t.sibling}var Ts=null;function $g(e,t){var i=e.alternate,o=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:Da(t,e),La(e),o&4&&(Mr(3,e,e.return),yc(3,e),Mr(5,e,e.return));break;case 1:Da(t,e),La(e),o&512&&(En||i===null||li(i,i.return)),o&64&&Gi&&(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=Ts;if(Da(t,e),La(e),o&512&&(En||i===null||li(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[kt]||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"))),Qn(h,o,i),h[te]=e,Vt(h),o=h;break e;case"link":var S=$v("link","href",f).get(o+(i.href||""));if(S){for(var E=0;E<S.length;E++)if(h=S[E],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(E,1);break t}}h=f.createElement(o),Qn(h,o,i),f.head.appendChild(h);break;case"meta":if(S=$v("meta","content",f).get(o+(i.content||""))){for(E=0;E<S.length;E++)if(h=S[E],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(E,1);break t}}h=f.createElement(o),Qn(h,o,i),f.head.appendChild(h);break;default:throw Error(l(468,o))}h[te]=e,Vt(h),o=h}e.stateNode=o}else Uv(f,e.type,e.stateNode);else e.stateNode=Pv(f,o,e.memoizedProps);else h!==o?(h===null?i.stateNode!==null&&(i=i.stateNode,i.parentNode.removeChild(i)):h.count--,o===null?Uv(f,e.type,e.stateNode):Pv(f,o,e.memoizedProps)):o===null&&e.stateNode!==null&&tm(e,e.memoizedProps,i.memoizedProps)}break;case 27:Da(t,e),La(e),o&512&&(En||i===null||li(i,i.return)),i!==null&&o&4&&tm(e,e.memoizedProps,i.memoizedProps);break;case 5:if(Da(t,e),La(e),o&512&&(En||i===null||li(i,i.return)),e.flags&32){f=e.stateNode;try{qa(f,"")}catch(Ye){Pt(e,e.return,Ye)}}o&4&&e.stateNode!=null&&(f=e.memoizedProps,tm(e,f,i!==null?i.memoizedProps:f)),o&1024&&(sm=!0);break;case 6:if(Da(t,e),La(e),o&4){if(e.stateNode===null)throw Error(l(162));o=e.memoizedProps,i=e.stateNode;try{i.nodeValue=o}catch(Ye){Pt(e,e.return,Ye)}}break;case 3:if(ad=null,f=Ts,Ts=td(t.containerInfo),Da(t,e),Ts=f,La(e),o&4&&i!==null&&i.memoizedState.isDehydrated)try{xo(t.containerInfo)}catch(Ye){Pt(e,e.return,Ye)}sm&&(sm=!1,Ug(e));break;case 4:o=Ts,Ts=td(e.stateNode.containerInfo),Da(t,e),La(e),Ts=o;break;case 12:Da(t,e),La(e);break;case 31:Da(t,e),La(e),o&4&&(o=e.updateQueue,o!==null&&(e.updateQueue=null,Pu(e,o)));break;case 13:Da(t,e),La(e),e.child.flags&8192&&e.memoizedState!==null!=(i!==null&&i.memoizedState!==null)&&(Uu=Je()),o&4&&(o=e.updateQueue,o!==null&&(e.updateQueue=null,Pu(e,o)));break;case 22:f=e.memoizedState!==null;var U=i!==null&&i.memoizedState!==null,ie=Gi,xe=En;if(Gi=ie||f,En=xe||U,Da(t,e),En=xe,Gi=ie,La(e),o&8192)e:for(t=e.stateNode,t._visibility=f?t._visibility&-2:t._visibility|1,f&&(i===null||U||Gi||En||gl(e)),i=null,t=e;;){if(t.tag===5||t.tag===26){if(i===null){U=i=t;try{if(h=U.stateNode,f)S=h.style,typeof S.setProperty=="function"?S.setProperty("display","none","important"):S.display="none";else{E=U.stateNode;var je=U.memoizedProps.style,le=je!=null&&je.hasOwnProperty("display")?je.display:null;E.style.display=le==null||typeof le=="boolean"?"":(""+le).trim()}}catch(Ye){Pt(U,U.return,Ye)}}}else if(t.tag===6){if(i===null){U=t;try{U.stateNode.nodeValue=f?"":U.memoizedProps}catch(Ye){Pt(U,U.return,Ye)}}}else if(t.tag===18){if(i===null){U=t;try{var pe=U.stateNode;f?Dv(pe,!0):Dv(U.stateNode,!1)}catch(Ye){Pt(U,U.return,Ye)}}}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,Pu(e,i))));break;case 19:Da(t,e),La(e),o&4&&(o=e.updateQueue,o!==null&&(e.updateQueue=null,Pu(e,o)));break;case 30:break;case 21:break;default:Da(t,e),La(e)}}function La(e){var t=e.flags;if(t&2){try{for(var i,o=e.return;o!==null;){if(_g(o)){i=o;break}o=o.return}if(i==null)throw Error(l(160));switch(i.tag){case 27:var f=i.stateNode,h=nm(e);Fu(e,h,f);break;case 5:var S=i.stateNode;i.flags&32&&(qa(S,""),i.flags&=-33);var E=nm(e);Fu(e,E,S);break;case 3:case 4:var U=i.stateNode.containerInfo,ie=nm(e);am(e,ie,U);break;default:throw Error(l(161))}}catch(xe){Pt(e,e.return,xe)}e.flags&=-3}t&4096&&(e.flags&=-4097)}function Ug(e){if(e.subtreeFlags&1024)for(e=e.child;e!==null;){var t=e;Ug(t),t.tag===5&&t.flags&1024&&t.stateNode.reset(),e=e.sibling}}function Wi(e,t){if(t.subtreeFlags&8772)for(t=t.child;t!==null;)Og(e,t.alternate,t),t=t.sibling}function gl(e){for(e=e.child;e!==null;){var t=e;switch(t.tag){case 0:case 11:case 14:case 15:Mr(4,t,t.return),gl(t);break;case 1:li(t,t.return);var i=t.stateNode;typeof i.componentWillUnmount=="function"&&Dg(t,t.return,i),gl(t);break;case 27:Mc(t.stateNode);case 26:case 5:li(t,t.return),gl(t);break;case 22:t.memoizedState===null&&gl(t);break;case 30:gl(t);break;default:gl(t)}e=e.sibling}}function Yi(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:Yi(f,h,i),yc(4,h);break;case 1:if(Yi(f,h,i),o=h,f=o.stateNode,typeof f.componentDidMount=="function")try{f.componentDidMount()}catch(ie){Pt(o,o.return,ie)}if(o=h,f=o.updateQueue,f!==null){var E=o.stateNode;try{var U=f.shared.hiddenCallbacks;if(U!==null)for(f.shared.hiddenCallbacks=null,f=0;f<U.length;f++)Nu(U[f],E)}catch(ie){Pt(o,o.return,ie)}}i&&S&64&&Rg(h),xc(h,h.return);break;case 27:zg(h);case 26:case 5:Yi(f,h,i),i&&o===null&&S&4&&Lg(h),xc(h,h.return);break;case 12:Yi(f,h,i);break;case 31:Yi(f,h,i),i&&S&4&&Fg(f,h);break;case 13:Yi(f,h,i),i&&S&4&&Pg(f,h);break;case 22:h.memoizedState===null&&Yi(f,h,i),xc(h,h.return);break;case 30:break;default:Yi(f,h,i)}t=t.sibling}}function im(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&&Jl(i))}function rm(e,t){e=null,t.alternate!==null&&(e=t.alternate.memoizedState.cache),t=t.memoizedState.cache,t!==e&&(t.refCount++,e!=null&&Jl(e))}function Es(e,t,i,o){if(t.subtreeFlags&10256)for(t=t.child;t!==null;)qg(e,t,i,o),t=t.sibling}function qg(e,t,i,o){var f=t.flags;switch(t.tag){case 0:case 11:case 15:Es(e,t,i,o),f&2048&&yc(9,t);break;case 1:Es(e,t,i,o);break;case 3:Es(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&&Jl(e)));break;case 12:if(f&2048){Es(e,t,i,o),e=t.stateNode;try{var h=t.memoizedProps,S=h.id,E=h.onPostCommit;typeof E=="function"&&E(S,t.alternate===null?"mount":"update",e.passiveEffectDuration,-0)}catch(U){Pt(t,t.return,U)}}else Es(e,t,i,o);break;case 31:Es(e,t,i,o);break;case 13:Es(e,t,i,o);break;case 23:break;case 22:h=t.stateNode,S=t.alternate,t.memoizedState!==null?h._visibility&2?Es(e,t,i,o):bc(e,t):h._visibility&2?Es(e,t,i,o):(h._visibility|=2,lo(e,t,i,o,(t.subtreeFlags&10256)!==0||!1)),f&2048&&im(S,t);break;case 24:Es(e,t,i,o),f&2048&&rm(t.alternate,t);break;default:Es(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,E=i,U=o,ie=S.flags;switch(S.tag){case 0:case 11:case 15:lo(h,S,E,U,f),yc(8,S);break;case 23:break;case 22:var xe=S.stateNode;S.memoizedState!==null?xe._visibility&2?lo(h,S,E,U,f):bc(h,S):(xe._visibility|=2,lo(h,S,E,U,f)),f&&ie&2048&&im(S.alternate,S);break;case 24:lo(h,S,E,U,f),f&&ie&2048&&rm(S.alternate,S);break;default:lo(h,S,E,U,f)}t=t.sibling}}function bc(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:bc(i,o),f&2048&&im(o.alternate,o);break;case 24:bc(i,o),f&2048&&rm(o.alternate,o);break;default:bc(i,o)}t=t.sibling}}var wc=8192;function oo(e,t,i){if(e.subtreeFlags&wc)for(e=e.child;e!==null;)Gg(e,t,i),e=e.sibling}function Gg(e,t,i){switch(e.tag){case 26:oo(e,t,i),e.flags&wc&&e.memoizedState!==null&&jS(i,Ts,e.memoizedState,e.memoizedProps);break;case 5:oo(e,t,i);break;case 3:case 4:var o=Ts;Ts=td(e.stateNode.containerInfo),oo(e,t,i),Ts=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 Vg(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 Sc(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];On=o,Yg(o,e)}Vg(e)}if(e.subtreeFlags&10256)for(e=e.child;e!==null;)Wg(e),e=e.sibling}function Wg(e){switch(e.tag){case 0:case 11:case 15:Sc(e),e.flags&2048&&Mr(9,e,e.return);break;case 3:Sc(e);break;case 12:Sc(e);break;case 22:var t=e.stateNode;e.memoizedState!==null&&t._visibility&2&&(e.return===null||e.return.tag!==13)?(t._visibility&=-3,$u(e)):Sc(e);break;default:Sc(e)}}function $u(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];On=o,Yg(o,e)}Vg(e)}for(e=e.child;e!==null;){switch(t=e,t.tag){case 0:case 11:case 15:Mr(8,t,t.return),$u(t);break;case 22:i=t.stateNode,i._visibility&2&&(i._visibility&=-3,$u(t));break;default:$u(t)}e=e.sibling}}function Yg(e,t){for(;On!==null;){var i=On;switch(i.tag){case 0:case 11:case 15:Mr(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:Jl(i.memoizedState.cache)}if(o=i.child,o!==null)o.return=i,On=o;else e:for(i=e;On!==null;){o=On;var f=o.sibling,h=o.return;if(Hg(o),o===i){On=null;break e}if(f!==null){f.return=h,On=f;break e}On=h}}}var Bw={getCacheForType:function(e){var t=gn(fn),i=t.data.get(e);return i===void 0&&(i=e(),t.data.set(e,i)),i},cacheSignal:function(){return gn(fn).controller.signal}},Fw=typeof WeakMap=="function"?WeakMap:Map,zt=0,Yt=null,wt=null,Ct=0,Ft=0,Ka=null,Tr=!1,co=!1,lm=!1,Ki=0,yn=0,Er=0,vl=0,om=0,Qa=0,uo=0,Cc=null,_a=null,cm=!1,Uu=0,Kg=0,qu=1/0,Gu=null,Rr=null,Ln=0,Dr=null,fo=null,Qi=0,um=0,dm=null,Qg=null,jc=0,fm=null;function Xa(){return(zt&2)!==0&&Ct!==0?Ct&-Ct:I.T!==null?ym():ss()}function Xg(){if(Qa===0)if((Ct&536870912)===0||xt){var e=qt;qt<<=1,(qt&3932160)===0&&(qt=262144),Qa=e}else Qa=536870912;return e=D.current,e!==null&&(e.flags|=32),Qa}function za(e,t,i){(e===Yt&&(Ft===2||Ft===9)||e.cancelPendingCommit!==null)&&(mo(e,0),Lr(e,Ct,Qa,!1)),vt(e,i),((zt&2)===0||e!==Yt)&&(e===Yt&&((zt&2)===0&&(vl|=i),yn===4&&Lr(e,Ct,Qa,!1)),oi(e))}function Zg(e,t,i){if((zt&6)!==0)throw Error(l(327));var o=!i&&(t&127)===0&&(t&e.expiredLanes)===0||Zn(e,t),f=o?Uw(e,t):hm(e,t,!0),h=o;do{if(f===0){co&&!o&&Lr(e,t,0,!1);break}else{if(i=e.current.alternate,h&&!Pw(i)){f=hm(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 E=e;f=Cc;var U=E.current.memoizedState.isDehydrated;if(U&&(mo(E,S).flags|=256),S=hm(E,S,!1),S!==2){if(lm&&!U){E.errorRecoveryDisabledLanes|=h,vl|=h,f=4;break e}h=_a,_a=f,h!==null&&(_a===null?_a=h:_a.push.apply(_a,h))}f=S}if(h=!1,f!==2)continue}}if(f===1){mo(e,0),Lr(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:Lr(o,t,Qa,!Tr);break e;case 2:_a=null;break;case 3:case 5:break;default:throw Error(l(329))}if((t&62914560)===t&&(f=Uu+300-Je(),10<f)){if(Lr(o,t,Qa,!Tr),as(o,0,!0)!==0)break e;Qi=t,o.timeoutHandle=Tv(Jg.bind(null,o,i,_a,Gu,cm,t,Qa,vl,uo,Tr,h,"Throttled",-0,0),f);break e}Jg(o,i,_a,Gu,cm,t,Qa,vl,uo,Tr,h,null,-0,0)}}break}while(!0);oi(e)}function Jg(e,t,i,o,f,h,S,E,U,ie,xe,je,le,pe){if(e.timeoutHandle=-1,je=t.subtreeFlags,je&8192||(je&16785408)===16785408){je={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:Ga},Gg(t,h,je);var Ye=(h&62914560)===h?Uu-Je():(h&4194048)===h?Kg-Je():0;if(Ye=kS(je,Ye),Ye!==null){Qi=h,e.cancelPendingCommit=Ye(lv.bind(null,e,t,h,i,o,f,S,E,U,xe,je,null,le,pe)),Lr(e,h,S,!ie);return}}lv(e,t,h,i,o,f,S,E,U)}function Pw(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(!ln(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 Lr(e,t,i,o){t&=~om,t&=~vl,e.suspendedLanes|=t,e.pingedLanes&=~t,o&&(e.warmLanes|=t),o=e.expirationTimes;for(var f=t;0<f;){var h=31-gt(f),S=1<<h;o[h]=-1,f&=~S}i!==0&&Jt(e,i,t)}function Vu(){return(zt&6)===0?(kc(0),!1):!0}function mm(){if(wt!==null){if(Ft===0)var e=wt.return;else e=wt,Ta=zi=null,Tf(e),Bi=null,ei=0,e=wt;for(;e!==null;)Eg(e.alternate,e),e=e.return;wt=null}}function mo(e,t){var i=e.timeoutHandle;i!==-1&&(e.timeoutHandle=-1,lS(i)),i=e.cancelPendingCommit,i!==null&&(e.cancelPendingCommit=null,i()),Qi=0,mm(),Yt=e,wt=i=Na(e.current,null),Ct=t,Ft=0,Ka=null,Tr=!1,co=Zn(e,t),lm=!1,uo=Qa=om=vl=Er=yn=0,_a=Cc=null,cm=!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-gt(o),h=1<<f;t|=e[f],o&=~h}return Ki=t,rl(),i}function ev(e,t){rt=null,I.H=pc,t===Js||t===to?(t=Cu(),Ft=3):t===lc?(t=Cu(),Ft=4):Ft=t===Gf?8:t!==null&&typeof t=="object"&&typeof t.then=="function"?6:1,Ka=t,wt===null&&(yn=1,zu(e,Wn(t,e.current)))}function tv(){var e=D.current;return e===null?!0:(Ct&4194048)===Ct?ue===null:(Ct&62914560)===Ct||(Ct&536870912)!==0?e===ue:!1}function nv(){var e=I.H;return I.H=pc,e===null?pc:e}function av(){var e=I.A;return I.A=Bw,e}function Wu(){yn=4,Tr||(Ct&4194048)!==Ct&&D.current!==null||(co=!0),(Er&134217727)===0&&(vl&134217727)===0||Yt===null||Lr(Yt,Ct,Qa,!1)}function hm(e,t,i){var o=zt;zt|=2;var f=nv(),h=av();(Yt!==e||Ct!==t)&&(Gu=null,mo(e,t)),t=!1;var S=yn;e:do try{if(Ft!==0&&wt!==null){var E=wt,U=Ka;switch(Ft){case 8:mm(),S=6;break e;case 3:case 2:case 9:case 6:D.current===null&&(t=!0);var ie=Ft;if(Ft=0,Ka=null,ho(e,E,U,ie),i&&co){S=0;break e}break;default:ie=Ft,Ft=0,Ka=null,ho(e,E,U,ie)}}$w(),S=yn;break}catch(xe){ev(e,xe)}while(!0);return t&&e.shellSuspendCounter++,Ta=zi=null,zt=o,I.H=f,I.A=h,wt===null&&(Yt=null,Ct=0,rl()),S}function $w(){for(;wt!==null;)sv(wt)}function Uw(e,t){var i=zt;zt|=2;var o=nv(),f=av();Yt!==e||Ct!==t?(Gu=null,qu=Je()+500,mo(e,t)):co=Zn(e,t);e:do try{if(Ft!==0&&wt!==null){t=wt;var h=Ka;t:switch(Ft){case 1:Ft=0,Ka=null,ho(e,t,h,1);break;case 2:case 9:if(fl(h)){Ft=0,Ka=null,iv(t);break}t=function(){Ft!==2&&Ft!==9||Yt!==e||(Ft=7),oi(e)},h.then(t,t);break e;case 3:Ft=7;break e;case 4:Ft=5;break e;case 7:fl(h)?(Ft=0,Ka=null,iv(t)):(Ft=0,Ka=null,ho(e,t,h,7));break;case 5:var S=null;switch(wt.tag){case 26:S=wt.memoizedState;case 5:case 27:var E=wt;if(S?qv(S):E.stateNode.complete){Ft=0,Ka=null;var U=E.sibling;if(U!==null)wt=U;else{var ie=E.return;ie!==null?(wt=ie,Yu(ie)):wt=null}break t}}Ft=0,Ka=null,ho(e,t,h,5);break;case 6:Ft=0,Ka=null,ho(e,t,h,6);break;case 8:mm(),yn=6;break e;default:throw Error(l(462))}}qw();break}catch(xe){ev(e,xe)}while(!0);return Ta=zi=null,I.H=o,I.A=f,zt=i,wt!==null?0:(Yt=null,Ct=0,rl(),yn)}function qw(){for(;wt!==null&&!Te();)sv(wt)}function sv(e){var t=Mg(e.alternate,e,Ki);e.memoizedProps=e.pendingProps,t===null?Yu(e):wt=t}function iv(e){var t=e,i=t.alternate;switch(t.tag){case 15:case 0:t=Sg(i,t,t.pendingProps,t.type,void 0,Ct);break;case 11:t=Sg(i,t,t.pendingProps,t.type.render,t.ref,Ct);break;case 5:Tf(t);default:Eg(i,t),t=wt=cl(t,Ki),t=Mg(i,t,Ki)}e.memoizedProps=e.pendingProps,t===null?Yu(e):wt=t}function ho(e,t,i,o){Ta=zi=null,Tf(t),Bi=null,ei=0;var f=t.return;try{if(Dw(e,f,t,i,Ct)){yn=1,zu(e,Wn(i,e.current)),wt=null;return}}catch(h){if(f!==null)throw wt=f,h;yn=1,zu(e,Wn(i,e.current)),wt=null;return}t.flags&32768?(xt||o===1?e=!0:co||(Ct&536870912)!==0?e=!1:(Tr=e=!0,(o===2||o===9||o===3||o===6)&&(o=D.current,o!==null&&o.tag===13&&(o.flags|=16384))),rv(t,e)):Yu(t)}function Yu(e){var t=e;do{if((t.flags&32768)!==0){rv(t,Tr);return}e=t.return;var i=zw(t.alternate,t,Ki);if(i!==null){wt=i;return}if(t=t.sibling,t!==null){wt=t;return}wt=t=e}while(t!==null);yn===0&&(yn=5)}function rv(e,t){do{var i=Iw(e.alternate,e);if(i!==null){i.flags&=32767,wt=i;return}if(i=e.return,i!==null&&(i.flags|=32768,i.subtreeFlags=0,i.deletions=null),!t&&(e=e.sibling,e!==null)){wt=e;return}wt=e=i}while(e!==null);yn=6,wt=null}function lv(e,t,i,o,f,h,S,E,U){e.cancelPendingCommit=null;do Ku();while(Ln!==0);if((zt&6)!==0)throw Error(l(327));if(t!==null){if(t===e.current)throw Error(l(177));if(h=t.lanes|t.childLanes,h|=Zo,hi(e,i,h,S,E,U),e===Yt&&(wt=Yt=null,Ct=0),fo=t,Dr=e,Qi=i,um=h,dm=f,Qg=o,(t.subtreeFlags&10256)!==0||(t.flags&10256)!==0?(e.callbackNode=null,e.callbackPriority=0,Yw(mt,function(){return fv(),null})):(e.callbackNode=null,e.callbackPriority=0),o=(t.flags&13878)!==0,(t.subtreeFlags&13878)!==0||o){o=I.T,I.T=null,f=ee.p,ee.p=2,S=zt,zt|=4;try{Ow(e,t,i)}finally{zt=S,ee.p=f,I.T=o}}Ln=1,ov(),cv(),uv()}}function ov(){if(Ln===1){Ln=0;var e=Dr,t=fo,i=(t.flags&13878)!==0;if((t.subtreeFlags&13878)!==0||i){i=I.T,I.T=null;var o=ee.p;ee.p=2;var f=zt;zt|=4;try{$g(t,e);var h=Am,S=il(e.containerInfo),E=h.focusedElem,U=h.selectionRange;if(S!==E&&E&&E.ownerDocument&&ji(E.ownerDocument.documentElement,E)){if(U!==null&&Va(E)){var ie=U.start,xe=U.end;if(xe===void 0&&(xe=ie),"selectionStart"in E)E.selectionStart=ie,E.selectionEnd=Math.min(xe,E.value.length);else{var je=E.ownerDocument||document,le=je&&je.defaultView||window;if(le.getSelection){var pe=le.getSelection(),Ye=E.textContent.length,st=Math.min(U.start,Ye),Ut=U.end===void 0?st:Math.min(U.end,Ye);!pe.extend&&st>Ut&&(S=Ut,Ut=st,st=S);var Z=js(E,st),Y=js(E,Ut);if(Z&&Y&&(pe.rangeCount!==1||pe.anchorNode!==Z.node||pe.anchorOffset!==Z.offset||pe.focusNode!==Y.node||pe.focusOffset!==Y.offset)){var se=je.createRange();se.setStart(Z.node,Z.offset),pe.removeAllRanges(),st>Ut?(pe.addRange(se),pe.extend(Y.node,Y.offset)):(se.setEnd(Y.node,Y.offset),pe.addRange(se))}}}}for(je=[],pe=E;pe=pe.parentNode;)pe.nodeType===1&&je.push({element:pe,left:pe.scrollLeft,top:pe.scrollTop});for(typeof E.focus=="function"&&E.focus(),E=0;E<je.length;E++){var Ce=je[E];Ce.element.scrollLeft=Ce.left,Ce.element.scrollTop=Ce.top}}ld=!!km,Am=km=null}finally{zt=f,ee.p=o,I.T=i}}e.current=t,Ln=2}}function cv(){if(Ln===2){Ln=0;var e=Dr,t=fo,i=(t.flags&8772)!==0;if((t.subtreeFlags&8772)!==0||i){i=I.T,I.T=null;var o=ee.p;ee.p=2;var f=zt;zt|=4;try{Og(e,t.alternate,t)}finally{zt=f,ee.p=o,I.T=i}}Ln=3}}function uv(){if(Ln===4||Ln===3){Ln=0,Pe();var e=Dr,t=fo,i=Qi,o=Qg;(t.subtreeFlags&10256)!==0||(t.flags&10256)!==0?Ln=5:(Ln=0,fo=Dr=null,dv(e,e.pendingLanes));var f=e.pendingLanes;if(f===0&&(Rr=null),hn(i),t=t.stateNode,Ae&&typeof Ae.onCommitFiberRoot=="function")try{Ae.onCommitFiberRoot(ze,t,void 0,(t.current.flags&128)===128)}catch{}if(o!==null){t=I.T,f=ee.p,ee.p=2,I.T=null;try{for(var h=e.onRecoverableError,S=0;S<o.length;S++){var E=o[S];h(E.value,{componentStack:E.stack})}}finally{I.T=t,ee.p=f}}(Qi&3)!==0&&Ku(),oi(e),f=e.pendingLanes,(i&261930)!==0&&(f&42)!==0?e===fm?jc++:(jc=0,fm=e):jc=0,kc(0)}}function dv(e,t){(e.pooledCacheLanes&=t)===0&&(t=e.pooledCache,t!=null&&(e.pooledCache=null,Jl(t)))}function Ku(){return ov(),cv(),uv(),fv()}function fv(){if(Ln!==5)return!1;var e=Dr,t=um;um=0;var i=hn(Qi),o=I.T,f=ee.p;try{ee.p=32>i?32:i,I.T=null,i=dm,dm=null;var h=Dr,S=Qi;if(Ln=0,fo=Dr=null,Qi=0,(zt&6)!==0)throw Error(l(331));var E=zt;if(zt|=4,Wg(h.current),qg(h,h.current,S,i),zt=E,kc(0,!1),Ae&&typeof Ae.onPostCommitFiberRoot=="function")try{Ae.onPostCommitFiberRoot(ze,h)}catch{}return!0}finally{ee.p=f,I.T=o,dv(e,t)}}function mv(e,t,i){t=Wn(i,t),t=qf(e.stateNode,t,2),e=ai(e,t,2),e!==null&&(vt(e,2),oi(e))}function Pt(e,t,i){if(e.tag===3)mv(e,e,i);else for(;t!==null;){if(t.tag===3){mv(t,e,i);break}else if(t.tag===1){var o=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof o.componentDidCatch=="function"&&(Rr===null||!Rr.has(o))){e=Wn(i,e),i=hg(2),o=ai(t,i,2),o!==null&&(pg(i,o,t,e),vt(o,2),oi(o));break}}t=t.return}}function pm(e,t,i){var o=e.pingCache;if(o===null){o=e.pingCache=new Fw;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)||(lm=!0,f.add(i),e=Gw.bind(null,e,t,i),t.then(e,e))}function Gw(e,t,i){var o=e.pingCache;o!==null&&o.delete(t),e.pingedLanes|=e.suspendedLanes&i,e.warmLanes&=~i,Yt===e&&(Ct&i)===i&&(yn===4||yn===3&&(Ct&62914560)===Ct&&300>Je()-Uu?(zt&2)===0&&mo(e,0):om|=i,uo===Ct&&(uo=0)),oi(e)}function hv(e,t){t===0&&(t=Fe()),e=Wa(e,t),e!==null&&(vt(e,t),oi(e))}function Vw(e){var t=e.memoizedState,i=0;t!==null&&(i=t.retryLane),hv(e,i)}function Ww(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),hv(e,i)}function Yw(e,t){return ye(e,t)}var Qu=null,po=null,gm=!1,Xu=!1,vm=!1,_r=0;function oi(e){e!==po&&e.next===null&&(po===null?Qu=po=e:po=po.next=e),Xu=!0,gm||(gm=!0,Qw())}function kc(e,t){if(!vm&&Xu){vm=!0;do for(var i=!1,o=Qu;o!==null;){if(e!==0){var f=o.pendingLanes;if(f===0)var h=0;else{var S=o.suspendedLanes,E=o.pingedLanes;h=(1<<31-gt(42|e)+1)-1,h&=f&~(S&~E),h=h&201326741?h&201326741|1:h?h|2:0}h!==0&&(i=!0,yv(o,h))}else h=Ct,h=as(o,o===Yt?h:0,o.cancelPendingCommit!==null||o.timeoutHandle!==-1),(h&3)===0||Zn(o,h)||(i=!0,yv(o,h));o=o.next}while(i);vm=!1}}function Kw(){pv()}function pv(){Xu=gm=!1;var e=0;_r!==0&&rS()&&(e=_r);for(var t=Je(),i=null,o=Qu;o!==null;){var f=o.next,h=gv(o,t);h===0?(o.next=null,i===null?Qu=f:i.next=f,f===null&&(po=i)):(i=o,(e!==0||(h&3)!==0)&&(Xu=!0)),o=f}Ln!==0&&Ln!==5||kc(e),_r!==0&&(_r=0)}function gv(e,t){for(var i=e.suspendedLanes,o=e.pingedLanes,f=e.expirationTimes,h=e.pendingLanes&-62914561;0<h;){var S=31-gt(h),E=1<<S,U=f[S];U===-1?((E&i)===0||(E&o)!==0)&&(f[S]=nr(E,t)):U<=t&&(e.expiredLanes|=E),h&=~E}if(t=Yt,i=Ct,i=as(e,e===t?i:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),o=e.callbackNode,i===0||e===t&&(Ft===2||Ft===9)||e.cancelPendingCommit!==null)return o!==null&&o!==null&&ae(o),e.callbackNode=null,e.callbackPriority=0;if((i&3)===0||Zn(e,i)){if(t=i&-i,t===e.callbackPriority)return t;switch(o!==null&&ae(o),hn(i)){case 2:case 8:i=an;break;case 32:i=mt;break;case 268435456:i=Kt;break;default:i=mt}return o=vv.bind(null,e),i=ye(i,o),e.callbackPriority=t,e.callbackNode=i,t}return o!==null&&o!==null&&ae(o),e.callbackPriority=2,e.callbackNode=null,2}function vv(e,t){if(Ln!==0&&Ln!==5)return e.callbackNode=null,e.callbackPriority=0,null;var i=e.callbackNode;if(Ku()&&e.callbackNode!==i)return null;var o=Ct;return o=as(e,e===Yt?o:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),o===0?null:(Zg(e,o,t),gv(e,Je()),e.callbackNode!=null&&e.callbackNode===i?vv.bind(null,e):null)}function yv(e,t){if(Ku())return null;Zg(e,t,!0)}function Qw(){oS(function(){(zt&6)!==0?ye(It,Kw):pv()})}function ym(){if(_r===0){var e=on;e===0&&(e=at,at<<=1,(at&261888)===0&&(at=256)),_r=e}return _r}function xv(e){return e==null||typeof e=="symbol"||typeof e=="boolean"?null:typeof e=="function"?e:gi(""+e)}function bv(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 Xw(e,t,i,o,f){if(t==="submit"&&i&&i.stateNode===f){var h=xv((f[Me]||null).action),S=o.submitter;S&&(t=(t=S[Me]||null)?xv(t.formAction):S.getAttribute("formAction"),t!==null&&(h=t,S=null));var E=new Pl("action","action",null,o,f);e.push({event:E,listeners:[{instance:null,listener:function(){if(o.defaultPrevented){if(_r!==0){var U=S?bv(f,S):new FormData(f);Hf(i,{pending:!0,data:U,method:f.method,action:h},null,U)}}else typeof h=="function"&&(E.preventDefault(),U=S?bv(f,S):new FormData(f),Hf(i,{pending:!0,data:U,method:f.method,action:h},h,U))},currentTarget:f}]})}}for(var xm=0;xm<ds.length;xm++){var bm=ds[xm],Zw=bm.toLowerCase(),Jw=bm[0].toUpperCase()+bm.slice(1);ra(Zw,"on"+Jw)}ra(Qo,"onAnimationEnd"),ra(gu,"onAnimationIteration"),ra(vu,"onAnimationStart"),ra("dblclick","onDoubleClick"),ra("focusin","onFocus"),ra("focusout","onBlur"),ra(yu,"onTransitionRun"),ra(jf,"onTransitionStart"),ra(xu,"onTransitionCancel"),ra(xr,"onTransitionEnd"),pn("onMouseEnter",["mouseout","mouseover"]),pn("onMouseLeave",["mouseout","mouseover"]),pn("onPointerEnter",["pointerout","pointerover"]),pn("onPointerLeave",["pointerout","pointerover"]),Lt("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),Lt("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),Lt("onBeforeInput",["compositionend","keypress","textInput","paste"]),Lt("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),Lt("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),Lt("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Ac="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(" "),eS=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(Ac));function wv(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 E=o[S],U=E.instance,ie=E.currentTarget;if(E=E.listener,U!==h&&f.isPropagationStopped())break e;h=E,f.currentTarget=ie;try{h(f)}catch(xe){ks(xe)}f.currentTarget=null,h=U}else for(S=0;S<o.length;S++){if(E=o[S],U=E.instance,ie=E.currentTarget,E=E.listener,U!==h&&f.isPropagationStopped())break e;h=E,f.currentTarget=ie;try{h(f)}catch(xe){ks(xe)}f.currentTarget=null,h=U}}}}function St(e,t){var i=t[ut];i===void 0&&(i=t[ut]=new Set);var o=e+"__bubble";i.has(o)||(Sv(t,e,2,!1),i.add(o))}function wm(e,t,i){var o=0;t&&(o|=4),Sv(i,e,o,t)}var Zu="_reactListening"+Math.random().toString(36).slice(2);function Sm(e){if(!e[Zu]){e[Zu]=!0,ha.forEach(function(i){i!=="selectionchange"&&(eS.has(i)||wm(i,!1,e),wm(i,!0,e))});var t=e.nodeType===9?e:e.ownerDocument;t===null||t[Zu]||(t[Zu]=!0,wm("selectionchange",!1,t))}}function Sv(e,t,i,o){switch(Xv(t)){case 2:var f=MS;break;case 8:f=TS;break;default:f=Om}i=f.bind(null,t,i,e),f=void 0,!Oo||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 Cm(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 E=o.stateNode.containerInfo;if(E===f)break;if(S===4)for(S=o.return;S!==null;){var U=S.tag;if((U===3||U===4)&&S.stateNode.containerInfo===f)return;S=S.return}for(;E!==null;){if(S=Qt(E),S===null)return;if(U=S.tag,U===5||U===6||U===26||U===27){o=h=S;continue e}E=E.parentNode}}o=o.return}gf(function(){var ie=h,xe=rs(i),je=[];e:{var le=Xo.get(e);if(le!==void 0){var pe=Pl,Ye=e;switch(e){case"keypress":if(Fl(i)===0)break e;case"keydown":case"keyup":pe=uu;break;case"focusin":Ye="focus",pe=$l;break;case"focusout":Ye="blur",pe=$l;break;case"beforeblur":case"afterblur":pe=$l;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":pe=Po;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":pe=tl;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":pe=dr;break;case Qo:case gu:case vu:pe=ht;break;case xr:pe=Fs;break;case"scroll":case"scrollend":pe=Fo;break;case"wheel":pe=du;break;case"copy":case"cut":case"paste":pe=cr;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":pe=Bs;break;case"toggle":case"beforetoggle":pe=wf}var st=(t&4)!==0,Ut=!st&&(e==="scroll"||e==="scrollend"),Z=st?le!==null?le+"Capture":null:le;st=[];for(var Y=ie,se;Y!==null;){var Ce=Y;if(se=Ce.stateNode,Ce=Ce.tag,Ce!==5&&Ce!==26&&Ce!==27||se===null||Z===null||(Ce=Zr(Y,Z),Ce!=null&&st.push(Nc(Y,Ce,se))),Ut)break;Y=Y.return}0<st.length&&(le=new pe(le,Ye,null,i,xe),je.push({event:le,listeners:st}))}}if((t&7)===0){e:{if(le=e==="mouseover"||e==="pointerover",pe=e==="mouseout"||e==="pointerout",le&&i!==Bl&&(Ye=i.relatedTarget||i.fromElement)&&(Qt(Ye)||Ye[Ge]))break e;if((pe||le)&&(le=xe.window===xe?xe:(le=xe.ownerDocument)?le.defaultView||le.parentWindow:window,pe?(Ye=i.relatedTarget||i.toElement,pe=ie,Ye=Ye?Qt(Ye):null,Ye!==null&&(Ut=d(Ye),st=Ye.tag,Ye!==Ut||st!==5&&st!==27&&st!==6)&&(Ye=null)):(pe=null,Ye=ie),pe!==Ye)){if(st=Po,Ce="onMouseLeave",Z="onMouseEnter",Y="mouse",(e==="pointerout"||e==="pointerover")&&(st=Bs,Ce="onPointerLeave",Z="onPointerEnter",Y="pointer"),Ut=pe==null?le:Ot(pe),se=Ye==null?le:Ot(Ye),le=new st(Ce,Y+"leave",pe,i,xe),le.target=Ut,le.relatedTarget=se,Ce=null,Qt(xe)===ie&&(st=new st(Z,Y+"enter",Ye,i,xe),st.target=se,st.relatedTarget=Ut,Ce=st),Ut=Ce,pe&&Ye)t:{for(st=tS,Z=pe,Y=Ye,se=0,Ce=Z;Ce;Ce=st(Ce))se++;Ce=0;for(var tt=Y;tt;tt=st(tt))Ce++;for(;0<se-Ce;)Z=st(Z),se--;for(;0<Ce-se;)Y=st(Y),Ce--;for(;se--;){if(Z===Y||Y!==null&&Z===Y.alternate){st=Z;break t}Z=st(Z),Y=st(Y)}st=null}else st=null;pe!==null&&Cv(je,le,pe,st,!1),Ye!==null&&Ut!==null&&Cv(je,Ut,Ye,st,!0)}}e:{if(le=ie?Ot(ie):window,pe=le.nodeName&&le.nodeName.toLowerCase(),pe==="select"||pe==="input"&&le.type==="file")var Et=Cs;else if(mu(le))if(sl)Et=gr;else{Et=Cf;var Qe=pr}else pe=le.nodeName,!pe||pe.toLowerCase()!=="input"||le.type!=="checkbox"&&le.type!=="radio"?ie&&pi(ie.elementType)&&(Et=Cs):Et=qn;if(Et&&(Et=Et(e,ie))){us(je,Et,i,xe);break e}Qe&&Qe(e,le,ie),e==="focusout"&&ie&&le.type==="number"&&ie.memoizedProps.value!=null&&Ss(le,"number",le.value)}switch(Qe=ie?Ot(ie):window,e){case"focusin":(mu(Qe)||Qe.contentEditable==="true")&&(vr=Qe,yr=ie,Us=null);break;case"focusout":Us=yr=vr=null;break;case"mousedown":ql=!0;break;case"contextmenu":case"mouseup":case"dragend":ql=!1,ki(je,i,xe);break;case"selectionchange":if(pu)break;case"keydown":case"keyup":ki(je,i,xe)}var pt;if(wi)e:{switch(e){case"compositionstart":var jt="onCompositionStart";break e;case"compositionend":jt="onCompositionEnd";break e;case"compositionupdate":jt="onCompositionUpdate";break e}jt=void 0}else mr?nl(e,i)&&(jt="onCompositionEnd"):e==="keydown"&&i.keyCode===229&&(jt="onCompositionStart");jt&&(Vo&&i.locale!=="ko"&&(mr||jt!=="onCompositionStart"?jt==="onCompositionEnd"&&mr&&(pt=vf()):(os=xe,lu="value"in os?os.value:os.textContent,mr=!0)),Qe=Ju(ie,jt),0<Qe.length&&(jt=new Uo(jt,e,null,i,xe),je.push({event:jt,listeners:Qe}),pt?jt.data=pt:(pt=Si(i),pt!==null&&(jt.data=pt)))),(pt=fu?Sf(e,i):en(e,i))&&(jt=Ju(ie,"onBeforeInput"),0<jt.length&&(Qe=new Uo("onBeforeInput","beforeinput",null,i,xe),je.push({event:Qe,listeners:jt}),Qe.data=pt)),Xw(je,e,ie,i,xe)}wv(je,t)})}function Nc(e,t,i){return{instance:e,listener:t,currentTarget:i}}function Ju(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=Zr(e,i),f!=null&&o.unshift(Nc(e,f,h)),f=Zr(e,t),f!=null&&o.push(Nc(e,f,h))),e.tag===3)return o;e=e.return}return[]}function tS(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5&&e.tag!==27);return e||null}function Cv(e,t,i,o,f){for(var h=t._reactName,S=[];i!==null&&i!==o;){var E=i,U=E.alternate,ie=E.stateNode;if(E=E.tag,U!==null&&U===o)break;E!==5&&E!==26&&E!==27||ie===null||(U=ie,f?(ie=Zr(i,h),ie!=null&&S.unshift(Nc(i,ie,U))):f||(ie=Zr(i,h),ie!=null&&S.push(Nc(i,ie,U)))),i=i.return}S.length!==0&&e.push({event:t,listeners:S})}var nS=/\r\n?/g,aS=/\u0000|\uFFFD/g;function jv(e){return(typeof e=="string"?e:""+e).replace(nS,`
9
- `).replace(aS,"")}function kv(e,t){return t=jv(t),jv(e)===t}function $t(e,t,i,o,f,h){switch(i){case"children":typeof o=="string"?t==="body"||t==="textarea"&&o===""||qa(e,o):(typeof o=="number"||typeof o=="bigint")&&t!=="body"&&qa(e,""+o);break;case"className":ir(e,"class",o);break;case"tabIndex":ir(e,"tabindex",o);break;case"dir":case"role":case"viewBox":case"width":case"height":ir(e,i,o);break;case"style":Il(e,o,h);break;case"data":if(t!=="object"){ir(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=gi(""+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=gi(""+o),e.setAttribute(i,o);break;case"onClick":o!=null&&(e.onclick=Ga);break;case"onScroll":o!=null&&St("scroll",e);break;case"onScrollEnd":o!=null&&St("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=gi(""+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":St("beforetoggle",e),St("toggle",e),sr(e,"popover",o);break;case"xlinkActuate":$a(e,"http://www.w3.org/1999/xlink","xlink:actuate",o);break;case"xlinkArcrole":$a(e,"http://www.w3.org/1999/xlink","xlink:arcrole",o);break;case"xlinkRole":$a(e,"http://www.w3.org/1999/xlink","xlink:role",o);break;case"xlinkShow":$a(e,"http://www.w3.org/1999/xlink","xlink:show",o);break;case"xlinkTitle":$a(e,"http://www.w3.org/1999/xlink","xlink:title",o);break;case"xlinkType":$a(e,"http://www.w3.org/1999/xlink","xlink:type",o);break;case"xmlBase":$a(e,"http://www.w3.org/XML/1998/namespace","xml:base",o);break;case"xmlLang":$a(e,"http://www.w3.org/XML/1998/namespace","xml:lang",o);break;case"xmlSpace":$a(e,"http://www.w3.org/XML/1998/namespace","xml:space",o);break;case"is":sr(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=Ol.get(i)||i,sr(e,i,o))}}function jm(e,t,i,o,f,h){switch(i){case"style":Il(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"?qa(e,o):(typeof o=="number"||typeof o=="bigint")&&qa(e,""+o);break;case"onScroll":o!=null&&St("scroll",e);break;case"onScrollEnd":o!=null&&St("scrollend",e);break;case"onClick":o!=null&&(e.onclick=Ga);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!is.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,""):sr(e,i,o)}}}function Qn(e,t,i){switch(t){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":St("error",e),St("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":St("invalid",e);var E=h=S=f=null,U=null,ie=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":U=xe;break;case"defaultChecked":ie=xe;break;case"value":h=xe;break;case"defaultValue":E=xe;break;case"children":case"dangerouslySetInnerHTML":if(xe!=null)throw Error(l(137,t));break;default:$t(e,t,o,xe,i,null)}}Is(e,h,E,U,ie,S,f,!1);return;case"select":St("invalid",e),o=S=h=null;for(f in i)if(i.hasOwnProperty(f)&&(E=i[f],E!=null))switch(f){case"value":h=E;break;case"defaultValue":S=E;break;case"multiple":o=E;default:$t(e,t,f,E,i,null)}t=h,i=S,e.multiple=!!o,t!=null?Ua(e,!!o,t,!1):i!=null&&Ua(e,!!o,i,!0);return;case"textarea":St("invalid",e),h=f=o=null;for(S in i)if(i.hasOwnProperty(S)&&(E=i[S],E!=null))switch(S){case"value":o=E;break;case"defaultValue":f=E;break;case"children":h=E;break;case"dangerouslySetInnerHTML":if(E!=null)throw Error(l(91));break;default:$t(e,t,S,E,i,null)}rr(e,o,f,h);return;case"option":for(U in i)i.hasOwnProperty(U)&&(o=i[U],o!=null)&&(U==="selected"?e.selected=o&&typeof o!="function"&&typeof o!="symbol":$t(e,t,U,o,i,null));return;case"dialog":St("beforetoggle",e),St("toggle",e),St("cancel",e),St("close",e);break;case"iframe":case"object":St("load",e);break;case"video":case"audio":for(o=0;o<Ac.length;o++)St(Ac[o],e);break;case"image":St("error",e),St("load",e);break;case"details":St("toggle",e);break;case"embed":case"source":case"link":St("error",e),St("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(ie in i)if(i.hasOwnProperty(ie)&&(o=i[ie],o!=null))switch(ie){case"children":case"dangerouslySetInnerHTML":throw Error(l(137,t));default:$t(e,t,ie,o,i,null)}return;default:if(pi(t)){for(xe in i)i.hasOwnProperty(xe)&&(o=i[xe],o!==void 0&&jm(e,t,xe,o,i,void 0));return}}for(E in i)i.hasOwnProperty(E)&&(o=i[E],o!=null&&$t(e,t,E,o,i,null))}function sS(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,E=null,U=null,ie=null,xe=null;for(pe in i){var je=i[pe];if(i.hasOwnProperty(pe)&&je!=null)switch(pe){case"checked":break;case"value":break;case"defaultValue":U=je;default:o.hasOwnProperty(pe)||$t(e,t,pe,null,o,je)}}for(var le in o){var pe=o[le];if(je=i[le],o.hasOwnProperty(le)&&(pe!=null||je!=null))switch(le){case"type":h=pe;break;case"name":f=pe;break;case"checked":ie=pe;break;case"defaultChecked":xe=pe;break;case"value":S=pe;break;case"defaultValue":E=pe;break;case"children":case"dangerouslySetInnerHTML":if(pe!=null)throw Error(l(137,t));break;default:pe!==je&&$t(e,t,le,pe,o,je)}}ea(e,S,E,U,ie,xe,h,f);return;case"select":pe=S=E=le=null;for(h in i)if(U=i[h],i.hasOwnProperty(h)&&U!=null)switch(h){case"value":break;case"multiple":pe=U;default:o.hasOwnProperty(h)||$t(e,t,h,null,o,U)}for(f in o)if(h=o[f],U=i[f],o.hasOwnProperty(f)&&(h!=null||U!=null))switch(f){case"value":le=h;break;case"defaultValue":E=h;break;case"multiple":S=h;default:h!==U&&$t(e,t,f,h,o,U)}t=E,i=S,o=pe,le!=null?Ua(e,!!i,le,!1):!!o!=!!i&&(t!=null?Ua(e,!!i,t,!0):Ua(e,!!i,i?[]:"",!1));return;case"textarea":pe=le=null;for(E in i)if(f=i[E],i.hasOwnProperty(E)&&f!=null&&!o.hasOwnProperty(E))switch(E){case"value":break;case"children":break;default:$t(e,t,E,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":le=f;break;case"defaultValue":pe=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)}Qr(e,le,pe);return;case"option":for(var Ye in i)le=i[Ye],i.hasOwnProperty(Ye)&&le!=null&&!o.hasOwnProperty(Ye)&&(Ye==="selected"?e.selected=!1:$t(e,t,Ye,null,o,le));for(U in o)le=o[U],pe=i[U],o.hasOwnProperty(U)&&le!==pe&&(le!=null||pe!=null)&&(U==="selected"?e.selected=le&&typeof le!="function"&&typeof le!="symbol":$t(e,t,U,le,o,pe));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 st in i)le=i[st],i.hasOwnProperty(st)&&le!=null&&!o.hasOwnProperty(st)&&$t(e,t,st,null,o,le);for(ie in o)if(le=o[ie],pe=i[ie],o.hasOwnProperty(ie)&&le!==pe&&(le!=null||pe!=null))switch(ie){case"children":case"dangerouslySetInnerHTML":if(le!=null)throw Error(l(137,t));break;default:$t(e,t,ie,le,o,pe)}return;default:if(pi(t)){for(var Ut in i)le=i[Ut],i.hasOwnProperty(Ut)&&le!==void 0&&!o.hasOwnProperty(Ut)&&jm(e,t,Ut,void 0,o,le);for(xe in o)le=o[xe],pe=i[xe],!o.hasOwnProperty(xe)||le===pe||le===void 0&&pe===void 0||jm(e,t,xe,le,o,pe);return}}for(var Z in i)le=i[Z],i.hasOwnProperty(Z)&&le!=null&&!o.hasOwnProperty(Z)&&$t(e,t,Z,null,o,le);for(je in o)le=o[je],pe=i[je],!o.hasOwnProperty(je)||le===pe||le==null&&pe==null||$t(e,t,je,le,o,pe)}function Av(e){switch(e){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function iS(){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,E=f.duration;if(h&&E&&Av(S)){for(S=0,E=f.responseEnd,o+=1;o<i.length;o++){var U=i[o],ie=U.startTime;if(ie>E)break;var xe=U.transferSize,je=U.initiatorType;xe&&Av(je)&&(U=U.responseEnd,S+=xe*(U<E?1:(E-ie)/(U-ie)))}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 km=null,Am=null;function ed(e){return e.nodeType===9?e:e.ownerDocument}function Nv(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 Mv(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 Nm(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 Mm=null;function rS(){var e=window.event;return e&&e.type==="popstate"?e===Mm?!1:(Mm=e,!0):(Mm=null,!1)}var Tv=typeof setTimeout=="function"?setTimeout:void 0,lS=typeof clearTimeout=="function"?clearTimeout:void 0,Ev=typeof Promise=="function"?Promise:void 0,oS=typeof queueMicrotask=="function"?queueMicrotask:typeof Ev<"u"?function(e){return Ev.resolve(null).then(e).catch(cS)}:Tv;function cS(e){setTimeout(function(){throw e})}function zr(e){return e==="head"}function Rv(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),xo(t);return}o--}else if(i==="$"||i==="$?"||i==="$~"||i==="$!"||i==="&")o++;else if(i==="html")Mc(e.ownerDocument.documentElement);else if(i==="head"){i=e.ownerDocument.head,Mc(i);for(var h=i.firstChild;h;){var S=h.nextSibling,E=h.nodeName;h[kt]||E==="SCRIPT"||E==="STYLE"||E==="LINK"&&h.rel.toLowerCase()==="stylesheet"||i.removeChild(h),h=S}}else i==="body"&&Mc(e.ownerDocument.body);i=f}while(i);xo(t)}function Dv(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 Tm(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":Tm(i),Bt(i);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(i.rel.toLowerCase()==="stylesheet")continue}e.removeChild(i)}}function uS(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[kt])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=vs(e.nextSibling),e===null)break}return null}function dS(e,t,i){if(t==="")return null;for(;e.nodeType!==3;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!i||(e=vs(e.nextSibling),e===null))return null;return e}function Lv(e,t){for(;e.nodeType!==8;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!t||(e=vs(e.nextSibling),e===null))return null;return e}function Em(e){return e.data==="$?"||e.data==="$~"}function Rm(e){return e.data==="$!"||e.data==="$?"&&e.ownerDocument.readyState!=="loading"}function fS(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 vs(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 Dm=null;function _v(e){e=e.nextSibling;for(var t=0;e;){if(e.nodeType===8){var i=e.data;if(i==="/$"||i==="/&"){if(t===0)return vs(e.nextSibling);t--}else i!=="$"&&i!=="$!"&&i!=="$?"&&i!=="$~"&&i!=="&"||t++}e=e.nextSibling}return null}function zv(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 Iv(e,t,i){switch(t=ed(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 Mc(e){for(var t=e.attributes;t.length;)e.removeAttributeNode(t[0]);Bt(e)}var ys=new Map,Ov=new Set;function td(e){return typeof e.getRootNode=="function"?e.getRootNode():e.nodeType===9?e:e.ownerDocument}var Xi=ee.d;ee.d={f:mS,r:hS,D:pS,C:gS,L:vS,m:yS,X:bS,S:xS,M:wS};function mS(){var e=Xi.f(),t=Vu();return e||t}function hS(e){var t=rn(e);t!==null&&t.tag===5&&t.type==="form"?eg(t):Xi.r(e)}var go=typeof document>"u"?null:document;function Hv(e,t,i){var o=go;if(o&&typeof t=="string"&&t){var f=dn(t);f='link[rel="'+e+'"][href="'+f+'"]',typeof i=="string"&&(f+='[crossorigin="'+i+'"]'),Ov.has(f)||(Ov.add(f),e={rel:e,crossOrigin:i,href:t},o.querySelector(f)===null&&(t=o.createElement("link"),Qn(t,"link",e),Vt(t),o.head.appendChild(t)))}}function pS(e){Xi.D(e),Hv("dns-prefetch",e,null)}function gS(e,t){Xi.C(e,t),Hv("preconnect",e,t)}function vS(e,t,i){Xi.L(e,t,i);var o=go;if(o&&e&&t){var f='link[rel="preload"][as="'+dn(t)+'"]';t==="image"&&i&&i.imageSrcSet?(f+='[imagesrcset="'+dn(i.imageSrcSet)+'"]',typeof i.imageSizes=="string"&&(f+='[imagesizes="'+dn(i.imageSizes)+'"]')):f+='[href="'+dn(e)+'"]';var h=f;switch(t){case"style":h=vo(e);break;case"script":h=yo(e)}ys.has(h)||(e=x({rel:"preload",href:t==="image"&&i&&i.imageSrcSet?void 0:e,as:t},i),ys.set(h,e),o.querySelector(f)!==null||t==="style"&&o.querySelector(Tc(h))||t==="script"&&o.querySelector(Ec(h))||(t=o.createElement("link"),Qn(t,"link",e),Vt(t),o.head.appendChild(t)))}}function yS(e,t){Xi.m(e,t);var i=go;if(i&&e){var o=t&&typeof t.as=="string"?t.as:"script",f='link[rel="modulepreload"][as="'+dn(o)+'"][href="'+dn(e)+'"]',h=f;switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":h=yo(e)}if(!ys.has(h)&&(e=x({rel:"modulepreload",href:e},t),ys.set(h,e),i.querySelector(f)===null)){switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(i.querySelector(Ec(h)))return}o=i.createElement("link"),Qn(o,"link",e),Vt(o),i.head.appendChild(o)}}}function xS(e,t,i){Xi.S(e,t,i);var o=go;if(o&&e){var f=Dt(o).hoistableStyles,h=vo(e);t=t||"default";var S=f.get(h);if(!S){var E={loading:0,preload:null};if(S=o.querySelector(Tc(h)))E.loading=5;else{e=x({rel:"stylesheet",href:e,"data-precedence":t},i),(i=ys.get(h))&&Lm(e,i);var U=S=o.createElement("link");Vt(U),Qn(U,"link",e),U._p=new Promise(function(ie,xe){U.onload=ie,U.onerror=xe}),U.addEventListener("load",function(){E.loading|=1}),U.addEventListener("error",function(){E.loading|=2}),E.loading|=4,nd(S,t,o)}S={type:"stylesheet",instance:S,count:1,state:E},f.set(h,S)}}}function bS(e,t){Xi.X(e,t);var i=go;if(i&&e){var o=Dt(i).hoistableScripts,f=yo(e),h=o.get(f);h||(h=i.querySelector(Ec(f)),h||(e=x({src:e,async:!0},t),(t=ys.get(f))&&_m(e,t),h=i.createElement("script"),Vt(h),Qn(h,"link",e),i.head.appendChild(h)),h={type:"script",instance:h,count:1,state:null},o.set(f,h))}}function wS(e,t){Xi.M(e,t);var i=go;if(i&&e){var o=Dt(i).hoistableScripts,f=yo(e),h=o.get(f);h||(h=i.querySelector(Ec(f)),h||(e=x({src:e,async:!0,type:"module"},t),(t=ys.get(f))&&_m(e,t),h=i.createElement("script"),Vt(h),Qn(h,"link",e),i.head.appendChild(h)),h={type:"script",instance:h,count:1,state:null},o.set(f,h))}}function Bv(e,t,i,o){var f=(f=me.current)?td(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=Dt(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=Dt(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(Tc(e)))&&!h._p&&(S.instance=h,S.state.loading=5),ys.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},ys.set(e,i),h||SS(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=yo(i),i=Dt(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="'+dn(e)+'"'}function Tc(e){return'link[rel="stylesheet"]['+e+"]"}function Fv(e){return x({},e,{"data-precedence":e.precedence,precedence:null})}function SS(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}),Qn(t,"link",i),Vt(t),e.head.appendChild(t))}function yo(e){return'[src="'+dn(e)+'"]'}function Ec(e){return"script[async]"+e}function Pv(e,t,i){if(t.count++,t.instance===null)switch(t.type){case"style":var o=e.querySelector('style[data-href~="'+dn(i.href)+'"]');if(o)return t.instance=o,Vt(o),o;var f=x({},i,{"data-href":i.href,"data-precedence":i.precedence,href:null,precedence:null});return o=(e.ownerDocument||e).createElement("style"),Vt(o),Qn(o,"style",f),nd(o,i.precedence,e),t.instance=o;case"stylesheet":f=vo(i.href);var h=e.querySelector(Tc(f));if(h)return t.state.loading|=4,t.instance=h,Vt(h),h;o=Fv(i),(f=ys.get(f))&&Lm(o,f),h=(e.ownerDocument||e).createElement("link"),Vt(h);var S=h;return S._p=new Promise(function(E,U){S.onload=E,S.onerror=U}),Qn(h,"link",o),t.state.loading|=4,nd(h,i.precedence,e),t.instance=h;case"script":return h=yo(i.src),(f=e.querySelector(Ec(h)))?(t.instance=f,Vt(f),f):(o=i,(f=ys.get(h))&&(o=x({},i),_m(o,f)),e=e.ownerDocument||e,f=e.createElement("script"),Vt(f),Qn(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,nd(o,i.precedence,e));return t.instance}function nd(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 E=o[S];if(E.dataset.precedence===t)h=E;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 Lm(e,t){e.crossOrigin==null&&(e.crossOrigin=t.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=t.referrerPolicy),e.title==null&&(e.title=t.title)}function _m(e,t){e.crossOrigin==null&&(e.crossOrigin=t.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=t.referrerPolicy),e.integrity==null&&(e.integrity=t.integrity)}var ad=null;function $v(e,t,i){if(ad===null){var o=new Map,f=ad=new Map;f.set(i,o)}else f=ad,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[kt]||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 E=o.get(S);E?E.push(h):o.set(S,[h])}}return o}function Uv(e,t,i){e=e.ownerDocument||e,e.head.insertBefore(i,t==="title"?e.querySelector("head > title"):null)}function CS(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 qv(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function jS(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(Tc(f));if(h){t=h._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(e.count++,e=sd.bind(e),t.then(e,e)),i.state.loading|=4,i.instance=h,Vt(h);return}h=t.ownerDocument||t,o=Fv(o),(f=ys.get(f))&&Lm(o,f),h=h.createElement("link"),Vt(h);var S=h;S._p=new Promise(function(E,U){S.onload=E,S.onerror=U}),Qn(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=sd.bind(e),t.addEventListener("load",i),t.addEventListener("error",i))}}var zm=0;function kS(e,t){return e.stylesheets&&e.count===0&&rd(e,e.stylesheets),0<e.count||0<e.imgCount?function(i){var o=setTimeout(function(){if(e.stylesheets&&rd(e,e.stylesheets),e.unsuspend){var h=e.unsuspend;e.unsuspend=null,h()}},6e4+t);0<e.imgBytes&&zm===0&&(zm=62500*iS());var f=setTimeout(function(){if(e.waitingForImages=!1,e.count===0&&(e.stylesheets&&rd(e,e.stylesheets),e.unsuspend)){var h=e.unsuspend;e.unsuspend=null,h()}},(e.imgBytes>zm?50:800)+t);return e.unsuspend=i,function(){e.unsuspend=null,clearTimeout(o),clearTimeout(f)}}:null}function sd(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)rd(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var id=null;function rd(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,id=new Map,t.forEach(AS,e),id=null,sd.call(e))}function AS(e,t){if(!(t.state.loading&4)){var i=id.get(e);if(i)var o=i.get(null);else{i=new Map,id.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=sd.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 Rc={$$typeof:R,Provider:null,Consumer:null,_currentValue:G,_currentValue2:G,_threadCount:0};function NS(e,t,i,o,f,h,S,E,U){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=zs(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=zs(0),this.hiddenUpdates=zs(null),this.identifierPrefix=o,this.onUncaughtError=f,this.onCaughtError=h,this.onRecoverableError=S,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=U,this.incompleteTransitions=new Map}function Gv(e,t,i,o,f,h,S,E,U,ie,xe,je){return e=new NS(e,t,i,S,U,ie,xe,je,E),t=1,h===!0&&(t|=24),h=Vn(3,null,null,t),e.current=h,h.stateNode=e,t=ac(),t.refCount++,e.pooledCache=t,t.refCount++,h.memoizedState={element:o,isDehydrated:i,cache:t},cc(h),e}function Vv(e){return e?(e=Ei,e):Ei}function Wv(e,t,i,o,f,h){f=Vv(f),o.context===null?o.context=f:o.pendingContext=f,o=Sn(t),o.payload={element:i},h=h===void 0?null:h,h!==null&&(o.callback=h),i=ai(e,o,t),i!==null&&(za(i,e,t),ml(i,e,t))}function Yv(e,t){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var i=e.retryLane;e.retryLane=i!==0&&i<t?i:t}}function Im(e,t){Yv(e,t),(e=e.alternate)&&Yv(e,t)}function Kv(e){if(e.tag===13||e.tag===31){var t=Wa(e,67108864);t!==null&&za(t,e,67108864),Im(e,67108864)}}function Qv(e){if(e.tag===13||e.tag===31){var t=Xa();t=lt(t);var i=Wa(e,t);i!==null&&za(i,e,t),Im(e,t)}}var ld=!0;function MS(e,t,i,o){var f=I.T;I.T=null;var h=ee.p;try{ee.p=2,Om(e,t,i,o)}finally{ee.p=h,I.T=f}}function TS(e,t,i,o){var f=I.T;I.T=null;var h=ee.p;try{ee.p=8,Om(e,t,i,o)}finally{ee.p=h,I.T=f}}function Om(e,t,i,o){if(ld){var f=Hm(o);if(f===null)Cm(e,t,o,od,i),Zv(e,o);else if(RS(f,e,t,i,o))o.stopPropagation();else if(Zv(e,o),t&4&&-1<ES.indexOf(e)){for(;f!==null;){var h=rn(f);if(h!==null)switch(h.tag){case 3:if(h=h.stateNode,h.current.memoizedState.isDehydrated){var S=ns(h.pendingLanes);if(S!==0){var E=h;for(E.pendingLanes|=2,E.entangledLanes|=2;S;){var U=1<<31-gt(S);E.entanglements[1]|=U,S&=~U}oi(h),(zt&6)===0&&(qu=Je()+500,kc(0))}}break;case 31:case 13:E=Wa(h,2),E!==null&&za(E,h,2),Vu(),Im(h,2)}if(h=Hm(o),h===null&&Cm(e,t,o,od,i),h===f)break;f=h}f!==null&&o.stopPropagation()}else Cm(e,t,o,null,i)}}function Hm(e){return e=rs(e),Bm(e)}var od=null;function Bm(e){if(od=null,e=Qt(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 od=e,null}function Xv(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(Mt()){case It:return 2;case an:return 8;case mt:case Pn:return 32;case Kt:return 268435456;default:return 32}default:return 32}}var Fm=!1,Ir=null,Or=null,Hr=null,Dc=new Map,Lc=new Map,Br=[],ES="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 Zv(e,t){switch(e){case"focusin":case"focusout":Ir=null;break;case"dragenter":case"dragleave":Or=null;break;case"mouseover":case"mouseout":Hr=null;break;case"pointerover":case"pointerout":Dc.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":Lc.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=rn(t),t!==null&&Kv(t)),e):(e.eventSystemFlags|=o,t=e.targetContainers,f!==null&&t.indexOf(f)===-1&&t.push(f),e)}function RS(e,t,i,o,f){switch(t){case"focusin":return Ir=_c(Ir,e,t,i,o,f),!0;case"dragenter":return Or=_c(Or,e,t,i,o,f),!0;case"mouseover":return Hr=_c(Hr,e,t,i,o,f),!0;case"pointerover":var h=f.pointerId;return Dc.set(h,_c(Dc.get(h)||null,e,t,i,o,f)),!0;case"gotpointercapture":return h=f.pointerId,Lc.set(h,_c(Lc.get(h)||null,e,t,i,o,f)),!0}return!1}function Jv(e){var t=Qt(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,Dn(e.priority,function(){Qv(i)});return}}else if(t===31){if(t=p(i),t!==null){e.blockedOn=t,Dn(e.priority,function(){Qv(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 cd(e){if(e.blockedOn!==null)return!1;for(var t=e.targetContainers;0<t.length;){var i=Hm(e.nativeEvent);if(i===null){i=e.nativeEvent;var o=new i.constructor(i.type,i);Bl=o,i.target.dispatchEvent(o),Bl=null}else return t=rn(i),t!==null&&Kv(t),e.blockedOn=i,!1;t.shift()}return!0}function ey(e,t,i){cd(e)&&i.delete(t)}function DS(){Fm=!1,Ir!==null&&cd(Ir)&&(Ir=null),Or!==null&&cd(Or)&&(Or=null),Hr!==null&&cd(Hr)&&(Hr=null),Dc.forEach(ey),Lc.forEach(ey)}function ud(e,t){e.blockedOn===t&&(e.blockedOn=null,Fm||(Fm=!0,n.unstable_scheduleCallback(n.unstable_NormalPriority,DS)))}var dd=null;function ty(e){dd!==e&&(dd=e,n.unstable_scheduleCallback(n.unstable_NormalPriority,function(){dd===e&&(dd=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(Bm(o||i)===null)continue;break}var h=rn(i);h!==null&&(e.splice(t,3),t-=3,Hf(h,{pending:!0,data:f,method:i.method,action:o},o,f))}}))}function xo(e){function t(U){return ud(U,e)}Ir!==null&&ud(Ir,e),Or!==null&&ud(Or,e),Hr!==null&&ud(Hr,e),Dc.forEach(t),Lc.forEach(t);for(var i=0;i<Br.length;i++){var o=Br[i];o.blockedOn===e&&(o.blockedOn=null)}for(;0<Br.length&&(i=Br[0],i.blockedOn===null);)Jv(i),i.blockedOn===null&&Br.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||ty(i);else if(S){var E=null;if(h&&h.hasAttribute("formAction")){if(f=h,S=h[Me]||null)E=S.formAction;else if(Bm(f)!==null)continue}else E=S.action;typeof E=="function"?i[o+1]=E:(i.splice(o,3),o-=3),ty(i)}}}function ny(){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 Pm(e){this._internalRoot=e}fd.prototype.render=Pm.prototype.render=function(e){var t=this._internalRoot;if(t===null)throw Error(l(409));var i=t.current,o=Xa();Wv(i,o,e,t,null,null)},fd.prototype.unmount=Pm.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var t=e.containerInfo;Wv(e.current,2,null,e,null,null),Vu(),t[Ge]=null}};function fd(e){this._internalRoot=e}fd.prototype.unstable_scheduleHydration=function(e){if(e){var t=ss();e={blockedOn:null,target:e,priority:t};for(var i=0;i<Br.length&&t!==0&&t<Br[i].priority;i++);Br.splice(i,0,e),i===0&&Jv(e)}};var ay=a.version;if(ay!=="19.2.7")throw Error(l(527,ay,"19.2.7"));ee.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 LS={bundleType:0,version:"19.2.7",rendererPackageName:"react-dom",currentDispatcherRef:I,reconcilerVersion:"19.2.7"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var md=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!md.isDisabled&&md.supportsFiber)try{ze=md.inject(LS),Ae=md}catch{}}return Ic.createRoot=function(e,t){if(!c(e))throw Error(l(299));var i=!1,o="",f=ug,h=dg,S=fg;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=Gv(e,1,!1,null,null,i,o,null,f,h,S,ny),e[Ge]=t.current,Sm(e),new Pm(t)},Ic.hydrateRoot=function(e,t,i){if(!c(e))throw Error(l(299));var o=!1,f="",h=ug,S=dg,E=fg,U=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&&(E=i.onRecoverableError),i.formState!==void 0&&(U=i.formState)),t=Gv(e,1,!0,t,i??null,o,f,U,h,S,E,ny),t.context=Vv(null),i=t.current,o=Xa(),o=lt(o),f=Sn(o),f.callback=null,ai(i,f,o),i=o,t.current.lanes=i,vt(t,i),oi(t),e[Ge]=t.current,Sm(e),new fd(t)},Ic.version="19.2.7",Ic}var py;function C0(){if(py)return Gm.exports;py=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(),Gm.exports=S0(),Gm.exports}var j0=C0();const k0="https://otbyfkjxrkngvjziawki.supabase.co",A0="sb_publishable_NpUs0RDJH2YnllsqTKO6TQ_1jTdSsNQ",N0={getItem:()=>null,setItem:()=>{},removeItem:()=>{}},gy=typeof window<"u"&&!!window.liveDesk,ft=v0(k0,A0,{auth:{autoRefreshToken:!0,persistSession:!gy,storage:gy?N0:void 0,detectSessionInUrl:!0,flowType:"pkce",storageKey:"livedesk.mindexec.supabase.auth"}}),M0=new Set(["browserLanguage","platform","online","viewport","timezone","screen"]),T0={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])=>M0.has(a)&&r!==void 0))}};function E0(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 R0(n=T0){return n.collect()}async function D0(n,a="livedesk"){const{data:r,error:l}=await ft.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 ft.rpc("register_product_access",{p_product_key:a,p_access_type:"free"});if(j)throw j}const[d,m,p]=await Promise.all([ft.from("products").select("id, product_key, name, description, sort_order").order("sort_order"),ft.from("product_admins").select("product_id, role").eq("user_id",n),ft.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)),x=c==="owner",b=x?v.map(j=>j.id):[...new Set([...g,...w])];return{products:v,access:{userId:n,globalRole:c,accessibleProductIds:b,managedProductIds:x?v.map(j=>j.id):g,canViewAllProducts:x,canViewAllPrivatePosts:x,canManageAllProducts:x,canCreateAnnouncements:x||g.length>0}}}async function L0(n=""){const{data:a,error:r}=await ft.rpc("search_support_posts",{p_query:n.trim()||null,p_limit:250});if(r)throw r;return a||[]}async function _0(n){const{data:a,error:r}=await ft.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 ft.storage.from("support-attachments").createSignedUrl(c.storage_path,3600);return{...c,signed_url:d.data?.signedUrl||void 0}}))}async function z0(){const{data:n,error:a}=await ft.from("support_notifications").select("*").order("created_at",{ascending:!1}).limit(30);if(a)throw a;return n||[]}async function I0(n){const{error:a}=await ft.rpc("mark_support_notification_read",{p_notification_id:n});if(a)throw a}async function vy(n){const{data:a,error:r}=await ft.from("support_comments").select("*").eq("post_id",n).order("created_at");if(r)throw r;return a||[]}async function O0(n){const{data:a,error:r}=await ft.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 H0(n){const{data:a,error:r}=await ft.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?R0():{}});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 B0=new Set(["image/png","image/jpeg","image/webp","text/plain","text/markdown","application/json","application/pdf"]);async function F0(n,a){if(!B0.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 ft.storage.from("support-attachments").upload(c,a,{contentType:a.type,upsert:!1});if(d.error)throw d.error;const{data:m,error:p}=await ft.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 ft.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 P0(n,a,r,l){const{error:c}=await ft.rpc("update_support_post",{p_post_id:n,p_title:a,p_body:r,p_visibility:l});if(c)throw c}async function $0(n,a){const{error:r}=await ft.rpc("add_support_comment",{p_post_id:n,p_body:a});if(r)throw r}async function U0(n){const{data:a,error:r}=await ft.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 q0(n,a){const{error:r}=await ft.rpc("change_support_post_status",{p_post_id:n,p_target_status:a});if(r)throw r}async function G0(n){const{error:a}=await ft.rpc("set_support_post_hidden",{p_post_id:n,p_hidden:!0});if(a)throw a}async function V0(n,a){const{error:r}=await ft.rpc("set_support_post_locked",{p_post_id:n,p_locked:a});if(r)throw r}async function W0(n,a){const{error:r}=await ft.rpc("set_support_post_pinned",{p_post_id:n,p_pinned:a});if(r)throw r}async function Y0(n,a){const{error:r}=await ft.rpc("mark_support_duplicate",{p_post_id:n,p_duplicate_of_post_id:a});if(r)throw r}async function K0(n,a){const{error:r}=await ft.rpc("accept_support_answer",{p_post_id:n,p_comment_id:a});if(r)throw r}async function Q0(n,a=!0){const{error:r}=await ft.rpc("hide_support_comment",{p_comment_id:n,p_hidden:a});if(r)throw r}const Mh=[{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"}],X0=[{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"}],Z0={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"]},J0={type:"all",product:"",status:"all",visibility:"all",sort:"recent",query:""};function Ym(){if(typeof window>"u")return J0;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 eC(n){return n==="all"?"":n==="question"?"questions":n==="issue"?"issues":n==="feature"?"features":"announcements"}function tC(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=eC(r.type),d=l.toString();return`/support${c?`/${c}`:""}${d?`?${d}`:""}`}function hd(n){const a=new Date(n);return Number.isFinite(a.getTime())?a.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"}):n}function Km(n){return n.replaceAll("-"," ").replace(/\b\w/g,a=>a.toUpperCase())}function yy(n){return n==="question"?BS:n==="issue"?FS:n==="feature"?PS:$S}function xy(n){return Mh.find(a=>a.id===n)?.shortLabel||n}function Qm(n,a){return n.find(r=>r.id===a)?.name||"Product"}function Ia(n){const a=E0(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 eb({session:n,currentProductKey:a="livedesk",appVersion:r="",onSignIn:l}){const[c,d]=u.useState(()=>Ym()),[m,p]=u.useState(null),[v,g]=u.useState([]),[w,x]=u.useState([]),[b,j]=u.useState(""),[C,k]=u.useState([]),[M,A]=u.useState([]),[T,R]=u.useState([]),[P,F]=u.useState(()=>new Set),[V,_]=u.useState(!0),[L,ne]=u.useState(""),[W,J]=u.useState(""),[O,be]=u.useState(!1),[re,K]=u.useState(!1),[I,ee]=u.useState(""),[G,q]=u.useState(()=>Ym().query),[oe,we]=u.useState(!1),[Q,$]=u.useState(!1),[he,fe]=u.useState(""),[me,Se]=u.useState(""),[Be,Oe]=u.useState("free"),[ge,Ze]=u.useState(""),[Ke,ce]=u.useState(""),[ve,ke]=u.useState("admin"),[Ne,He]=u.useState(""),[$e,Xe]=u.useState(""),[ye,ae]=u.useState(""),[Te,Pe]=u.useState(""),[Je,Mt]=u.useState(""),[It,an]=u.useState([]),[mt,Pn]=u.useState({productId:"",postType:"question",title:"",body:"",visibility:"public",includeEnvironment:!0,files:[]}),Kt=u.useCallback(H=>{const Le={...c,...H};d(Le),typeof window<"u"&&window.history.pushState({},"",tC(c,H))},[c]);u.useEffect(()=>{const H=()=>d(Ym());return window.addEventListener("popstate",H),()=>window.removeEventListener("popstate",H)},[]);const X=u.useCallback(async()=>{const H=await L0(c.query);return x(H),n?.user.id&&F(await O0(n.user.id)),H},[c.query,n?.user.id]),De=u.useCallback(async()=>{if(!n?.user.id){p(null),g([]),x([]),j(""),R([]),_(!1);return}_(!0),J("");try{const H=await D0(n.user.id,a);p(H.access),g(H.products),await X(),R(await z0())}catch(H){J(Ia(H))}finally{_(!1)}},[a,X,n?.user.id]);u.useEffect(()=>{De()},[De]);const ze=u.useMemo(()=>m?m.canViewAllProducts?v:v.filter(H=>m.accessibleProductIds.includes(H.id)):[],[m,v]),Ae=u.useMemo(()=>{const H=ze.find(Le=>Le.product_key===c.product);return m?.canViewAllProducts&&!c.product||c.product==="all"&&m?.canViewAllProducts?"all":H?H.product_key:ze.some(Le=>Le.product_key===a)?a:ze[0]?.product_key||""},[m?.canViewAllProducts,ze,a,c.product]),et=Ae==="all"?"":ze.find(H=>H.product_key===Ae)?.id||"",gt=u.useMemo(()=>{const H=new Map(v.map(lt=>[lt.id,lt.product_key]));return[...w.filter(lt=>c.type!=="all"&&lt.post_type!==c.type||Ae!=="all"&&et&&lt.product_id!==et||c.status==="needs-response"&&!["open","needs-info"].includes(lt.status)||c.status!=="all"&&c.status!=="needs-response"&&lt.status!==c.status||c.visibility!=="all"&&lt.visibility!==c.visibility?!1:H.has(lt.product_id))].sort((lt,hn)=>c.sort==="votes"?hn.vote_count-lt.vote_count||hn.updated_at.localeCompare(lt.updated_at):c.sort==="newest"?hn.created_at.localeCompare(lt.created_at):Number(hn.is_pinned)-Number(lt.is_pinned)||hn.updated_at.localeCompare(lt.updated_at))},[w,v,c.sort,c.status,c.type,c.visibility,et,Ae]),Re=gt.find(H=>H.id===b)||gt[0]||null,fa=!!(Re&&m&&(m.canViewAllProducts||m.managedProductIds.includes(Re.product_id))),$n=!!(Re&&n?.user.id===Re.author_id)||fa;u.useEffect(()=>{if(!Re){j(""),k([]),K(!1);return}Re.id!==b&&j(Re.id)},[Re,b]),u.useEffect(()=>{let H=!0;return b?(vy(b).then(Le=>{H&&k(Le)}).catch(Le=>{H&&J(Ia(Le))}),_0(b).then(Le=>{H&&A(Le)}).catch(Le=>{H&&J(Ia(Le))}),()=>{H=!1}):(k([]),A([]),()=>{H=!1})},[b]),u.useEffect(()=>{!mt.productId&&ze[0]&&Pn(H=>({...H,productId:et||ze[0].id}))},[ze,mt.productId,et]),u.useEffect(()=>{q(c.query)},[c.query]),u.useEffect(()=>{!me&&ze[0]&&Se(ze[0].id),!Ke&&ze[0]&&ce(ze[0].id)},[ze,me,Ke]);const at=H=>{Re&&x(Le=>Le.map(lt=>lt.id===Re.id?{...lt,...H}:lt))},qt=async H=>{if(H.preventDefault(),!(!n||!mt.productId)){ne("create"),J("");try{const Le=await H0({productId:mt.productId,postType:mt.postType,title:mt.title,body:mt.body,visibility:mt.postType==="announcement"?"public":mt.visibility,appVersion:r,includeEnvironment:mt.postType==="issue"&&mt.includeEnvironment});for(const hn of It)await F0(Le,hn);const lt=await X();be(!1),an([]),Pn(hn=>({...hn,title:"",body:"",files:[]})),j(Le),lt.some(hn=>hn.id===Le)||await De()}catch(Le){J(Ia(Le))}finally{ne("")}}},un=async H=>{if(H.preventDefault(),!!Re){ne("edit"),J("");try{await P0(Re.id,Re.title,Re.body,Re.visibility),K(!1),await X()}catch(Le){J(Ia(Le))}finally{ne("")}}},ns=async H=>{if(H.preventDefault(),!(!Re||!I.trim())){ne("comment"),J("");try{await $0(Re.id,I),ee(""),k(await vy(Re.id)),await X()}catch(Le){J(Ia(Le))}finally{ne("")}}},as=async()=>{if(!(!Re||Re.post_type!=="feature")){ne("vote"),J("");try{const H=await U0(Re.id);F(Le=>{const lt=new Set(Le);return H.voted?lt.add(Re.id):lt.delete(Re.id),lt}),at({vote_count:H.totalVotes})}catch(H){J(Ia(H))}finally{ne("")}}},Zn=async H=>{if(Re){ne("status"),J("");try{await q0(Re.id,H),at({status:H}),await X()}catch(Le){J(Ia(Le))}finally{ne("")}}},nr=async()=>{if(!(!Re||!window.confirm("Hide this Support post from the board?"))){ne("hide"),J("");try{await G0(Re.id),j(""),await X()}catch(H){J(Ia(H))}finally{ne("")}}},Fe=async()=>{if(Re){ne("lock"),J("");try{await V0(Re.id,!Re.is_locked),at({is_locked:!Re.is_locked}),await X()}catch(H){J(Ia(H))}finally{ne("")}}},zs=async()=>{if(Re){ne("pin"),J("");try{await W0(Re.id,!Re.is_pinned),at({is_pinned:!Re.is_pinned}),await X()}catch(H){J(Ia(H))}finally{ne("")}}},vt=async H=>{if(Re){ne(`accept-${H}`),J("");try{await K0(Re.id,H),at({accepted_comment_id:H,status:Re.post_type==="question"?"answered":Re.status}),await X()}catch(Le){J(Ia(Le))}finally{ne("")}}},hi=async()=>{if(!(!Re||!Te||Te===Re.id)){ne("duplicate"),J("");try{await Y0(Re.id,Te),j(""),Pe(""),await X()}catch(H){J(Ia(H))}finally{ne("")}}},Jt=async H=>{if(!H.read_at)try{await I0(H.id),R(Le=>Le.map(lt=>lt.id===H.id?{...lt,read_at:new Date().toISOString()}:lt))}catch(Le){J(Ia(Le))}H.post_id&&j(H.post_id),we(!1)};return n?V&&!m?s.jsxs("section",{className:"support-page support-loading",children:[s.jsx(Eo,{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:()=>we(H=>!H),title:"Notifications",children:[s.jsx(IS,{size:16})," ",T.filter(H=>!H.read_at).length>0&&s.jsx("b",{children:T.filter(H=>!H.read_at).length})]}),oe&&s.jsxs("div",{className:"support-notification-popover",children:[s.jsx("strong",{children:"Notifications"}),T.length===0?s.jsx("span",{className:"support-muted",children:"No notifications yet."}):T.map(H=>s.jsxs("button",{type:"button",className:H.read_at?"":"unread",onClick:()=>{Jt(H)},children:[s.jsx("b",{children:H.title}),s.jsx("span",{children:H.body}),s.jsx("small",{children:hd(H.created_at)})]},H.id))]})]}),m?.canViewAllProducts&&s.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>$(H=>!H),children:[s.jsx(Ht,{size:16})," Admin"]}),s.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{De()},disabled:V,children:[s.jsx(Eo,{size:16,className:V?"support-spin":""})," Refresh"]}),s.jsxs("button",{className:"support-primary-button",type:"button",onClick:()=>be(!0),disabled:ze.length===0,children:[s.jsx($m,{size:17})," New request"]})]})}),W&&s.jsxs("div",{className:"support-error",role:"alert",children:[s.jsx(Sa,{size:17})," ",s.jsx("span",{children:W}),s.jsx("button",{type:"button",onClick:()=>J(""),"aria-label":"Dismiss error",children:s.jsx(Sa,{size:15})})]}),O&&s.jsxs("form",{className:"support-composer",onSubmit:H=>{qt(H)},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:()=>be(!1),"aria-label":"Close composer",children:s.jsx(Sa,{size:18})})]}),s.jsxs("div",{className:"support-form-grid",children:[s.jsxs("label",{children:[s.jsx("span",{children:"Product"}),s.jsx("select",{value:mt.productId,onChange:H=>Pn(Le=>({...Le,productId:H.target.value})),children:ze.map(H=>s.jsx("option",{value:H.id,children:H.name},H.id))})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Type"}),s.jsx("select",{value:mt.postType,onChange:H=>Pn(Le=>({...Le,postType:H.target.value})),children:Mh.filter(H=>H.id!=="announcement"||m?.canCreateAnnouncements).map(H=>s.jsx("option",{value:H.id,children:H.label},H.id))})]}),s.jsxs("label",{className:"support-form-wide",children:[s.jsx("span",{children:"Title"}),s.jsx("input",{required:!0,minLength:3,maxLength:180,value:mt.title,onChange:H=>Pn(Le=>({...Le,title:H.target.value})),placeholder:"A short, searchable summary"})]}),s.jsxs("label",{className:"support-form-wide",children:[s.jsx("span",{children:mt.postType==="issue"?"What happened?":mt.postType==="feature"?"Describe the desired behavior":mt.postType==="announcement"?"Announcement":"Question"}),s.jsx("textarea",{required:!0,value:mt.body,onChange:H=>Pn(Le=>({...Le,body:H.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:mt.visibility,disabled:mt.postType==="announcement",onChange:H=>Pn(Le=>({...Le,visibility:H.target.value})),children:[s.jsx("option",{value:"public",children:"Public"}),s.jsx("option",{value:"private",children:"Private"})]})]}),mt.postType==="issue"&&s.jsxs("label",{className:"support-checkbox",children:[s.jsx("input",{type:"checkbox",checked:mt.includeEnvironment,onChange:H=>Pn(Le=>({...Le,includeEnvironment:H.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:H=>an(Array.from(H.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:It.length>0?`${It.length} attachment${It.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(Xc,{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:()=>Kt({type:"all"}),children:"All"}),Mh.map(H=>{const Le=yy(H.id);return s.jsxs("button",{className:c.type===H.id?"active":"",type:"button",onClick:()=>Kt({type:H.id}),children:[s.jsx(Le,{size:15})," ",H.label]},H.id)})]}),Q&&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(Ht,{size:19})]}),s.jsxs("div",{className:"support-admin-grid",children:[s.jsxs("form",{onSubmit:H=>{},children:[s.jsx("strong",{children:"Grant product access"}),s.jsx("input",{type:"email",required:!0,placeholder:"User email",value:he,onChange:H=>fe(H.target.value)}),s.jsx("select",{value:me,onChange:H=>Se(H.target.value),children:ze.map(H=>s.jsx("option",{value:H.id,children:H.name},H.id))}),s.jsxs("select",{value:Be,onChange:H=>Oe(H.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:Je==="access",children:[s.jsx(ui,{size:15})," Grant access"]})]}),s.jsxs("form",{onSubmit:H=>{},children:[s.jsx("strong",{children:"Assign product admin"}),s.jsx("input",{type:"email",required:!0,placeholder:"Admin email",value:ge,onChange:H=>Ze(H.target.value)}),s.jsx("select",{value:Ke,onChange:H=>ce(H.target.value),children:ze.map(H=>s.jsx("option",{value:H.id,children:H.name},H.id))}),s.jsxs("select",{value:ve,onChange:H=>ke(H.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:Je==="product-admin",children:[s.jsx(Ht,{size:15})," Assign admin"]})]}),s.jsxs("form",{onSubmit:H=>{},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:Ne,onChange:H=>He(H.target.value)}),s.jsx("input",{required:!0,placeholder:"Product name",value:$e,onChange:H=>Xe(H.target.value)}),s.jsx("input",{placeholder:"Description",value:ye,onChange:H=>ae(H.target.value)}),s.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:Je==="product",children:[s.jsx($m,{size:15})," Add product"]})]})]})]}),s.jsxs("form",{className:"support-search-bar",onSubmit:H=>{H.preventDefault(),Kt({query:G.trim()})},children:[s.jsxs("label",{children:[s.jsx("span",{children:"Search Support"}),s.jsx("input",{value:G,onChange:H=>q(H.target.value),placeholder:"Search titles and request details"})]}),s.jsxs("button",{className:"support-secondary-button",type:"submit",children:[s.jsx(sy,{size:15})," Search"]}),c.query&&s.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{q(""),Kt({query:""})},"aria-label":"Clear search",children:s.jsx(Sa,{size:16})})]}),s.jsxs("div",{className:"support-filter-bar",children:[s.jsxs("div",{className:"support-filter-title",children:[s.jsx(sy,{size:16}),s.jsx("span",{children:"Filter"})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Product"}),s.jsxs("select",{value:Ae,onChange:H=>Kt({product:H.target.value}),disabled:!m?.canViewAllProducts&&ze.length<=1,children:[s.jsx("option",{value:"all",children:"All products"}),ze.map(H=>s.jsx("option",{value:H.product_key,children:H.name},H.id))]})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Status"}),s.jsx("select",{value:c.status,onChange:H=>Kt({status:H.target.value}),children:X0.map(H=>s.jsx("option",{value:H.id,children:H.label},H.id))})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Visibility"}),s.jsxs("select",{value:c.visibility,onChange:H=>Kt({visibility:H.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:H=>Kt({sort:H.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(Ht,{size:15})," Owner view"]}),s.jsx("button",{type:"button",onClick:()=>Kt({status:"needs-response"}),children:"Needs response"}),s.jsx("button",{type:"button",onClick:()=>Kt({visibility:"private"}),children:"Private requests"}),s.jsx("button",{type:"button",onClick:()=>Kt({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:[gt.length," request",gt.length===1?"":"s"]}),s.jsx("small",{children:Ae==="all"?"All products":Qm(ze,et)})]}),gt.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."}),ze.length>0&&s.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>be(!0),children:[s.jsx($m,{size:16})," Create the first request"]})]}):gt.map(H=>{const Le=yy(H.post_type);return s.jsxs("button",{type:"button",className:`support-post-row ${H.id===Re?.id?"active":""}`,onClick:()=>{j(H.id),K(!1)},children:[s.jsx("span",{className:"support-post-row-icon",children:s.jsx(Le,{size:17})}),s.jsxs("span",{className:"support-post-row-copy",children:[s.jsxs("span",{className:"support-post-row-meta",children:[s.jsx("b",{children:Qm(v,H.product_id)}),s.jsx("em",{children:xy(H.post_type)}),H.visibility==="private"&&s.jsx(Rs,{size:13})]}),s.jsx("strong",{children:H.title}),s.jsxs("small",{children:[Km(H.status)," · ",hd(H.updated_at)," · ",H.comment_count," comments"]})]}),H.post_type==="feature"&&s.jsxs("span",{className:"support-vote-count",children:[s.jsx(Gx,{size:14})," ",H.vote_count]})]},H.id)})]}),s.jsx("section",{className:"support-post-detail","aria-label":"Support post detail",children:Re?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:Qm(v,Re.product_id)}),s.jsx("span",{className:"support-type-badge",children:xy(Re.post_type)}),s.jsx("span",{className:`support-status-badge status-${Re.status}`,children:Km(Re.status)}),Re.visibility==="private"&&s.jsxs("span",{className:"support-private-badge",children:[s.jsx(Rs,{size:13})," Private"]})]}),s.jsxs("div",{className:"support-detail-actions",children:[$n&&s.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>K(H=>!H),title:"Edit post",children:s.jsx(OS,{size:16})}),fa&&s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{zs()},disabled:L==="pin",title:Re.is_pinned?"Unpin post":"Pin post",children:s.jsx(iy,{size:16})}),s.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{Fe()},disabled:L==="lock",title:Re.is_locked?"Unlock post":"Lock post",children:s.jsx(Rs,{size:16})}),s.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{nr()},disabled:L==="hide",title:"Hide post",children:s.jsx(ry,{size:16})})]})]})]}),re?s.jsxs("form",{className:"support-edit-form",onSubmit:H=>{un(H)},children:[s.jsx("input",{value:Re.title,onChange:H=>at({title:H.target.value}),minLength:3,maxLength:180,required:!0}),s.jsx("textarea",{value:Re.body,onChange:H=>at({body:H.target.value}),rows:9,required:!0}),s.jsxs("div",{className:"support-edit-actions",children:[s.jsxs("select",{value:Re.visibility,onChange:H=>at({visibility:H.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(ui,{size:16})," Save changes"]})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("h3",{children:Re.title}),s.jsx("div",{className:"support-detail-body",children:Re.body.split(`
10
- `).map((H,Le)=>s.jsx("p",{children:H||" "},`${Re.id}-body-${Le}`))})]}),s.jsxs("div",{className:"support-detail-meta",children:[s.jsxs("span",{children:["Opened ",hd(Re.created_at)]}),Re.app_version&&s.jsxs("span",{children:["Version ",Re.app_version]}),Re.platform&&s.jsx("span",{children:Re.platform}),Re.is_locked&&s.jsxs("span",{children:[s.jsx(Rs,{size:13})," Locked"]}),Re.is_pinned&&s.jsxs("span",{children:[s.jsx(iy,{size:13})," Pinned"]})]}),s.jsxs("div",{className:"support-detail-controls",children:[Re.post_type==="feature"&&s.jsxs("button",{className:`support-vote-button ${P.has(Re.id)?"voted":""}`,type:"button",onClick:()=>{as()},disabled:L==="vote",children:[s.jsx(HS,{size:16})," ",P.has(Re.id)?"Voted":"Vote"," ",s.jsx("b",{children:Re.vote_count})]}),fa&&s.jsxs("label",{className:"support-status-control",children:[s.jsx("span",{children:"Change status"}),s.jsx("select",{value:Re.status,onChange:H=>{Zn(H.target.value)},disabled:L==="status",children:(Z0[Re.post_type]||[]).map(H=>s.jsx("option",{value:H,children:Km(H)},H))})]}),fa&&s.jsxs(s.Fragment,{children:[s.jsxs("select",{className:"support-status-control",value:Te,onChange:H=>Pe(H.target.value),children:[s.jsx("option",{value:"",children:"Duplicate of..."}),gt.filter(H=>H.id!==Re.id&&H.product_id===Re.product_id).map(H=>s.jsx("option",{value:H.id,children:H.title.slice(0,55)},H.id))]}),s.jsx("button",{className:"support-secondary-button",type:"button",onClick:()=>{hi()},disabled:!Te||L==="duplicate",children:"Merge duplicate"})]})]}),M.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:[M.length," file",M.length===1?"":"s"]})]})}),M.map(H=>s.jsxs("a",{href:H.signed_url,target:"_blank",rel:"noreferrer",children:[s.jsx(Xh,{size:14})," ",H.file_name,s.jsxs("small",{children:[Math.ceil(H.size_bytes/1024)," KB"]})]},H.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"]})]}),Re.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(H=>s.jsxs("article",{className:`support-comment ${H.is_staff_answer?"staff":""} ${Re.accepted_comment_id===H.id?"accepted":""}`,children:[s.jsxs("div",{className:"support-comment-head",children:[s.jsx("strong",{children:H.is_staff_answer?"LiveDesk Support":H.author_id===n.user.id?"You":"Support user"}),H.is_staff_answer&&s.jsxs("span",{children:[s.jsx(Ht,{size:13})," Staff answer"]}),Re.accepted_comment_id===H.id&&s.jsxs("span",{children:[s.jsx(_n,{size:13})," Accepted"]}),s.jsx("time",{children:hd(H.created_at)})]}),s.jsx("p",{children:H.body}),s.jsxs("div",{className:"support-comment-actions",children:[(n.user.id===Re.author_id||fa)&&Re.post_type==="question"&&Re.accepted_comment_id!==H.id&&s.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{vt(H.id)},disabled:L===`accept-${H.id}`,children:[s.jsx(ui,{size:14})," Accept answer"]}),fa&&s.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{Q0(H.id)},title:"Hide comment",children:s.jsx(ry,{size:14})})]})]},H.id))}),!Re.is_locked&&s.jsxs("form",{className:"support-comment-form",onSubmit:H=>{ns(H)},children:[s.jsx("textarea",{value:I,onChange:H=>ee(H.target.value),placeholder:"Add a focused reply...",rows:3}),s.jsxs("button",{className:"support-primary-button",type:"submit",disabled:L==="comment"||!I.trim(),children:[s.jsx(Xc,{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(Ht,{size:17})," Sign in with Google"]})]})})}function pd(n){return!!n&&typeof n=="object"}function tb(n){let a=n;return pd(a)&&"data"in a&&(a=a.data),pd(a)&&"session"in a&&(a=a.session),!pd(a)||typeof a.access_token!="string"||!a.access_token||!pd(a.user)||typeof a.user.id!="string"||!a.user.id?null:a}function by(n){return n?.access_token?n.refresh_token?"":"refresh-token-required":"access-token-required"}const Vc=5179,kn=Kr(`http://127.0.0.1:${Vc}`);function nC(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 aC(n){const a=n.trim().toLowerCase();return a==="localhost"||a==="127.0.0.1"||a==="::1"||a==="[::1]"}function sC(n){const a=n.trim().toLowerCase();return!a||a==="0.0.0.0"||a==="::"||a==="[::]"}function iC(n){const a=nC(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 rC(n){return n.includes(":")&&!n.startsWith("[")?`[${n}]`:n}function lC(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||sC(c)?null:{host:c,port:d}}catch{return null}}function Kr(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 oC(n){const a=lC(n);return a?Kr(`http://${rC(a.host)}:${Vc}`):""}function wy(n){const r=[n?.endpoint,...Array.isArray(n?.endpoint_candidates)?n.endpoint_candidates:[]].map(l=>oC(String(l||""))).filter(Boolean);return[...new Set(r)]}function Wc(n=kn){if(!(typeof window>"u"||window.location.protocol!=="https:"))try{const a=new URL(n);if(a.protocol!=="http:")return;if(aC(a.hostname))return"loopback";if(iC(a.hostname))return"local"}catch{return}}function lf(n,a=kn){const r=new URL(n,Kr(a));return r.protocol=r.protocol==="https:"?"wss:":"ws:",r.toString()}async function We(n,a,r=kn){const l=Kr(r),c={...a,headers:{"Content-Type":"application/json",...a?.headers||{}},cache:"no-store"},d=Wc(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 nb({baseUrl:n=kn,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 We("/api/runtime/status",void 0,n),g=String(v.role||"").toLowerCase(),w=String(v.state||"").toLowerCase(),x=Number(v.runtimePid||0),b=r>1?x>1&&x!==r:x>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 cC(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 ab(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 kl(n){await navigator.clipboard.writeText(n)}function sb({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 ib={hub:"Use this computer as Hub. Hub connects to and manages Client computers.","switch-to-hub":"Switch this computer from Client to Hub. It will manage Client computers instead of sharing its own screen.",client:"Keep this computer in Client mode so its screens, files, audio, and remote controls remain available to the active Hub.",wall:"Show live thumbnails from every connected Client. Choose a display, change tile size, or move into Control without opening another connection.",control:"Open the selected Client at full resolution and send mouse and keyboard input through the existing Hub session.","share-files":"Browse files on the Hub, send files to selected Clients, and manage shared folders and transfer progress.",agents:"Run Hub-hosted Codex tasks on connected Clients within the selected permissions, timeouts, and audit controls."},Th={en:ib,ko:{hub:"이 컴퓨터를 Hub로 사용합니다. Hub는 Client 컴퓨터를 연결하고 관리합니다.","switch-to-hub":"이 컴퓨터를 Client에서 Hub로 바꿉니다. 자신의 화면 공유를 멈추고 Client 컴퓨터를 관리합니다.",client:"이 컴퓨터를 Client 모드로 유지합니다. 화면, 파일, 오디오와 원격 제어 기능이 활성 Hub에서 계속 사용 가능하도록 연결합니다.",wall:"연결된 모든 Client의 실시간 화면을 한곳에 표시합니다. 모니터와 타일 크기를 선택하고 새 연결 없이 Control로 이동할 수 있습니다.",control:"선택한 Client 화면을 전체 해상도로 열고 기존 Hub 세션을 통해 마우스와 키보드 입력을 전송합니다.","share-files":"Hub의 파일을 탐색하고 선택한 Client로 전송하며 공유 폴더와 전송 진행 상태를 관리합니다.",agents:"Hub에서 실행되는 Codex 작업을 연결된 Client에 전달합니다. 선택한 권한, 제한 시간과 감사 기록 범위 안에서만 실행됩니다."},ja:{hub:"このコンピューターを LiveDesk Hub として運用します。Hub は Client 接続、Wall、Control、ファイル共有、Agents を一か所で管理する統合コントロールセンターで、ネットワーク変更後に押すと安全な接続情報も更新します。","switch-to-hub":"このコンピューターを Client から Hub に切り替えます。新しい役割を保存して同じデスクトップランタイムを再起動し、Wall を開きます。Client としての共有は停止します。",client:"このコンピューターを Client モードで維持し、画面、ファイル、音声、リモート操作をアクティブ Hub から利用できるようにします。",wall:"接続中のすべての Client のライブ画面を一覧表示します。ディスプレイやタイルサイズを選び、新しい接続なしで Control に移動できます。",control:"選択した Client をフル解像度で開き、既存の Hub セッションからマウスとキーボード入力を送信します。","share-files":"Hub のファイルを参照し、選択した Client への送信、共有フォルダー、転送状況を管理します。",agents:"Hub 上の Codex タスクを接続中の Client で実行します。選択した権限、タイムアウト、監査設定が適用されます。"},zh:{hub:"将此电脑作为 LiveDesk Hub 运行。Hub 是统一控制中心,可集中管理 Client 连接、Wall、Control、文件共享和 Agents;网络变化后按下此按钮还会刷新安全连接信息。","switch-to-hub":"将此电脑从 Client 切换为 Hub。LiveDesk 保存新角色、重启同一桌面运行时并打开 Wall;此电脑将停止作为 Client 共享。",client:"让此电脑保持 Client 模式,使活动 Hub 可以继续使用它的屏幕、文件、音频和远程控制。",wall:"集中显示所有已连接 Client 的实时缩略图。可以选择显示器、调整磁贴大小,并在不新建连接的情况下进入 Control。",control:"以完整分辨率打开所选 Client,并通过现有 Hub 会话发送鼠标和键盘输入。","share-files":"浏览 Hub 文件、向所选 Client 发送文件,并管理共享文件夹和传输进度。",agents:"在已连接 Client 上运行由 Hub 托管的 Codex 任务,并遵守所选权限、超时和审计控制。"},"zh-TW":{hub:"將此電腦作為 LiveDesk Hub 運作。Hub 是統一控制中心,可集中管理 Client 連線、Wall、Control、檔案分享與 Agents;網路變更後按下此按鈕也會更新安全連線資訊。","switch-to-hub":"將此電腦從 Client 切換為 Hub。LiveDesk 會儲存新角色、重新啟動同一桌面執行階段並開啟 Wall;此電腦將停止以 Client 身分共享。",client:"讓此電腦維持 Client 模式,使作用中 Hub 可繼續使用它的畫面、檔案、音訊與遠端控制。",wall:"集中顯示所有已連線 Client 的即時縮圖。可選擇顯示器、調整圖塊大小,並在不建立新連線的情況下進入 Control。",control:"以完整解析度開啟所選 Client,並透過現有 Hub 工作階段傳送滑鼠與鍵盤輸入。","share-files":"瀏覽 Hub 檔案、傳送檔案到所選 Client,並管理共享資料夾與傳輸進度。",agents:"在已連線 Client 上執行由 Hub 託管的 Codex 工作,並遵守所選權限、逾時與稽核控制。"},es:{hub:"Usa este equipo como LiveDesk Hub. Hub es el centro de control unificado para conexiones Client, Wall, Control, archivos y Agents; púlsalo tras cambios de red para actualizar el acceso seguro.","switch-to-hub":"Cambia este equipo de Client a Hub. LiveDesk guarda el nuevo rol, reinicia el mismo entorno de escritorio y abre Wall; el equipo deja de compartirse como Client.",client:"Mantiene este equipo en modo Client para que sus pantallas, archivos, audio y control remoto sigan disponibles desde el Hub activo.",wall:"Muestra miniaturas en vivo de todos los Clients conectados. Elige pantalla y tamaño, o entra en Control sin abrir otra conexión.",control:"Abre el Client seleccionado a resolución completa y envía ratón y teclado por la sesión Hub existente.","share-files":"Explora archivos del Hub, envíalos a los Clients seleccionados y administra carpetas compartidas y transferencias.",agents:"Ejecuta tareas Codex alojadas en el Hub sobre Clients conectados, respetando permisos, límites de tiempo y auditoría."},fr:{hub:"Utilise cet ordinateur comme LiveDesk Hub. Hub est le centre de contrôle unifié des connexions Client, de Wall, Control, des fichiers et des Agents ; appuyez après un changement réseau pour actualiser l’accès sécurisé.","switch-to-hub":"Bascule cet ordinateur de Client vers Hub. LiveDesk enregistre le nouveau rôle, redémarre le même environnement de bureau et ouvre Wall ; le partage Client s’arrête.",client:"Maintient cet ordinateur en mode Client afin que ses écrans, fichiers, sons et commandes à distance restent disponibles depuis le Hub actif.",wall:"Affiche les miniatures en direct de tous les Clients connectés. Choisissez l’écran et la taille, ou passez à Control sans nouvelle connexion.",control:"Ouvre le Client sélectionné en pleine résolution et transmet souris et clavier via la session Hub existante.","share-files":"Parcourez les fichiers du Hub, envoyez-les aux Clients sélectionnés et gérez dossiers partagés et transferts.",agents:"Exécute des tâches Codex hébergées par le Hub sur les Clients connectés, selon les permissions, délais et règles d’audit."},de:{hub:"Verwendet diesen Computer als LiveDesk Hub. Hub ist die gemeinsame Steuerzentrale für Client-Verbindungen, Wall, Control, Dateien und Agents; nach Netzwerkänderungen aktualisiert ein Klick den sicheren Zugriff.","switch-to-hub":"Wechselt diesen Computer von Client zu Hub. LiveDesk speichert die neue Rolle, startet dieselbe Desktop-Laufzeit neu und öffnet Wall; die Client-Freigabe endet.",client:"Hält diesen Computer im Client-Modus, damit Bildschirme, Dateien, Audio und Fernsteuerung am aktiven Hub verfügbar bleiben.",wall:"Zeigt Live-Vorschaubilder aller verbundenen Clients. Display und Kachelgröße wählen oder ohne neue Verbindung zu Control wechseln.",control:"Öffnet den gewählten Client in voller Auflösung und sendet Maus- und Tastatureingaben über die bestehende Hub-Sitzung.","share-files":"Dateien auf dem Hub durchsuchen, an gewählte Clients senden sowie Freigaben und Übertragungen verwalten.",agents:"Führt Hub-gehostete Codex-Aufgaben auf verbundenen Clients innerhalb der gewählten Berechtigungen, Zeitlimits und Auditregeln aus."},"pt-BR":{hub:"Usa este computador como LiveDesk Hub. Hub é o centro de controle unificado para conexões Client, Wall, Control, arquivos e Agents; após mudanças de rede, pressione para atualizar o acesso seguro.","switch-to-hub":"Muda este computador de Client para Hub. O LiveDesk salva a nova função, reinicia o mesmo runtime de desktop e abre o Wall; o compartilhamento como Client é encerrado.",client:"Mantém este computador no modo Client para que telas, arquivos, áudio e controle remoto continuem disponíveis no Hub ativo.",wall:"Mostra miniaturas ao vivo de todos os Clients conectados. Escolha a tela e o tamanho ou entre em Control sem criar outra conexão.",control:"Abre o Client selecionado em resolução total e envia mouse e teclado pela sessão Hub existente.","share-files":"Navegue pelos arquivos do Hub, envie para Clients selecionados e gerencie pastas compartilhadas e transferências.",agents:"Executa tarefas Codex hospedadas no Hub em Clients conectados, respeitando permissões, limites de tempo e auditoria."},it:{hub:"Usa questo computer come LiveDesk Hub. Hub è il centro di controllo unificato per connessioni Client, Wall, Control, file e Agents; dopo modifiche di rete, premilo per aggiornare l’accesso sicuro.","switch-to-hub":"Passa questo computer da Client a Hub. LiveDesk salva il nuovo ruolo, riavvia lo stesso runtime desktop e apre Wall; la condivisione come Client termina.",client:"Mantiene questo computer in modalità Client, rendendo schermi, file, audio e controllo remoto disponibili all’Hub attivo.",wall:"Mostra le anteprime live di tutti i Client connessi. Scegli display e dimensione oppure passa a Control senza una nuova connessione.",control:"Apre il Client selezionato a piena risoluzione e invia mouse e tastiera tramite la sessione Hub esistente.","share-files":"Esplora i file dell’Hub, inviali ai Client selezionati e gestisci cartelle condivise e trasferimenti.",agents:"Esegue attività Codex ospitate dall’Hub sui Client connessi rispettando permessi, timeout e controlli di audit."},id:{hub:"Gunakan komputer ini sebagai LiveDesk Hub. Hub adalah pusat kendali terpadu untuk koneksi Client, Wall, Control, file, dan Agents; tekan setelah perubahan jaringan untuk memperbarui akses aman.","switch-to-hub":"Alihkan komputer ini dari Client menjadi Hub. LiveDesk menyimpan peran baru, memulai ulang runtime desktop yang sama, lalu membuka Wall; berbagi sebagai Client berhenti.",client:"Pertahankan komputer ini dalam mode Client agar layar, file, audio, dan kendali jarak jauh tetap tersedia bagi Hub aktif.",wall:"Tampilkan thumbnail live semua Client yang terhubung. Pilih layar dan ukuran tile atau masuk ke Control tanpa koneksi baru.",control:"Buka Client terpilih pada resolusi penuh dan kirim input mouse serta keyboard melalui sesi Hub yang ada.","share-files":"Jelajahi file Hub, kirim ke Client terpilih, serta kelola folder bersama dan progres transfer.",agents:"Jalankan tugas Codex yang di-host Hub pada Client terhubung sesuai izin, batas waktu, dan kontrol audit."},vi:{hub:"Dùng máy tính này làm LiveDesk Hub. Hub là trung tâm điều khiển hợp nhất cho kết nối Client, Wall, Control, tệp và Agents; nhấn sau khi đổi mạng để làm mới quyền truy cập an toàn.","switch-to-hub":"Chuyển máy tính này từ Client sang Hub. LiveDesk lưu vai trò mới, khởi động lại cùng môi trường desktop và mở Wall; việc chia sẻ dưới dạng Client sẽ dừng.",client:"Giữ máy tính này ở chế độ Client để màn hình, tệp, âm thanh và điều khiển từ xa luôn sẵn sàng cho Hub đang hoạt động.",wall:"Hiển thị ảnh thu nhỏ trực tiếp của mọi Client đã kết nối. Chọn màn hình, cỡ ô hoặc vào Control mà không tạo kết nối mới.",control:"Mở Client đã chọn ở độ phân giải đầy đủ và gửi chuột, bàn phím qua phiên Hub hiện có.","share-files":"Duyệt tệp trên Hub, gửi tới Client đã chọn và quản lý thư mục chia sẻ cùng tiến trình truyền.",agents:"Chạy tác vụ Codex do Hub lưu trữ trên các Client đã kết nối trong phạm vi quyền, thời gian chờ và kiểm toán đã chọn."},th:{hub:"ใช้คอมพิวเตอร์เครื่องนี้เป็น LiveDesk Hub โดย Hub คือศูนย์ควบคุมรวมสำหรับการเชื่อมต่อ Client, Wall, Control, ไฟล์ และ Agents และกดหลังเปลี่ยนเครือข่ายเพื่อรีเฟรชการเข้าถึงที่ปลอดภัย","switch-to-hub":"เปลี่ยนคอมพิวเตอร์นี้จาก Client เป็น Hub โดย LiveDesk จะบันทึกบทบาทใหม่ รีสตาร์ต desktop runtime เดิม และเปิด Wall พร้อมหยุดแชร์ในฐานะ Client",client:"ให้คอมพิวเตอร์นี้อยู่ในโหมด Client เพื่อให้ Hub ที่ใช้งานเข้าถึงหน้าจอ ไฟล์ เสียง และการควบคุมระยะไกลได้ต่อเนื่อง",wall:"แสดงภาพสดแบบย่อของ Client ที่เชื่อมต่อทั้งหมด เลือกจอและขนาด tile หรือเข้า Control ได้โดยไม่เปิดการเชื่อมต่อใหม่",control:"เปิด Client ที่เลือกแบบความละเอียดเต็ม และส่งเมาส์กับคีย์บอร์ดผ่าน session ของ Hub ที่มีอยู่","share-files":"เรียกดูไฟล์บน Hub ส่งไปยัง Client ที่เลือก และจัดการโฟลเดอร์แชร์กับความคืบหน้าการโอน",agents:"เรียกใช้งาน Codex ที่โฮสต์บน Hub กับ Client ที่เชื่อมต่อ ภายใต้สิทธิ์ timeout และการตรวจสอบที่เลือก"},hi:{hub:"इस कंप्यूटर को LiveDesk Hub के रूप में उपयोग करें। Hub, Client कनेक्शन, Wall, Control, फ़ाइल और Agents का एकीकृत नियंत्रण केंद्र है; नेटवर्क बदलने के बाद सुरक्षित पहुँच ताज़ा करने के लिए इसे दबाएँ।","switch-to-hub":"इस कंप्यूटर को Client से Hub में बदलता है। LiveDesk नई भूमिका सहेजता है, उसी desktop runtime को restart करके Wall खोलता है और Client sharing रोक देता है।",client:"इस कंप्यूटर को Client मोड में रखता है ताकि इसकी स्क्रीन, फ़ाइलें, ऑडियो और remote control सक्रिय Hub पर उपलब्ध रहें।",wall:"सभी जुड़े Clients के live thumbnail दिखाता है। स्क्रीन और tile आकार चुनें या नया connection खोले बिना Control में जाएँ।",control:"चुने हुए Client को पूर्ण resolution में खोलता है और मौजूदा Hub session से mouse तथा keyboard input भेजता है।","share-files":"Hub की फ़ाइलें देखें, चुने हुए Clients को भेजें और shared folders तथा transfer progress प्रबंधित करें।",agents:"चुनी हुई permissions, timeout और audit controls के भीतर जुड़े Clients पर Hub-hosted Codex tasks चलाता है।"},ar:{hub:"استخدم هذا الكمبيوتر بوصفه LiveDesk Hub. يمثّل Hub مركز التحكم الموحّد لاتصالات Client وWall وControl والملفات وAgents؛ اضغط عليه بعد تغييرات الشبكة لتحديث الوصول الآمن.","switch-to-hub":"يحوّل هذا الكمبيوتر من Client إلى Hub. يحفظ LiveDesk الدور الجديد ويعيد تشغيل بيئة سطح المكتب نفسها ويفتح Wall، ويتوقف الجهاز عن المشاركة كـ Client.",client:"يبقي هذا الكمبيوتر في وضع Client لتظل شاشاته وملفاته وصوته والتحكم عن بعد متاحة من Hub النشط.",wall:"يعرض صورا حية مصغرة لكل Clients المتصلين. اختر الشاشة وحجم البلاطات أو انتقل إلى Control من دون اتصال جديد.",control:"يفتح Client المحدد بالدقة الكاملة ويرسل إدخال الماوس ولوحة المفاتيح عبر جلسة Hub الحالية.","share-files":"استعرض ملفات Hub وأرسلها إلى Clients المحددين وأدر المجلدات المشتركة وتقدم النقل.",agents:"يشغّل مهام Codex المستضافة على Hub في Clients المتصلين ضمن الصلاحيات والمهل وضوابط التدقيق المحددة."},tr:{hub:"Bu bilgisayarı LiveDesk Hub olarak kullanır. Hub; Client bağlantıları, Wall, Control, dosyalar ve Agents için birleşik kontrol merkezidir; ağ değişikliklerinden sonra güvenli erişimi yenilemek için basın.","switch-to-hub":"Bu bilgisayarı Client rolünden Hub rolüne geçirir. LiveDesk yeni rolü kaydeder, aynı masaüstü runtime’ını yeniden başlatıp Wall’u açar; Client paylaşımı durur.",client:"Bu bilgisayarı Client modunda tutar; ekran, dosya, ses ve uzaktan kontrol özellikleri etkin Hub tarafından kullanılabilir kalır.",wall:"Bağlı tüm Client ekranlarının canlı küçük görüntülerini gösterir. Ekran ve kutu boyutunu seçin veya yeni bağlantı açmadan Control’e geçin.",control:"Seçili Client’ı tam çözünürlükte açar ve mevcut Hub oturumu üzerinden fare ile klavye girdisi gönderir.","share-files":"Hub dosyalarını gezin, seçili Client’lara gönderin ve paylaşılan klasörlerle aktarım ilerlemesini yönetin.",agents:"Hub üzerinde barındırılan Codex görevlerini seçili izinler, zaman aşımları ve denetim kontrolleri içinde bağlı Client’larda çalıştırır."}};function of(n){const a=n?[n]:typeof navigator>"u"?["en"]:navigator.languages?.length?navigator.languages:[navigator.language];for(const r of a){const l=String(r||"").trim(),c=l.toLowerCase();if(!c)continue;if(c.startsWith("zh-tw")||c.startsWith("zh-hk"))return"zh-TW";if(c.startsWith("zh"))return"zh";if(c.startsWith("pt"))return"pt-BR";const d=c.split("-")[0];if(Th[l])return l;if(Th[d])return d}return"en"}function Wd(n,a){const r=of(a);return Th[r]?.[n]||ib[n]}function Eh(n,a,r){return`${n}
11
- ${Wd(a,r)}`}const rb={eyebrow:"Change computer role",title:"Switch this computer to Hub?",description:"LiveDesk will stop sharing this computer as a Client, save the Hub role, restart the local runtime, and open Wall in this same window.",restartNotice:"Remote streams from this computer will end while LiveDesk restarts.",cancel:"Cancel",confirm:"Switch to Hub",closeLabel:"Close Hub switch confirmation"},uC={en:rb,ko:{eyebrow:"컴퓨터 역할 변경",title:"이 컴퓨터를 Hub로 전환하시겠습니까?",description:"이 컴퓨터의 Client 공유를 중지하고 Hub 역할을 저장한 뒤 로컬 런타임을 재시작하여 같은 창에서 Wall을 엽니다.",restartNotice:"LiveDesk가 재시작되는 동안 이 컴퓨터의 원격 스트림이 종료됩니다.",cancel:"취소",confirm:"Hub로 전환",closeLabel:"Hub 전환 확인 닫기"},ja:{eyebrow:"コンピューターの役割を変更",title:"このコンピューターを Hub に切り替えますか?",description:"このコンピューターの Client 共有を停止し、Hub の役割を保存してローカルランタイムを再起動し、同じウィンドウで Wall を開きます。",restartNotice:"LiveDesk の再起動中、このコンピューターのリモートストリームは終了します。",cancel:"キャンセル",confirm:"Hub に切り替える",closeLabel:"Hub 切り替え確認を閉じる"},zh:{eyebrow:"更改电脑角色",title:"将此电脑切换为 Hub?",description:"LiveDesk 将停止此电脑的 Client 共享,保存 Hub 角色,重启本地运行时,并在同一窗口中打开 Wall。",restartNotice:"LiveDesk 重启期间,此电脑的远程流将会结束。",cancel:"取消",confirm:"切换为 Hub",closeLabel:"关闭 Hub 切换确认"},"zh-TW":{eyebrow:"變更電腦角色",title:"要將此電腦切換為 Hub 嗎?",description:"LiveDesk 將停止此電腦的 Client 分享、儲存 Hub 角色、重新啟動本機執行階段,並在同一視窗中開啟 Wall。",restartNotice:"LiveDesk 重新啟動期間,此電腦的遠端串流將會結束。",cancel:"取消",confirm:"切換為 Hub",closeLabel:"關閉 Hub 切換確認"},es:{eyebrow:"Cambiar función del equipo",title:"¿Cambiar este equipo a Hub?",description:"LiveDesk dejará de compartir este equipo como Client, guardará la función Hub, reiniciará el entorno local y abrirá Wall en esta misma ventana.",restartNotice:"Los streams remotos de este equipo terminarán mientras LiveDesk se reinicia.",cancel:"Cancelar",confirm:"Cambiar a Hub",closeLabel:"Cerrar confirmación de cambio a Hub"},fr:{eyebrow:"Changer le rôle de l’ordinateur",title:"Basculer cet ordinateur vers Hub ?",description:"LiveDesk arrêtera le partage Client de cet ordinateur, enregistrera le rôle Hub, redémarrera le runtime local et ouvrira Wall dans cette même fenêtre.",restartNotice:"Les flux distants de cet ordinateur prendront fin pendant le redémarrage de LiveDesk.",cancel:"Annuler",confirm:"Basculer vers Hub",closeLabel:"Fermer la confirmation de bascule vers Hub"},de:{eyebrow:"Computerrolle ändern",title:"Diesen Computer auf Hub umstellen?",description:"LiveDesk beendet die Client-Freigabe dieses Computers, speichert die Hub-Rolle, startet die lokale Laufzeit neu und öffnet Wall im selben Fenster.",restartNotice:"Die Remote-Streams dieses Computers enden während des LiveDesk-Neustarts.",cancel:"Abbrechen",confirm:"Auf Hub umstellen",closeLabel:"Bestätigung für Hub-Wechsel schließen"},"pt-BR":{eyebrow:"Alterar função do computador",title:"Mudar este computador para Hub?",description:"O LiveDesk interromperá o compartilhamento deste computador como Client, salvará a função Hub, reiniciará o runtime local e abrirá o Wall nesta mesma janela.",restartNotice:"Os streams remotos deste computador serão encerrados enquanto o LiveDesk reinicia.",cancel:"Cancelar",confirm:"Mudar para Hub",closeLabel:"Fechar confirmação de mudança para Hub"},it:{eyebrow:"Cambia ruolo del computer",title:"Passare questo computer a Hub?",description:"LiveDesk interromperà la condivisione Client di questo computer, salverà il ruolo Hub, riavvierà il runtime locale e aprirà Wall nella stessa finestra.",restartNotice:"Gli stream remoti di questo computer termineranno durante il riavvio di LiveDesk.",cancel:"Annulla",confirm:"Passa a Hub",closeLabel:"Chiudi la conferma del passaggio a Hub"},id:{eyebrow:"Ubah peran komputer",title:"Alihkan komputer ini menjadi Hub?",description:"LiveDesk akan menghentikan berbagi komputer ini sebagai Client, menyimpan peran Hub, memulai ulang runtime lokal, lalu membuka Wall di jendela yang sama.",restartNotice:"Stream jarak jauh dari komputer ini akan berakhir saat LiveDesk dimulai ulang.",cancel:"Batal",confirm:"Alihkan ke Hub",closeLabel:"Tutup konfirmasi peralihan Hub"},vi:{eyebrow:"Đổi vai trò máy tính",title:"Chuyển máy tính này thành Hub?",description:"LiveDesk sẽ dừng chia sẻ máy tính này dưới dạng Client, lưu vai trò Hub, khởi động lại runtime cục bộ và mở Wall trong cùng cửa sổ.",restartNotice:"Các luồng từ xa của máy tính này sẽ kết thúc trong khi LiveDesk khởi động lại.",cancel:"Hủy",confirm:"Chuyển sang Hub",closeLabel:"Đóng xác nhận chuyển sang Hub"},th:{eyebrow:"เปลี่ยนบทบาทคอมพิวเตอร์",title:"เปลี่ยนคอมพิวเตอร์เครื่องนี้เป็น Hub หรือไม่",description:"LiveDesk จะหยุดแชร์คอมพิวเตอร์เครื่องนี้ในฐานะ Client บันทึกบทบาท Hub รีสตาร์ทรันไทม์ภายในเครื่อง และเปิด Wall ในหน้าต่างเดิม",restartNotice:"สตรีมระยะไกลจากคอมพิวเตอร์เครื่องนี้จะสิ้นสุดลงระหว่างที่ LiveDesk รีสตาร์ท",cancel:"ยกเลิก",confirm:"เปลี่ยนเป็น Hub",closeLabel:"ปิดการยืนยันการเปลี่ยนเป็น Hub"},hi:{eyebrow:"कंप्यूटर की भूमिका बदलें",title:"इस कंप्यूटर को Hub में बदलें?",description:"LiveDesk इस कंप्यूटर की Client साझेदारी बंद करेगा, Hub भूमिका सहेजेगा, स्थानीय रनटाइम पुनः आरंभ करेगा और इसी विंडो में Wall खोलेगा।",restartNotice:"LiveDesk के पुनः आरंभ होने के दौरान इस कंप्यूटर की रिमोट स्ट्रीम समाप्त हो जाएँगी।",cancel:"रद्द करें",confirm:"Hub में बदलें",closeLabel:"Hub परिवर्तन की पुष्टि बंद करें"},ar:{eyebrow:"تغيير دور الكمبيوتر",title:"هل تريد تحويل هذا الكمبيوتر إلى Hub؟",description:"سيوقف LiveDesk مشاركة هذا الكمبيوتر كـ Client، ويحفظ دور Hub، ويعيد تشغيل وقت التشغيل المحلي، ثم يفتح Wall في النافذة نفسها.",restartNotice:"ستنتهي التدفقات البعيدة من هذا الكمبيوتر أثناء إعادة تشغيل LiveDesk.",cancel:"إلغاء",confirm:"التحويل إلى Hub",closeLabel:"إغلاق تأكيد التحويل إلى Hub"},tr:{eyebrow:"Bilgisayar rolünü değiştir",title:"Bu bilgisayar Hub rolüne geçirilsin mi?",description:"LiveDesk bu bilgisayarın Client paylaşımını durdurur, Hub rolünü kaydeder, yerel çalışma zamanını yeniden başlatır ve Wall’u aynı pencerede açar.",restartNotice:"LiveDesk yeniden başlatılırken bu bilgisayarın uzak akışları sona erer.",cancel:"İptal",confirm:"Hub’a geçir",closeLabel:"Hub geçişi onayını kapat"}},lb={eyebrow:"Computer role",title:"Use this computer as Hub?",description:"Hub connects to and manages Client computers.",restartNotice:"If another computer is Hub, this computer will become the new Hub.",cancel:"Cancel",confirm:"Use as Hub",closeLabel:"Close Hub confirmation"},dC={en:lb,ko:{eyebrow:"컴퓨터 역할",title:"이 컴퓨터를 Hub로 사용할까요?",description:"Hub는 Client 컴퓨터를 연결하고 관리합니다.",restartNotice:"다른 컴퓨터가 Hub라면 이 컴퓨터가 새 Hub가 됩니다.",cancel:"취소",confirm:"Hub로 설정",closeLabel:"Hub 설정 확인 닫기"}};function fC(n){const a=of(n);return uC[a]||rb}function mC(n){const a=of(n);return dC[a]||lb}const hC=[{id:"docs",label:"Doc",icon:Gd},{id:"support",label:"Support",icon:qc},{id:"pricing",label:"Pricing",icon:jo},{id:"settings",label:"Settings",icon:Zh}],Sy=[0,1e3,2e3,5e3,1e4,2e4,3e4];function pC(){return typeof window>"u"?"":window.location.port==="5179"?window.location.origin:"http://127.0.0.1:5179"}async function xl(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 Rh(n){return`${Math.max(0,Math.min(100,Number(n||0))).toFixed(0)}%`}function Xm(n){return Number.isFinite(n)?`${Math.max(0,Math.min(100,Number(n))).toFixed(0)}%`:"—"}function ob(n){return Number.isFinite(n)?Rh(Number(n)):"0%"}function Ml(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 Cy(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 gC(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 vC(n,a){return!Number.isFinite(a)||Number(a)<=0?"Dedicated memory unavailable":Number.isFinite(n)?`${Ml(n)} / ${Ml(a)}`:`${Ml(a)} available`}function yC(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 gd({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:ob(c)}})})]})}function xC(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 bC(n){const a=n?.user.user_metadata||{},r=a.avatar_url||a.picture;return typeof r=="string"?r.trim():""}function wC({page:n,status:a}){const l={docs:{label:"DOC",title:"Using this computer",body:"This computer connects to its assigned Hub automatically. Keep LiveDesk running and manage screens, files, and remote control from the Hub."},pricing:{label:"PRICING",title:"LiveDesk plans",body:"Plans are based on how many computers the Hub manages. This Client computer does not need a separate subscription or setup."},settings:{label:"SETTINGS",title:"Computer preferences",body:"LiveDesk keeps the verified sign-in on this computer and reconnects to the assigned Hub automatically."}}[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 Hub."})]}),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 SC({session:n,status:a,pin:r,error:l,roleChangeMessage:c,videoAccelerationBusy:d,slotInput:m,slotBusy:p,onSignIn:v,onPinChange:g,onSubmitPin:w,onSlotInputChange:x,onSaveSlot:b,onEnableVideoAcceleration:j}){const C=a?.connectionState==="connected",k=a?.videoAcceleration,M=d||k?.busy||k?.state==="installing",A=k?.ready?`${k.encoder||"H.264"} · ${k.driver||"VAAPI"}`:M?"Setting up…":k?.message||"Setup available",T=a?.system?.memoryTotalBytes?Number(a.system.memoryUsedBytes||0)/a.system.memoryTotalBytes*100:0,R=a?.system?.gpus||[],P=R.find(O=>Number.isFinite(O.usagePercent)||Number.isFinite(O.memoryTotalBytes))||R[0],F=Number.isFinite(P?.usagePercent)?Number(P?.usagePercent):null,V=Number.isFinite(P?.memoryTotalBytes)&&Number(P?.memoryTotalBytes)>0&&Number.isFinite(P?.memoryUsedBytes)?Number(P?.memoryUsedBytes)/Number(P?.memoryTotalBytes)*100:null,_=a?.system?.disks||[],L=a?.system?.network,ne=L?.interfaces||[],W=[...new Set(ne.map(O=>O.name).filter(Boolean))],J=ne.map(O=>O.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 ${C?"connected":""}`,children:[s.jsx(Zt,{size:15})," ",C?"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(Wx,{size:14})," Uptime ",yC(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(gd,{icon:Ah,label:"CPU",value:Rh(a?.system?.cpuUsagePercent),detail:a?.system?.cpuLogicalCores?`${a.system.cpuLogicalCores} logical cores · Current processor usage`:"Current processor usage",percent:a?.system?.cpuUsagePercent}),s.jsx(gd,{icon:US,label:"Memory",value:Rh(T),detail:gC(a?.system?.memoryUsedBytes,a?.system?.memoryTotalBytes),percent:T}),s.jsx(gd,{icon:qS,label:"GPU",value:Xm(F),detail:P?.name||(a?.system?.hardwareCollecting?"Detecting graphics hardware…":"Graphics usage unavailable"),percent:F}),s.jsx(gd,{icon:Vr,label:"VRAM",value:Xm(V),detail:vC(P?.memoryUsedBytes,P?.memoryTotalBytes),percent:V})]})]}),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:_.length>0?`${_.length} ${_.length===1?"drive":"drives"}`:a?.system?.hardwareCollecting?"Detecting…":"Unavailable"})]}),s.jsxs("div",{className:"client-disk-list",children:[_.map(O=>s.jsxs("article",{className:"client-disk-row",children:[s.jsxs("div",{className:"client-disk-row-head",children:[s.jsxs("span",{children:[s.jsx(Nl,{size:16}),s.jsx("strong",{children:O.mount||"Disk"}),s.jsx("small",{children:O.name||"Local disk"})]}),s.jsx("strong",{children:Xm(O.usedPercent)})]}),s.jsxs("small",{children:[Ml(O.freeBytes)," free · ",Ml(O.totalBytes)," total"]}),s.jsx("i",{"aria-hidden":"true",children:s.jsx("b",{style:{width:ob(O.usedPercent)}})})]},`${O.mount}-${O.name||""}`)),_.length===0&&s.jsxs("div",{className:"client-disk-empty",children:[s.jsx(Nl,{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:W.length>0?W.join(", "):"Detecting adapter"})]}),s.jsxs("div",{className:"client-network-live",children:[s.jsxs("div",{className:"client-network-adapter",children:[s.jsx(El,{size:18}),s.jsxs("span",{children:[s.jsx("strong",{children:W.join(", ")||"Network"}),s.jsx("small",{children:J.join(" / ")||"Checking active connection"})]})]}),s.jsxs("div",{className:"client-network-rate download",children:[s.jsx(GS,{size:17}),s.jsxs("span",{children:[s.jsx("small",{children:"Receive"}),s.jsx("strong",{children:Cy(L?.receiveBytesPerSecond)})]})]}),s.jsxs("div",{className:"client-network-rate upload",children:[s.jsx(VS,{size:17}),s.jsxs("span",{children:[s.jsx("small",{children:"Send"}),s.jsx("strong",{children:Cy(L?.sendBytesPerSecond)})]})]}),s.jsxs("small",{className:"client-network-total",children:["Total ",Ml(L?.receivedBytes)," received / ",Ml(L?.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:C?"Connected to the Hub":a?.authenticated?"Finding the Hub":"Connect this computer"}),C?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(Ht,{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(ko,{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(bn,{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:v,children:[s.jsx(Tl,{size:16})," Sign in with Google"]}):s.jsxs("p",{className:"client-unified-success",children:[s.jsx(_n,{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(Ao,{size:16}),s.jsx("input",{value:r,onChange:O=>g(O.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:w,disabled:r.length!==6,children:"Connect"})]})]}),k?.supported&&s.jsxs("div",{className:`client-video-acceleration state-${k.ready?"ready":k.state||"setup-required"}`,children:[s.jsx(Ah,{size:17}),s.jsxs("span",{children:[s.jsx("strong",{children:"Hardware video"}),s.jsx("small",{children:A})]}),!k.ready&&k.canInstall&&s.jsx("button",{type:"button",onClick:j,disabled:M,title:"Install and verify Linux FFmpeg hardware video support",children:M?"Setting up":"Enable"})]}),(l||a?.lastError)&&s.jsxs("p",{className:"client-unified-error",role:"alert",children:[s.jsx(Jh,{size:15})," ",l||a?.lastError]}),c&&s.jsx("p",{className:"client-unified-success",children:c}),s.jsxs("div",{className:"client-slot-setting",children:[s.jsxs("label",{htmlFor:"client-slot-number",children:[s.jsx("span",{children:"Slot"}),s.jsx("input",{id:"client-slot-number",value:m,onChange:O=>x(O.target.value),inputMode:"numeric",pattern:"[0-9]*",placeholder:"1-999","aria-label":"Wall slot number",disabled:!C||p})]}),s.jsxs("button",{type:"button",onClick:b,disabled:!C||p||!m,"aria-label":"Save slot number",title:"Save slot number",children:[s.jsx(Zh,{size:17}),s.jsx("span",{children:p?"Saving":"Set"})]})]})]})]})]})}function CC(){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,x]=u.useState(""),[b,j]=u.useState(!1),[C,k]=u.useState(!1),[M,A]=u.useState(""),[T,R]=u.useState(!1),[P,F]=u.useState(null),[V,_]=u.useState(!1),[L,ne]=u.useState("computer"),[W,J]=u.useState(!1),O=u.useRef(null),be=u.useRef(null),re=u.useRef(!1),K=u.useRef(!1),I=u.useRef(!1),ee=u.useRef(0),G=u.useRef(!1),q=u.useMemo(pC,[]),oe=u.useMemo(()=>xC(r),[r]),we=u.useMemo(()=>bC(r),[r]),Q=oe.slice(0,1).toUpperCase()||"L",$=u.useCallback(async()=>{if(g(""),window.liveDesk?.auth?.signInWithGoogle){const ye=await window.liveDesk.auth.signInWithGoogle();return ye?.ok===!1?(g(ye.error||"LiveDesk could not open the system browser for Google sign-in."),!1):!0}return window.location.assign(`${q}/auth/google`),!0},[q]),he=u.useCallback(async()=>{I.current||(I.current=!0,g("Your saved Google sign-in is incomplete. LiveDesk is reopening sign-in once to repair it."),await ft.auth.signOut({scope:"local"}).catch(()=>{}),l(null),await $()||(I.current=!1))},[$]),fe=u.useCallback(async ye=>{const ae=by(ye);if(ae)throw new Error(ae);if(re.current)return!1;re.current=!0;try{const Te=await window.liveDesk?.auth?.persistSession?.(ye);if(Te?.ok===!1)throw new Error(Te.error||"LiveDesk could not validate the desktop session.");for(let Pe=0;Pe<2;Pe+=1){const Je=await xl(q,Pe>0),Mt=await fetch(`${q}/api/auth/session`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":Je},signal:AbortSignal.timeout(1e4),body:JSON.stringify({accessToken:ye.access_token,refreshToken:ye.refresh_token,expiresAt:ye.expires_at,user:{id:ye.user.id,email:ye.user.email}})}),It=await Mt.json().catch(()=>({}));if(Mt.status===403&&Pe===0){sessionStorage.removeItem("livedesk.client.csrf");continue}if(!Mt.ok)throw new Error(It.error||`Client runtime returned HTTP ${Mt.status}.`);return g(""),!0}throw new Error("Client runtime rejected the session transfer.")}finally{re.current=!1}},[q]),me=u.useCallback(async()=>{try{const ye=await fetch(`${q}/api/client/status`,{cache:"no-store"}),ae=await ye.json().catch(()=>({}));if(!ye.ok)throw new Error(ae.error||`Client runtime returned HTTP ${ye.status}.`);if(ae.csrfToken&&sessionStorage.setItem("livedesk.client.csrf",ae.csrfToken),String(ae.role||"").toLowerCase()==="hub")throw new Error("This computer is assigned to the Hub role.");a(ae)}catch(ye){g(ye instanceof Error?ye.message:String(ye))}},[q]);u.useEffect(()=>{me();const ye=window.setInterval(()=>{me()},2e3);return()=>window.clearInterval(ye)},[me]),u.useEffect(()=>{if(G.current)return;const ye=Number(n?.slotNumber||0);A(ye>0?String(ye):"")},[n?.slotNumber]),u.useEffect(()=>{if(!P)return;const ye=window.setTimeout(()=>F(null),5e3);return()=>window.clearTimeout(ye)},[P]);const Se=u.useCallback(async()=>{const ye=Date.now();if(!(!n?.authenticated||n.connectionState==="connected"||!["waiting","reconnecting"].includes(String(n.agent?.state||""))||ye-ee.current<4e3)){ee.current=ye;try{const ae=await fetch(`${q}/api/client/reconnect`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await xl(q)},body:JSON.stringify({onlyIfWaiting:!0,reason:"app-active"})});if(!ae.ok)throw new Error(`Client reconnect returned HTTP ${ae.status}.`);await me()}catch(ae){g(ae instanceof Error?ae.message:String(ae))}}},[q,me,n]);u.useEffect(()=>{const ye=()=>{Se()},ae=()=>{Se()},Te=()=>{document.visibilityState==="visible"&&Se()};return window.addEventListener("online",ye),window.addEventListener("focus",ae),document.addEventListener("visibilitychange",Te),()=>{window.removeEventListener("online",ye),window.removeEventListener("focus",ae),document.removeEventListener("visibilitychange",Te)}},[Se]),u.useEffect(()=>{if(!c||!n||!r?.access_token||n.authenticated)return;if(by(r)==="refresh-token-required"){he().catch(Je=>{I.current=!1,g(Je instanceof Error?Je.message:String(Je))});return}let ye=!1,ae,Te=0;const Pe=async()=>{if(ye)return;try{const Mt=await fe(r);if(await me(),Mt)return}catch(Mt){g(Mt instanceof Error?Mt.message:String(Mt))}if(ye)return;const Je=Sy[Math.min(Te,Sy.length-1)];Te+=1,ae=window.setTimeout(()=>{Pe()},Je)};return Pe(),()=>{ye=!0,ae!==void 0&&window.clearTimeout(ae)}},[c,me,he,r,n,fe]),u.useEffect(()=>{const ye=new URLSearchParams(window.location.search),ae=ye.get("auth_error");if(!ae)return;g(ae),ye.delete("auth_error");const Te=ye.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${Te?`?${Te}`:""}${window.location.hash}`)},[]),u.useEffect(()=>{let ye=!0;if(!window.liveDesk?.auth)return l(null),d(!0),me(),()=>{ye=!1};const ae=window.liveDesk?.auth?.onComplete?.(Pe=>{Pe.ok&&Pe.session?ft.auth.setSession(Pe.session).catch(Je=>g(Je instanceof Error?Je.message:String(Je))):Pe.error&&g(Pe.error)});(async()=>{try{const Pe=window.liveDesk?.auth?.getSession?await window.liveDesk.auth.getSession():await ft.auth.getSession();if(!ye)return;const Je=tb(Pe);l(Je),me()}catch(Pe){ye&&g(Pe instanceof Error?Pe.message:String(Pe))}finally{ye&&d(!0)}})();const{data:Te}=ft.auth.onAuthStateChange((Pe,Je)=>{ye&&(l(Je),d(!0),me())});return()=>{ye=!1,ae?.(),Te.subscription.unsubscribe()}},[me]),u.useEffect(()=>{if(!c||!n||K.current||I.current||r||n.authenticated)return;const ye=new URLSearchParams(window.location.search);if(!ye.has("livedesk_launch"))return;K.current=!0,ye.delete("livedesk_launch");const ae=ye.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${ae?`?${ae}`:""}${window.location.hash}`),$().catch(Te=>g(Te instanceof Error?Te.message:String(Te)))},[c,r,$,n]);const Be=async()=>{J(!1),window.liveDesk?.auth?.persistSession?(await ft.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 xl(q)}}).catch(()=>{}),l(null),await me()};u.useEffect(()=>{if(!W)return;const ye=Te=>{Te.target instanceof Element&&Te.target.closest(".account-popover, .rail-account")||J(!1)},ae=Te=>{Te.key==="Escape"&&J(!1)};return window.addEventListener("pointerdown",ye),window.addEventListener("keydown",ae),()=>{window.removeEventListener("pointerdown",ye),window.removeEventListener("keydown",ae)}},[W]);const Oe=u.useCallback((ye=!0)=>{b||(_(!1),ye&&window.requestAnimationFrame(()=>be.current?.focus()))},[b]),ge=u.useCallback(()=>{b||!n?.authenticated||(be.current=document.activeElement instanceof HTMLElement?document.activeElement:null,x(""),_(!0))},[b,n?.authenticated]);u.useEffect(()=>{if(!V)return;const ye=window.requestAnimationFrame(()=>O.current?.focus()),ae=Pe=>{Pe.target instanceof Element&&Pe.target.closest(".client-hub-switch-popover, .client-hub-switch-trigger")||Oe(!1)},Te=Pe=>{Pe.key==="Escape"&&Oe()};return window.addEventListener("pointerdown",ae),window.addEventListener("keydown",Te),()=>{window.cancelAnimationFrame(ye),window.removeEventListener("pointerdown",ae),window.removeEventListener("keydown",Te)}},[Oe,V]);const Ze=async()=>{g("");try{const ye=await fetch(`${q}/api/client/pin`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await xl(q)},body:JSON.stringify({pin:m})}),ae=await ye.json().catch(()=>({}));if(!ye.ok||ae?.ok===!1)throw new Error(ae?.error||"PIN could not be accepted.");p(""),await me()}catch(ye){g(ye instanceof Error?ye.message:String(ye))}},Ke=async()=>{_(!1),j(!0),x(""),g("");try{const ye=await fetch(`${q}/api/runtime/switch-role`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await xl(q)},body:JSON.stringify({role:"hub"})}),ae=await ye.json().catch(()=>({}));if(!ye.ok||ae?.ok===!1)throw new Error(ae?.error||`Role change failed with HTTP ${ye.status}.`);x("Hub role accepted. LiveDesk is restarting this computer with the Hub Wall.");const Te=Number(n?.runtimePid||0);await nb({baseUrl:q,targetRole:"hub",previousRuntimePid:Te,allowedStates:["running"]}),window.location.reload()}catch(ye){g(ye instanceof Error?ye.message:String(ye)),j(!1)}},ce=async()=>{if(T)return;const ye=Number(M);if(!Number.isInteger(ye)||ye<1||ye>999){F({kind:"error",message:"Enter a slot number from 1 to 999."});return}R(!0),F(null);try{const ae=await fetch(`${q}/api/client/slot`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await xl(q)},body:JSON.stringify({slotNumber:ye})}),Te=await ae.json().catch(()=>({}));if(!ae.ok||Te.ok===!1){if(Te.error==="slot-taken"){const Pe=Te.conflict?.deviceName||Te.conflict?.hostname||Te.conflict?.deviceId||"another computer";throw new Error(`Slot ${String(ye).padStart(3,"0")} is already used by ${Pe}.`)}throw new Error(Te.error||`Slot update failed with HTTP ${ae.status}.`)}G.current=!1,A(String(ye)),a(Te),F({kind:"success",message:`Slot ${String(ye).padStart(3,"0")} saved. LiveDesk is reconnecting this Client.`})}catch(ae){F({kind:"error",message:ae instanceof Error?ae.message:String(ae)})}finally{R(!1),await me()}},ve=async()=>{if(!C){k(!0),g("");try{const ye=await fetch(`${q}/api/client/video-acceleration/install`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await xl(q)},body:JSON.stringify({confirm:!0})}),ae=await ye.json().catch(()=>({}));if(a(ae),!ye.ok||ae.videoAcceleration?.ready!==!0)throw new Error(ae.videoAcceleration?.error||ae.error||"Linux hardware video setup did not complete.")}catch(ye){g(ye instanceof Error?ye.message:String(ye))}finally{k(!1),await me()}}},ke=!!(n?.authenticated||r),Ne=u.useMemo(()=>of(),[]),He=Wd("switch-to-hub",Ne),$e=Wd("client",Ne),Xe=fC(Ne);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(sb,{size:25})}),s.jsx("nav",{className:"rail-tools","aria-label":"Client navigation",children:s.jsxs("div",{className:"client-main-tool-slot",children:[s.jsxs("button",{className:"rail-tool client-main-tool client-hub-tool client-hub-switch-trigger accent-blue",type:"button",onClick:ge,disabled:b||!n?.authenticated,"aria-busy":b,"aria-expanded":V,"aria-haspopup":"dialog","aria-controls":V?"client-hub-switch-popover":void 0,"aria-label":`Hub. ${He}`,"data-tooltip":V?void 0:Eh("Hub","switch-to-hub",Ne),children:[s.jsx(Vr,{size:19}),s.jsx("span",{children:b?"Switching…":"Hub"})]}),s.jsxs("button",{className:`rail-tool client-main-tool accent-blue ${L==="computer"?"active":""}`,type:"button",onClick:()=>ne("computer"),"aria-current":L==="computer"?"page":void 0,"aria-label":`Client. ${$e}`,"data-tooltip":Eh("Client","client",Ne),children:[s.jsx(Zt,{size:19}),s.jsx("span",{children:"Client"})]})]})}),s.jsxs("div",{className:"rail-footer",children:[hC.map(ye=>{const ae=ye.icon;return s.jsxs("button",{className:`rail-tool compact ${L===ye.id?"active":""}`,type:"button",onClick:()=>ne(ye.id),title:ye.label,children:[s.jsx(ae,{size:18}),s.jsx("span",{children:ye.label})]},ye.id)}),s.jsxs("button",{className:`rail-account ${ke?"signed-in":""}`,type:"button",onClick:()=>J(ye=>!ye),"aria-expanded":W,"aria-haspopup":"dialog",title:ke?"Account":"Sign in",children:[r&&we?s.jsx("img",{src:we,alt:oe,referrerPolicy:"no-referrer"}):r?s.jsx("span",{className:"avatar-fallback",children:Q}):ke?s.jsx(Ht,{size:18}):s.jsx(Tl,{size:18}),s.jsx("span",{children:ke?"Account":"Sign in"})]})]})]}),V&&s.jsxs("section",{id:"client-hub-switch-popover",className:"client-hub-switch-popover",role:"dialog","aria-modal":"false","aria-labelledby":"client-hub-switch-title","aria-describedby":"client-hub-switch-description client-hub-switch-restart",children:[s.jsxs("header",{className:"client-hub-switch-head",children:[s.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:s.jsx(Vr,{size:19})}),s.jsx("span",{className:"client-hub-switch-eyebrow",children:Xe.eyebrow}),s.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>Oe(),"aria-label":Xe.closeLabel,children:s.jsx(Sa,{size:17})})]}),s.jsx("h2",{id:"client-hub-switch-title",children:Xe.title}),s.jsx("p",{id:"client-hub-switch-description",children:Xe.description}),s.jsxs("p",{id:"client-hub-switch-restart",className:"client-hub-switch-notice",children:[s.jsx(Ht,{size:16,"aria-hidden":"true"}),s.jsx("span",{children:Xe.restartNotice})]}),s.jsxs("div",{className:"client-hub-switch-actions",children:[s.jsx("button",{type:"button",onClick:()=>Oe(),children:Xe.cancel}),s.jsxs("button",{ref:O,className:"primary",type:"button",onClick:()=>{Ke()},disabled:b||!n?.authenticated,children:[s.jsx(Vr,{size:16}),Xe.confirm]})]})]}),W&&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&&we?s.jsx("img",{src:we,alt:oe,referrerPolicy:"no-referrer"}):r?s.jsx("span",{children:Q}):s.jsx(Tl,{size:18})}),s.jsxs("div",{children:[s.jsx("strong",{children:r?oe:ke?"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":ke?"Active for this run":"Not saved"}),s.jsx("dt",{children:"Role"}),s.jsx("dd",{children:"Client"})]}),ke?s.jsxs("button",{className:"account-popover-action",onClick:()=>{Be()},type:"button",children:[s.jsx(Vx,{size:16}),"Logout"]}):s.jsxs("button",{className:"account-popover-action primary",onClick:()=>{J(!1),$()},type:"button",children:[s.jsx(Tl,{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(bn,{size:18})}),s.jsxs("div",{children:[s.jsx("h1",{children:"LiveDesk"}),s.jsx("p",{children:"Client workspace"})]})]})}),L==="support"?s.jsx("section",{className:"client-unified-page",children:s.jsx(eb,{session:r,currentProductKey:"livedesk",appVersion:n?.appVersion||"",onSignIn:()=>{$()}})}):L!=="computer"?s.jsx("section",{className:"client-unified-page",children:s.jsx(wC,{page:L,status:n})}):s.jsx(SC,{session:r,status:n,pin:m,error:v,roleChangeMessage:w,videoAccelerationBusy:C,slotInput:M,slotBusy:T,onSignIn:()=>{$()},onPinChange:ye=>p(ye.replace(/\D/g,"").slice(0,6)),onSubmitPin:()=>{Ze()},onSlotInputChange:ye=>{G.current=!0,A(ye.replace(/\D/g,"").slice(0,3))},onSaveSlot:()=>{ce()},onEnableVideoAcceleration:()=>{ve()}})]}),P&&s.jsxs("div",{className:`client-side-toast ${P.kind}`,role:P.kind==="error"?"alert":"status",children:[P.kind==="error"?s.jsx(Jh,{size:18}):s.jsx(_n,{size:18}),s.jsx("span",{children:P.message}),s.jsx("button",{type:"button",onClick:()=>F(null),"aria-label":"Dismiss notification",children:s.jsx(Sa,{size:16})})]})]})}function Ur(n,a,r){if(r<0||a<0||a+r>n.length)throw new Error("Invalid LZO1X block: input overrun.")}function Zm(n,a,r){let l=0;for(;Ur(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 vd(n,a,r,l){if(Ur(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 jC(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 cb(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,vd(n,l,r,m),c=4}else n[l.inputIndex]>=18&&(c=n[l.inputIndex]-17,l.inputIndex+=1,vd(n,l,r,c));for(;;){Ur(n,l.inputIndex,1);const m=n[l.inputIndex];l.inputIndex+=1;let p,v;if((m&192)!==0)Ur(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+=Zm(n,l,31)),Ur(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+=Zm(n,l,7)),Ur(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+=Zm(n,l,15)),vd(n,l,r,g),c=4;continue}else c!==4?(Ur(n,l.inputIndex,1),p=m&3,v=l.outputIndex-((m>>2)+(n[l.inputIndex]<<2)+1),l.inputIndex+=1,d=2):(Ur(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=jC(r,l.outputIndex,v,d),c=p,vd(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 jy=16,ky=8,kC=24*1024*1024,ub=new Uint8Array(new Uint32Array([16909060]).buffer)[0]===4,Dh=new Uint32Array(65536);for(let n=0;n<Dh.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);Dh[n]=ub?(a|r<<8|l<<16|4278190080)>>>0:(a<<24|r<<16|l<<8|255)>>>0}function Pr(n,a){return n[a]|n[a+1]<<8}function AC(n,a){const r=Number(a);if(!Number.isSafeInteger(r)||r<jy||r>kC)throw new Error(`Invalid Mode 5 packet length: ${a}.`);const l=n instanceof Uint8Array?n:new Uint8Array(n),c=cb(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=Pr(c,6),p=Pr(c,8),v=Pr(c,10),g=Pr(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 x=jy;for(let b=0;b<g;b+=1){if(x+ky>c.length)throw new Error("Mode 5 tile header is truncated.");const j=Pr(c,x),C=Pr(c,x+2),k=Pr(c,x+4),M=Pr(c,x+6);x+=ky;const A=k*M*2;if(k<=0||M<=0||k>v||M>v||j+k>m||C+M>p||x+A>c.length)throw new Error(`Invalid Mode 5 tile ${b}.`);w.push({x:j,y:C,width:k,height:M,pixels:c.subarray(x,x+A)}),x+=A}if(x!==c.length)throw new Error(`Mode 5 packet has ${c.length-x} trailing bytes.`);return{keyFrame:d,width:m,height:p,tileSize:v,tiles:w}}function NC(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=ub&&(g.pixels.byteOffset&1)===0?new Uint16Array(g.pixels.buffer,g.pixels.byteOffset,g.pixels.byteLength>>>1):null;let x=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 k=x<<1,M=w?w[x]:g.pixels[k]|g.pixels[k+1]<<8;v[j]=Dh[M],x+=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 Ba=new WeakMap,eu=new WeakMap,Lh=new WeakMap,tu=new Set,Al=new Set,Yd=new WeakMap,_h=new WeakMap,zh=new WeakMap,Kd=new WeakMap,db=4,MC=2,TC=2,EC=2,RC=18,DC=40,LC=0,_C=250,fb=80,Ay=5,zC=150,IC=24,OC=180,HC=1200,BC=18,FC=.65,PC=2e3,$C=500,sp=250,UC=globalThis.LIVEDESK_ENABLE_CANVAS_VISUAL_SAMPLING===!0;let Qd=!1;function qC(){return typeof navigator>"u"?!1:/mac/i.test(`${navigator.platform||""} ${navigator.userAgent||""}`)}function GC(){const n=Math.max(1,Number(navigator.hardwareConcurrency||8));return Math.max(4,Math.min(16,Math.round(n/2)))}let Rl={h264DecodeAcceleration:"prefer-hardware",h264HardwareDecoderBudget:GC()};function VC(n){n.h264DecodeAcceleration&&(Rl={...Rl,h264DecodeAcceleration:n.h264DecodeAcceleration}),Number.isFinite(Number(n.h264HardwareDecoderBudget))&&(Rl.h264HardwareDecoderBudget=Math.max(1,Math.min(64,Math.round(Number(n.h264HardwareDecoderBudget)))))}function mb(n,a=Rl.h264DecodeAcceleration){const r=Yd.get(n);return r?.requested===a?(r.actual!=="prefer-hardware"&&Al.delete(n),r.actual):(r&&Yd.delete(n),a!=="prefer-hardware"?(Al.delete(n),a):Al.has(n)?"prefer-hardware":Al.size<Rl.h264HardwareDecoderBudget?(Al.add(n),"prefer-hardware"):"prefer-software")}function cf(n,a){return a!=="prefer-hardware"?!1:(Yd.set(n,{requested:a,actual:"prefer-software"}),Al.delete(n),!0)}function WC(n,a,r,l=64){try{let c=_h.get(n);c||(c={canvas:document.createElement("canvas"),lastHash:"",initialized:!1},_h.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"),x=!c.initialized||w!==c.lastHash;return c.initialized=!0,c.lastHash=w,{visualHash:w,visualChanged:x}}catch{return{visualHash:"",visualChanged:!0}}}function Ih(n,a,r,l=sp,c=64,d){if(!UC&&d)return hb(n,d);let m=zh.get(n);m||(m={lastHash:"",initialized:!1,lastCanvasSampleAt:0},zh.set(n,m));const p=performance.now();if(m.initialized&&l>0&&p-m.lastCanvasSampleAt<l)return{visualHash:m.lastHash,visualChanged:!1};const v=WC(n,a,r,c);return m.initialized=!0,m.lastHash=v.visualHash,m.lastCanvasSampleAt=p,v}function hb(n,a){let r=Kd.get(n);r||(r={lastHash:"",initialized:!1},Kd.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 pb(n,a){const r=Lh.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 Lh.set(n,d),d}return null}function YC(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 KC(n){return String(n.frameMode||n.mode||"").toLowerCase()==="mode3-h264-hw"||String(n.codec||"").toLowerCase()==="h264"||String(n.mimeType||"").toLowerCase()==="video/h264"}function QC(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 Ny(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 XC(n,a){const r=new Uint8Array(a);let l=0,c=0;for(;l<n.length;){const d=n[l];l+=1;const m=Ny(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=Ny(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 x=c-v;for(let b=0;b<w;b+=1)r[c]=r[x],c+=1,x+=1}if(c!==r.length)throw new Error("Invalid LZ4 block: incomplete output.");return r}function ZC(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)),x=a*r*2,b=Math.floor(n.uncompressedByteLength||x);if(w!==2||b!==x)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=cb(n.payload,x),C=new Uint8ClampedArray(a*r*4);for(let k=0,M=0;k<j.length;k+=2,M+=4){const A=j[k]|j[k+1]<<8,T=A>>11&31,R=A>>5&63,P=A&31;C[M]=T<<3|T>>2,C[M+1]=R<<2|R>>4,C[M+2]=P<<3|P>>2,C[M+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=XC(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,x=0;x<g.length;w+=4,x+=4)g[x]=v[w+2],g[x+1]=v[w+1],g[x+2]=v[w],g[x+3]=v[w+3];return new ImageData(g,a,r)}function My(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=Ba.get(n);if(l&&l.decoder.state!=="closed"&&l.latencyMode===a)return l;l&&Ls(n);let c;return c={decoder:new r({output:m=>{if(Ba.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,x=Number(v?.frame.durationUs||0),b=Number(m.duration||0),j=Math.max(16,Math.min(250,(x>0?x: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>rp(c);)Xd(c,c.decodedFrames.shift());gb(c),c.renderTimer!==null&&c.renderScheduledAt>0&&performance.now()-c.renderScheduledAt>$C&&(typeof document>"u"||document.visibilityState==="visible")&&(window.cancelAnimationFrame(c.renderTimer),c.renderTimer=null,c.renderScheduledAt=0),c.renderTimer!==null&&c.decodedFrames.length>=db&&(window.cancelAnimationFrame(c.renderTimer),c.renderTimer=null,c.renderScheduledAt=0),Zd(n,c)},error:()=>{Ba.get(n)===c&&(cf(n,c.hardwareAcceleration),ip(c),tu.delete(n),Ba.delete(n))}}),configured:!1,configKey:"",codec:"",hardwareAcceleration:mb(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},Ba.set(n,c),tu.add(n),c}function ip(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 Xd(n,a){a&&(a.videoFrame.close(),n.droppedForLatency+=1)}function rp(n){return n.latencyMode==="interactive"?TC:String(n.decodedFrames[0]?.pending?.frame.frameMode||n.decodedFrames[0]?.pending?.frame.mode||"").toLowerCase()==="mode4-h264-atlas"?MC:db}function gb(n,a=performance.now()){const r=rp(n);for(;n.decodedFrames.length>r;)Xd(n,n.decodedFrames.shift());const l=n.latencyMode==="interactive"?fb:_C;let c=n.decodedFrames[0];for(;n.decodedFrames.length>1&&c?.pending&&a-c.pending.queuedAt>l;)Xd(n,n.decodedFrames.shift()),c=n.decodedFrames[0]}function vb(n,a){if(a.hardwareAcceleration!=="prefer-hardware"||a.flushTimer!==null||a.flushInFlight)return;const r=a.latencyMode==="interactive"?IC:zC,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>PC&&a.pendingFrames.delete(p);if(Ba.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{Ba.get(n)===a&&Fd(a)}finally{a.flushInFlight=!1;const p=performance.now()-m;if(l&&p>=OC&&a.hardwareAcceleration==="prefer-hardware"){Qd=!0,cf(n,a.hardwareAcceleration),Ls(n);return}Ba.get(n)===a&&a.inputSerial>d&&a.pendingFrames.size>0&&(l||performance.now()-a.lastOutputAt>=r)&&vb(n,a)}},r)}function Ty(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=pb(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"?hb(n,r.pending.frame):Ih(n,r.width,r.height,sp,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 Zd(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(gb(a,c),a.decodedFrames.length===0)return;if(a.latencyMode==="interactive"){const v=a.targetPaintIntervalMs<=DC,g=a.targetPaintIntervalMs<=20;if(g&&!a.interactiveBufferPrimed){a.interactiveBufferStartedAt<=0&&(a.interactiveBufferStartedAt=c,a.interactiveBufferWaitCount+=1);const k=a.decodedFrames.length>=EC,M=c-a.interactiveBufferStartedAt>=RC;if(!k&&!M){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],x=w?.pending?Math.max(0,c-w.pending.queuedAt):0,b=a.lastPaintAt>0?a.lastPaintAt+r:c;if(!(!v||c+Ay>=b||x>=fb)){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}const C=a.decodedFrames.shift();if(C)try{Ty(n,a,C)}catch{}a.decodedFrames.length===0&&(a.interactiveQueueDrainCount+=1,a.interactiveBufferPrimed=!1,a.interactiveBufferStartedAt=0),Zd(n,a);return}const d=a.lastPaintAt>0?a.lastPaintAt+r:c+LC;if(!(c+Ay>=d||a.decodedFrames.length>=Math.max(1,rp(a)-1))){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}const p=a.decodedFrames.shift();if(p)try{Ty(n,a,p)}catch{}Zd(n,a)};a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l)}function yb(n,a){if(Ba.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;)Xd(a,a.decodedFrames.shift());return a.lastPaintAt=0,a.interactiveBufferPrimed=!1,a.interactiveBufferStartedAt=0,Zd(n,a),!0}function Jm(){if(!(typeof document>"u"||document.visibilityState!=="visible"))for(const n of tu){const a=Ba.get(n);if(!a||a.decoder.state==="closed"){tu.delete(n);continue}yb(n,a)}}typeof document<"u"&&typeof window<"u"&&(document.addEventListener("visibilitychange",Jm),window.addEventListener("focus",Jm),window.addEventListener("pageshow",Jm));function Ls(n){Al.delete(n),tu.delete(n),Kd.delete(n);const a=Ba.get(n);if(a){Ba.delete(n);try{ip(a),a.decoder.state!=="closed"&&a.decoder.close()}catch{}}}function Oc(n){n&&(Yd.delete(n),Lh.delete(n),zh.delete(n),_h.delete(n),Kd.delete(n),eu.delete(n),Ls(n))}function Fd(n,a=1){try{n.decoder.state!=="closed"&&n.decoder.reset()}catch{}n.configured=!1,n.configKey="",n.keyFrameSeen=!1,n.pendingFrames.clear(),ip(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 yd(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 JC(n,a){if(a.latencyMode!=="interactive"||a.hardwareAcceleration!=="prefer-hardware")return!1;const r=performance.now();if(r-a.healthSampleStartedAt<HC)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<BC||c/Math.max(1,l)>=FC?!1:(Qd=!0,cf(n,a.hardwareAcceleration),Ls(n),!0)}function eh(n,a=1){if(!n)return!1;const r=Ba.get(n);return r?(r.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(a))),Ls(n),!0):!1}function ej(n){if(!n)return!1;const a=Ba.get(n);return a?yb(n,a):!1}function tj(n,a,r,l="interactive"){Ls(n);const c=performance.now(),d=AC(a.payload,a.uncompressedByteLength||0),m=String(a.streamId||"mode5");let p=eu.get(n);if(!p||p.streamId!==m||p.width!==d.width||p.height!==d.height){const k=new Uint8ClampedArray(d.width*d.height*4);for(let M=3;M<k.length;M+=4)k[M]=255;p={streamId:m,width:d.width,height:d.height,rgba:k,imageData:new ImageData(k,d.width,d.height),keyFrameSeen:!1,inputSerial:0,outputSerial:0},eu.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=NC(p.rgba,p.width,p.height,d),x=performance.now();(n.width!==p.width||n.height!==p.height)&&(n.width=p.width,n.height=p.height);const b=pb(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,x-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 th=[{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 Ey(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 nj(n){let a=0;for(;a<n.length;){const r=Ey(n,a);if(!r)break;const l=r.index+r.length,c=Ey(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 aj(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=th.find(g=>d<=g.maxFrameSize&&p<=g.maxMacroblocksPerSecond)||th[th.length-1];return nj(l)||c||`avc1.42E0${v.code.toString(16).toUpperCase().padStart(2,"0")}`}function sj(n,a,r,l,c="smooth"){eu.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=My(n,c);const w=aj(m,p,v,a.payload,g.codec),x=String(a.frameMode||a.mode||"").toLowerCase(),b=c==="interactive"&&l==="prefer-hardware"&&qC(),C=x==="mode4-h264-atlas"?"prefer-software":mb(n,c==="interactive"&&(Qd||b)?"prefer-software":l),k=[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!==k&&(Ls(n),g=My(n,c),g.onPaint=r);const M={codec:w,codedWidth:m,codedHeight:p,hardwareAcceleration:C,optimizeForLatency:!0,avc:{format:d}};g.configured||yd(g,M,k,C);const A=a.isKeyFrame===!0||String(a.chunkType||"").toLowerCase()==="key";Number(a.frameSeq||0);const T=Number(a.streamFrameSeq||0);if(T>0&&g.lastInputFrameSeq!==void 0){if(T<=g.lastInputFrameSeq){if(!A||T===g.lastInputFrameSeq)return;Fd(g,g.lastInputFrameSeq-T+1),yd(g,M,k,C)}if(T>g.lastInputFrameSeq+1){if(Fd(g,T-g.lastInputFrameSeq-1),!A)return;yd(g,M,k,C)}}if(T>0&&(g.lastInputFrameSeq=T),!A&&!g.keyFrameSeen)return;A&&(g.keyFrameSeen=!0);const R=Number(g.decoder.decodeQueueSize||0);if(R>8){if(g.latencyMode==="interactive"&&g.hardwareAcceleration==="prefer-hardware"){Qd=!0,cf(n,g.hardwareAcceleration),Ls(n);return}if(Fd(g),!A)return;yd(g,M,k,C),g.keyFrameSeen=!0}const P=g.nextChunkTimestampUs;g.nextChunkTimestampUs+=v,g.pendingFrames.set(P,{frame:a,queuedAt:performance.now(),queueSize:R}),g.inputSerial+=1,g.lastInputAt=performance.now();const F=new EncodedVideoChunk({type:A?"key":"delta",timestamp:P,duration:v,data:a.payload});try{g.decoder.decode(F)}catch(V){throw Ls(n),V}vb(n,g),JC(n,g)}async function nh(n,a,r,l,c,d="smooth"){if(QC(a)){r()||tj(n,a,l,d);return}if(KC(a)){r()||sj(n,a,l,c,d);return}if(eu.delete(n),YC(a)){Ls(n);const x=ZC(a);if(r())return;(n.width!==x.width||n.height!==x.height)&&(n.width=x.width,n.height=x.height);const b=n.getContext("2d"),j=performance.now();b?.putImageData(x,0,0);const C=performance.now(),k=Ih(n,x.width,x.height,sp,64,a);l?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.codec||a.mimeType,width:x.width,height:x.height,byteLength:a.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,C-j),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:Rl.h264DecodeAcceleration,decoderLabel:"lzo-rgb565",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:k.visualHash,visualChanged:k.visualChanged,paintedAt:C});return}Ls(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 x=performance.now();w.clearRect(0,0,v,g),w.drawImage(p,0,0,v,g);const b=performance.now(),j=Ih(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-x),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:Rl.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 Ry="livedesk_remote_host_targets",ij="livedesk_entitlements",lp=new TextDecoder;function rj(n){const r=(Array.isArray(n)?n:[n||kn]).map(l=>Kr(l||kn));return[...new Set(r.filter(Boolean))]}function lj(){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&&ft.auth.setSession(p.session)});(window.liveDesk?.auth?.getSession?.()||ft.auth.getSession()).then(p=>{c&&(a(tb(p)),l(!1))});const{data:{subscription:m}}=ft.auth.onAuthStateChange((p,v)=>{a(v),l(!1),window.liveDesk?.auth?.persistSession?.(v)});return()=>{c=!1,d?.(),m.unsubscribe()}},[]),{session:n,loading:r}}function oj(n,a=!0){const[r,l]=u.useState(null),[c,d]=u.useState([]),[m,p]=u.useState(""),[v,g]=u.useState(""),[w,x]=u.useState(0),b=u.useRef(new Map),j=Array.isArray(n)?n.join(`
12
- `):String(n||""),C=u.useMemo(()=>rj(n),[j]),k=u.useMemo(()=>C.find(T=>Wc(T)==="loopback")||C[0]||kn,[C]),M=u.useCallback(async()=>{if(!a){l(null),d([]),g(""),p("");return}let T=null;const R=Date.now(),P=C.filter(F=>(b.current.get(F)||0)<=R);if(P.length===0)throw new Error("No LiveDesk Hub endpoint is reachable. Retrying shortly.");for(const F of P)try{const[V,_]=await Promise.all([We("/api/remote/status",void 0,F),We("/api/remote/devices",void 0,F)]);if(!Array.isArray(_.devices))throw new Error("Invalid Hub devices response.");b.current.delete(F),l(V),d(_.devices),g(F),p("");return}catch(V){T=V,b.current.set(F,Date.now()+1e4)}throw g(""),T||new Error("No LiveDesk Hub endpoint is reachable.")},[a,C]),A=u.useCallback(()=>{b.current.clear(),M().catch(T=>{p(T instanceof Error?T.message:String(T))}),x(T=>T+1)},[M]);return u.useEffect(()=>{if(!a){l(null),d([]),g(""),p("");return}let T=!0;const R=async()=>{try{await M()}catch(F){T&&p(F instanceof Error?F.message:String(F))}};R();const P=window.setInterval(R,2500);return()=>{T=!1,window.clearInterval(P)}},[a,M,w]),{status:r,devices:c,error:m,refresh:A,hubBaseUrl:v||k,hubCandidates:C}}function cj(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 ft.from(Ry).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=ft.channel(`livedesk-remote-host-targets-${d.replace(/[^a-zA-Z0-9]/g,"")}`).on("postgres_changes",{event:"*",schema:"public",table:Ry,filter:`user_id=eq.${d}`},v=>r(v.new)).subscribe();return()=>{ft.removeChannel(p)}},[d]),{target:a,error:l,refresh:m}}function uj(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:x}=await ft.from(ij).select("*").eq("user_id",p).eq("product_key","livedesk").maybeSingle();if(x){m(x.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 Yc={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},dj=2500,fj=3e4,mj=64*1024,hj=6,pj=hj,xb=new Map;function gj(n){return xb.get(n)}const Dy={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function vj(n,a,r){const l=Number(a);if(!Number.isFinite(l)||l<=0)return 0;const c=r-l,d=n.minimumHubClockOffsetMs;if(!Number.isFinite(d)||c<Number(d))return n.minimumHubClockOffsetMs=c,0;const m=Math.max(0,c-Number(d));return m>fj?(n.minimumHubClockOffsetMs=c,0):m}function Ly(n,a,r=kn,l={}){const[c,d]=u.useState(new Map),[m,p]=u.useState("idle"),[v,g]=u.useState(""),[w,x]=u.useState(Yc),b=u.useRef(new Map),j=u.useRef(new Map),C=u.useRef(0),k=u.useRef(new Map),M=u.useRef({enabled:!1,token:"",reason:""}),A=u.useRef(new Set),[T,R]=u.useState(0),P=u.useRef(l.onFrame),F=u.useRef(l.onStreamReady),V=u.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),_=u.useMemo(()=>[...n].sort().join(","),[n]),L=Number.isFinite(l.fps)?Number(l.fps):2,ne=Number.isFinite(l.maxWidth)?Number(l.maxWidth):640,W=Number.isFinite(l.maxHeight)?Number(l.maxHeight):360,J=Number.isFinite(l.quality)?Number(l.quality):45,O=String(l.frameMode||l.mode||"mode3-h264-hw").trim()||"mode3-h264-hw",be=l.streamPurpose==="control"?"control":"wall",re=l.forceRestart===!0,K=String(l.forceRestartToken||"").trim(),I=String(l.restartReason||"").trim();M.current={enabled:re,token:K,reason:I};const ee=u.useMemo(()=>{const he=Object.entries(l.monitorSelections||{}).filter(([fe])=>!!fe).sort(([fe],[me])=>fe.localeCompare(me));return JSON.stringify(Object.fromEntries(he))},[l.monitorSelections]);u.useEffect(()=>{P.current=l.onFrame},[l.onFrame]),u.useEffect(()=>{F.current=l.onStreamReady},[l.onStreamReady]);const G=u.useCallback((he,fe="livedesk-frame-socket-release")=>{he.disposed=!0;try{he.socket.readyState===WebSocket.CONNECTING||he.socket.readyState===WebSocket.OPEN?he.socket.close(1e3,fe):he.socket.close()}catch{}},[]),q=u.useCallback(()=>{const he=[...j.current.values()].map(fe=>fe.socket);if(he.length===0){p("idle");return}if(he.some(fe=>fe.readyState===WebSocket.OPEN)){p("open");return}if(he.some(fe=>fe.readyState===WebSocket.CONNECTING)){p("connecting");return}p("closed")},[]),oe=u.useCallback((he,fe,me,Se)=>{if(fe.disposed||fe.socket.readyState!==WebSocket.OPEN)return!1;try{return fe.socket.send(JSON.stringify({...fe.payload,type:"restart-live",deviceIds:[he],forceRestart:!0,restartReason:me,restartToken:Se})),!0}catch{return!1}},[]),we=u.useCallback((he,fe)=>{if(!he||he.byteLength<5)return;const me=Date.now(),Be=new DataView(he).getUint32(0,!1);if(Be<=0||Be+4>he.byteLength)return;const Oe=new Uint8Array(he,4,Be),ge=JSON.parse(lp.decode(Oe));if(vj(fe,ge.hubPacketEpochMs,me)>dj)return;const Ke=new Uint8Array(he,4+Be),ce={deviceId:String(ge.deviceId||""),kind:ge.kind==="thumbnail"?"thumbnail":"live",frameSeq:Number(ge.frameSeq||0),streamFrameSeq:Number(ge.streamFrameSeq||0)||void 0,streamId:String(ge.streamId||""),commandId:ge.commandId?String(ge.commandId):void 0,sessionId:ge.sessionId?String(ge.sessionId):void 0,captureGeneration:Number(ge.captureGeneration||0)||void 0,streamPurpose:ge.streamPurpose?String(ge.streamPurpose):void 0,width:Number(ge.width||0),height:Number(ge.height||0),sourceWidth:Number(ge.sourceWidth||0)||void 0,sourceHeight:Number(ge.sourceHeight||0)||void 0,mimeType:String(ge.mimeType||"image/jpeg"),mode:ge.mode?String(ge.mode):void 0,frameMode:ge.frameMode?String(ge.frameMode):void 0,frameProfile:ge.frameProfile?String(ge.frameProfile):void 0,encoding:ge.encoding?String(ge.encoding):void 0,codec:ge.codec?String(ge.codec):void 0,compression:ge.compression?String(ge.compression):void 0,pixelFormat:ge.pixelFormat?String(ge.pixelFormat):void 0,bytesPerPixel:Number(ge.bytesPerPixel||0)||0,uncompressedByteLength:Number(ge.uncompressedByteLength||0)||0,h264Format:ge.h264Format?String(ge.h264Format):void 0,isKeyFrame:ge.isKeyFrame===!0,chunkType:ge.chunkType?String(ge.chunkType):void 0,timestampUs:Number(ge.timestampUs||0)||0,durationUs:Number(ge.durationUs||0)||0,sourceGapMs:Number(ge.sourceGapMs||0)||0,agentSendGapMs:Number(ge.agentSendGapMs||0)||0,agentSendDurationMs:Number(ge.agentSendDurationMs||0)||0,agentSendDurationFrameSeq:Number(ge.agentSendDurationFrameSeq||0)||0,agentPaceMs:Number(ge.agentPaceMs||0)||0,agentQueueBeforePaceMs:Number(ge.agentQueueBeforePaceMs||0)||0,agentFrameAgeMs:Number(ge.agentFrameAgeMs||0)||0,droppedByAgent:Number(ge.droppedByAgent||0)||0,hubIngressDropped:Number(ge.hubIngressDropped||0)||0,hubClientDropped:Number(ge.hubClientDropped||0)||0,hardwareEncoder:ge.hardwareEncoder?String(ge.hardwareEncoder):void 0,platformProfile:ge.platformProfile?String(ge.platformProfile):void 0,monitorIndex:Number.isFinite(Number(ge.monitorIndex))?Number(ge.monitorIndex):void 0,monitorCount:Number.isFinite(Number(ge.monitorCount))?Number(ge.monitorCount):void 0,requestedFps:Number(ge.requestedFps||0)||0,effectiveFps:Number(ge.effectiveFps||0)||0,captureAverageMs:Number(ge.captureAverageMs||0)||0,captureP95Ms:Number(ge.captureP95Ms||0)||0,slowFrameCount:Number(ge.slowFrameCount||0)||0,captureHelperRestarts:Number(ge.captureHelperRestarts||0)||0,capturedAt:String(ge.capturedAt||""),receivedAt:String(ge.receivedAt||""),hubPacketAt:ge.hubPacketAt?String(ge.hubPacketAt):void 0,hubPacketEpochMs:Number.isFinite(Number(ge.hubPacketEpochMs))?Number(ge.hubPacketEpochMs):void 0,browserReceivedEpochMs:me,byteLength:Number(ge.byteLength||Ke.byteLength),contentHash:ge.contentHash?String(ge.contentHash):void 0,captureMs:Number(ge.captureMs||0)||0,captureStageMs:Number(ge.captureStageMs||0)||0,convertMs:Number(ge.convertMs||0)||0,compressMs:Number(ge.compressMs||0)||0,captureSourceSerial:Number(ge.captureSourceSerial||0)||0,captureSourceSkipped:Number(ge.captureSourceSkipped||0)||0,deltaTileSize:Number(ge.deltaTileSize||0)||0,deltaTileCount:Number(ge.deltaTileCount||0)||0,deltaVisualTileCount:Number(ge.deltaVisualTileCount||0)||0,deltaRefreshTileCount:Number(ge.deltaRefreshTileCount||0)||0,deltaTotalTiles:Number(ge.deltaTotalTiles||0)||0,payload:Ke};if(!ce.deviceId)return;const ve={streamId:fe.lastFrameStreamId,commandId:fe.lastFrameCommandId,order:fe.lastFrameOrder},ke=Number(ce.streamFrameSeq||ce.frameSeq||0),Ne=!!ve.commandId&&!!ce.commandId,He=ve.streamId===ce.streamId&&(!Ne||ve.commandId===ce.commandId),$e=ve.order;if(He&&$e>=ke&&($e===ke||Ne))return;fe.lastFrameStreamId=ce.streamId,fe.lastFrameCommandId=ce.commandId||"",fe.lastFrameOrder=ke;const Xe=V.current;Xe.totalFrames+=1,Xe.totalBytes+=Ke.byteLength,Xe.sampleFrames+=1,Xe.sampleBytes+=Ke.byteLength;const ye=!b.current.has(ce.deviceId);b.current.set(ce.deviceId,ce),ye&&d(new Map(b.current)),P.current?.(ce)},[]);u.useEffect(()=>{const he=window.setInterval(()=>{const fe=performance.now(),me=V.current,Se=Math.max(1,fe-me.sampleStartedAt);x({totalFrames:me.totalFrames,totalBytes:me.totalBytes,framesPerSecond:me.sampleFrames*1e3/Se,bytesPerSecond:me.sampleBytes*1e3/Se,sampleMs:Se,lastUpdatedAt:Date.now()}),d(new Map(b.current)),me.sampleFrames=0,me.sampleBytes=0,me.sampleStartedAt=fe},2e3);return()=>{window.clearInterval(he)}},[]),u.useEffect(()=>{const he=_?_.split(",").filter(Boolean):[],fe=new Set(he),me=performance.now();for(const[Se,Be]of j.current.entries())fe.has(Se)||(G(Be,"livedesk-device-unsubscribed"),j.current.delete(Se),k.current.delete(Se),b.current.delete(Se));if(he.length===0){for(const Se of j.current.values())G(Se,"livedesk-no-devices");j.current.clear(),k.current.clear(),b.current=new Map,d(new Map),g(""),V.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},x(Yc),q();return}V.current.sampleStartedAt<=0&&(V.current.sampleStartedAt=me,x({...Yc,lastUpdatedAt:Date.now()}));for(const Se of he){const Be=l.monitorSelections?.[Se],Oe=Number.isFinite(Number(Be))?{[Se]:Number(Be)}:{},ge={type:"subscribe",deviceIds:[Se],autoStartLive:a,fps:L,maxWidth:ne,maxHeight:W,quality:J,mode:O,frameMode:O,streamPurpose:be,monitorSelections:Oe},Ze=JSON.stringify(ge),Ke=j.current.get(Se);if(Ke){const Ne=Ke.socket.readyState===WebSocket.CONNECTING||Ke.socket.readyState===WebSocket.OPEN;if(Ke.payloadKey===Ze&&Ne&&!Ke.disposed)continue}const ce=Ke&&(Ke.socket.readyState===WebSocket.CONNECTING||Ke.socket.readyState===WebSocket.OPEN)&&!Ke.disposed?Ke.handoffFrom&&!Ke.handoffCompleted?Ke.handoffFrom:Ke:void 0;Ke&&Ke!==ce&&G(Ke,"livedesk-subscription-superseded");const ve=new WebSocket(lf(`/api/remote/frames/ws?devices=${encodeURIComponent(Se)}`,r));ve.binaryType="arraybuffer";const ke={socket:ve,payload:ge,payloadKey:Ze,generation:C.current+1,disposed:!1,handoffFrom:ce,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1};C.current=ke.generation,j.current.set(Se,ke),ve.addEventListener("open",()=>{if(ke.disposed||j.current.get(Se)!==ke){G(ke,"livedesk-stale-frame-socket");return}g("");const Ne=M.current,He=Ne.enabled&&(!Ne.token||k.current.get(Se)!==Ne.token);ve.send(JSON.stringify({...ke.payload,forceRestart:He,restartReason:He?Ne.reason:"",restartToken:He?Ne.token:""})),He&&Ne.token&&k.current.set(Se,Ne.token);const $e=ke.handoffFrom;ke.handoffFrom=void 0,ke.handoffCompleted=!0,$e&&!$e.disposed&&G($e,"livedesk-subscription-replaced"),q()}),ve.addEventListener("message",Ne=>{if(ke.disposed||j.current.get(Se)!==ke)return;if(typeof Ne.data=="string"){try{const $e=JSON.parse(Ne.data);if($e?.type==="RemoteFrameSubscriptionError")g(String($e.error||"control-stream-start-failed"));else if($e?.type==="RemoteFrameLiveAutoStart"){const ye=(Array.isArray($e.skipped)?$e.skipped:[]).find(ae=>ae?.deviceId===Se);if(ye)g(String(ye.reason||"control-stream-start-failed"));else if(Array.isArray($e.started)){const ae=$e.started.find(Te=>Te?.deviceId===Se);ae&&(g(""),ae.ready===!0&&ae.streamPurpose==="control"&&ae.sessionId&&ae.commandId&&Number(ae.captureGeneration||0)>0&&F.current?.({deviceId:Se,sessionId:String(ae.sessionId),streamId:String(ae.streamId||""),streamPurpose:"control",commandId:String(ae.commandId),captureGeneration:Number(ae.captureGeneration),monitorIndex:Number(ae.monitorIndex||0)}))}}else $e?.type==="RemoteFrameStreamReady"&&$e.deviceId===Se&&$e.streamPurpose==="control"&&$e.sessionId&&$e.commandId&&Number($e.captureGeneration||0)>0&&(g(""),F.current?.({deviceId:Se,sessionId:String($e.sessionId),streamId:String($e.streamId||""),streamPurpose:"control",commandId:String($e.commandId),captureGeneration:Number($e.captureGeneration),monitorIndex:Number($e.monitorIndex||0)}))}catch{}return}const He=Ne.data instanceof ArrayBuffer?Ne.data:null;He&&(g(""),we(He,ke))}),ve.addEventListener("error",()=>{ke.disposed||j.current.get(Se)!==ke||p("connecting")}),ve.addEventListener("close",()=>{const Ne=!ke.disposed;ke.disposed=!0;const He=j.current.get(Se);let $e=!1;if(He===ke){const Xe=ke.handoffFrom;ke.handoffFrom=void 0,Xe&&!Xe.disposed&&(Xe.socket.readyState===WebSocket.CONNECTING||Xe.socket.readyState===WebSocket.OPEN)?(j.current.set(Se,Xe),$e=!0):j.current.delete(Se)}if(q(),Ne&&He===ke&&!$e){const Xe=window.setTimeout(()=>{A.current.delete(Xe),R(ye=>ye+1)},750);A.current.add(Xe)}})}q()},[a,G,_,L,O,we,r,W,ne,ee,l.monitorSelections,J,T,be,q]),u.useEffect(()=>{if(!re||!K)return;const he=_?_.split(",").filter(Boolean):[];for(const fe of he){if(k.current.get(fe)===K)continue;const me=j.current.get(fe);!me||!oe(fe,me,I,K)||k.current.set(fe,K)}},[_,re,K,I,oe]),u.useEffect(()=>()=>{for(const he of j.current.values())G(he,"livedesk-hook-unmount");j.current.clear();for(const he of A.current)window.clearTimeout(he);A.current.clear()},[G]);const Q=u.useCallback((he,fe="browser-stale")=>{const me=Array.isArray(he)&&he.length>0?he:_.split(",").filter(Boolean);if(me.length===0)return!1;let Se=!1;for(const Be of me){const Oe=j.current.get(Be);!Oe||Oe.socket.readyState!==WebSocket.OPEN||(Se=oe(Be,Oe,fe,`${Date.now()}-${Math.random().toString(36).slice(2)}`)||Se)}return Se},[_,oe]),$=u.useCallback((he,fe="browser-reconnect")=>{const me=Array.isArray(he)&&he.length>0?he:_.split(",").filter(Boolean);if(me.length===0)return!1;let Se=!1;for(const Be of me){const Oe=j.current.get(Be);Oe&&(G(Oe,`livedesk-${fe}`),j.current.delete(Be),k.current.delete(Be),b.current.delete(Be),Se=!0)}return Se&&d(new Map(b.current)),R(Be=>Be+1),q(),!0},[G,_,q]);return{frames:c,state:m,error:v,stats:w,restartLive:Q,reconnectLive:$}}function yj(n,a,r=kn,l={}){const[c,d]=u.useState(null),[m,p]=u.useState(null),[v,g]=u.useState("idle"),[w,x]=u.useState(Yc),b=u.useRef(null),j=u.useRef(l.onFrame),C=u.useRef(null),k=u.useRef(0),M=u.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),A=u.useMemo(()=>[...new Set(n.filter(Boolean))].join(","),[n]),T=u.useMemo(()=>[...new Set((l.captureDeviceIds||n).filter(Boolean))].join(","),[n,l.captureDeviceIds]),R=u.useMemo(()=>JSON.stringify(l.monitorSelections||{}),[l.monitorSelections]),P=u.useMemo(()=>({deviceIds:A.split(",").filter(Boolean),captureDeviceIds:T.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||{}}),[T,A,R,l.fps,l.height,l.monitorSelections,l.tileHeight,l.tileWidth,l.width]),F=u.useMemo(()=>JSON.stringify(P),[P]),V=u.useRef(P);V.current=P;const _=a&&P.deviceIds.length>0,L=u.useCallback(W=>W.readyState!==WebSocket.OPEN?!1:(W.send(JSON.stringify({type:"configure",...V.current})),!0),[]);u.useEffect(()=>{j.current=l.onFrame},[l.onFrame]),u.useEffect(()=>{const W=window.setInterval(()=>{const J=M.current,O=performance.now(),be=Math.max(1,O-J.sampleStartedAt);x({totalFrames:J.totalFrames,totalBytes:J.totalBytes,framesPerSecond:J.sampleFrames*1e3/be,bytesPerSecond:J.sampleBytes*1e3/be,sampleMs:be,lastUpdatedAt:Date.now()});const re=C.current;re&&re.frameSeq!==k.current&&(k.current=re.frameSeq,d(re)),J.sampleFrames=0,J.sampleBytes=0,J.sampleStartedAt=O},1e3);return()=>window.clearInterval(W)},[]),u.useEffect(()=>{if(!_){b.current?.close(),b.current=null,d(null),C.current=null,k.current=0,p(null),g("idle"),x(Yc);return}let W=!1,J=0;const O=()=>{if(W)return;const be=new WebSocket(lf("/api/remote/atlas/ws",r));be.binaryType="arraybuffer",b.current=be,g("connecting"),be.addEventListener("open",()=>{M.current.sampleStartedAt=performance.now(),g("open"),L(be)}),be.addEventListener("message",re=>{if(typeof re.data=="string"){try{const I=JSON.parse(re.data);I?.type==="Mode4AtlasLayout"&&p({layoutVersion:Number(I.layoutVersion||0),width:Number(I.width||1920),height:Number(I.height||1080),columns:Number(I.columns||1),rows:Number(I.rows||1),tiles:Array.isArray(I.tiles)?I.tiles:[]})}catch{}return}const K=re.data instanceof ArrayBuffer?re.data:null;if(!(!K||K.byteLength<5))try{const I=Date.now(),G=new DataView(K).getUint32(0,!1);if(G<=0||G+4>K.byteLength)return;const q=JSON.parse(lp.decode(new Uint8Array(K,4,G))),oe=new Uint8Array(K,4+G),we={deviceId:String(q.deviceId||"__livedesk_mode4_atlas__"),kind:"live",frameSeq:Number(q.frameSeq||0),streamFrameSeq:Number(q.streamFrameSeq||0)||void 0,streamId:String(q.streamId||"mode4-atlas"),commandId:q.commandId?String(q.commandId):void 0,width:Number(q.width||1920),height:Number(q.height||1080),sourceWidth:Number(q.sourceWidth||q.width||1920),sourceHeight:Number(q.sourceHeight||q.height||1080),mimeType:String(q.mimeType||"video/h264"),mode:String(q.mode||"mode4-h264-atlas"),frameMode:String(q.frameMode||"mode4-h264-atlas"),frameProfile:String(q.frameProfile||"mode4-h264-atlas-v1"),encoding:String(q.encoding||"video-atlas"),codec:String(q.codec||"h264"),compression:String(q.compression||"video/h264"),h264Format:String(q.h264Format||"annexb"),isKeyFrame:q.isKeyFrame===!0,chunkType:String(q.chunkType||""),timestampUs:Number(q.timestampUs||0),durationUs:Number(q.durationUs||0),hardwareEncoder:q.hardwareEncoder?String(q.hardwareEncoder):void 0,platformProfile:q.platformProfile?String(q.platformProfile):void 0,capturedAt:String(q.capturedAt||""),receivedAt:String(q.receivedAt||""),hubPacketAt:q.hubPacketAt?String(q.hubPacketAt):void 0,hubPacketEpochMs:Number(q.hubPacketEpochMs||0)||void 0,browserReceivedEpochMs:I,byteLength:oe.byteLength,layoutVersion:Number(q.layoutVersion||0),atlasComposeMs:Number(q.atlasComposeMs||0),atlasPoolStarved:Number(q.atlasPoolStarved||0),atlasReadyTiles:Number(q.atlasReadyTiles||0),atlasTileCount:Number(q.atlasTileCount||0),atlasInputRevision:Number(q.atlasInputRevision||0),atlasSourceNewestAtEpochMs:Number(q.atlasSourceNewestAtEpochMs||0),atlasSourceOldestAtEpochMs:Number(q.atlasSourceOldestAtEpochMs||0),atlasSourceMaxAgeMs:Number(q.atlasSourceMaxAgeMs||0),payload:oe},Q=M.current;Q.totalFrames+=1,Q.totalBytes+=oe.byteLength,Q.sampleFrames+=1,Q.sampleBytes+=oe.byteLength,C.current=we,k.current===0&&(k.current=we.frameSeq,d(we)),j.current?.(we)}catch{}}),be.addEventListener("error",()=>g("error")),be.addEventListener("close",()=>{b.current===be&&(b.current=null),!W&&(g("closed"),J=window.setTimeout(O,1200))})};return O(),()=>{W=!0,window.clearTimeout(J),b.current?.close(),b.current=null}},[_,r,L]),u.useEffect(()=>{if(!_)return;const W=b.current;W&&L(W)},[F,_,L]);const ne=u.useCallback(()=>{const W=b.current;return W?L(W):!1},[L]);return{frame:c,layout:m,state:v,stats:w,refreshInputs:ne}}function xj(n,a=kn){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,x]=u.useState(Dy),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(""),x(Dy);return}let C=!1,k=0;const M=()=>{if(C)return;const A=new WebSocket(lf("/api/remote/input/ws",a));r.current=A,b.current.sampleStartedAt=performance.now(),p("connecting"),g(""),A.addEventListener("open",()=>{C||r.current!==A||(g(""),p("open"))}),A.addEventListener("message",T=>{if(!(C||r.current!==A||typeof T.data!="string"))try{const R=JSON.parse(T.data);if(R?.type==="RemoteInputError"){g(String(R.error||R.result?.error||"Remote input failed.")),p("error");return}if(R?.type!=="RemoteInputApplied")return;const P=Number(R.inputSeq||0),F=d.current.get(P);F!==void 0&&(b.current.lastRoundTripMs=Math.max(0,performance.now()-F),d.current.delete(P)),b.current.lastInputSeq=P,b.current.lastAgentApplyMs=Math.max(0,Number(R.agentApplyMs||0))}catch{}}),A.addEventListener("close",()=>{C||r.current!==A||(r.current=null,p("closed"),k=window.setTimeout(M,1200))}),A.addEventListener("error",()=>{!C&&r.current===A&&p("error")})};return M(),()=>{C=!0,window.clearTimeout(k);const A=r.current;r.current=null,A?.close(),d.current.clear()}},[n,a]),u.useEffect(()=>{if(!n)return;const C=window.setInterval(()=>{const k=performance.now(),M=b.current,A=Math.max(1,k-M.sampleStartedAt);x({totalSent:M.totalSent,totalDropped:M.totalDropped,sentPerSecond:M.sampleSent*1e3/A,droppedPerSecond:M.sampleDropped*1e3/A,bufferedAmount:r.current?.bufferedAmount||0,lastInputType:M.lastInputType,lastInputSeq:M.lastInputSeq,lastRoundTripMs:M.lastRoundTripMs,lastAgentApplyMs:M.lastAgentApplyMs,lastUpdatedAt:Date.now()}),M.sampleSent=0,M.sampleDropped=0,M.sampleStartedAt=k},1e3);return()=>window.clearInterval(C)},[n]);const j=u.useCallback((C,k)=>{const M=r.current;if(!M||M.readyState!==WebSocket.OPEN||!C)return!1;const A=String(k.type||"").toLowerCase(),T=A==="pointermove",P=T||A==="wheel",F=b.current;if(T&&M.bufferedAmount>mj)return F.totalDropped+=1,F.sampleDropped+=1,F.lastInputType="pointermove-drop",!1;const V=l.current+1;l.current=V;const _=Date.now(),L=!P||V-c.current>=pj;for(L&&(d.current.set(V,performance.now()),P&&(c.current=V)),T||xb.set(C,{inputSeq:V,inputType:A||"input",sentAt:performance.now()});d.current.size>256;){const ne=d.current.keys().next().value;if(ne===void 0)break;d.current.delete(ne)}return M.send(JSON.stringify({type:"input",requestId:P?"":crypto.randomUUID(),fireAndForget:P,deviceId:C,input:{...k,inputSeq:V,requestAck:L,issuedAtEpochMs:_,issuedAt:new Date(_).toISOString()}})),F.totalSent+=1,F.sampleSent+=1,F.lastInputType=A||"input",!0},[]);return{state:m,sendInput:j,stats:w,error:v}}function bj(n){const a=String(n||"").toLowerCase();return a.includes("audio/pcm")||a.includes("audio/l16")||a.includes("f32le")||a.includes("s16le")}const xd={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},wj=.08,Sj=.25,Cj=.02,_y=300,jj=4,bd=1500,ah=5e3,kj=2e3,Aj=1e4,wd=[0,1e3,3e3];function zy(n){const a=Date.parse(String(n||""));return Number.isFinite(a)?Math.max(0,Date.now()-a):0}function Nj(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),x=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 M=(C*l+b)*p;j[C]=m?Math.max(-1,Math.min(1,x.getInt16(M,!0)/32768)):Math.max(-1,Math.min(1,x.getFloat32(M,!0)))}}return w}function Mj(n,a,r=kn){const l=u.useRef(null),c=u.useRef(0),[d,m]=u.useState("idle"),[p,v]=u.useState(null),[g,w]=u.useState(xd),[x,b]=u.useState("");return u.useEffect(()=>{if(!a||!n){m("idle"),v(null),w(xd),b("");return}m("connecting"),v(null),w(xd),b("");const j=window.AudioContext||window.webkitAudioContext;if(!j){m("unsupported"),w(xd),b("Audio playback is not supported in this browser.");return}const C=new j;l.current=C,c.current=C.currentTime;const k=new WebSocket(lf("/api/remote/audio/ws?devices="+encodeURIComponent(n),r));k.binaryType="arraybuffer";const M=new Set,A={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 T=!1,R=0,P=!1,F=0,V=0;const _=(I=!0)=>{for(const ee of M)try{ee.stop()}catch{}M.clear(),I&&(c.current=C.currentTime+wj)},L=()=>{A.audioContextState=String(C.state),!T&&(A.audioContextState==="suspended"||A.audioContextState==="interrupted"?m("suspended"):A.audioContextState==="closed"&&(m("error"),b("The browser audio context is closed. Toggle Remote Audio off and on to recover.")))},ne=async()=>{if(T||String(C.state)==="closed")return!1;try{if(String(C.state)!=="running"&&await C.resume(),A.audioContextState=String(C.state),!T&&!P&&A.audioContextState==="running"){const I=A.lastAcceptedAt>0&&performance.now()-A.lastAcceptedAt<=bd,ee=A.lastCaptureStatusAt>0&&performance.now()-A.lastCaptureStatusAt<=ah&&A.captureAlive&&A.helperAlive;m(I?"playing":ee?"silent":"open")}return A.audioContextState==="running"}catch(I){return T||(m("suspended"),b(I instanceof Error?"Audio playback is suspended: "+I.message:"Audio playback is suspended.")),!1}},W=async()=>{if(T||P||k.readyState!==WebSocket.OPEN)return;if(F>=wd.length){m("error"),b("Remote audio stopped sending frames. Toggle Audio off and on to retry.");return}const I=F;F+=1,P=!0,A.stalledCount+=1,A.automaticRestarts+=1,m("reconnecting");try{const ee=await We("/api/remote/devices/"+encodeURIComponent(n)+"/audio/stop",{method:"POST",body:JSON.stringify({})},r);if(ee.ok===!1)throw new Error(ee.error||"Remote audio stop failed.");if(T)return;const G=await We("/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(G.ok===!1)throw new Error(G.error||"Remote audio start failed.");const q=performance.now();R=q,A.lastPacketAt=q,A.lastAcceptedAt=0,A.lastCaptureStatusAt=0,A.lastPcmAtEpochMs=0,A.captureAlive=!1,A.helperAlive=!1,A.silentForMs=0,V=q+(wd[I+1]??3e3),b(""),T||m("open")}catch(ee){T||(V=performance.now()+(wd[I+1]??3e3),m("error"),b(ee instanceof Error?"Remote audio restart failed: "+ee.message:"Remote audio restart failed."))}finally{P=!1}},J=()=>{A.drops+=1},O=window.setInterval(()=>{if(T)return;const I=performance.now(),ee=A.lastPacketAt>0?Math.max(0,I-A.lastPacketAt):R>0?Math.max(0,I-R):0,G=A.lastAcceptedAt>0?Math.max(0,I-A.lastAcceptedAt):0,q=A.lastCaptureStatusAt>0?Math.max(0,I-A.lastCaptureStatusAt):0,oe=k.readyState===WebSocket.OPEN,we=A.lastCaptureStatusAt>0,Q=we&&q<=ah,$=we&&(!A.captureAlive||!A.helperAlive)&&q>kj,he=we&&q>ah,fe=!we&&R>0&&I-R>Aj,me=R>0&&(A.lastAcceptedAt<=0?I-R>bd:G>bd);oe&&R>0&&($||he||fe)?F>=wd.length&&!P?(m("error"),b("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!P&&I>=V?W():P||m("stalled"):oe&&me&&!P&&A.audioContextState!=="suspended"&&A.audioContextState!=="interrupted"&&m(Q?"silent":"open"),w({queuedMs:Math.max(0,(c.current-C.currentTime)*1e3),browserAgeMs:A.browserAgeMs,captureAgeMs:A.captureAgeMs,captureStatusAgeMs:q,silentForMs:A.silentForMs,captureAlive:A.captureAlive,helperAlive:A.helperAlive,captureRestartCount:A.captureRestartCount,localProcessingAgeMs:A.localProcessingAgeMs,lastPacketAgeMs:ee,lastAcceptedAgeMs:G,framesReceived:A.framesReceived,drops:A.drops,resyncs:A.resyncs,pendingDecodes:A.pendingDecodes,lastFrameSeq:A.lastFrameSeq,audioContextState:A.audioContextState,stalledCount:A.stalledCount,automaticRestarts:A.automaticRestarts,lastUpdatedAt:Date.now()})},250),be=()=>{L(),(String(C.state)==="suspended"||String(C.state)==="interrupted")&&ne()},re=()=>{document.visibilityState==="visible"&&ne()},K=()=>{ne()};return C.addEventListener("statechange",be),document.addEventListener("visibilitychange",re),window.addEventListener("pageshow",K),window.addEventListener("pointerdown",K),window.addEventListener("keydown",K),m("connecting"),b(""),L(),k.addEventListener("open",()=>{T||(R=performance.now(),A.lastPacketAt=R,A.lastAcceptedAt=0,A.lastCaptureStatusAt=0,A.lastPcmAtEpochMs=0,A.captureAlive=!1,A.helperAlive=!1,A.silentForMs=0,m("open"),k.send(JSON.stringify({type:"subscribe",deviceIds:[n]})),ne())}),k.addEventListener("message",I=>{if(typeof I.data=="string")return;const ee=I.data instanceof ArrayBuffer?I.data:null;if(!ee||ee.byteLength<5)return;const G=performance.now();A.lastPacketAt=G,(async()=>{try{const oe=new DataView(ee).getUint32(0,!1);if(oe<=0||oe+4>ee.byteLength){J();return}const we=new Uint8Array(ee,4,oe),Q=JSON.parse(lp.decode(we)),$=ee.slice(4+oe),he=String(Q.frameKind||Q.kind||"").toLowerCase();if(Q.type==="remote.audio.status"||he==="audio-status"){if(A.lastCaptureStatusAt=G,A.captureAlive=Q.captureAlive===!0,A.helperAlive=Q.helperAlive===!0,A.captureRestartCount=Math.max(0,Number(Q.restartCount||0)||0),A.lastPcmAtEpochMs=Math.max(0,Number(Q.lastPcmAtEpochMs||0)||0),A.silentForMs=Math.max(0,Number(Q.silentForMs||0)||0),A.captureAgeMs=A.lastPcmAtEpochMs>0?Math.max(0,Date.now()-A.lastPcmAtEpochMs):A.silentForMs,A.captureAlive&&A.helperAlive){if(F=0,V=0,!P){b("");const me=String(C.state)==="running",Se=A.lastAcceptedAt>0&&performance.now()-A.lastAcceptedAt<=bd;m(me?Se?"playing":"silent":"suspended")}}else P||m("stalled");return}const fe={deviceId:String(Q.deviceId||""),frameSeq:Number(Q.frameSeq||0),streamId:String(Q.streamId||""),mimeType:String(Q.mimeType||"audio/webm;codecs=opus"),sampleRate:Number(Q.sampleRate||48e3),channels:Number(Q.channels||2),capturedAt:String(Q.capturedAt||""),receivedAt:String(Q.receivedAt||""),byteLength:Number(Q.byteLength||$.byteLength),payload:$};if(!fe.deviceId||T)return;if(performance.now()-G>_y){J();return}if(A.pendingDecodes>=jj){J();return}A.pendingDecodes+=1;try{const me=bj(fe.mimeType)?Nj(C,fe,$):await C.decodeAudioData($.slice(0));if(A.localProcessingAgeMs=Math.max(0,performance.now()-G),T)return;if(A.localProcessingAgeMs>_y){J();return}if(fe.frameSeq>0&&fe.frameSeq<=A.lastFrameSeq){J();return}if(A.activeStreamId&&fe.streamId!==A.activeStreamId&&fe.frameSeq<=A.lastFrameSeq){J();return}fe.streamId&&fe.streamId!==A.activeStreamId&&(A.activeStreamId=fe.streamId,A.lastFrameSeq=0,_());const Se=C.currentTime;Math.max(0,c.current-Se)>Sj&&(_(),A.resyncs+=1);const Oe=C.createBufferSource();Oe.buffer=me,Oe.connect(C.destination),M.add(Oe),Oe.onended=()=>{M.delete(Oe),Oe.onended=null};const ge=Math.max(C.currentTime+Cj,c.current);Oe.start(ge),c.current=ge+me.duration,A.browserAgeMs=zy(fe.receivedAt),A.captureAgeMs=zy(fe.capturedAt),A.lastAcceptedAt=performance.now(),A.framesReceived+=1,A.lastFrameSeq=fe.frameSeq,F=0,V=0,v(fe),ne();const Ze=String(C.state)==="running";Ze&&b(""),m(Ze?"playing":"suspended")}finally{A.pendingDecodes=Math.max(0,A.pendingDecodes-1)}}catch(q){T||(m("error"),b(q instanceof Error?q.message:String(q)))}})()}),k.addEventListener("error",()=>{T||(m("error"),b("Remote audio WebSocket error."))}),k.addEventListener("close",()=>{T||m("closed")}),()=>{T=!0,window.clearInterval(O),C.removeEventListener("statechange",be),document.removeEventListener("visibilitychange",re),window.removeEventListener("pageshow",K),window.removeEventListener("pointerdown",K),window.removeEventListener("keydown",K),_(!1),k.close(),C.close().catch(()=>{}),l.current===C&&(l.current=null)}},[n,a,r]),{state:d,lastFrame:p,stats:g,error:x}}const Tj=3;function Iy(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,Tj);return c<=d?0:c>=l-d?1:c/l}function Ej(n,a,r){return{normalizedX:Iy(n,r.left,r.width),normalizedY:Iy(a,r.top,r.height)}}const di=Object.freeze({smallDirectDeviceLimit:4,interactiveDirectFps:30,controlWallReuseMaxFps:30,scalableAtlasInputFps:8,atlasOutputFps:20,maxDirectFramesPerSecond:96,directDecodeAcceleration:"prefer-software",directLatencyMode:"interactive",configuredLatencyMode:"smooth"});function Rj(n,a){const r=Math.max(0,Math.floor(Number(a)||0));return n===!0&&r>0&&r<=di.smallDirectDeviceLimit}function Hc({mode4Enabled:n,directMode4WallEnabled:a,isMac:r}){return!n||a||r?"direct":"atlas"}function Dj({mode4Enabled:n,directMode4WallEnabled:a,adaptiveFps:r,directDeviceCount:l}){const c=Math.max(1,Math.floor(Number(r)||1));if(!n)return c;if(a)return Math.max(di.interactiveDirectFps,c);const d=Math.max(1,Math.floor(Number(l)||1));return Math.max(1,Math.min(c,Math.floor(di.maxDirectFramesPerSecond/d)))}function Lj(n,a){return n?{acceleration:di.directDecodeAcceleration,latencyMode:di.directLatencyMode}:{acceleration:a,latencyMode:di.configuredLatencyMode}}const Oh={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}}},_j=[{id:"connection",label:"Connection",icon:El},{id:"security",label:"Security",icon:Ht},{id:"control",label:"Control",icon:Zt},{id:"wall",label:"Wall",icon:Zc},{id:"files-audio",label:"Files & Audio",icon:Co},{id:"agent",label:"Agent",icon:Ds},{id:"advanced",label:"Advanced",icon:Vd}];function bl(n,a){return n?.settings?.[a]||Oh.settings[a]}function dt({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 Nt({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 Zi({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 zj({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[x,b]=u.useState(c),[j,C]=u.useState(null),[k,M]=u.useState("loading"),[A,T]=u.useState(""),[R,P]=u.useState("idle"),[F,V]=u.useState("");u.useEffect(()=>{let me=!0;return M("loading"),We("/api/settings",void 0,n).then(Se=>{me&&(C({revision:Number(Se.revision||0),updatedAt:Se.updatedAt,settings:Se.settings}),M("saved"))}).catch(Se=>{me&&(T(Se instanceof Error?Se.message:String(Se)),C(Oh),M("failed"))}),()=>{me=!1}},[n]);const _=async(me,Se,Be)=>{const Oe=j||Oh,ge=Oe,Ze={...Oe,settings:{...Oe.settings,[me]:{...bl(Oe,me),[Se]:Be}}};C(Ze),M("saving"),T("");try{const Ke=await We("/api/settings",{method:"PATCH",body:JSON.stringify({revision:Oe.revision,[me]:{[Se]:Be}})},n);C({revision:Ke.revision,updatedAt:Ke.updatedAt,settings:Ke.settings}),M("saved")}catch(Ke){C(ge),M("failed"),T(Ke instanceof Error?Ke.message:String(Ke))}},L=(me,Se)=>Be=>{_(me,Se,Be)},ne=async()=>{if(a!=="hub"||!r||!l){P("failed"),V("Sign in to this Hub before changing its runtime role.");return}P("changing"),V("");try{const me=await We("/api/runtime/status",void 0,n);await We("/api/runtime/role",{method:"POST",headers:{Authorization:`Bearer ${l}`},body:JSON.stringify({role:"client"})},n),P("accepted"),await nb({baseUrl:n,targetRole:"client",previousRuntimePid:Number(me.runtimePid||0),allowedStates:["running","waiting-auth"]}),cC(5179)}catch(me){P("failed"),V(me instanceof Error?me.message:String(me))}},W=bl(j,"security"),J=bl(j,"connection"),O=bl(j,"control"),be=bl(j,"wall"),re=bl(j,"filesAudio"),K=bl(j,"agent"),I=u.useMemo(()=>W.allowInternetConnections===!1?{label:"Local only",tone:"local",detail:"Internet connections are disabled."}:W.requireEncryptedConnections&&W.requireNewDeviceApproval&&W.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."},[W]),ee=`settings-panel-${x}`,G=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(El,{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(Yx,{size:14})," ",k==="saving"?"Saving":k==="failed"?"Failed":k==="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(Ao,{size:20})]}),s.jsx(dt,{icon:Ao,title:"Use PIN to add new devices",description:"Allow temporary PIN pairing from the client.",recommended:!0,children:s.jsx(Nt,{checked:!!J.usePinToAddDevices,onChange:L("connection","usePinToAddDevices"),label:"Use PIN to add new devices"})}),s.jsx(dt,{icon:Ht,title:"Approve new devices on this Hub",description:"Ask for approval before an unfamiliar computer becomes trusted.",children:s.jsx(Nt,{checked:!!J.approveNewDevices,onChange:L("connection","approveNewDevices"),label:"Approve new devices"})}),s.jsx(dt,{icon:bn,title:"Show connection notifications",description:"Show a short notice when a computer connects or leaves.",children:s.jsx(Nt,{checked:!!J.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(Vd,{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:()=>{ne()},disabled:R==="changing"||a!=="hub",type:"button",children:R==="changing"?"Switching role…":"Switch this computer to Client"})]})]}),q=s.jsxs("div",{className:"settings-tab-content product-settings-content",children:[s.jsxs("section",{className:`security-status-card ${I.tone}`,children:[s.jsxs("div",{children:[s.jsx("span",{children:"Security status"}),s.jsx("strong",{children:I.label}),s.jsx("small",{children:I.detail})]}),s.jsx(Ht,{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(dt,{icon:Ht,title:"Access mode",description:"Choose the default boundary for remote sessions.",recommended:!0,children:s.jsx(Zi,{value:String(W.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(dt,{icon:El,title:"Require encrypted connections",description:"External connections cannot disable this protection.",recommended:!0,children:s.jsx(Nt,{checked:!!W.requireEncryptedConnections,onChange:L("security","requireEncryptedConnections"),label:"Require encrypted connections"})}),s.jsx(dt,{icon:El,title:"Allow internet connections",description:"Keep off unless you intentionally expose this Hub beyond the LAN.",children:s.jsx(Nt,{checked:!!W.allowInternetConnections,onChange:L("security","allowInternetConnections"),label:"Allow internet connections"})}),s.jsx(dt,{icon:Zt,title:"Allow LAN connections",description:"Permit connections from the local network.",children:s.jsx(Nt,{checked:!!W.allowLanConnections,onChange:L("security","allowLanConnections"),label:"Allow LAN connections"})}),s.jsx(dt,{icon:Ht,title:"Require approval for new devices",description:"New computers must be approved before remote access is granted.",children:s.jsx(Nt,{checked:!!W.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(bn,{size:20})]}),s.jsx(dt,{icon:Zt,title:"Show an indicator while Control is active",description:"Make active remote control visible on the local computer.",children:s.jsx(Nt,{checked:!!W.visibleControlIndicator,onChange:L("security","visibleControlIndicator"),label:"Show Control indicator"})}),s.jsx(dt,{icon:Rs,title:"Lock the remote computer when Control ends",description:"Protect the local screen after a Control session.",children:s.jsx(Nt,{checked:!!W.lockOnControlEnd,onChange:L("security","lockOnControlEnd"),label:"Lock after Control ends"})}),s.jsx(dt,{icon:bn,title:"Disconnect idle Control sessions",description:"Automatically close inactive Control sessions.",children:s.jsx(Nt,{checked:!!W.disconnectIdleControlSessions,onChange:L("security","disconnectIdleControlSessions"),label:"Disconnect idle sessions"})}),s.jsx(dt,{icon:bn,title:"Idle timeout",description:"Time before an inactive Control session closes.",disabled:!W.disconnectIdleControlSessions,children:s.jsx(Zi,{value:Number(W.idleControlMinutes),onChange:me=>L("security","idleControlMinutes")(Number(me)),disabled:!W.disconnectIdleControlSessions,label:"Idle timeout",options:[["5","5 minutes"],["15","15 minutes"],["30","30 minutes"],["60","1 hour"],["1440","Never"]]})})]})]}),oe=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(dt,{icon:Zt,title:"Keyboard and mouse control",description:"Allow the Hub to send keyboard and pointer input.",recommended:!0,children:s.jsx(Nt,{checked:!!O.allowKeyboardMouse,onChange:L("control","allowKeyboardMouse"),label:"Keyboard and mouse control"})}),s.jsx(dt,{icon:WS,title:"System shortcuts",description:"Allow shortcut keys such as Alt-Tab and the system key.",children:s.jsx(Nt,{checked:!!O.allowSystemShortcuts,onChange:L("control","allowSystemShortcuts"),label:"System shortcuts"})}),s.jsx(dt,{icon:Ao,title:"Clipboard text sharing",description:"Share plain text through the remote session.",children:s.jsx(Nt,{checked:!!O.allowClipboardText,onChange:L("control","allowClipboardText"),label:"Clipboard text sharing"})}),s.jsx(dt,{icon:bn,title:"Remote restart",description:"Allow restart requests from Control.",disabled:!O.allowKeyboardMouse,children:s.jsx(Nt,{checked:!!O.allowRemoteRestart,onChange:L("control","allowRemoteRestart"),disabled:!O.allowKeyboardMouse,label:"Remote restart"})}),s.jsx(dt,{icon:Zt,title:"Switching monitors",description:"Allow the viewer to select another connected display.",children:s.jsx(Nt,{checked:!!O.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(_n,{size:20})]}),s.jsx(dt,{icon:Zt,title:"Open Control on double-click",description:"Double-clicking a Wall tile opens its Control view.",children:s.jsx(Nt,{checked:!!O.openControlOnDoubleClick,onChange:L("control","openControlOnDoubleClick"),label:"Open Control on double-click"})}),s.jsx(dt,{icon:bn,title:"Start audio with Control",description:"Keep audio muted by default for new sessions.",children:s.jsx(Nt,{checked:!!O.startRemoteAudioWithControl,onChange:L("control","startRemoteAudioWithControl"),label:"Start audio with Control"})}),s.jsx(dt,{icon:Zt,title:"Fit remote screen to window",description:"Scale the remote display to the available Control area.",children:s.jsx(Nt,{checked:!!O.fitRemoteScreen,onChange:L("control","fitRemoteScreen"),label:"Fit remote screen"})}),s.jsx(dt,{icon:bn,title:"Keep Control ready between pages",description:"Faster reconnection for 1 minute.",recommended:!0,children:s.jsx(Nt,{checked:!!O.keepControlReadyBetweenPages,onChange:L("control","keepControlReadyBetweenPages"),label:"Keep Control ready between pages"})})]})]}),we=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(Zc,{size:20})]}),s.jsx(dt,{icon:Ds,title:"Performance mode",description:"Automatic mode balances responsiveness and image quality.",recommended:!0,children:s.jsx(Zi,{value:String(be.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(bn,{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(([me,Se,Be])=>s.jsx(dt,{icon:Zt,title:Se,description:Be,children:s.jsx(Nt,{checked:!!be[me],onChange:L("wall",me),label:Se})},me))]})]}),Q=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(Co,{size:20})]}),s.jsx(dt,{icon:Co,title:"Allow file transfer",description:"Permit Hub-to-device file delivery.",recommended:!0,children:s.jsx(Nt,{checked:!!re.allowFileTransfer,onChange:L("filesAudio","allowFileTransfer"),label:"Allow file transfer"})}),s.jsx(dt,{icon:Zc,title:"Allow folder sync",description:"Enable recurring folder synchronization.",disabled:!re.allowFileTransfer,children:s.jsx(Nt,{checked:!!re.allowFolderSync,onChange:L("filesAudio","allowFolderSync"),disabled:!re.allowFileTransfer,label:"Allow folder sync"})}),s.jsx(dt,{icon:Ht,title:"Ask before receiving files",description:"Require local confirmation before a transfer is written.",children:s.jsx(Nt,{checked:!!re.askBeforeReceivingFiles,onChange:L("filesAudio","askBeforeReceivingFiles"),label:"Ask before receiving files"})}),s.jsx(dt,{icon:Co,title:"Allow overwrite",description:"Permit replacing an existing destination file.",children:s.jsx(Nt,{checked:!!re.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(bn,{size:20})]}),s.jsx(dt,{icon:bn,title:"Allow remote audio",description:"Permit audio capture from connected computers.",recommended:!0,children:s.jsx(Nt,{checked:!!re.allowRemoteAudio,onChange:L("filesAudio","allowRemoteAudio"),label:"Allow remote audio"})}),s.jsx(dt,{icon:bn,title:"Start audio muted",description:"New audio sessions begin silent.",children:s.jsx(Nt,{checked:!!re.startAudioMuted,onChange:L("filesAudio","startAudioMuted"),label:"Start audio muted"})}),s.jsx(dt,{icon:bn,title:"Automatically recover audio",description:"Recover from temporary capture or transport stalls.",children:s.jsx(Nt,{checked:!!re.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(dt,{icon:bn,title:"Keep a Last 30s buffer",description:"Keep recent video in memory only until you explicitly save it.",children:s.jsx(Nt,{checked:!!re.rollingBufferEnabled,onChange:L("filesAudio","rollingBufferEnabled"),label:"Keep a Last 30s buffer"})}),s.jsx(dt,{icon:bn,title:"Recording quality",description:"Choose the WebM bitrate profile.",children:s.jsx(Zi,{value:String(re.recordingQuality),onChange:L("filesAudio","recordingQuality"),label:"Recording quality",options:[["standard","Standard"],["high","High"]]})}),s.jsx(dt,{icon:bn,title:"Timelapse interval",description:"Capture one frame at the selected interval.",children:s.jsx(Zi,{value:Number(re.timelapseIntervalSeconds),onChange:me=>L("filesAudio","timelapseIntervalSeconds")(Number(me)),label:"Timelapse interval",options:[["5","5 seconds"],["10","10 seconds"],["30","30 seconds"],["60","60 seconds"]]})}),s.jsx(dt,{icon:Zt,title:"Include remote cursor",description:"Include the cursor indicator when the source provides it.",children:s.jsx(Nt,{checked:!!re.includeRemoteCursor,onChange:L("filesAudio","includeRemoteCursor"),label:"Include remote cursor"})}),s.jsx(dt,{icon:Co,title:"Capture save location",description:"Captures are stored inside the Hub capture library.",children:s.jsx(Zi,{value:String(re.captureSaveLocation),onChange:L("filesAudio","captureSaveLocation"),label:"Capture save location",options:[[String(re.captureSaveLocation||"LiveDesk Captures"),"LiveDesk Captures"]]})}),s.jsx(dt,{icon:Co,title:"Automatic deletion",description:"Keep saved captures until you delete them.",children:s.jsx(Zi,{value:String(re.captureAutoDelete),onChange:L("filesAudio","captureAutoDelete"),label:"Automatic deletion",options:[["never","Never"],["7-days","After 7 days"],["30-days","After 30 days"]]})})]}),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:"Agent safety"}),s.jsx("h3",{children:"AI workstation operations"})]}),s.jsx(Ds,{size:20})]}),s.jsx(dt,{icon:Ds,title:"Enable AI Agent on devices",description:"Allow Agent runs to reach connected workstations.",recommended:!0,children:s.jsx(Nt,{checked:!!K.enabled,onChange:L("agent","enabled"),label:"Enable AI Agent"})}),s.jsx(dt,{icon:Ht,title:"Default permission mode",description:"Safe Auto keeps destructive operations behind approval.",children:s.jsx(Zi,{value:String(K.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(dt,{icon:Ht,title:"Ask before destructive operations",description:"Locked on for Safe Auto and destructive actions.",disabled:!K.enabled,children:s.jsx(Nt,{checked:!!K.askBeforeDestructive,onChange:L("agent","askBeforeDestructive"),disabled:!K.enabled,label:"Ask before destructive operations"})}),s.jsx(dt,{icon:bn,title:"Keep Agent audit history",description:"Retain an inspectable record of Agent runs.",children:s.jsx(Nt,{checked:!!K.keepAuditHistory,onChange:L("agent","keepAuditHistory"),label:"Keep Agent audit history"})}),s.jsx(dt,{icon:bn,title:"Stop Agent tasks after timeout",description:"Maximum runtime for one task.",children:s.jsx(Zi,{value:Number(K.timeoutMinutes),onChange:me=>L("agent","timeoutMinutes")(Number(me)),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(Ht,{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(([me,Se])=>s.jsx(dt,{icon:Ht,title:Se,description:me.includes("allowCommand")||me.includes("Installation")||me.includes("Power")?"Disabled by default for safety.":"Applied by the Hub and checked again by the Client.",children:s.jsx(Nt,{checked:!!K[me],onChange:L("agent",me),label:Se})},me))]}),s.jsx("p",{className:"settings-help",children:"The existing Codex runtime and audit controls remain available below in Advanced and the Agent diagnostics panel."})]}),fe=x==="connection"?G:x==="security"?q:x==="control"?oe:x==="wall"?we:x==="files-audio"?Q:x==="agent"?s.jsxs(s.Fragment,{children:[$,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(Vd,{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:_j.map(({id:me,label:Se,icon:Be})=>s.jsxs("button",{className:x===me?"active":"",id:`settings-tab-${me}`,role:"tab","aria-selected":x===me,"aria-controls":`settings-panel-${me}`,tabIndex:x===me?0:-1,onClick:()=>b(me),type:"button",children:[s.jsx(Be,{size:16}),Se]},me))}),A&&s.jsx("div",{className:"agent-settings-alert error",role:"alert",children:A}),s.jsx("section",{className:"settings-page-panel",id:ee,role:"tabpanel","aria-labelledby":`settings-tab-${x}`,tabIndex:0,children:fe})]})}function Ij({children:n}){return s.jsx("div",{className:"settings-tab-content",children:n})}function Oj({children:n}){return s.jsx("div",{className:"settings-tab-content",children:n})}function Hj({children:n}){return s.jsx("div",{className:"settings-tab-content",children:n})}const bb={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 Oy(n){return{...bb,...n||{}}}function Bj({hubUrl:n}){const[a,r]=u.useState(bb),[l,c]=u.useState(null),[d,m]=u.useState(""),[p,v]=u.useState(""),[g,w]=u.useState(""),[x,b]=u.useState("");u.useEffect(()=>{let L=!0;return We("/api/settings/agent",void 0,n).then(ne=>{L&&(c(ne.settings),r(Oy(ne.settings)))}).catch(ne=>{L&&b(ne instanceof Error?ne.message:String(ne))}),()=>{L=!1}},[n]);const j=(L,ne)=>r(W=>({...W,[L]:ne})),C=L=>{c(L),r(Oy(L))},k=async()=>{v("save"),b(""),w("");try{const L={...a};d.trim()&&(L.apiKey=d.trim());const ne=await We("/api/settings/agent",{method:"PUT",body:JSON.stringify(L)},n);C(ne.settings),m(""),w("Agent settings saved.")}catch(L){b(L instanceof Error?L.message:String(L))}finally{v("")}},M=async()=>{v("reset"),b("");try{const L=await We("/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("")}},A=async()=>{v("test"),b(""),w("");try{const L=await We("/api/settings/agent/test",{method:"POST",body:JSON.stringify({})},n),ne=await We("/api/settings/agent",void 0,n);C(ne.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("")}},T=async()=>{v("clear-key"),b("");try{const L=await We("/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",P=l?.securityStatus,F=P?.state||"unavailable",V=F==="verified"?"Verified":F==="configured"?"Configured":"Unavailable",_=[["Codex home",P?.isolatedCodexHome],["Environment variables",P?.restrictedEnvironment],["LiveDesk MCP only",P?.livedeskMcpOnly],["Selected-device scope",P?.selectedDeviceScopeEnforced],["Fail-closed execution",P?.failClosed]];return s.jsxs("div",{className:"settings-tab-content agent-settings-content",children:[s.jsx("section",{className:"settings-section-card agent-enable-card",children: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"})]})}),x&&s.jsx("div",{className:"agent-settings-alert error",role:"alert",children:x}),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(Ao,{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:()=>{A()},disabled:p!==""||a.provider!=="codex",type:"button",children:[s.jsx(YS,{size:15})," ",p==="test"?"Testing":"Test connection"]})]}),s.jsxs("p",{className:"settings-help",children:[s.jsx(KS,{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(QS,{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(Ht,{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(Ao,{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:()=>{T()},disabled:p!==""||!l?.hasApiKey,type:"button",children:[s.jsx(ep,{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(_n,{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(Ht,{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(Jh,{size:15}),s.jsx("span",{children:L}),s.jsx("strong",{children:"Blocked"})]},L)),_.map(([L])=>s.jsxs("div",{className:"agent-safety-row",children:[s.jsx(Ht,{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:V})]},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:()=>{M()},disabled:p!=="",type:"button",children:[s.jsx(Gc,{size:15})," Reset defaults"]}),s.jsxs("button",{className:"text-button primary",onClick:()=>{k()},disabled:p!=="",type:"button",children:[s.jsx(Yx,{size:15})," ",p==="save"?"Saving":"Save Agent settings"]})]})]})}new Date().valueOf();function fi(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 op(n,a){return typeof n=="function"?typeof a=="object"?n(a):n():n}function Ro(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 Fj(n,a="data-id"){const r=Ro(n,a);return r?r.getAttribute(a):null}function nu(n,a="data-id"){const r=Ro(n,a);return r?uf(r,a):null}function uf(n,a="data-id"){const r=n.getAttribute(a);return r?Pj(r):null}function Hn(n){return typeof n=="string"?":"+n:n}function Pj(n){if(n.startsWith(":"))return n.substring(1);const a=n*1;return isNaN(a)?n:a}function $j(){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 Fa=$j();function cp(n){Object.assign(Fa,n)}function Hy(n,a,r){function l(c){const d=Ro(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)}Fa.addEvent(n,r,l)}function Do(n,a){Hy(n,a,"click"),a.dblclick&&Hy(n,a.dblclick,"dblclick")}function Uj(n,a){for(let r=n.length-1;r>=0;r--)if(n[r]===a){n.splice(r,1);break}}function qj(n,a,r){for(let l=0;l<tr.length;l++){if(l===r)continue;const c=tr[l],d=c.props.parent?.();if(d&&n.contains(d)&&c.node.contains(a))return!0}return!1}var wb=new Date,Jd=!1,Sd=[],tr=[],By=n=>{const a=n.target;if(Jd||!a.isConnected){Jd=!1;return}for(let r=tr.length-1;r>=0;r--){const{node:l,date:c,props:d}=tr[r];if(!(c>wb)&&!l.contains(a)&&l!==a&&(qj(l,a,r)||(d.callback&&d.callback(n),d.modal||n.defaultPrevented)))break}},Gj=n=>{wb=new Date,Jd=!0;for(let a=tr.length-1;a>=0;a--){const{node:r}=tr[a];if(!r.contains(n.target)&&r!==n.target){Jd=!1;break}}};function mi(n,a){Sd.length||(Sd=[Fa.addGlobalEvent("click",By,n),Fa.addGlobalEvent("contextmenu",By,n),Fa.addGlobalEvent("mousedown",Gj,n)]),typeof a!="object"&&(a={callback:a});const r={node:n,date:new Date,props:a};return tr.push(r),{destroy(){Uj(tr,r),tr.length||(Sd.forEach(l=>l()),Sd=[])}}}var Cd=n=>n.indexOf("bottom")!==-1,jd=n=>n.indexOf("left")!==-1,kd=n=>n.indexOf("right")!==-1,sh=n=>n.indexOf("top")!==-1,Fy=n=>n.indexOf("fit")!==-1,Bc=n=>n.indexOf("overlap")!==-1,Vj=n=>n.split("-").every(a=>["center","fit"].indexOf(a)>-1),Wj=n=>{const a=n.match(/(start|center|end)/);return a?a[0]:null};function Yj(n,a){let r=0;const l=Fa.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 Rn,oa,Fc,Xn;function Sb(n,a,r="bottom",l=0,c=0){if(!n)return null;Rn=l,oa=c,Fc="auto";let d=0,m=0,p=r;const v=Cb(n),g=Bc(r)?Fa.getTopNode(n):v;if(!v)return null;const w=v.getBoundingClientRect(),x=n.getBoundingClientRect(),b=g.getBoundingClientRect(),j=window.getComputedStyle(g),C={left:0,top:0,bottom:0,right:0};for(const P in C){const F=`border-${P}-width`;C[P]=parseFloat(j.getPropertyValue(F))}if(a){const P=Yj(a,v);d=Math.max(P+1,20)}if(a){if(Xn=a.getBoundingClientRect(),Fy(r)&&(Fc=Xn.width+"px"),r!=="point")if(Vj(r))Fy(r)?Rn=0:(Rn=b.width/2,m=1),oa=(b.height-x.height)/2;else{const P=Bc(r)?0:1;Rn=kd(r)?Xn.right+P:Xn.left-P,oa=Cd(r)?Xn.bottom+1:Xn.top;const F=Wj(r);F&&(kd(r)||jd(r)?F==="center"?oa-=(x.height-Xn.height)/2:F==="end"&&(oa-=x.height-Xn.height):(Cd(r)||sh(r))&&(F==="center"?Rn-=(x.width-Xn.width)/2:F==="end"&&(Rn-=x.width-Xn.width),Bc(r)||(Rn+=1)))}}else Xn={left:l,right:l,top:c,bottom:c};const k=(jd(r)||kd(r))&&(Cd(r)||sh(r));jd(r)&&(m=2);const M=Rn-x.width-b.left;a&&jd(r)&&!k&&M<0&&(Rn=Xn.right,m=0,p=p.replace("left","right"));const A=Rn+x.width*(1-m/2)-b.right;if(A>0)if(!kd(r))Rn=b.right-C.right-x.width;else{const P=Xn.left-b.x-x.width;a&&!k&&P>=0?(Rn=Xn.left-x.width,p=p.replace("right","left")):Rn-=A+C.right}m&&(Rn=Math.round(Rn-x.width*m/2));const T=M<0||A>0||!k;sh(r)&&(oa=Xn.top-x.height,a&&oa<b.y&&T&&(oa=Xn.bottom,p=p.replace("top","bottom")));const R=oa+x.height-b.bottom;return R>0&&(a&&Cd(r)&&T?(oa-=x.height+Xn.height+1,p=p.replace("bottom","top")):oa-=R+C.bottom),Rn-=w.left+C.left,oa-=w.top+C.top,Rn=(Bc(r)?Rn:Math.max(Rn,0))+g.scrollLeft,oa=(Bc(r)?oa:Math.max(oa,0))+g.scrollTop,Fc=Fc||"auto",{at:p,x:Rn,y:oa,z:d,width:Fc}}function Cb(n){const a=Fa.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 Kj(n){const a=[];let r=n;const l=Fa.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 Py=new Date().valueOf();function up(){return Py+=1,Py}function ua(n){return n<10?"0"+n:n.toString()}function Qj(n){const a=ua(n);return a.length==2?"0"+a:a}function jb(n){const a=Math.floor(n/11)*11;return{start:a,end:a+11}}function ih(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 $y=["",""];function Xj(n,a,r){switch(n){case"%d":return ua(a.getDate());case"%m":return ua(a.getMonth()+1);case"%j":return a.getDate();case"%n":return a.getMonth()+1;case"%y":return ua(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 ua((a.getHours()+11)%12+1);case"%g":return(a.getHours()+11)%12+1;case"%G":return a.getHours();case"%H":return ua(a.getHours());case"%i":return ua(a.getMinutes());case"%a":return((a.getHours()>11?r.pm:r.am)||$y)[0];case"%A":return((a.getHours()>11?r.pm:r.am)||$y)[1];case"%s":return ua(a.getSeconds());case"%S":return Qj(a.getMilliseconds());case"%W":return ua(ih(a));case"%w":{const l=r.weekStart??1;if(l===1)return ua(ih(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)),ua(ih(m))}case"%c":{let l=a.getFullYear()+"";return l+="-"+ua(a.getMonth()+1),l+="-"+ua(a.getDate()),l+="T",l+=ua(a.getHours()),l+=":"+ua(a.getMinutes()),l+=":"+ua(a.getSeconds()),l}case"%Q":return Math.floor(a.getMonth()/3)+1;default:return n}}var Zj=/%[a-zA-Z]/g;function No(n,a){return typeof n=="function"?n:function(r){return r?(r.getMonth||(r=new Date(r)),n.replace(Zj,l=>Xj(l,r,a))):""}}function Uy(n){return n&&typeof n=="object"&&!Array.isArray(n)}function Hh(n,a){for(const r in a){const l=a[r];Uy(n[r])&&Uy(l)?n[r]=Hh({...n[r]},a[r]):n[r]=a[r]}return n}function su(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=Hh({...a},n):l=Hh({...n},a),su(l)}}}var Jj=Jx();const ek="en-US",tk={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},nk={ok:"OK",cancel:"Cancel",select:"Select","No data":"No data","Rows per page":"Rows per page","Total pages":"Total pages"},ak={timeFormat:"%H:%i",dateFormat:"%m/%d/%Y",monthYearFormat:"%F %Y",yearFormat:"%Y"},kb={core:nk,calendar:tk,formats:ak,lang:ek},dp=u.createContext(""),Ab=u.createContext({}),_s=u.createContext(null),Nb=u.createContext(null),Fn=Object.freeze(Object.defineProperty({__proto__:null,fieldId:Nb,helpers:Ab,i18n:_s,theme:dp},Symbol.toStringTag,{value:"Module"}));function Mb(n){const a=u.useContext(Nb),[r]=u.useState(()=>n||a||up());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 x=n?n.split(" ").filter(b=>b!=="").map(b=>"wx-"+b).join(" "):"";return a+(a?" ":"")+x},[n,a]),w=x=>{v&&v(x)};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 sk({id:n,label:a="",inputValue:r="",value:l=!1,onChange:c,disabled:d=!1,css:m=""}){const p=Mb(n),[v,g]=fi(l),w=({target:x})=>{const b=x.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 fp({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(dp);return u.useEffect(()=>{m(a||ik(c.current)||Fa.getTopNode(c.current))},[c.current]),s.jsxs(s.Fragment,{children:[s.jsx("span",{ref:c,style:{display:"none"}}),c.current&&d?Jj.createPortal(s.jsx("div",{className:`wx-3ZWsT0 wx-${n||p}-theme`,children:r}),d):null]})}function ik(n){const a=Fa.getTopNode(n);for(;n&&n!==a&&!n.getAttribute("data-wx-portal-root");)n=n.parentNode;return n}function rk({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),[x,b]=u.useState(0),[j,C]=u.useState("auto"),[k,M]=u.useState(!1),A=u.useRef(null),T=u.useRef(null),R=u.useRef(m);u.useEffect(()=>{R.current=m},[m]);function P(V){return l&&(c+"").indexOf("%")>-1?c.replace(/(\d+)%/,(_,L)=>(L=L*l.offsetWidth/100+"px",c.replace(_,L))):c&&c!=="auto"?c:V}const F=u.useCallback(()=>{if(!A.current)return;const V=Sb(A.current,l,r,n,a);V&&(w(V.x),b(V.y),C(P(V.width)))},[A,l,r,n,a,c]);return u.useLayoutEffect(()=>{const V=L=>{R.current&&L.target!==T.current&&A.current&&!A.current.contains(L.target)&&R.current(L)};let _;return requestAnimationFrame(()=>{F(),M(!0),v&&A.current&&(T.current=Cb(A.current),T.current&&T.current.addEventListener("scroll",V,!0)),l&&(_=new ResizeObserver(F),_.observe(l))}),()=>{v&&T.current&&T.current.removeEventListener("scroll",V,!0),_?.disconnect()}},[]),u.useLayoutEffect(()=>{F()},[l,r,n,a]),u.useEffect(()=>{const V=_=>{R.current&&R.current(_)};if(A.current)return mi(A.current,{callback:V,parent:()=>l}).destroy},[l]),s.jsx("div",{ref:A,className:["wx-37M6Fj","wx-popup",d].filter(Boolean).join(" "),style:{position:"absolute",visibility:k?"visible":"hidden",top:x+"px",left:g+"px",width:j},children:p})}function lk({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,x]=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(),k=document.body.getBoundingClientRect();C.right>=k.right&&x("end"),C.bottom>=k.bottom&&g("top")}}},[]),u.useEffect(()=>{if(p.current){const j=C=>{b.current&&b.current(C)};return mi(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 mp({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),x=u.useMemo(()=>`${n}-${a}`,[n,a]);return u.useLayoutEffect(()=>{w.current&&g(w.current.parentNode)},[]),s.jsxs(s.Fragment,{children:[v&&(l?s.jsx(lk,{onCancel:c,position:n,align:a,autoFit:r,width:d,...p,children:m}):s.jsx(fp,{children:s.jsx(rk,{parent:v,at:x,onCancel:c,width:d,...p,children:m})})),s.jsx("span",{ref:w,className:"wx-portal-node wx-32GZ52"})]})}function df(){return su(kb)}function ok(){let n=null,a=!1,r=!1,l,c,d,m;const p=(x,b,j,C,k)=>{l=x,c=b,d=j,m=C,r=k},v=x=>{n=x,a=n!==null,d(n)},g=(x,b)=>{if(!r&&x!==null&&l){const j=l.querySelectorAll(".wx-list > .wx-item")[x];j&&(j.scrollIntoView({block:"nearest"}),b&&b.preventDefault())}},w=(x,b)=>{const j=x===null?null:Math.max(0,Math.min(n+x,c.length-1));j!==n&&(v(j),l?g(j,b):requestAnimationFrame(()=>g(j,b)))};return{move:x=>{const b=nu(x),j=c.findIndex(C=>C.id===b);j!==n&&v(j)},keydown:(x,b)=>{switch(x.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,x);break;case"ArrowUp":w(a?-1:b||0,x);break}},init:p,navigate:w}}const qy=10,ck=u.memo(function({data:n,checkboxes:a,itemTemplate:r,value:l}){return s.jsxs(s.Fragment,{children:[a&&s.jsx(sk,{id:n.id,css:"wx-list-checkbox",value:l&&l.includes(n.id)}),r?op(r,{option:n}):n.label]})});function Gy({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(ck,{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),x=u.useRef(ok()),[b,j]=u.useState(null),C=u.useRef(b),[k,M]=u.useState(0),[A,T]=u.useState(24),R=u.useRef(!1),P=(u.useContext(_s)||df()).getGroup("core"),F=u.useRef(n);u.useEffect(()=>{F.current=n},[n]);const V=u.useRef(p);u.useEffect(()=>{V.current=p},[p]);const _=u.useRef(0);u.useEffect(()=>{_.current=A},[A]);const L=u.useCallback(Q=>{Q&&Q.stopPropagation();const $=F.current,he=V.current,fe=C.current;let me;const Se=$[fe]?.id;m?he&&he.includes(Se)?me=he.filter(Be=>Be!==Se):me=[...he||[],Se]:me=Se,r&&r({id:me})},[m,r]),ne=u.useRef(L);u.useEffect(()=>{ne.current=L},[L]);const W=u.useCallback(Q=>{if(g.current){let $=Q*_.current-g.current.clientHeight+_.current;M($),g.current.scrollTop=$}},[_.current]),J=u.useCallback(Q=>{g.current=Q,c&&(Q&&!w.current&&C.current!==null&&requestAnimationFrame(()=>{g.current&&(W(C.current),w.current=!0)}),Q||(w.current=!1))},[W]),O=u.useCallback(Q=>{if(!Q||R.current)return;const $=Q.getBoundingClientRect().height;$&&(T($),_.current=$,R.current=!0)},[]);u.useEffect(()=>{x.current.init(g.current,n,Q=>{j(Q),C.current=Q},Q=>ne.current(Q),c)},[n,g.current,c]),u.useEffect(()=>{const Q=(he,fe)=>{x.current.navigate(he,fe),W(C.current)},$=(he,fe)=>{const me=C.current,Se=F.current;if(me!==0&&me!==Se.length-1&&(he.key==="ArrowDown"||he.key==="ArrowUp")&&he.preventDefault(),x.current.keydown(he,fe),g.current){const Be=g.current.scrollTop<=C.current*_.current,Oe=g.current.scrollTop+g.current.clientHeight>=C.current*_.current+_.current;Be?Oe||W(C.current):(g.current.scrollTop=C.current*_.current,M(g.current.scrollTop))}};l&&l({navigate:c?Q:x.current.navigate,keydown:c?$:x.current.keydown,move:x.current.move})},[]);const be=u.useRef(0),re=u.useRef(n);re.current!==n&&(re.current=n,be.current+=1);const K=u.useCallback(()=>{x.current.navigate(null)},[x]),I=u.useCallback(Q=>{c&&M(Q.target.scrollTop)},[c]),ee=u.useMemo(()=>Math.ceil((g.current?.clientHeight||0)/A),[A,k]),G=u.useMemo(()=>{if(!c)return{start:0,end:n.length};if(!n.length)return{start:0,end:0};const Q=Math.floor(k/A),$=Q+ee;return{start:Math.max(0,Q-qy),end:Math.min(n.length,$+qy)}},[c,n,k,A,ee]),q=u.useMemo(()=>{if(!c)return n;const{start:Q,end:$}=G;return n.slice(Q,$).map(he=>({...he}))},[c,n,G]),oe=G.start*A,we=n.length*A;return u.useEffect(()=>{c&&M(0)},[n,c]),u.useEffect(()=>{b===null&&(w.current=!1)},[b]),b===null?null:s.jsx(mp,{onCancel:K,...v,children:s.jsx("div",{className:"wx-233fr7 wx-list",ref:J,onClick:L,onMouseMove:x.current.move,onScroll:I,children:n.length?c?s.jsx("div",{className:"wx-233fr7 wx-list-wrapper",style:{height:`${we}px`},children:s.jsx("div",{className:"wx-233fr7 wx-list-content",style:{transform:`translateY(${oe}px)`},children:s.jsx(Gy,{visibleRange:G,visibleItems:q,navIndex:b,measureRefCallback:O,checkboxes:d,itemTemplate:a,value:p})})}):s.jsx(Gy,{visibleRange:G,visibleItems:q,navIndex:b,measureRefCallback:O,checkboxes:d,itemTemplate:a,value:p}):s.jsx("div",{className:"wx-233fr7 wx-no-data",children:P("No data")})})},be.current)}function hp({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:x="",icon:b="",clear:j=!1,onChange:C}){const k=Mb(a),[M,A]=fi(n),T=u.useRef(null),R=u.useMemo(()=>b&&x.indexOf("wx-icon-left")===-1?"wx-icon-right "+x:x,[b,x]),P=u.useMemo(()=>b&&x.indexOf("wx-icon-left")!==-1,[b,x]);u.useEffect(()=>{const ne=setTimeout(()=>{l&&T.current&&T.current.focus(),c&&T.current&&T.current.select()},1);return()=>clearTimeout(ne)},[l,c]);const F=u.useCallback(ne=>{const W=ne.target.value;A(W),C&&C({value:W,input:!0})},[C]),V=u.useCallback(ne=>C&&C({value:ne.target.value}),[C]);function _(ne){ne.stopPropagation(),A(""),C&&C({value:""})}let L=d;return d!=="password"&&d!=="number"&&(L="text"),u.useEffect(()=>{const ne=V,W=T.current;return W.addEventListener("change",ne),()=>{W&&W.removeEventListener("change",ne)}},[V]),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:T,id:k,readOnly:r,disabled:p,placeholder:m,type:L,title:g,value:M,onInput:F}),j&&!p&&M?s.jsxs(s.Fragment,{children:[s.jsx("i",{className:"wx-hQ64J4 wx-icon wxi-close",onClick:_}),P&&s.jsx("i",{className:`wx-hQ64J4 wx-icon ${b}`})]}):b?s.jsx("i",{className:`wx-hQ64J4 wx-icon ${b}`}):null]})}function uk({date:n,type:a,part:r,onShift:l}){const{calendar:c,formats:d}=u.useContext(_s).getRaw(),m=n.getFullYear(),p=u.useMemo(()=>{switch(a){case"month":return No(d.monthYearFormat,c)(n);case"year":return No(d.yearFormat,c)(n);case"duodecade":{const{start:g,end:w}=jb(m),x=No(d.yearFormat,c);return`${x(new Date(g,0,1))} - ${x(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 pp({onClick:n,children:a}){return s.jsx("button",{className:"wx-3s8W4d wx-button",onClick:n,children:a})}function dk({value:n,current:a,part:r="",markers:l=null,css:c="",onCancel:d,onChange:m}){const p=(u.useContext(_s)||df()).getRaw().calendar,v=(p.weekStart||7)%7,g=p.dayShort.slice(v).concat(p.dayShort.slice(0,v)),w=(F,V,_)=>new Date(F.getFullYear(),F.getMonth()+(V||0),F.getDate()+(_||0));let x=r!=="normal";function b(F){const V=F.getDay();return V===0||V===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 k=u.useRef(0);function M(F,V){V.timeStamp!==k.current&&(k.current=V.timeStamp,V.stopPropagation(),m&&m(new Date(F)),d&&d())}const A=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]),T=u.useMemo(()=>{const F=j(),V=C(),_=a.getMonth();let L=[];for(let ne=F;ne<=V;ne.setDate(ne.getDate()+1)){const W={day:ne.getDate(),in:ne.getMonth()===_,date:ne.valueOf()};let J="";if(J+=W.in?"":" wx-inactive",J+=A.indexOf(W.date)>-1?" wx-selected":"",x){const O=W.date==A[0],be=W.date==A[1];O&&!be?J+=" wx-left":be&&!O&&(J+=" wx-right"),W.date>A[0]&&W.date<A[1]&&(J+=" wx-inrange")}if(J+=b(ne)?" wx-weekend":"",l){const O=l(ne);O&&(J+=" "+O)}L.push({...W,css:J})}return L},[a,A,x,l]),R=u.useRef(null);let P=u.useRef({});return P.current.click=M,u.useEffect(()=>{Do(R.current,P.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:T.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 fk({value:n,current:a,part:r,onCancel:l,onChange:c,onShift:d}){const m=u.useRef(new Date),[p,v]=fi(n||m.current),[g,w]=fi(a||m.current),x=u.useContext(_s).getRaw().calendar,b=x.monthShort||[],j=u.useMemo(()=>g.getMonth(),[g]),C=u.useCallback((A,T)=>{if(A!=null){T.stopPropagation();const R=new Date(g);R.setMonth(A),w(R),d&&d({current:R})}r==="normal"&&v(new Date(g)),l&&l()},[g,r,d,l]),k=u.useCallback(()=>{const A=new Date(Tb(p,r)||g);A.setMonth(g.getMonth()),A.setFullYear(g.getFullYear()),c&&c(A)},[p,g,r,c]),M=u.useCallback(A=>{const T=A.target.closest("[data-id]");if(T){const R=parseInt(T.getAttribute("data-id"),10);C(R,A)}},[C]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"wx-34U8T8 wx-months",onClick:M,children:b.map((A,T)=>s.jsx("div",{className:"wx-34U8T8 wx-month"+(j===T?" wx-current":""),"data-id":T,children:A},T))}),s.jsx("div",{className:"wx-34U8T8 wx-buttons",children:s.jsx(pp,{onClick:k,children:x.done})})]})}const rh="wx-1XEF33",mk=({value:n,current:a,onCancel:r,onChange:l,onShift:c,part:d})=>{const m=u.useContext(_s).getRaw().calendar,[p,v]=fi(a),[g,w]=fi(n),x=u.useMemo(()=>p.getFullYear(),[p]),b=u.useMemo(()=>{const{start:A,end:T}=jb(x),R=[];for(let P=A;P<=T;++P)R.push(P);return R},[x]),j={click:C};function C(A,T){if(A){T.stopPropagation();const R=new Date(p);R.setFullYear(A),v(R),c&&c({current:R})}d==="normal"&&w(new Date(p)),r&&r()}function k(){const A=new Date(Tb(g,d)||p);A.setFullYear(p.getFullYear()),l&&l(A)}const M=u.useRef(null);return u.useEffect(()=>{M.current&&Do(M.current,j)},[]),s.jsxs(s.Fragment,{children:[s.jsx("div",{className:rh+" wx-years",ref:M,children:b.map((A,T)=>s.jsx("div",{className:rh+` wx-year ${x==A?"wx-current":""} ${T===0?"wx-prev-decade":""} ${T===11?"wx-next-decade":""}`,"data-id":A,children:A},T))}),s.jsx("div",{className:rh+" wx-buttons",children:s.jsx(pp,{onClick:k,children:m.done})})]})},Vy={month:{component:dk,next:pk,prev:hk},year:{component:fk,next:vk,prev:gk},duodecade:{component:mk,next:xk,prev:yk}};function hk(n){return n=new Date(n),n.setMonth(n.getMonth()-1),n}function pk(n){return n=new Date(n),n.setMonth(n.getMonth()+1),n}function gk(n){return n=new Date(n),n.setFullYear(n.getFullYear()-1),n}function vk(n){return n=new Date(n),n.setFullYear(n.getFullYear()+1),n}function yk(n){return n=new Date(n),n.setFullYear(n.getFullYear()-10),n}function xk(n){return n=new Date(n),n.setFullYear(n.getFullYear()+10),n}function Tb(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 bk=["clear","today"];function wk(n){if(n==="done")return-1;if(n==="clear")return null;if(n==="today")return new Date}function Sk({value:n,current:a,onCurrentChange:r,part:l="normal",markers:c=null,buttons:d,css:m="",onShift:p,onChange:v}){const g=u.useContext(_s).getGroup("calendar"),[w,x]=u.useState("month"),b=Array.isArray(d)?d:d?bk:[],j=(T,R)=>{T.preventDefault(),v&&v({value:R})},C=()=>{w==="duodecade"?x("year"):w==="year"&&x("month")},k=T=>{const{diff:R,current:P}=T;if(R===0){w==="month"?x("year"):w==="year"&&x("duodecade");return}if(R){const F=Vy[w];r(R>0?F.next(a):F.prev(a))}else P&&r(P);p&&p()},M=T=>{x("month"),v&&v({select:!0,value:T})},A=u.useMemo(()=>Vy[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(uk,{date:a,part:l,type:w,onShift:k}),s.jsxs("div",{children:[s.jsx(A,{value:n,current:a,onCurrentChange:r,part:l,markers:c,onCancel:C,onChange:M,onShift:k}),w==="month"&&b.length>0&&s.jsx("div",{className:"wx-2Gr4AS wx-buttons",children:b.map(T=>s.jsx("div",{className:"wx-2Gr4AS wx-button-item",children:s.jsx(pp,{onClick:R=>j(R,wk(T)),children:g(T)})},T))})]})]})})}function gp(n){let{words:a=null,optional:r=!1,children:l}=n,c=u.useContext(_s);const d=u.useMemo(()=>{let m=c;return(!m||!m.extend)&&(m=su(kb)),a!==null&&(m=m.extend(a,r)),m},[a,r,c]);return s.jsx(_s.Provider,{value:d,children:l})}function Wy(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 Ck=["clear","today"];function Eb({value:n,current:a,markers:r=null,buttons:l=Ck,css:c="",onChange:d}){const[m,p]=fi(n),[v,g]=fi(a);u.useEffect(()=>{Wy(v,m,g,!1)},[m,v]);const w=u.useCallback(b=>{const j=b.value;j?(p(new Date(j)),Wy(v,new Date(j),g,!0)):p(null),d&&d({value:j?new Date(j):null})},[d,v]),x=u.useCallback(b=>{g(b)},[g]);return v?s.jsx(gp,{children:s.jsx(Sk,{value:m,current:v,markers:r,buttons:l,css:c,onChange:w,onCurrentChange:x})}):null}function jk(n){return n||(n={}),n.width||(n.width="unset"),n}const kk=["clear","today"];function Ak({value:n,id:a,disabled:r=!1,error:l=!1,placeholder:c="",format:d="",buttons:m=kk,css:p="",title:v="",tooltip:g,editable:w=!1,clear:x=!1,onChange:b,dropdown:j={}}){const{calendar:C,formats:k}=(u.useContext(_s)||df()).getRaw(),M=d||k?.dateFormat;let A=typeof M=="function"?M:No(M,C);const[T,R]=u.useState(n),[P,F]=u.useState(!1);u.useEffect(()=>{R(n)},[n]);function V(){F(!1)}function _(W){const J=W===T||W&&T&&W.valueOf()===T.valueOf()||!W&&!T;R(W),J||b&&b({value:W}),setTimeout(V,1)}const L=u.useMemo(()=>T?A(T):"",[T,A]);function ne({value:W,input:J}){if(!w&&!x||J)return;let O=typeof w=="function"?w(W):W?new Date(W):null;O=isNaN(O)?T||null:O||null,_(O)}return u.useEffect(()=>{const W=V;return window.addEventListener("scroll",W),()=>window.removeEventListener("scroll",W)},[]),s.jsxs("div",{className:"wx-1lKOFG wx-datepicker",onClick:()=>F(!0),children:[s.jsx(hp,{css:`wx-date-input ${p}`,title:v,tooltip:g,value:L,id:a,readonly:!w,disabled:r,error:l,placeholder:c,onInput:V,onChange:ne,icon:"wxi-calendar",clear:x}),P&&!r&&s.jsx(mp,{onCancel:V,...jk(j),children:s.jsx(Eb,{buttons:m,value:T,onChange:W=>_(W.value)})})]})}function Nk({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:x,onChange:b,dropdown:j={}}){const C=u.useRef(null),k=u.useRef(null);let[M,A]=fi(n);function T(_){C.current=_.navigate,k.current=_.keydown}const R=u.useMemo(()=>M||M===0?(r||a).find(_=>_.id===M):null,[M,r,a]),P=u.useCallback(({id:_})=>{(_||_===0)&&(A(_),C.current(null),b&&b({value:_}))},[A,b]),F=u.useCallback(_=>{_.stopPropagation(),A(""),b&&b({value:""})},[A,b]),V=u.useCallback(()=>a.findIndex(_=>_.id===M),[a,M]);return s.jsxs("div",{className:`wx-2YgblL wx-richselect ${w} ${d?"wx-2YgblL wx-error":""} ${c?"wx-2YgblL wx-disabled":""} ${x?"":"wx-2YgblL wx-nowrap"}`,title:m,onClick:()=>C.current(V()),onKeyDown:_=>k.current(_,V()),tabIndex:0,"data-tooltip-text":p,children:[s.jsx("div",{className:"wx-2YgblL wx-label",children:R?x?x(R):R[v]:l?s.jsx("span",{className:"wx-2YgblL wx-placeholder",children:l}):" "}),g&&!c&&M?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:T,onSelect:P,...j,children:({option:_})=>x?x(_):_[v]})]})}const Mk=({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?op(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 Tk({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 Ek({data:n=[]}){return s.jsx("div",{className:"wx-3nwoO9 wx-notices",children:n.map(a=>s.jsx(Tk,{notice:a},a.id))})}function Bh({title:n="",buttons:a=["cancel","ok"],header:r,children:l,footer:c,css:d="",onConfirm:m,onCancel:p}){const v=(u.useContext(_s)||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 x(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=>x(j,b),children:v(b)})},b))})]})})}function Rk({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||up(),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(Bh,{title:r.title,buttons:r.buttons,onConfirm:r.resolve,onCancel:r.reject,children:r.message}),s.jsx(Ek,{data:c})]})}const Dk=u.forwardRef(Rk);function Lk(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(Ab.Provider,{value:l,children:s.jsx(Dk,{ref:r,children:a})})}const _k=({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:x,active:b,onChange:j})=>{const[C,k]=fi(n),M=u.useMemo(()=>(C?"pressed":"")+(a?" "+a:""),[C,a]),A=u.useCallback(T=>{let R=!C;d&&d(T),T.defaultPrevented||(k(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:M,icon:C&&c||r,onClick:A,disabled:l,children:op(b,{value:C})}):x?s.jsx(Kc,{title:m,tooltip:p,text:C&&w||g,css:v,type:M,icon:C&&c||r,onClick:A,disabled:l,children:x}):s.jsx(Kc,{title:m,tooltip:p,text:C&&w||g,css:v,type:M,icon:C&&c||r,onClick:A,disabled:l})};function zk(){return s.jsx(s.Fragment,{})}function Yy(n){const{fonts:a=!0,children:r}=n;return s.jsx(dp.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(zk,{}),s.jsx("link",{rel:"stylesheet",href:"https://cdn.svar.dev/fonts/wxi/wx-icons.css"})]})]})})}cp(Fa);const vp={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 Rb=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 Ik=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]:Ky(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=Ad(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=Ad(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=Ad(p,l.id);Ok(p,g);const w=c?v.data.length:Ad(v,d.id)+(a==="after"?1:0);if(Ky(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&&Db(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 Db(n,a){n.forEach(r=>{a.push(r),r.open===!0&&Db(r.data,a)})}function Ok(n,a){const r=[...n.data];r.splice(a,1),n.data=r}function Ky(n,a,r){const l=[...n.data];l.splice(a,0,r),n.data=l}function Ad(n,a){return n?.data.findIndex(r=>r.id===a)}var Lb=2,Hk=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 x=c+(c?".":"")+p;v?(v.__parse(w,x,d,m)&&(l[p]=w),m&Lb?d[x]=v.__trigger:v.__trigger()):(w&&w.__reactive?r[p]=this._wrapNested(w,w,x,d):r[p]=this._wrapWritable(w),l[p]=w),d[x]=d[x]||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 Qy(n,a){return Object.defineProperty(n,"__reactive",{value:!0,enumerable:!1,writable:!1}),n}var Bk=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=>_b(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,Lb);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 _b(n,a,r){const l=a.get(n);if(!l)return r;const c=Object.keys(l).map(d=>_b(d,a,r+1));return Math.max(...c)}var Fk=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 bo=1024;function au(n){return n<bo?`${n} B`:n<bo**2?`${(n/bo).toFixed(1)} KB`:n<bo**3?`${(n/bo**2).toFixed(1)} MB`:`${(n/bo**3).toFixed(1)} GB`}function Xy(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(Zy(a)),d=l.sort(Zy(a));return[...c,...d]}function Pk(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 $k(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 Zy({key:n,order:a}){const r=a==="asc"?Pk:$k;return(l,c)=>r(l[n],c[n])}function yp(n,a){const r=n==="/"?1:n.split("/").length;return r>=a.length?null:a[r].id}function Uk(n){return n.length>1?n[n.length-2].id:null}let qk=class extends Ik{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 x=this.serialize(d);x.length&&r.push(...x)}),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()}}},Gk=class extends Hk{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:x,_sorts:b}=v[d];w=Xy(w,b[x]);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 k=p.byId(C);k&&g.push(k)});const{path:w,_sorts:x}=v[d],b=Xy(g,x[w]),j=[];j[d]={_selected:b},this.setState({panels:j},m)}});this._router=new Bk(super.setState.bind(this),r,{data:d=>new qk(d)});const l=this.in=new Fk;l.on("select-file",({id:d,toggle:m,range:p,panel:v,type:g})=>{const{panels:w,activePanel:x}=this.getState();typeof v>"u"&&(v=x),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 k=C.findIndex(T=>T.id==w[v]._lastSelected),M=C.findIndex(T=>T.id==d);M<k&&([k,M]=[M,k]);const A=C.slice(k,M+1).map(T=>T.id);b=[...new Set([...b,...A])]}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 x=[];typeof m>"u"&&(m=g),x[m]={path:d},this.setState({panels:x}),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 x=v.normalizeFile(w,w.parent);d.newId=x.id,x.data=null,v.add(x);let b={[m]:x.id};w.data?.forEach(C=>b={...v.moveFiles([C.id],x.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(),x=v.copyFiles(m,p);d.newIds=m.map(b=>x[b]),this.setState({data:v}),g[w].path==p&&(l.exec("select-file",{}),m.forEach(b=>{l.exec("select-file",{id:x[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(),x=v.moveFiles(m,p);if(x){d.newIds=m.map(j=>x[j]);const b=g.map(j=>({selected:j.selected,_crumbs:j._crumbs,_lastSelected:j._lastSelected,_sorts:j._sorts}));this._updatePanels(b,x,!0),this.setState({data:v,panels:b}),g[w].path==p&&(l.exec("select-file",{}),m.forEach(j=>{l.exec("select-file",{id:x[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 x=[];x[p]={_sorts:{...w[p]._sorts,[v]:{key:d,order:m}}},this.setState({panels:x})}),this.initOnce()}initOnce(){const a=[];for(let l=0;l<2;l++)a[l]=Qy({_crumbs:[],_files:[],_selected:[],_sorts:{},path:"/",selected:[],...a[l]});const r={panels:Qy(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 Vk(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 Wk(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 Yk(n,a="data-id"){const r=Wk(n,a);return r?r.getAttribute(a):null}new Date().valueOf();function Kk(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 x;const b=v?.[0]?r.getFile(v[0]):null;v?.length?v.length>1?x=a.menuOptions("multiselect"):x=a.menuOptions(b.type,b):x=a.menuOptions("body");const j=`${g?"ctrl+":""}${w?"shift+":""}${d}`,C=x?x.find(M=>M.hotkey?.toLowerCase()===j):!1,k=a.performAction;if(C)switch(j){case"ctrl+c":k("copy");break;case"ctrl+x":k("move");break;case"ctrl+v":k("paste",b);break;case"delete":k("delete");break;case"ctrl+r":m.preventDefault(),k("rename",b);break;case"ctrl+d":m.preventDefault(),k("download",b);break;default:C.handler?.({context:b})}switch(d){case"enter":{if(g||w)break;const{_crumbs:M,_selectNavigation:A}=p;if(A){const T=Uk(M);if(T){const R=yp(T,M);r.exec("set-path",{id:T,selected:[R]})}}else if(v.length===1){const T=r.getFile(v[0]);T&&r.exec(T.type==="folder"?"set-path":"open-file",{id:T.id})}break}case"arrowup":case"arrowleft":{const{_files:M,_selected:A,path:T,_selectNavigation:R}=p;let P;if(A.length){const F=A.at(0).id,V=M.findIndex(_=>_.id===F);if(V!==-1){const _=V-1;M[_]?P=M[_].id:T!=="/"&&!(g||w)&&r.exec("select-file",{type:"navigation"})}}else{if(R)break;if(T!=="/"){r.exec("select-file",{type:"navigation"});break}P=M.at(0)?.id}P&&r.exec("select-file",{id:P,toggle:g,range:w});break}case"arrowdown":case"arrowright":{const{_files:M,_selected:A,path:T,_selectNavigation:R}=p;let P;if(A.length){const F=A.at(-1).id,V=M.findIndex(_=>_.id===F);if(V!==-1){const _=V+1;M[_]&&(P=M[_].id)}}else{if(T!=="/"&&!R){r.exec("select-file",{type:"navigation"});break}P=M.at(0)?.id}P&&r.exec("select-file",{id:P,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:+Yk(p,"data-panel")})})}return n.addEventListener("keydown",c),{destroy:()=>{n.removeEventListener("keydown",c)}}}function Qk(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 Xk(n,a="data-id"){const r=n.getAttribute(a);return r?Zk(r):null}function Zk(n){if(n.startsWith(":"))return n.substring(1);const a=n*1;return isNaN(a)?n:a}function Jk(){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 e1=Jk();new Date().valueOf();function zb(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 t1(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 ct(n,a){const r=n.getState(),l=n.getReactiveState();return t1(l[a],r[a],a)}function n1(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 ws(n,a){const r=n.getState(),l=n.getReactiveState();return n1(l[a],r[a])}function Ib(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 Ob(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 Jy(n,a,r){function l(c){const d=Qk(c);if(!d)return;const m=Xk(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 e1.addEvent(n,r,l)}function a1(n,a){const r=[Jy(n,a,"click")];return a.dblclick&&r.push(Jy(n,a.dblclick,"dblclick")),()=>{r.forEach(l=>l())}}function Hb(n,a){return n.map((r,l)=>{const c=a(r,l);return r.data&&r.data.length&&(c.data=Hb(r.data,a)),c}).filter(Boolean)}function Bb(n,a){const r=[];return n.forEach(l=>{if(l.data){const c=Bb(l.data,a);c.length&&r.push({...l,data:c})}else a(l)&&r.push(l)}),r}function s1(n){return Hb(n,(a,r)=>{const l={...a,id:a.id||up()};return l.type&&(l.comp=l.type),l.comp==="separator"&&n[r-1]?.comp==="separator"?null:l})}const Fb={};function i1(n){return Fb[n]||n}function r1(n,a){Fb[n]=a}function l1({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?i1(r.comp):null,[r]);return s.jsxs("div",{ref:l,className:`wx-cDCz9rZQ wx-option ${r.css||""} ${r.disabled?"wx-disabled":""}`,"data-id":Hn(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 xp({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,x]=u.useState(-1e4),[b,j]=u.useState(-1e4),[C,k]=u.useState(20),[M,A]=u.useState(),T=u.useRef(null),[R,P]=u.useState(!1),[F,V]=u.useState(null),_=u.useCallback(()=>{const re=Sb(T.current,c,l,a,r);re&&(x(re.x),j(re.y),A(re.width));let K=re?.z??20;const I=c?Kj(c):[];let ee=0;for(const G of I){const q=parseInt(getComputedStyle(G).zIndex,10);q>ee&&(ee=q)}ee>=K&&(K=ee+1),k(K)},[c,l,a,r]);u.useEffect(()=>{d&&d(_)},[]);const L=u.useCallback(()=>{P(!1)},[]),ne=u.useCallback((re,K)=>{P(re),V(K)},[]),W=u.useMemo(()=>s1(n),[n]);u.useEffect(()=>{_()},[c,_]);const J=u.useRef(v),O=u.useRef(g),be=u.useRef(c);return u.useEffect(()=>{J.current=v},[v]),u.useEffect(()=>{O.current=g},[g]),u.useEffect(()=>{be.current=c},[c]),u.useEffect(()=>{if(!T.current)return;function re(K){O.current?O.current(K):J.current&&J.current({action:null,option:null})}return mi(T.current,{callback:re,modal:!0,parent:()=>be.current}).destroy},[]),s.jsx("div",{ref:T,"data-wx-menu":"true",className:`wx-XMmAGqVx wx-menu ${p}`,style:{position:"absolute",top:b+"px",left:w+"px",width:M,zIndex:C},onMouseLeave:L,children:W.map(re=>s.jsxs(u.Fragment,{children:[re.comp==="separator"?s.jsx("div",{className:"wx-XMmAGqVx wx-separator"}):s.jsx(l1,{option:re,onShow:ne,onClick:K=>{if(!re.data&&!K.defaultPrevented){const I={context:m,action:re,option:re,event:K};re.handler&&re.handler(I),v&&v(I),K.stopPropagation()}}}),re.data&&R===re.id?s.jsx(xp,{css:p,options:re.data,at:"right-overlap",parent:F,context:m,onClick:v,onCancel:g}):null]},re.id))})}const Pb=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,x]=u.useState(null),[b,j]=u.useState(null),[C,k]=u.useState(0),[M,A]=u.useState(0),T=u.useRef(null),R=u.useMemo(()=>`data-${d.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,[d]),P=u.useMemo(()=>w!==null&&m?Bb(r,L=>m(L,w)):r,[w,m,r]);function F(L){j(null),g&&g(L)}function V(L){if(T.current===L){T.current=null;return}j(null),g&&g({action:null,option:null})}const _=u.useCallback((L,ne)=>{if(!L){j(null);return}if(L.defaultPrevented)return;const W=L.target;if(W&&W.dataset&&W.dataset.menuIgnore)return;if(b&&b===W){j(null),L.preventDefault();return}k(L.clientX+1),A(L.clientY+1);let J=typeof ne<"u"?ne:nu(W,R);c&&(J=c(J,L),!J)||(x(J),j(W),T.current=L.nativeEvent||L,L.preventDefault())},[b,R,c]);return u.useImperativeHandle(a,()=>({show:_}),[_]),s.jsxs(s.Fragment,{children:[v?s.jsx("span",{onClick:_,"data-menu-ignore":"true",children:typeof v=="function"?v():v}):null,b?s.jsx(fp,{children:s.jsx(xp,{css:p,at:l,top:M,left:C,parent:b,context:w,onClick:F,onCancel:V,options:P},b)}):null]})}),o1=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 x(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 k=C.target;for(;!k.dataset.menuIgnore;)v(k),k=k.parentNode}return s.jsxs(s.Fragment,{children:[s.jsx("span",{onClick:j,"data-menu-ignore":"true",children:d}),p?s.jsx(fp,{children:s.jsx(xp,{css:c,at:l,parent:p,options:r,onClick:w,onCancel:x})}):null]})}),c1=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),x=u.useCallback((b,j)=>{w.current.show(b,j)},[]);return u.useImperativeHandle(a,()=>({show:x}),[x]),s.jsxs(s.Fragment,{children:[v?s.jsx("span",{onContextMenu:x,"data-menu-ignore":"true",children:v}):null,s.jsx(Pb,{css:p,at:l,options:r,resolver:c,dataKey:d,filter:m,ref:w,onClick:g})]})}),u1={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 d1=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 $b(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 d1(r,c,m,v,n)),g.current.files=a,g.current.ready=l,g.current.signal=d,g.current.drag=p,g.current}function f1(n,a){{if(n){const r=n.getGroup(a);if(r)return r}return su(u1).getGroup(a)}}const m1=()=>Math.random().toString(36).substr(2,9),h1=({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),x=u.useRef(null),[b,j]=u.useState({}),C=$b(),k=n||C,M=u.useContext(Fn.i18n),A=f1(M,"uploader");u.useEffect(()=>{w.current&&l&&(w.current.webkitdirectory=!0)},[l]),u.useEffect(()=>{if(!d&&x.current&&!m)return k.droparea(x.current)},[d,m,x]);const T=W=>{const J=new FormData;return J.append("upload",W.file),fetch(c,{method:"POST",body:J}).then(O=>O.json()).then(O=>({id:W.id,...O}),()=>({id:W.id,status:"error"})).catch(O=>(console.log(O),{id:W.id,status:"error"}))},R=(W,J)=>{const O=k.updateFile(W,J),be={...O,status:k.getState()};O&&O.uploaded&&O.uploaded(be),g&&g(be),O.temp&&k.deleteFile(O.id)},P=W=>{if(!W)return;const J=typeof c=="function"?c(W):T(W);k.setReady(J.then(O=>{O.status=O.status||"server",R(W.id,O)}).catch(O=>{R(W.id,{status:"error",error:O})}))},F=(W,J)=>{const O={...J||b,id:m1(),status:"client",name:W.name,file:W};O.selected&&O.selected(O),v&&v(O),k.addFile(O,r),P(O),w.current&&(w.current.value="")},V=(W,J,O)=>{W.isFile?W.file(be=>{F(be,O)}):W.isDirectory&&W.createReader().readEntries(be=>{be.forEach(re=>{V(re,J+re.name+"/",O)})})},_=W=>{Array.from(W.target.files).forEach(J=>F(J))},L=(W,J)=>{Array.from(W.dataTransfer.items).forEach(O=>{const be=O.webkitGetAsEntry();be&&V(be,"",J)})},ne=()=>{w.current&&w.current.click()};return u.useEffect(()=>{if(k.signal){const[W,J,O]=k.signal;j(J),W==="click"?ne():W==="drop"&&L(O,J),k.setSignal(null)}},[k.signal]),d?s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:_,accept:a,multiple:r,disabled:m}),p]}):s.jsxs("div",{className:`wx-at1A8tb8 wx-label ${k.drag?"wx-active":""} ${m?"wx-disabled":""}`,ref:x,children:[s.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:_,accept:a,multiple:r,disabled:m}),p||s.jsx("div",{className:"wx-at1A8tb8 wx-dropzone",children:s.jsxs("span",{children:[A("Drop files here or")," ",s.jsx("span",{className:"wx-at1A8tb8 wx-action",onClick:ne,children:A("select files")})]})})]})};new Date().valueOf();function p1(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 p1(n,a);return n===a}function Fh(n){if(typeof n!="object"||n===null)return n;if(n instanceof Date)return new Date(n);if(n instanceof Array)return n.map(Fh);const a={};for(const r in n)a[r]=Fh(n[r]);return a}var Ub=2,g1=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&Ub?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}}}},v1=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=>qb(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,Ub);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 qb(n,a,r){const l=a.get(n);if(!l)return r;const c=Object.keys(l).map(d=>qb(d,a,r+1));return Math.max(...c)}var y1=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 x1(n){return a=>a[n]}function b1(n){return(a,r)=>a[n]=r}function Yr(n,a){return(a.getter||x1(a.id))(n)}function lh(n,a,r){return(a.setter||b1(a.id))(n,r)}function w1(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 Wr(n,a){let r=Yr(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 S1(n,a){const r=/\n|"|;|,/;let l="";const c=a.rows||`
13
- `,d=a.cols||" ",m=n._columns,p=n.flatData;a.header!==!1&&m[0].header&&(l=ex("header",m,l,d,c));for(let v=0;v<p.length;v++){const g=[];for(let w=0;w<m.length;w++){let x=Wr(p[v],m[w]);r.test(x)&&(x='"'+x.replace(/"/g,'""')+'"'),g.push(x)}l+=(l?c:"")+g.join(d)}return a.footer!==!1&&m[0].footer&&(l=ex("footer",m,l,d,c)),l}function ex(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 C1="portrait",j1=100,k1="a4",A1={a3:{width:11.7,height:16.5},a4:{width:8.27,height:11.7},letter:{width:8.5,height:11}};function N1(n,a){const r=[];let l=[],c=0;const d=n.filter(p=>!p.hidden),m=M1(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 tx(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],x=v.width;for(;!w.rowspan&&!w.colspan;)g++,w=n[d+g][a][p],x+=w.width;v.colspan=g,v.width=x,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((x,b)=>x+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(x=>x?.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 M1(n){const{mode:a,ppi:r,paper:l}=n,{width:c,height:d}=A1[l];return T1(a==="portrait"?c:d,r)}function T1(n,a){return n*a}function E1(n={}){const{mode:a,ppi:r,paper:l}=n;return{mode:a||C1,ppi:r||j1,paper:l||k1}}function Gb(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 R1(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 nx=["resize-column","hide-column","update-cell"],D1=["delete-row","update-row","update-cell"],L1=["move-item"],_1=["resize-column","move-item"];class z1{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=Yr(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(_1.includes(r)){(l.inProgress&&!this.progress[r]||typeof l.inProgress!="boolean")&&(L1.includes(r)&&this.setPrev("flatData"),nx.includes(r)&&this.setPrev("columns")),this.progress[r]=l.inProgress;return}D1.includes(r)&&this.setPrev("data"),nx.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]=Fh(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 Vb(n,a){return typeof n>"u"||n===null?-1:typeof a>"u"||a===null?1:n===a?0:n>a?1:-1}function I1(n,a){return-Vb(n,a)}function O1(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"?Vb:I1;return function(l,c){return r(Yr(l,a),Yr(c,a))}}function H1(n,a){if(!n||!n.length)return;const r=n.map(l=>{const c=a.find(d=>d.id==l.key);return O1(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 Nd=28,B1=20;function F1(){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 ef(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 x=d.getBoundingClientRect(),b=Math.ceil(x.width)+(l&&l.length?l[w]:0),j=Math.ceil(x.height);v=Math.max(v||0,b),g=Math.max(g||0,j)}return d.remove(),{width:v,height:g}}function ax(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:x,collapsed:b,rowspan:j,css:C}=p[g];if(!w){d[g]=Math.max(d[g]||0,l);continue}let k=0;if(x&&!b){let M=`wx-measure-cell-${a}`;if(M+=C?` ${C}`:"",k=ef(w,M,c).width,(j>1||!p[g+1])&&r>g+1){const A=j||r-g,T=d.slice(g,g+A).reduce((R,P)=>R+P,0);if(T<k){const R=Math.ceil((k-T)/A);for(let P=g;P<g+A;P++)d[P]=(d[P]||l)+R}continue}}d[g]=Math.max(d[g]||l,k)}}return d}function P1(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=Wr(p,n);v&&(l.push(v),n.treetoggle?c.push(a[m].$level*Nd+(a[m].$count?Nd:0)+(n.draggable?Nd:0)):n.draggable&&c.push(Nd))}return ef(l,d,r,c).width}function $1(n,a){const r="wx-measure-cell-header",l=n.sort?B1:0;let c=n.header;if(typeof c=="string")return ef(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=ef(v,g,a).width;m===c.length-1&&(w+=l),d=Math.max(d||0,w)}return d}const U1={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&&G1(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 Wb(n){return U1[n]}function q1(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=Yr(v,c);return d?.handler?d.handler(g,p):Wb(m)(g,p)})}return l=>{for(let c=0;c<r.length;c++)if(!r[c](l))return!1;return!0}}function G1(n,a){return n.getFullYear()===a.getFullYear()&&n.getMonth()===a.getMonth()&&n.getDate()===a.getDate()}let V1=class extends g1{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 v1(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 x=this.normalizeSizes(v,m,g,w,p);for(let b=0;b<v.length;b++)this.normalizeColumns(v,b,"header",g,x),this.normalizeColumns(v,b,"footer",w,x);this.setState({_columns:v,_sizes:x},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,x=!p&&w.some(b=>b.rowHeight);this.setState({flatData:w,_rowHeightFromData:x},c)}}],{sizes:c=>({...r,...c})});const l=this.in=new y1;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:Yr(p,v)??"",renderedValue:Wr(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)};lh(p,m,c),d.renderedValue=Wr(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:x,select:b}=c;if(c.id=g.id=c.id||g.id||Md(),w||x){const C=w||x,k=m.findIndex(M=>M.id===C);m=[...m],m.splice(k+(x?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(x=>x.id!==g)};this.isSelected(g)&&(w.selectedRows=m.filter(x=>x!==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,x=this.getColumn(g);if(p){const b={...this._branches[v]};lh(b,x,w);const j=this.updateTreeRow(b);b.$parent===0&&(m=j)}else{const b=m.findIndex(C=>C.id===v),j={...m[b]};lh(j,x,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:x}=w;let{selectedRows:b}=w;if(b.length||(m=d=!1),m){const{data:j}=this.getState();let C=j.findIndex(M=>M.id===b[b.length-1]),k=j.findIndex(M=>M.id===c);C>k&&([C,k]=[k,C]),j.slice(C,k+1).forEach(M=>{this.isSelected(M.id)||b.push(M.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]}),x?.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],x=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 k=b.slice(0,C);g=P1(x,k,j)}if(m==="header"||m===!0){const{_skin:b}=this.getState();g=Math.max($1(x,b),g)}}x.width=Math.max(17,g),delete x.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,x)=>w+(x.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:x}=v;if(p){const T=[...w];T.sort(p),this.setState({data:T});return}const{order:b="asc"}=c;let j=v.sortMarks;const C=Object.keys(j),k=C.length;!m||!k||k===1&&j[d]?j={[d]:{order:b}}:(k===1&&(j[C[0]]={...j[C[0]],index:0}),j={...j,[d]:{order:b,index:typeof m=="number"?m:j[d]?.index??k}});const M=Object.keys(j).sort((T,R)=>j[T].index-j[R].index).map(T=>({key:T,order:j[T].order}));this.setState({sortMarks:j});const A=H1(M,g);if(A){const T=[...w];x?this.sortTree(T,A):T.sort(A),this.setState({data:T})}}),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:x}=v;let b=v.filterValues;const j={};m&&(b={...b,[m]:d},j.filterValues=b);const C=p??q1(b,x);let k=[];w?k=this.filterTree(g,C,k):g.forEach(M=>{C(M)&&k.push(M.id)}),j._filterIds=k,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:x}=this.getState(),b=w.findIndex(k=>k.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(k=>k.id===p);if(b===-1||j===-1||m===!1)return;let C;x||(C=this.moveItem(d,p,g,v)),this.setState({data:x?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:x}=v;const b=this.getRow(d);if(!b)return;const j={...b,id:Md()};c.id=j.id;const C=g.findIndex(M=>M.id===m);if(C===-1)return;x.splice(C+(p==="after"?1:0),0,j),x=[...x];const k={data:x};w&&(k._filterIds=[...w,j.id]),this.setState(k)}),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=S1(this.getState(),c.csv||{});c.download!==!1?w1(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,x=v?this.getPrevRow(v.row)?.id:p[p.length-1]?.id;w&&x&&(this.in.exec("focus-cell",{row:x,column:w,eventSource:"key"}),g&&this.in.exec("select-row",{id:x}));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,x=v?this.getNextRow(v.row)?.id:p[0]?.id;w&&x&&(this.in.exec("focus-cell",{row:x,column:w,eventSource:"key"}),g&&this.in.exec("select-row",{id:x}));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 x=p.id,b=this.getNextEditor(this.getRow(x),this.getColumn(w));if(!b){const j=this.getNextRow(x);j&&(x=j.id,b=this.getNextEditor(j))}b&&(this.in.exec("open-editor",{id:x,column:b.id}),this.in.exec("focus-cell",{row:x,column:b.id,eventSource:"key"}),g&&!this.isSelected(x)&&this.in.exec("select-row",{id:x}))}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 x=p.id,b=this.getPrevEditor(this.getRow(x),this.getColumn(w));if(!b){const j=this.getPrevRow(x);j&&(x=j.id,b=this.getPrevEditor(j))}b&&(this.in.exec("open-editor",{id:x,column:b.id}),this.in.exec("focus-cell",{row:x,column:b.id,eventSource:"key"}),g&&!this.isSelected(x)&&this.in.exec("select-row",{id:x}))}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 x=g[0]?.id,b=this._getFirstVisibleColumn()?.id;x&&b&&(this.in.exec("focus-cell",{row:x,column:b,eventSource:"key"}),w&&!this.isSelected(x)&&this.in.exec("select-row",{id:x}))}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 x=g.at(-1).id,b=this._getLastVisibleColumn()?.id;x&&b&&(this.in.exec("focus-cell",{row:x,column:b,eventSource:"key"}),w&&!this.isSelected(x)&&this.in.exec("select-row",{id:x}))}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 x=-1,b=-1,j=0,C=0;if(c.column){x=0;const k=d.findIndex(M=>M.id===c.column);j=d[k].width;for(let M=m.left??0;M<k;M++){const A=d[M];A.hidden||(x+=A.width)}}if(c.row&&!g){const k=v.findIndex(M=>M.id===c.row);k>=0&&(w?(b=v.slice(0,k).reduce((M,A)=>M+(A.rowHeight||p.rowHeight),0),C=v[k].rowHeight):b=p.rowHeight*k)}this.setState({scroll:{top:b,left:x,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=E1(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=F1()),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 z1(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 x=l[r+w];x&&(x.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 x=1;x<w.rowspan;x++){p.splice(g+x,0,{_hidden:!0});for(let b=1;b<w.colspan;b++)a[r+b][l].splice(g+x,0,{})}if(w.rowspan){const x=(w.rowspan===c?v:v.slice(g,w.rowspan+g)).reduce((b,j)=>b+j,0);w.height=x,g+w.rowspan!=c&&w.height--}if(w.colspan){let x=m.width,b=m.flexgrow||0;const j=w.colspan;for(let C=1;C<j;C++){const k=a[r+C];k&&(k.hidden?w.colspan-=1:k.flexgrow?b+=k.flexgrow:x+=k.width||d.columnWidth),b?w.flexgrow=b:w.width=x}}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=Md());return a}normalizeTreeRows(a,r,l){return!r&&!l&&(this._branches={0:{data:a}}),a.forEach(c=>{c.id||(c.id=Md()),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=Yr(g,d);return m?.handler?m.handler(w,v):Wb(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=Wr(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=ax(a,"header",l,r.headerHeight,d),p=ax(a,"footer",c,r.footerHeight,d),v=m.reduce((w,x)=>w+x,0),g=p.reduce((w,x)=>w+x,0);return{...r,headerRowHeights:m,footerRowHeights:p,headerHeight:v,footerHeight:g}}},W1=new Date().valueOf();function Md(){return"temp://"+W1++}function Y1(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 K1=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)}}},Mo=[],Q1={subscribe:n=>{X1();const a=new K1;return Mo.push(a),n(a),()=>{const r=Mo.findIndex(l=>l===a);r>=0&&Mo.splice(r,1)}}},sx=!1;function X1(){sx||(sx=!0,document.addEventListener("keydown",n=>{if(Mo.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=Mo.length-1;c>=0;c--){const d=Mo[c],m=d.store.get(l)||d.store.get(r);m&&d.node.contains(n.target)&&m(n,{key:l,evKey:r})}}}))}const Z1={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 J1(n,{keys:a,exec:r}){if(!a)return;function l(m){const p=m.target;return p.tagName==="INPUT"||p.tagName==="TEXTAREA"||Y1(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=Q1.subscribe(m=>{m.configure(c,n)});return{destroy:()=>{d()}}}function eA(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 x=n.scrollTop;d<x?n.scrollTop=d:d+m>x+v&&(n.scrollTop=d-v+m)}if(c>=0){const x=n.scrollLeft;c<x?n.scrollLeft=c:c+p>x+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 ts=u.createContext(null);function tA(n,a){const r=new ResizeObserver(l=>{requestAnimationFrame(()=>a(l[0].contentRect))});return r.observe(n.parentNode),{destroy(){r.disconnect()}}}const ix=5,nA=700;function Pd(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 Ph(n,a){const r=Pd(a);return{x:n.clientX-r.x,y:n.clientY-r.y}}function aA(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(_){const L=Ro(_);L&&(l={container:v,sourceNode:_.target,from:uf(L),pos:Ph(_,n)},d=l.pos,x(_))}function x(_){if(!l)return;const L=l.pos=Ph(_,n);if(!m){if(!p&&!_?.target?.getAttribute("draggable-data")&&Math.abs(d.x-L.x)<ix&&Math.abs(d.y-L.y)<ix)return;if(F(_)===!1)return V()}if(p){const ne=window.scrollX||document.documentElement.scrollLeft||document.body.scrollLeft,W=window.scrollY||document.documentElement.scrollTop||document.body.scrollTop;l.targetNode=document.elementFromPoint(_.pageX-ne,_.pageY-W)}else l.targetNode=_.target;r.move&&r.move(_,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(_){v.parentNode&&v.parentNode.removeChild(v),v.innerHTML="",m&&r.end&&r.end(_,l),l=d=null,V()}function j(_){r.getReorder&&!r.getReorder()||_.button===0&&(P(_),window.addEventListener("mousemove",C),window.addEventListener("mouseup",k),w(_))}function C(_){x(_)}function k(_){b(_)}function M(_){if(r.getReorder&&!r.getReorder())return;c=setTimeout(()=>{p=!0,w(_.touches[0])},nA),P(_);function L(){c&&g(),_.target.removeEventListener("touchmove",A),_.target.removeEventListener("touchend",L),b(_)}_.target.addEventListener("touchmove",A),_.target.addEventListener("touchend",L),n.addEventListener("contextmenu",T)}function A(_){m?(_.preventDefault(),x(_.touches[0])):c&&g()}function T(_){if(m||c)return _.preventDefault(),!1}function R(_){_.preventDefault()}function P(_){if(!r.getDraggableInfo)return;const{hasDraggable:L}=r.getDraggableInfo();(!L||_.target.getAttribute("draggable-data"))&&(document.body.style.userSelect="none",document.body.style.webkitUserSelect="none")}function F(_){if(m=!0,r.start){if(r.start(_,l)===!1)return!1;n.appendChild(v),document.body.style.cursor="move"}}function V(_){m=p=!1,document.body.style.cursor="",document.body.style.userSelect="",document.body.style.webkitUserSelect="",window.removeEventListener("mousemove",C),window.removeEventListener("mouseup",k),_&&(n.removeEventListener("mousedown",j),n.removeEventListener("touchstart",M),n.removeEventListener("dragstart",R))}return n.addEventListener("mousedown",j),n.addEventListener("touchstart",M),n.addEventListener("dragstart",R),{destroy(){V(!0)}}}const sA=.004;function iA(){return{dirX:0,dirY:0,scrollSpeedFactor:1}}function rA(n,a,r,l){const{node:c,left:d,top:m,bottom:p,sense:v,xScroll:g,yScroll:w}=l,x=Ph(n,c);r.scrollState||(r.scrollState=iA());let b=0,j=0;x.x<d+v?b=-1:x.x>a.width-v&&(b=1),x.y<m+Math.round(v/2)?j=-1:x.y>a.height-p-Math.round(v/2)&&(j=1),(r.scrollState.dirX!==b||r.scrollState.dirY!==j)&&(Yb(r),r.scrollState.dirX=b,r.scrollState.dirY=j),(g&&r.scrollState.dirX!==0||w&&r.scrollState.dirY!==0)&&lA(r,l,{x:r.scrollState.dirX,y:r.scrollState.dirY})}function lA(n,a,r){n.autoScrollTimer||(n.autoScrollTimer=setTimeout(()=>{n.activeAutoScroll=setInterval(oA,15,n,a,r)},250))}function Yb(n){n.scrollSpeedFactor=1,n.autoScrollTimer&&(n.autoScrollTimer=clearTimeout(n.autoScrollTimer),n.activeAutoScroll=clearInterval(n.activeAutoScroll))}function oA(n,a,r){const{x:l,y:c}=r;n.scrollSpeedFactor+=sA,l!==0&&uA(n,a,l),c!==0&&cA(n,a,c)}function cA(n,a,r){const l=a.node.scrollTop;Kb(l+Math.round(a.sense/3)*n.scrollSpeedFactor*r,"scrollTop",a)}function uA(n,a,r){const l=a.node.scrollLeft;Kb(l+Math.round(a.sense/3)*n.scrollSpeedFactor*r,"scrollLeft",a)}function Kb(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 Qb(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 dA(n){const{row:a,column:r,cellStyle:l=null,columnStyle:c=null,children:d,focusable:m}=n,p=u.useContext(ts),v=ct(p,"focusCell"),g=ct(p,"search"),w=ct(p,"reorder"),x=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,V){let _="wx-cell";return _+=r.fixed?" "+(r.fixed===-1?"wx-shadow":"wx-fixed"):"",_+=F?" "+F(r):"",_+=V?" "+V(a,r):"",_+=r.treetoggle?" wx-tree-cell":"",_}const C=u.useMemo(()=>j(c,l),[c,l,r,a]),k=u.useMemo(()=>typeof r.draggable=="function"?r.draggable(a,r)!==!1:r.draggable,[r,a]),M=u.useRef(null);u.useEffect(()=>{M.current&&m&&v?.row===a.id&&v?.column===r.id&&M.current.focus()},[v,m,a.id,r.id]);const A=u.useCallback(()=>{m&&!v&&p.exec("focus-cell",{row:a.id,column:r.id,eventSource:"focus"})},[p,m,v,a.id,r.id]);function T(F){const V=new RegExp(`(${g.value.trim()})`,"gi");return String(F).split(V).map(_=>({text:_,highlight:V.test(_)}))}const R=u.useMemo(()=>{const F=r.fixed&&r.fixed.left===-1||r.fixed.right===-1,V=r.fixed&&r.fixed.right;return[C,F?"wx-shadow":"",V?"wx-fixed-right":""].filter(Boolean).join(" ")},[C,r]),P=r.cell;return s.jsxs("div",{className:"wx-TSCaXsGV "+R,ref:M,onFocus:A,style:b,"data-row-id":Hn(a.id),"data-col-id":Hn(r.id),tabIndex:m?"0":"-1",role:"gridcell","aria-colindex":r._colindex,"aria-readonly":r.editor?void 0:!0,children:[w&&r.draggable?k?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,P?s.jsx(P,{api:p,row:a,column:r,onAction:({action:F,data:V})=>p.exec(F,V)}):d?d():x?s.jsx("span",{children:T(Wr(a,r)).map(({highlight:F,text:V},_)=>F?s.jsx("mark",{className:"wx-TSCaXsGV wx-search",children:V},_):s.jsx("span",{children:V},_))}):Wr(a,r)]})}function rx(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 fA({filter:n,column:a,action:r,filterValue:l}){function c({value:d}){r({value:d,key:a.id})}return s.jsx(hp,{...n.config??{},value:l,onChange:c})}function mA({filter:n,column:a,action:r,filterValue:l}){const c=u.useContext(ts),d=ct(c,"flatData"),m=u.useMemo(()=>n?.config?.options||a?.options||v(),[n,a,d]),p=u.useMemo(()=>n?.config?.template,[n]);function v(){const x=[];return d.forEach(b=>{const j=Yr(b,a);x.includes(j)||x.push(j)}),x.map(b=>({id:b,label:b}))}function g({value:x}){r({value:x,key:a.id})}function w(x){x.key!=="Tab"&&x.preventDefault()}return s.jsx("div",{style:{width:"100%"},onKeyDown:w,children:s.jsx(Nk,{placeholder:"",clear:!0,...n?.config??{},options:m,value:l,onChange:g,children:x=>p?p(x):x.label})})}function hA({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(Ak,{placeholder:"",clear:!0,...n?.config??{},value:l,onChange:c})})}function Xb(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:x}=n,[b,j]=zb(a||[]),C=u.useMemo(()=>(b||[]).map(W=>r.find(J=>J.id===W)).filter(Boolean),[b,r]),k=u.useRef(null),M=u.useRef(null),[A,T]=u.useState(null),R=()=>{const W=b||[];if(!W.length)return 0;const J=r.find(O=>W.includes(O.id));return J?r.indexOf(J):0};function P(W){M.current=W.navigate,T(()=>W.keydown),g&&W.navigate(R())}u.useEffect(()=>{g&&(k.current?.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges())},[]);function F({id:W}){j(W),w&&w({value:W})}function V(W){W.stopPropagation(),j([]),w&&w({value:[]})}function _(){M.current?.(R())}function L(){M.current?.(null)}function ne(W){A?.(W,R())}return s.jsxs("div",{ref:k,className:"wx-multiselect wx-aadNNOwy",onClick:_,onKeyDown:ne,tabIndex:0,children:[s.jsx("div",{className:"wx-label wx-aadNNOwy",children:m?m(C):p?s.jsx(p,{data:C,onAction:x}):d?s.jsx("span",{className:"wx-text wx-aadNNOwy",children:d}):C.length?s.jsx("span",{className:"wx-text wx-aadNNOwy",children:C.map(W=>W.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:V}):s.jsx("i",{className:"wx-icon wxi-angle-down wx-aadNNOwy"}),s.jsx(ff,{items:r,onReady:P,onSelect:F,multiselect:!0,checkboxes:!0,value:b||[],onCancel:L,...v,children:({option:W})=>s.jsx("div",{className:"wx-option wx-aadNNOwy",children:m?m(W):p?s.jsx(p,{data:W,onAction:x}):W.label})})]})}function pA({filter:n,column:a,action:r,filterValue:l}){const c=u.useContext(Fn.i18n)?.getGroup("grid")||su(vp).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(x=>a.optionsMap.get(x)).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(Xb,{placeholder:"",...d,options:m,value:l||[],text:p,onChange:v})})}const gA={text:fA,richselect:mA,datepicker:hA,multiselect:pA};function vA({filter:n,column:a}){const r=u.useContext(ts),l=ct(r,"filterValues");function c(m){r.exec("filter-rows",m)}const d=u.useMemo(()=>gA[n.type],[n.type]);return s.jsx(d,{filter:n,column:a,action:c,filterValue:l[a.id]})}function yA(n){const{cell:a,column:r,row:l,lastRow:c,sortRow:d,columnStyle:m,bodyHeight:p,hasSplit:v}=n,g=u.useContext(ts),w=ct(g,"sortMarks"),x=u.useMemo(()=>w?w[r.id]:void 0,[w,r.id]),b=u.useRef(),j=u.useCallback(re=>{b.current=a.flexgrow?re.parentNode.clientWidth:a.width},[a.flexgrow,a.width]),C=u.useCallback((re,K)=>{g.exec("resize-column",{id:a.id,width:Math.max(1,(b.current||0)+re),inProgress:K})},[g,a.id]),k=u.useCallback(re=>C(re,!0),[C]),M=u.useCallback(re=>C(re,!1),[C]),A=u.useCallback(re=>{if(!r.sort||a.filter)return;let K=x?.order;K&&(K=K==="asc"?"desc":"asc"),g.exec("sort-rows",{key:a.id,add:re.ctrlKey||re.metaKey,order:K})},[g,a.id,a.filter,r.sort,x?.order]),T=u.useCallback(re=>{re&&re.stopPropagation(),g.exec("collapse-column",{id:a.id,row:l})},[g,a.id,l]),R=u.useCallback(re=>{re.key==="Enter"&&T()},[T]),P=u.useCallback(re=>{re.key==="Enter"&&!a.filter&&A(re)},[A,a.filter]),F=u.useMemo(()=>a.collapsed&&r.collapsed,[a.collapsed,r.collapsed]),V=u.useMemo(()=>F&&!v&&a.collapsible!=="header",[F,v,a.collapsible]),_=u.useMemo(()=>V?{top:-p/2,position:"absolute"}:{},[V,p]),L=u.useMemo(()=>hf(a.width,a.flexgrow,r.fixed,r.left,a.right??r.right,a.height+(F&&V?p:0)),[a.width,a.flexgrow,r.fixed,r.left,a.right,r.right,a.height,F,V,p]),ne=u.useMemo(()=>Qb(r,a,m),[r,a,m]),W=u.useCallback(()=>Object.fromEntries(Object.entries(a).filter(([re])=>re!=="cell")),[a]),J=`wx-cell ${ne} ${a.css||""} wx-collapsed`,O=["wx-cell",ne,a.css||"",a.filter?"wx-filter":"",r.fixed&&r.fixed.right?"wx-fixed-right":""].filter(Boolean).join(" "),be=u.useRef(null);return u.useEffect(()=>{const re=be.current;if(!re)return;const K=rx(re,{down:j,move:k,up:M});return()=>{typeof K=="function"&&K()}},[j,k,M,rx]),F?s.jsx("div",{className:"wx-RsQD74qC "+J,style:L,role:"button","aria-label":`Expand column ${a.text||""}`,"aria-expanded":!a.collapsed,tabIndex:0,onKeyDown:R,onClick:T,"data-header-id":Hn(r.id),children:s.jsx("div",{className:"wx-RsQD74qC wx-text",style:_,children:a.text||""})}):s.jsxs("div",{className:"wx-RsQD74qC "+O,style:L,onClick:A,"data-header-id":Hn(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":!x?.order||a.filter?"none":x?.order==="asc"?"ascending":"descending",onKeyDown:P,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:T,children:s.jsx("i",{className:`wx-RsQD74qC wxi-angle-${a.collapsed?"down":"right"}`})}):null,a.cell?(()=>{const re=a.cell;return s.jsx(re,{api:g,cell:W(),column:r,row:l,onAction:({action:K,data:I})=>g.exec(K,I)})})():a.filter?s.jsx(vA,{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:be,onClick:re=>re.stopPropagation(),children:s.jsx("div",{})}):null,d?s.jsx("div",{className:"wx-RsQD74qC wx-sort",children:x?s.jsxs(s.Fragment,{children:[typeof x.index<"u"?s.jsx("div",{className:"wx-RsQD74qC wx-order",children:x.index+1}):null,s.jsx("i",{className:`wx-RsQD74qC wxi-arrow-${x.order==="asc"?"up":"down"}`})]}):null}):null]})}function xA({cell:n,column:a,row:r,columnStyle:l}){const c=u.useContext(ts),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(()=>Qb(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?tp.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 lx({deltaLeft:n,contentWidth:a,columns:r,type:l="header",columnStyle:c,bodyHeight:d}){const m=u.useContext(ts),p=ct(m,"_sizes"),v=ct(m,"split"),g=u.useMemo(()=>p?.[`${l}RowHeights`],[p,l]),w=u.useMemo(()=>{let k=[];if(r&&r.length){const M=r[0][l].length;for(let A=0;A<M;A++){let T=0;k.push([]),r.forEach((R,P)=>{const F={...R[l][A]};T||k[A].push(F),F.colspan>1?T=F.colspan-1:T&&T--})}}return k},[r,l]),x=u.useMemo(()=>v?.left||v?.right,[v]);function b(k){return r.find(M=>M.id===k)}function j(k,M){let A=M;return k.rowspan&&(A+=k.rowspan-1),A===w.length-1}function C(k,M,A){if(!A.sort)return!1;for(let T=w.length-1;T>=0;T--){const R=A.header[T];if(!R.filter&&!R._hidden)return M===T}return j(k,M)}return s.jsx("div",{className:`wx-sAsPVaUK wx-${l}`,style:{paddingLeft:`${n}px`,width:`${a}px`},role:"rowgroup",children:w.map((k,M)=>s.jsx("div",{className:l==="header"?"wx-sAsPVaUK wx-h-row":"wx-sAsPVaUK wx-f-row",style:{height:`${g?.[M]}px`,display:"flex"},role:"row",children:k.map(A=>{const T=b(A.id);return l==="header"?s.jsx(yA,{cell:A,columnStyle:c,column:T,row:M,lastRow:j(A,M),bodyHeight:d,sortRow:C(A,M,T),hasSplit:x},A.id):s.jsx(xA,{cell:A,columnStyle:c,column:b(A.id),row:M},A.id)})},M))})}function bA({overlay:n}){const a=u.useContext(ts);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 wA(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=mi(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||[]),x=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]),k=u.useMemo(()=>(g||[]).findIndex(_=>_.id===d),[g,d]),M=u.useRef(null),A=u.useRef(null),T=u.useCallback(_=>{M.current=_.navigate,A.current=_.keydown,M.current(k)},[k,M]),R=u.useCallback(_=>{const L=_?.target?.value??"";v(L);const ne=L?(n?.options||[]).filter(W=>(W.label||"").toLowerCase().includes(L.toLowerCase())):n?.options||[];w(ne),ne.length?M.current(-1/0):M.current(null)},[n]),P=u.useRef(null);u.useEffect(()=>{P.current&&P.current.focus()},[]);const F=u.useRef(r);u.useEffect(()=>{F.current=r},[r]),u.useEffect(()=>{if(!P.current)return;const _=mi(P.current,()=>F.current(!0));return()=>_.destroy()},[]),u.useEffect(()=>{m(n?.value),v(n?.renderedValue),w(n?.options||[])},[n]);const V=u.useCallback(({id:_})=>{l(_),r()},[l,r]);return s.jsxs(s.Fragment,{children:[s.jsx("input",{className:"wx-0UYfSd1x wx-input",ref:P,value:p??"",onChange:R,onKeyDown:_=>A.current?A.current(_,k):void 0}),s.jsx(ff,{items:g,onReady:T,onSelect:V,...C,onCancel:c,children:({option:_})=>x?x(_):b?s.jsx(b,{data:_,onAction:a}):_.label})]})}function CA({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 x=u.useRef(null),[b,j]=u.useState(null);return u.useEffect(()=>{x.current&&x.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),u.useEffect(()=>{if(!b)return;const C=mi(b,()=>r(!0));return()=>C.destroy()},[b,r]),s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"wx-lNWNYUb6 wx-value",ref:x,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(mp,{...g,onCancel:c,children:s.jsx("div",{ref:j,className:"wx-lNWNYUb6",children:s.jsx(Eb,{value:d,onChange:w,buttons:n.config?.buttons})})})]})}function jA(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),[x]=u.useState(a.options),b=u.useMemo(()=>x.findIndex(R=>R.id===w),[x,w]);function j({id:R}){c(R),l()}let C;const[k,M]=u.useState();function A(R){C=R.navigate,M(()=>R.keydown),C(b)}const T=u.useRef(null);return u.useEffect(()=>{T.current&&T.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),u.useEffect(()=>{if(!T.current)return;const R=mi(T.current,()=>l(!0));return()=>R.destroy()},[l]),s.jsxs(s.Fragment,{children:[s.jsx("div",{ref:T,className:"wx-ywGRk611 wx-value",tabIndex:0,onClick:d,onKeyDown:R=>{k(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:x,onReady:A,onSelect:j,...v,onCancel:d,children:({option:R})=>m.template?m.template(R):m.cell?(()=>{const P=m.cell;return s.jsx(P,{data:R,onAction:r})})():R.label})]})}function kA(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 x=u.useRef(null);return u.useEffect(()=>{if(!x.current)return;const b=mi(x.current,()=>l(!0));return()=>b.destroy()},[l]),s.jsx("div",{ref:x,className:"wx-value wx-aacZ4gNU",onClick:()=>l(!0),children:s.jsx(Xb,{value:p,options:m,text:v,template:d.template,cell:d.cell,clear:d.clear,dropdown:g,autoOpen:!0,onChange:w,onAction:r})})}const AA={text:wA,combo:SA,datepicker:CA,richselect:jA,multiselect:kA};function NA({column:n,row:a}){const r=u.useContext(ts),l=ct(r,"editor"),c=u.useCallback((C,k)=>{r.exec("close-editor",{ignore:C}),k&&r.exec("focus-cell",{...k,eventSource:"click"})},[r]),d=u.useCallback(C=>{const k=C?null:{row:l?.id,column:l?.column};c(!1,k)},[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 k=typeof C=="string"?C:C.type;return AA[k]},[n,a]),x=u.useRef(null);u.useEffect(()=>{x.current&&typeof g=="string"&&x.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:x,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:k})=>r.exec(C,k)}):null})}function ox(n){const{columns:a,type:r,columnStyle:l}=n,c=u.useContext(ts),{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(x=>{const b=m.find(k=>k.id===x.id),j=`wx-print-cell-${r}${v(b)}${x.filter?" wx-print-cell-filter":""}${x.vertical?" wx-vertical":""}`,C=x.cell;return s.jsx("th",{style:Ib(Gb(x,p.columnWidth)),className:"wx-Gy81xq2u "+j,rowSpan:x.rowspan,colSpan:x.colspan,children:C?s.jsx(C,{api:c,cell:Object.fromEntries(Object.entries(x).filter(([k])=>k!=="cell")),column:b,row:w}):x.filter?s.jsx("div",{className:"wx-Gy81xq2u wx-print-filter",children:R1(d,m,x)}):s.jsx("div",{className:"wx-Gy81xq2u wx-text",children:x.text??""})},x.id)})},w))})}function MA(n){const{columns:a,rowStyle:r,columnStyle:l,cellStyle:c,header:d,footer:m,reorder:p}=n,v=u.useContext(ts),{flatData:g,_sizes:w}=v.getState(),x=d&&tx(a,"header",w.headerRowHeights),b=m&&tx(a,"footer",w.footerRowHeights);function j(k,M){let A="";return A+=l?" "+l(M):"",A+=c?" "+c(k,M):"",A}function C(k,M){return typeof M.draggable=="function"?M.draggable(k,M)!==!1:M.draggable}return s.jsxs("table",{className:`wx-8NTMLH0z wx-print-grid ${a.some(k=>k.flexgrow)?"wx-flex-columns":""}`,children:[d?s.jsx("thead",{children:s.jsx(ox,{columns:x,type:"header",columnStyle:l})}):null,s.jsx("tbody",{children:g.map((k,M)=>s.jsx("tr",{className:"wx-8NTMLH0z wx-row"+(r?" "+r(k):""),style:{height:`${k.rowHeight||w.rowHeight}px`},children:a.map(A=>A.collapsed?null:s.jsxs("td",{className:`wx-8NTMLH0z wx-print-cell wx-cell ${j(k,A)}`,style:Ib(Gb(A,w.columnWidth)),children:[p&&A.draggable?s.jsx("span",{className:"wx-8NTMLH0z wx-print-draggable",children:C(k,A)?s.jsx("i",{className:"wx-8NTMLH0z wxi-drag"}):null}):null,A.treetoggle?s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{marginLeft:k.$level*28+"px"}}),k.$count?s.jsx("i",{className:`wx-8NTMLH0z wx-print-grid-tree-toggle wxi-menu-${k.open!==!1?"down":"right"}`}):null]}):null,A.cell?(()=>{const T=A.cell;return s.jsx(T,{api:v,row:k,column:A})})():s.jsx("span",{children:Wr(k,A)})]},A.id))},M))}),m?s.jsx("tfoot",{children:s.jsx(ox,{columns:b,type:"footer",columnStyle:l})}):null]})}function TA(n){const{config:a,...r}=n,l=u.useContext(ts),{_skin:c,_columns:d}=l.getState(),m=u.useMemo(()=>N1(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 x=`@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(x)),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(MA,{columns:v,...r})},g))})}function EA(n){const{header:a,footer:r,overlay:l,multiselect:c,onreorder:d,rowStyle:m,columnStyle:p,cellStyle:v,autoRowHeight:g,resize:w,clientWidth:x,clientHeight:b,responsiveLevel:j,hotkeys:C}=n,k=u.useContext(ts),M=ct(k,"dynamic"),A=ct(k,"_columns"),T=ct(k,"flatData"),R=ct(k,"split"),P=ct(k,"_sizes"),[F,V]=ws(k,"selectedRows"),_=ct(k,"select"),L=ct(k,"editor"),ne=ct(k,"scrollLeft"),W=ct(k,"scrollTop"),J=ct(k,"tree"),O=ct(k,"focusCell"),be=ct(k,"_print"),re=ct(k,"undo"),K=ct(k,"reorder"),I=ct(k,"_rowHeightFromData"),[ee,G]=u.useState(0);u.useEffect(()=>{G(zs())},[]);const[q,oe]=u.useState(0),we=u.useMemo(()=>(A||[]).some(te=>!te.hidden&&te.flexgrow),[A]),Q=u.useMemo(()=>P?.rowHeight||0,[P]),$=u.useRef(null),[he,fe]=u.useState(null),[me,Se]=u.useState(null),Be=u.useMemo(()=>{let te=[],Me=0;return R&&R.left&&(te=(A||[]).slice(0,R.left).filter(Ge=>!Ge.hidden).map(Ge=>({...Ge})),te.forEach(Ge=>{Ge.fixed={left:1,leftSize:R.left},Ge.left=Me,Me+=Ge.width}),te.length&&(te[te.length-1].fixed.left=-1)),{columns:te,width:Me}},[R,A]),Oe=u.useMemo(()=>{let te=[],Me=0;if(R&&R.right){te=(A||[]).slice(R.right*-1).filter(Ge=>!Ge.hidden).map(Ge=>({...Ge}));for(let Ge=te.length-1;Ge>=0;Ge--){const ut=te[Ge];ut.fixed={right:1},ut.right=Me,Me+=ut.width}te.length&&(te[0].fixed={right:-1})}return{columns:te,width:Me}},[R,A]),ge=u.useMemo(()=>{const te=(A||[]).slice(R?.left||0,(A||[]).length-(R?.right??0)).filter(Me=>!Me.hidden);return te.forEach(Me=>{Me.fixed=0}),te},[A,R]),Ze=u.useMemo(()=>(A||[]).reduce((te,Me)=>(Me.hidden||(te+=Me.width),te),0),[A]),Ke=1;function ce(te,Me,Ge){let ut=Me,sn=te;if(ge.length){let Gt=ge.length;for(let nt=te;nt>=0;nt--)ge[nt][Ge].forEach(kt=>{kt.colspan>1&&nt>te-kt.colspan&&nt<Gt&&(Gt=nt)});if(Gt!==ge.length&&Gt<te){for(let nt=Gt;nt<te;nt++)ut-=ge[nt].width;sn=Gt}}return{index:sn,delta:ut}}const ve=u.useMemo(()=>{let te,Me,Ge;const ut=ne||0,sn=(ne||0)+(x||0);let Gt=0,nt=0,kt=0,Bt=0;ge.forEach((Lt,pn)=>{ut>kt&&(Gt=pn,Bt=kt),kt=kt+Lt.width,sn>kt&&(nt=pn+Ke)});const Qt={header:0,footer:0};for(let Lt=nt;Lt>=Gt;Lt--)["header","footer"].forEach(pn=>{ge[Lt]&&ge[Lt][pn].forEach(ar=>{const Pa=ar.colspan;if(Pa&&Pa>1){const Ca=Pa-(nt-Lt+1);Ca>0&&(Qt[pn]=Math.max(Qt[pn],Ca))}})});const rn=ce(Gt,Bt,"header"),Ot=ce(Gt,Bt,"footer"),Dt=rn.delta,Vt=rn.index,ha=Ot.delta,is=Ot.index;return we&&Ze>(x||0)?te=Me=Ge=[...Be.columns,...ge,...Oe.columns]:(te=[...Be.columns,...ge.slice(Gt,nt+1),...Oe.columns],Me=[...Be.columns,...ge.slice(Vt,nt+Qt.header+1),...Oe.columns],Ge=[...Be.columns,...ge.slice(is,nt+Qt.footer+1),...Oe.columns]),{data:te||[],header:Me||[],footer:Ge||[],d:Bt,df:ha,dh:Dt}},[ge,Be,Oe,ne,x,we,Ze]),ke=u.useMemo(()=>a&&P?.headerHeight||0,[a,P]),Ne=u.useMemo(()=>r&&P?.footerHeight||0,[r,P]),He=u.useMemo(()=>x&&b?Ze>=x:!1,[x,b,Ze]),[$e,Xe]=u.useState(!1),ye=u.useMemo(()=>(b||0)-ke-Ne-(He?ee:0),[b,ke,Ne,He,ee]),ae=u.useMemo(()=>Math.ceil((ye||0)/(Q||1))+1,[ye,Q]),Te=u.useRef([]),[Pe,Je]=u.useState(0),[Mt,It]=u.useState(void 0),an=u.useMemo(()=>{let te=0,Me=0;const Ge=2,ut=W||0;if(g){let nt=ut;for(;nt>0;)nt-=Te.current[te]||Q,te++;Me=ut-nt;for(let kt=Math.max(0,te-Ge-1);kt<te;kt++)Me-=Te.current[te-kt]||Q;te=Math.max(0,te-Ge)}else{if(I){let nt=0,kt=0;for(let Ot=0;Ot<(T||[]).length;Ot++){const Dt=T[Ot].rowHeight||Q;if(kt+Dt>ut){nt=Ot;break}kt+=Dt}te=Math.max(0,nt-Ge);for(let Ot=0;Ot<te;Ot++)Me+=T[Ot].rowHeight||Q;let Bt=0,Qt=0;for(let Ot=nt+1;Ot<(T||[]).length;Ot++){const Dt=T[Ot].rowHeight||Q;if(Bt++,Qt+Dt>ye)break;Qt+=Dt}const rn=Math.min(M?M.rowCount:(T||[]).length,nt+Bt+Ge);return{d:Me,start:te,end:rn}}te=Math.floor(ut/(Q||1)),te=Math.max(0,te-Ge),Me=te*(Q||0)}const sn=M?M.rowCount:(T||[]).length,Gt=Math.min(sn,te+(ae||0)+Ge);return{d:Me,start:te,end:Gt}},[g,I,W,Q,M,T,ae,ye]),mt=u.useMemo(()=>{const te=M?M.rowCount:(T||[]).length;if(g)return Pe+an.d+(te-(Mt||0))*(Q||0);if(!I)return te*(Q||0);let Me=0;for(let Ge=0;Ge<te;Ge++)Me+=T[Ge]?.rowHeight||Q;return Me},[M,T,Q,g,I,Pe,an.d,Mt]),Pn=u.useRef({});Pn.current={clientWidth:x,clientHeight:b,fullHeight:mt,headerHeight:ke,footerHeight:Ne,fullWidth:Ze,SCROLLSIZE:ee};const Kt=u.useCallback(()=>{const te=Pn.current;Xe(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(Kt);return()=>window.cancelAnimationFrame(te)},[q,Kt]),u.useEffect(()=>{Kt()},[b,Kt]);const X=u.useMemo(()=>we&&Ze<=(x||0)?(x||0)-0-($e?ee:0):Ze,[we,Ze,x,$e,ee,He]),De=u.useMemo(()=>we&&Ze<=(x||0)?x||0:X<(x||0)?Ze+($e?ee:0):-1,[we,Ze,x,X,$e,ee]),ze=u.useRef({});u.useEffect(()=>{if(M&&(ze.current.start!==an.start||ze.current.end!==an.end)){const{start:te,end:Me}=an;ze.current={start:te,end:Me},k&&k.exec&&k.exec("request-data",{row:{start:te,end:Me}})}},[M,an,k]);const Ae=u.useMemo(()=>M?T||[]:(T||[]).slice(an.start,an.end),[M,T,an]),et=u.useMemo(()=>(F||[]).filter(te=>(Ae||[]).some(Me=>Me.id===te)),[V,Ae]),gt=u.useMemo(()=>an.start,[an.start]),Re=u.useRef({top:W,left:ne});Re.current={top:W,left:ne};const fa=u.useCallback(te=>{const Me=te.target.scrollTop,Ge=te.target.scrollLeft,ut=Re.current;(Me!==ut.top||Ge!==ut.left)&&k.exec("scroll-to",{top:Me,left:Ge})},[k]),$n=u.useCallback(te=>{te.shiftKey&&te.preventDefault(),$.current&&$.current.focus&&$.current.focus()},[]),at=u.useCallback(()=>!!(A||[]).find(te=>!!te.draggable),[A]),qt=u.useRef(null),un=u.useRef(null),ns=u.useRef({dblclick:(te,Me)=>{const Ge={id:te,column:nu(Me,"data-col-id")};k.exec("open-editor",Ge)},click:(te,Me)=>{if(Me.target.closest("input")||qt.current)return;const Ge=nu(Me,"data-col-id");if(O?.id!==te&&k.exec("focus-cell",{row:te,column:Ge,eventSource:"click"}),_===!1)return;const ut=c&&(Me.ctrlKey||Me.metaKey),sn=c&&Me.shiftKey;(ut||F.length>1||!F.includes(te))&&k.exec("select-row",{id:te,toggle:ut,range:sn})},"toggle-row":te=>{const Me=k.getRow(te);k.exec(Me.open!==!1?"close-row":"open-row",{id:te})},"ignore-click":()=>!1}),as=u.useMemo(()=>({top:ke,bottom:Ne,left:Be.width,xScroll:He,yScroll:$e,sense:g&&me?me.offsetHeight:Math.max(P?.rowHeight||0,40),node:$.current&&$.current.firstElementChild}),[ke,Ne,Be.width,He,$e,g,me,P]);function Zn(te,Me){const{container:Ge,sourceNode:ut,from:sn}=Me;if(at()&&!ut.getAttribute("draggable-data"))return!1;fe(sn),J&&k.getRow(sn).open&&k.exec("close-row",{id:sn,nested:!0});const Gt=Ro(ut),nt=Gt.cloneNode(!0);nt.classList.remove("wx-selected"),nt.querySelectorAll("[tabindex]").forEach(rn=>rn.setAttribute("tabindex","-1")),Ge.appendChild(nt),Se(nt);const kt=(ne||0)-ve.d,Bt=$e?ee:0;Ge.style.width=Math.min((x||0)-Bt,we&&Ze<=(x||0)?X:X-Bt)+kt+"px";const Qt=Pd(Gt);Me.offset={x:kt,y:-Math.round(Qt.height/2)},un.current||(un.current=te.clientY)}function nr(te,Me){const{from:Ge}=Me,ut=Me.pos,sn=Pd($.current);ut.x=sn.x;const Gt=as.top;if(ut.y<Gt)ut.y=Gt;else{const nt=sn.height-(He&&ee>0?ee:Math.round(as.sense/2))-as.bottom;ut.y>nt&&(ut.y=nt)}if($.current.contains(Me.targetNode)){const nt=Ro(Me.targetNode),kt=nt&&uf(nt);if(kt&&kt!==Ge){Me.to=kt;const Bt=g?me?.offsetHeight:P?.rowHeight;if(me&&((W||0)===0||ut.y>Gt+Bt-1)){const Qt=nt.getBoundingClientRect(),rn=Pd(me).y,Ot=Qt.y,Dt=rn>Ot?-1:1,Vt=Dt===1?"after":"before",ha=k.getState().flatData,is=Math.abs(ha.findIndex(pn=>pn.id===Ge)-ha.findIndex(pn=>pn.id===kt)),Lt=is!==1?Vt==="before"?"after":"before":Vt;if(is===1&&(Dt===-1&&te.clientY>un.current||Dt===1&&te.clientY<un.current))return;un.current=te.clientY,k.exec("move-item",{id:Ge,target:kt,mode:Lt,inProgress:!0})}}d&&d({event:te,context:Me})}rA(te,sn,Me,as)}function Fe(te,Me){const{from:Ge,to:ut}=Me;k.exec("move-item",{id:Ge,target:ut,inProgress:!1}),qt.current=setTimeout(()=>{qt.current=0},1),fe(null),Se(null),un.current=null,Yb(Me)}function zs(){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 vt=u.useMemo(()=>De>0?{width:`${De}px`}:void 0,[De]),hi=u.useRef(null);function Jt(){Promise.resolve().then(()=>{let te=0,Me=gt;const Ge=hi.current;Ge&&(Array.from(Ge.children).forEach((ut,sn)=>{Te.current[gt+sn]=ut.offsetHeight,te+=ut.offsetHeight,Me++}),Je(te),It(Me))})}u.useEffect(()=>{Ae&&g&&Jt()},[Ae,g,gt]);let[H,Le]=u.useState();u.useEffect(()=>{if(O&&(!_||!et.length||et.includes(O.row)))Le({...O});else if(Ae.length&&ve.data.length){if(!H||et.length&&!et.includes(H.row)||Ae.findIndex(te=>te.id===H.row)===-1||ve.data.findIndex(te=>te.id===H.column&&!te.collapsed)===-1){const te=et[0]||Ae[0].id,Me=ve.data.findIndex(Ge=>!Ge.collapsed);Le(Me!==-1?{row:te,column:ve.data[Me].id}:null)}}else Le(null)},[O]);const lt=u.useRef(null);u.useEffect(()=>{const te=$.current;if(!te)return;const Me=tA(te,w);return()=>{typeof Me=="function"&&Me()}},[w]);const hn=u.useRef({});Object.assign(hn.current,{start:Zn,move:nr,end:Fe,getReorder:()=>K,getDraggableInfo:()=>({hasDraggable:at()})}),u.useEffect(()=>{const te=$.current;return te?aA(te,hn).destroy:void 0},[K,$.current]),u.useEffect(()=>{const te=$.current;return te?J1(te,{keys:C!==!1&&{...Z1,"ctrl+z":re,"ctrl+y":re,...C},exec:Me=>k.exec("hotkey",Me)}).destroy:void 0},[k,re,C]);const ss=u.useRef({scroll:k.getReactiveState().scroll,scrollLeft:k.getReactiveState().scrollLeft,scrollTop:k.getReactiveState().scrollTop});ss.current.getWidth=()=>(x||0)-($e?ee:0),ss.current.getHeight=()=>ye,ss.current.getScrollMargin=()=>Be.width+Oe.width,u.useEffect(()=>{eA(lt.current,ss.current)},[]);const Dn=u.useRef(null);u.useEffect(()=>{const te=Dn.current;if(!te)return;const Me=[];Me.push(mi(te,()=>O&&k.exec("focus-cell",{eventSource:"click"})).destroy),Me.push(a1(te,ns.current)),oe(te.clientHeight);const Ge=new ResizeObserver(()=>{oe(te.clientHeight)});return Ge.observe(te),Me.push(()=>Ge.disconnect()),()=>Me.forEach(ut=>ut())},[]);const ma=`wx-grid ${j?`wx-responsive-${j}`:""}`;return u.useEffect(()=>{O&&(Ae.some(te=>te.id===O.row)&&ve.data.some(te=>te.id===O.column&&!te.collapsed)||k.exec("focus-cell",{eventSource:"destroy"}))},[O,Ae,ve.data,k]),s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"wx-4VuBwK2D "+ma,style:{"--header-height":`${ke}px`,"--footer-height":`${Ne}px`,"--split-left-width":`${Be.width}px`,"--split-right-width":`${Oe.width}px`},children:s.jsx("div",{ref:$,className:"wx-4VuBwK2D wx-table-box",style:vt,role:J?"treegrid":"grid","aria-colcount":ve.data.length,"aria-rowcount":Ae.length,"aria-multiselectable":J&&c?!0:void 0,tabIndex:-1,children:s.jsxs("div",{ref:lt,className:"wx-4VuBwK2D wx-scroll",style:{overflowX:He?"scroll":"hidden",overflowY:$e?"scroll":"hidden"},onScroll:fa,children:[a?s.jsx("div",{className:"wx-4VuBwK2D wx-header-wrapper",children:s.jsx(lx,{contentWidth:X,deltaLeft:ve.dh,columns:ve.header,columnStyle:p,bodyHeight:ye-+r})}):null,s.jsxs("div",{ref:Dn,className:"wx-4VuBwK2D wx-body",style:{width:`${X}px`,height:`${mt}px`},onMouseDown:te=>$n(te),children:[l?s.jsx(bA,{overlay:l}):null,s.jsx("div",{ref:hi,className:"wx-4VuBwK2D wx-data",style:{paddingTop:`${an.d}px`,paddingLeft:`${ve.d}px`},children:Ae.map((te,Me)=>{const Ge=F.indexOf(te.id)!==-1,ut=he===te.id,sn="wx-row"+(g?" wx-autoheight":"")+(m?" "+m(te):"")+(Ge?" wx-selected":"")+(ut?" wx-inactive":""),Gt=g?{minHeight:`${te.rowHeight||Q}px`}:{height:`${te.rowHeight||Q}px`};return s.jsx("div",{className:"wx-4VuBwK2D "+sn,"data-id":Hn(te.id),"data-context-id":Hn(te.id),style:Gt,role:"row","aria-rowindex":Me,"aria-expanded":te.open,"aria-level":J?te.$level+1:void 0,"aria-selected":J?Ge:void 0,tabIndex:-1,children:ve.data.map(nt=>nt.collapsed?s.jsx("div",{className:"wx-4VuBwK2D wx-cell wx-collapsed"},nt.id):L?.id===te.id&&L.column===nt.id?s.jsx(NA,{row:te,column:nt},nt.id):s.jsx(dA,{row:te,column:nt,columnStyle:p,cellStyle:v,reorder:K,focusable:H?.row===te.id&&H?.column===nt.id},nt.id))},te.id)})})]}),r&&(T||[]).length?s.jsx(lx,{type:"footer",contentWidth:X,deltaLeft:ve.df,columns:ve.footer,columnStyle:p}):null]})})}),be?s.jsx(TA,{config:be,rowStyle:m,columnStyle:p,cellStyle:v,header:a,footer:r,reorder:K}):null]})}const RA=n=>n.split("-").map(a=>a?a.charAt(0).toUpperCase()+a.slice(1):"").join(""),DA=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:x=null,reorder:b=!1,onReorder:j=null,autoRowHeight:C=!1,sizes:k,split:M,tree:A=!1,autoConfig:T=!1,init:R=null,responsive:P=null,sortMarks:F,undo:V=!1,hotkeys:_=null,filterValues:L,...ne},W){const J=u.useRef();J.current=ne;const O=u.useMemo(()=>new V1(Ob),[]),be=u.useMemo(()=>O.in,[O]),re=u.useRef(null);re.current===null&&(re.current=new Rb((Oe,ge)=>{const Ze="on"+RA(Oe);J.current&&J.current[Ze]&&J.current[Ze](ge)}),be.setNext(re.current));const K=u.useMemo(()=>({getState:O.getState.bind(O),getReactiveState:O.getReactive.bind(O),getStores:()=>({data:O}),exec:be.exec,setNext:Oe=>(re.current=re.current.setNext(Oe),re.current),intercept:be.intercept.bind(be),on:be.on.bind(be),detach:be.detach.bind(be),getRow:O.getRow.bind(O),getColumn:O.getColumn.bind(O)}),[O,be]),[I,ee]=u.useState(0),[G,q]=u.useState(0),[oe,we]=u.useState(null),[Q,$]=u.useState(null),he=u.useMemo(()=>{if(T&&!a.length&&n.length){const Oe=n[0],ge=[];for(let Ze in Oe)if(Ze!=="id"&&Ze[0]!=="$"){let Ke={id:Ze,header:Ze[0].toUpperCase()+Ze.slice(1)};typeof T=="object"&&(Ke={...Ke,...T}),ge.push(Ke)}return ge}return(Q&&Q.columns)??a},[T,a,n,Q]),fe=u.useMemo(()=>(Q&&Q.sizes)??k,[Q,k]),me=u.useCallback(Oe=>{if(ee(Oe.width),q(Oe.height),P){const ge=Object.keys(P).map(Number).sort((Ze,Ke)=>Ze-Ke).find(Ze=>Oe.width<=Ze)??null;ge!==oe&&($(P[ge]),we(ge))}},[P,oe]),Se=u.useContext(Fn.theme),Be=u.useRef(0);return u.useEffect(()=>{if(!Be.current)R&&R(K);else{const Oe=O.getState();O.init({data:n,columns:he,split:M||Oe.split,sizes:fe||Oe.sizes,selectedRows:d||Oe.selectedRows,dynamic:w,tree:A,sortMarks:F||Oe.sortMarks,filterValues:L||Oe.filterValues,undo:V,reorder:b,_skin:Se,_select:m})}Be.current++},[O,n,he,M,fe,d,w,A,F,L,V,b,Se,m,R,K]),Be.current===0&&O.init({data:n,columns:he,split:M||{left:0},sizes:fe||{},selectedRows:d||[],dynamic:w,tree:A,sortMarks:F||{},filterValues:L||{},undo:V,reorder:b,_skin:Se,select:m}),u.useImperativeHandle(W,()=>({...K}),[K]),s.jsx(ts.Provider,{value:K,children:s.jsx(gp,{words:vp,optional:!0,children:s.jsx(EA,{header:v,footer:g,overlay:x,rowStyle:r,columnStyle:l,cellStyle:c,onReorder:j,multiselect:p,autoRowHeight:C,clientWidth:I,clientHeight:G,responsiveLevel:oe,resize:me,hotkeys:_})})})});cp(Fa);const Bn=u.createContext(null),bp=u.createContext(null),wp=u.createContext(null);function LA({children:n}){const a=u.useContext(Fn.i18n),r=u.useMemo(()=>a.getGroup("filemanager"),[a]),l=u.useContext(Bn),[c]=ws(l,"panels"),d=ct(l,"activePanel"),m=c[d].path,[p,v]=u.useState(null),[g,w]=u.useState(null),[x,b]=u.useState(""),[j,C]=u.useState(""),[k,M]=u.useState(!1);function A(){const F=x.trim();if(!F){M(!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}),T()}function T(){v(null),M(null),C(""),b("")}function R(){l.exec("delete-files",{ids:g.selected}),w(null)}const P=u.useMemo(()=>({showPrompt(F){const V=F.item.name||(F.item.type==="folder"?r("New folder"):`${r("New file")}.txt`);C(V),b(V),v({...F})},showConfirm(F){w({...F})}}),[r]);return s.jsxs(bp.Provider,{value:P,children:[s.jsx(Lk,{children:n}),p?s.jsx(Bh,{title:r(`Enter ${p.item.type} name`),onConfirm:A,onCancel:T,children:s.jsx(hp,{error:k,select:!0,focus:!0,value:x,onChange:({value:F})=>b(F)})}):null,g?s.jsx(Bh,{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,V)=>s.jsx("li",{children:F},V))}):null}):null]})}let cx={"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 _A(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 zA({item:n}){const a=u.useContext(Bn),r=u.useContext(Fn.i18n).getGroup("filemanager"),l=u.useContext(Bn).templates,[c]=ws(a,"panels"),d=ct(a,"activePanel"),m=ct(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,x]=u.useMemo(()=>_A(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":Hn("/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":Hn(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:x})]})]}),s.jsx("div",{"data-action-id":Hn(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:x})]})}),s.jsx("div",{"data-action-id":Hn(n.id),className:"wx-GAOa4kDV wx-more",children:s.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]})]})})}function Zb(){const n=u.useContext(Bn),a=u.useContext(Fn.i18n),r=u.useMemo(()=>a.getGroup("filemanager"),[a]),[l]=ws(n,"panels"),c=ct(n,"activePanel"),d=ct(n,"mode"),m=l[c]._files,p=l[c].selected,v=l[c].path,g=l[c]._crumbs,w=l[c]._selectNavigation,x=u.useCallback((T,R)=>{const P=R&&(R.ctrlKey||R.metaKey),F=R&&R.shiftKey;if(T==="/wx-filemanager-parent-link"){if(p.length&&(P||F))return;n.exec("select-file",{type:"navigation"});return}let V=T==="body"&&R?null:T;const _=R.target.className.indexOf("wx-more")!==-1||R.target.className.indexOf("wxi-dots-v")!==-1;setTimeout(()=>{n.exec("select-file",{id:V,toggle:P&&!_,range:F&&!_,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(T=>{if(T==="/wx-filemanager-parent-link")return b();d==="search"&&n.exec("filter-files",{text:""});const R=m.find(P=>P.id===T);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((T,R)=>{(!p?.length||!p.filter(P=>P?.id===T).length>0)&&x(T,R)},[p,x]),k=u.useMemo(()=>v!=="/"?[{id:"/wx-filemanager-parent-link",name:r("Back to parent folder"),navigation:w},...m]:m,[v,r,w,m]),M=u.useRef(null),A=u.useRef();return u.useEffect(()=>{M.current&&(A.current?(A.current.click=x,A.current._dblclick=j,A.current.context=C):(A.current={click:x,dblclick:T=>A.current._dblclick(T),_dblclick:j,context:C},Do(M.current,A.current)))},[x,j,C]),d=="search"&&!k.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":Hn("body"),ref:M,children:k.map(T=>s.jsx(zA,{item:T},T.id))})}function Dl({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 IA(){const n=u.useContext(Fn.i18n).getGroup("filemanager"),a=u.useContext(Bn),r=ct(a,"activePanel"),[l]=ws(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(Dl,{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(Zb,{})]})}function oh({narrowMode:n,extraInfo:a}){const r=u.useContext(Bn),{preview:l,icon:c}=r.templates,d=u.useContext(Fn.i18n),m=u.useMemo(()=>d.getGroup("filemanager"),[d]),p=u.useMemo(()=>No("%D, %d %F %Y, %H:%i",d.getRaw().calendar),[d]),[v,g]=ws(r,"panels"),w=ct(r,"activePanel"),x=ct(r,"preview"),b=ct(r,"search"),j=u.useMemo(()=>{const _=v&&w!=null&&v[w]?._selected?.length||0;return b&&!_},[b,g,w]),C=u.useMemo(()=>{const _=v&&w!=null?v[w]:null;return _?j?_._files:_._selected:[]},[j,g,w]),k=u.useCallback((_,L)=>(_?`${_} ${m(_>1?"folders":"folder")} `:"")+(L?`${L} ${m(L>1?"files":"file")}`:""),[m]),M=u.useCallback(()=>{r.exec("show-preview",{mode:!x})},[r,x]),A=u.useCallback(_=>_.type==="folder"?m("Folder"):_.ext||m("Unknown file"),[m]),T=u.useMemo(()=>{let _,L,ne,W,J,O,be,re;if(C.length===1&&!j){L=C[0],_=L.name;const K=l(L,400,500);K?(ne=K,W=""):(W=c(L,"big"),ne=""),J=L.type!=="folder"}else{if(L=J=null,_="",C.length){let K=0,I=0,ee=0,G=[],q;C.forEach(we=>{typeof we.size>"u"&&(q=!0,K=void 0),q||(K+=we.size),G.push(A(we)),we.type==="folder"?I++:ee++});const oe=new Set(G);O=oe.size>1?m("multiple"):[...oe][0],be=k(I,ee),re=K,j||(_=m("Multiple files"))}W=c({type:j?"search":C.length?"multiple":"none"},"big"),ne=""}return{name:_,item:L,previewSrc:ne,iconSrc:W,showDownloadIcon:J,type:O,totalCount:be,totalSize:re}},[C,j,l,c,m,A,k]),R=u.useCallback(()=>{r.exec("download-file",{id:C[0].id})},[r,C]),P=u.useCallback(async _=>{if(!a||!_)return null;try{return await a(_)}catch(L){return console.log(L),null}},[a]),[F,V]=u.useState(null);return u.useEffect(()=>{let _=!1;return V(null),Promise.resolve(P(T.item)).then(L=>{_||V(L)}).catch(()=>{_||V(null)}),()=>{_=!0}},[P,T.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:T.name}),s.jsxs("div",{className:"wx-O0BTtRrH wx-icons",children:[T.showDownloadIcon?s.jsx(Dl,{name:"download",onClick:R}):null,n?s.jsx(Dl,{name:"close",onClick:M}):null]})]}),T.previewSrc?s.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:s.jsx("img",{src:T.previewSrc,alt:m("A miniature file preview")})}):T.iconSrc?s.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:s.jsx("img",{src:T.iconSrc,alt:m("A miniature file preview")})}):s.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:T.item?s.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${T.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:[T.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:A(T.item)}),typeof T.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:au(T.item.size)})]}):null,s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Date")}),s.jsxs("span",{className:"wx-O0BTtRrH wx-value",children:[p(T.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:T.totalCount}),s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Type")}),s.jsx("span",{className:"wx-O0BTtRrH wx-value",children:T.type}),typeof T.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:au(T.totalSize)})]}):null]}),F?Object.entries(F).map(([_,L])=>s.jsxs(tp.Fragment,{children:[s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:_}),s.jsx("span",{className:"wx-O0BTtRrH wx-value",children:L})]},_)):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:T.name}),s.jsx("div",{className:"wx-O0BTtRrH wx-icons",children:n?s.jsx(Dl,{name:"close",onClick:M}):null})]}),s.jsx("div",{className:"wx-O0BTtRrH wx-no-info-wrapper",children:s.jsxs("div",{className:"wx-O0BTtRrH wx-no-info",children:[T.previewSrc?s.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:s.jsx("img",{src:T.previewSrc,alt:m("A miniature file preview")})}):T.iconSrc?s.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:s.jsx("img",{src:T.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 Jb({panel:n}){const a=u.useContext(Bn),r=u.useContext(Fn.i18n),l=u.useMemo(()=>r.getGroup("filemanager"),[r]),[c,d]=ws(a,"panels"),m=u.useMemo(()=>c[n]._files,[d,n]),p=u.useMemo(()=>c[n]._crumbs||[],[d,n]);function v(C){const k=yp(C,p);a.exec("set-path",{id:C,panel:n,...k&&{selected:[k]}})}const[g,w]=u.useState(null);u.useEffect(()=>{m&&w(null)},[m]);function x(){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},Do(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(Dl,{name:"refresh",spin:!!g,onClick:x})}),p.map((C,k)=>s.jsxs(tp.Fragment,{children:[k?s.jsx(Dl,{name:"angle-right"}):null,s.jsx("div",{className:"wx-SNY5LTYx wx-item","data-id":Hn(C.id),"data-menu-ignore":"true",children:C.id=="/"?l(C.name):C.name})]},k))]})}function OA({row:n}){const a=u.useContext(Fn.i18n),[r]=u.useState(()=>a.getGroup("filemanager")),l=u.useContext(Bn).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 ew({children:n}){const a=u.useContext(Bn),r=ct(a,"activePanel"),l=u.useContext(wp),c=u.useRef(null);let d=u.useRef({});return d.current.drop=()=>{const m=c.current,p=Fj(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 $h({panel:n,active:a=!1,onClick:r,onContextMenu:l}){const c=u.useContext(Bn),d=u.useContext(Fn.i18n),m=u.useMemo(()=>d.getGroup("filemanager"),[d]),p=u.useMemo(()=>No("%d %M %Y",d.getRaw().calendar),[d]),[v]=ws(c,"panels"),g=v[n].selected,w=v[n].path,x=v[n]._crumbs,b=v[n]._sorts,j=v[n]._selectNavigation,C=v[n]._files,k=u.useMemo(()=>[{id:"name",header:m("Name"),flexgrow:3,sort:!0,resize:!0,cell:OA},{id:"size",header:m("Size"),width:100,sort:!0,resize:!0,template:O=>typeof O=="number"?au(O):""},{id:"date",header:m("Date"),width:120,sort:!0,resize:!0,template:O=>O?p(O):""}],[m,p]),M=u.useRef(null),A=u.useRef(null),T=u.useMemo(()=>j?["/wx-filemanager-parent-link"]:[...g],[j,g]);function R(O,be){if(be&&be.target&&be.target.className&&be.target.className.indexOf("wx-grip")!==-1)return;const re=be&&(be.ctrlKey||be.metaKey),K=be&&be.shiftKey;if(O==="/wx-filemanager-parent-link"){if(g.length&&(re||K))return;c.exec("select-file",{type:"navigation"});return}let I=O==="body"&&be?null:O;!M.current&&!A.current?c.exec("select-file",{id:I,toggle:re,range:K,panel:n}):(M.current=null,A.current=null)}function P(){x.length>1&&c.exec("set-path",{id:x[x.length-2].id,panel:n,selected:[x[x.length-1].id]})}function F(O){if(O==="/wx-filemanager-parent-link")return P();const be=C.find(re=>re.id===O);be&&(be.type==="folder"?c.exec("set-path",{id:be.id,panel:n}):c.exec("open-file",{id:be.id}))}function V(O){const be=O.key,re=b[w];let K=re?"asc":"desc";re&&re.key===be&&(K=re.order==="asc"?"desc":"asc"),c.exec("sort-files",{key:be,order:K,panel:n,path:w})}function _(O){O.intercept("sort-rows",be=>(M.current=!0,V(be),!1)),O.intercept("select-row",()=>!1),O.on("resize-column",()=>A.current=!0),O.intercept("hotkey",()=>!1)}const L=u.useMemo(()=>w!=="/"?[{id:"/wx-filemanager-parent-link",name:m("Back to parent folder")},...C]:C,[w,C,m]),ne=u.useMemo(()=>{if(L&&b&&b[w]){const{key:O,order:be}=b[w];return{[O]:{order:be}}}},[L,b,w]),W=u.useRef(null),J=u.useRef();return u.useEffect(()=>{J.current?(J.current.click=R,J.current._dblclick=F):(J.current={click:R,dblclick:O=>J.current._dblclick(O),_dblclick:F},Do(W.current,J.current))},[R,F]),s.jsxs("div",{onClick:r,onContextMenu:l,className:"wx-SSaVhET7 wx-wrapper",children:[s.jsx(Jb,{panel:n}),s.jsx("div",{"data-id":Hn("body"),className:`wx-SSaVhET7 wx-list ${a?"wx-active":""}`,ref:W,children:s.jsx(ew,{children:s.jsx(DA,{init:_,data:L,columns:k,selectedRows:T,columnStyle:()=>"wx-SSaVhET7 wx-each-cell",sizes:{rowHeight:42,headerHeight:42},sortMarks:ne})})})]})}function HA(){const n=u.useContext(Bn),a=ct(n,"activePanel");function r(l){n.exec("set-active-panel",{panel:l})}return s.jsxs("div",{className:"wx-L55BfJa2 wx-panels","data-id":Hn("body"),children:[s.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":0,children:s.jsx($h,{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($h,{panel:1,active:a==1,onClick:()=>r(1),onContextMenu:()=>r(1)})})]})}function tw({folderIcon:n=!1,folder:a={}}){const r=u.useContext(Bn),[l,c]=ws(r,"panels"),d=ct(r,"activePanel"),m=u.useMemo(()=>l[d].path,[c,d]),p=u.useContext(Fn.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]),x=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":Hn(a.id),className:`wx-NYfhvGIt wx-folder${m===a.id?" wx-selected":""}`,style:{paddingLeft:`${x}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(tw,{folder:j},j.id):null)}):null]})}function BA(){const n=u.useContext(Bn),[a,r]=ws(n,"data"),[l,c]=ws(n,"panels"),d=ct(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=yp(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 x=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},Do(x.current,b.current))},[v,p]),s.jsx("ul",{ref:x,className:"wx-LyHJ6R6A",children:g.map(j=>j.type==="folder"?s.jsx(tw,{folder:j},j.id):null)})}function FA(){const n=u.useContext(Bn),a=u.useContext(Fn.i18n),r=u.useMemo(()=>a.getGroup("filemanager"),[a]),l=ct(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:[au(c)," ",r("of")," ",au(d)," ",r("used")]})]}):null}function PA({option:n}){const a=u.useContext(Fn.i18n).getGroup("filemanager"),r=u.useContext(wp),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 $A({readonly:n,menuOptions:a}){const r=u.useContext(Fn.i18n).getGroup("filemanager"),{showPrompt:l}=u.useContext(bp);u.useEffect(()=>{r1("upload",PA)},[]);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(o1,{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(FA,{})]})}function UA({value:n="",onSearch:a}){const[r,l]=zb(n),c=u.useContext(Fn.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 qA({narrowMode:n=!1,onShowTree:a}){const r=u.useContext(Bn),l=u.useContext(Fn.i18n).getGroup("filemanager"),c=ct(r,"mode"),d=ct(r,"preview"),m=ct(r,"search"),p=[{icon:"wxi-view-sequential",id:"table"},{icon:"wxi-view-grid",id:"cards"},{icon:"wxi-view-column",id:"panels"}];function v({value:x}){r.exec("set-mode",{mode:x})}function g(x){x.preventDefault(),r.exec("show-preview",{mode:!d})}function w(x){r.exec("filter-files",{text:x.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":Hn("toggle-tree"),children:s.jsx(Dl,{onClick:()=>a&&a(),name:"subtask"})}):s.jsx("div",{className:"wx-5PZQQztG wx-name",children:l("Files")}),s.jsx(UA,{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(_k,{onClick:g,value:d,children:s.jsx("i",{className:"wx-5PZQQztG wxi-eye"})})}),s.jsx("div",{className:"wx-5PZQQztG wx-modes",children:s.jsx(Mk,{value:c,options:p,onChange:v})})]})]})}function GA(){const n=u.useContext(Bn),a=ct(n,"activePanel");return s.jsxs("div",{className:"wx-NwohNJzN wx-wrapper",children:[s.jsx(Jb,{panel:a}),s.jsx(ew,{children:s.jsx(Zb,{})})]})}function VA({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),x=$b(),b=u.useContext(Bn),{showPrompt:j,showConfirm:C}=u.useContext(bp),k=u.useContext(Fn.i18n),M=u.useMemo(()=>k.getGroup("filemanager"),[k]),A=ct(b,"mode"),T=ct(b,"preview"),R=ct(b,"activePanel"),[P,F]=ws(b,"panels"),V=u.useMemo(()=>(P&&R!=null?P[R]:null)?.selected??[],[F,R]),_=u.useMemo(()=>(P&&R!=null?P[R]:null)?.path,[F,R]),[L,ne]=u.useState([]);u.useEffect(()=>{const oe=l.current;if(!oe)return;const we=new ResizeObserver(Q=>{const $=Q[0]?.borderBoxSize?.[0]?.inlineSize;typeof $=="number"&&v($<768)});return we.observe(oe),()=>{we.disconnect()}},[]);const W=u.useCallback(()=>{w(oe=>!oe)},[]),J=u.useCallback(oe=>{p&&nu(oe)!=="toggle-tree"&&w(!1)},[p]);u.useEffect(()=>{const oe=c.current;if(oe)return mi(oe,J).destroy},[J]),u.useEffect(()=>{const oe=c.current;if(!oe)return;const we=new ResizeObserver(()=>{oe&&m(oe.clientWidth)});return we.observe(oe),oe&&m(oe.clientWidth),()=>{we.disconnect()}},[]);const O=u.useMemo(()=>({icon:"wxi-eye",text:"Preview",id:"preview"}),[]),be=u.useCallback(oe=>{let we=p?[O]:[];return oe==="file"&&(we=[...we,...a().filter(Q=>Q.id==="download")]),we},[p,O,a]),re=u.useRef(null),K=u.useCallback((oe,we,Q)=>{const $=Q?[we.id]:V;switch(oe){case"download":b.exec("download-file",{id:we.id});break;case"copy":case"move":re.current={action:oe,ids:$};break;case"paste":re.current&&b.exec(re.current.action==="copy"?"copy-files":"move-files",{ids:re.current.ids,target:we?.type==="folder"?we.id:_});break;case"rename":j({item:we});break;case"delete":C({selected:$});break;case"preview":b.exec("show-preview",{mode:!T});break}},[b,V,_,j,C,T]),I=u.useCallback(()=>P?.[R],[P,R]);u.useEffect(()=>{const oe=l.current;if(!oe)return;const we=Kk(oe,{api:b,menuOptions:n?be:a,performAction:K,getPanel:I});return()=>{typeof we=="function"?we():we&&typeof we.destroy=="function"&&we.destroy()}},[b,n,be,a,K,I]);const ee=u.useCallback((oe,we)=>{const Q=oe?b.getFile(oe):null,$=we.target.closest(".tree-item.folder");let he;if(n)he=be(Q?.type);else{switch(oe){case"body":he=a(oe);break;default:if(Q)if(!$&&V.length>1)he=p?[O,...a("multiselect")]:a("multiselect");else if(oe==="/")he=a("folder",Q).filter(fe=>fe.id==="paste");else{const fe=a(Q.type,Q);fe&&(he=p?[O,...fe]:fe)}}A==="search"&&(he=he?.filter(fe=>fe.id!=="paste"))}if(Q?.id&&(!V.length||!V.some(fe=>fe===Q.id))&&!$&&b.exec("select-file",{id:Q.id}),he?.length)return he.forEach(fe=>{$&&(fe.hotkey=""),fe.text&&(fe.text=M(fe.text)),fe.hotkey&&(fe.subtext=fe.hotkey)}),ne(he),Q||{}},[b,n,be,a,V,p,O,A,M]),G=u.useCallback(oe=>{const{action:we,context:Q}=oe;we&&K(we.id,Q,!we.hotkey)},[K]);async function q(oe){await Promise.resolve();const{name:we,size:Q}=oe.file;b.exec("create-file",{file:{name:we,size:Q,date:new Date,file:oe.file},parent:_})}return s.jsx("div",{className:"wx-RJbNonjJ wx-filemanager wx-flex",ref:l,"data-menu-ignore":"false",children:p&&T?s.jsx("div",{className:"wx-RJbNonjJ wx-info-narrow",children:s.jsx(oh,{narrowMode:p,extraInfo:r})}):s.jsxs(s.Fragment,{children:[s.jsx(qA,{narrowMode:p,onShowTree:W}),s.jsx(c1,{dataKey:"id",at:"point",options:L,resolver:ee,onClick:G,children:s.jsxs(Pb,{dataKey:"actionId",options:L,resolver:ee,onClick:G,children:[s.jsx(h1,{data:x,apiOnly:!0,uploadURL:q}),s.jsx(wp.Provider,{value:x,children:s.jsx("div",{className:"wx-RJbNonjJ wx-content-wrapper wx-flex",children:A!=="panels"&&A!=="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($A,{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${T?"":"-fit"}`,"data-id":Hn("body"),children:A==="table"?s.jsx($h,{panel:R}):s.jsx(GA,{})}),T?s.jsx("div",{className:"wx-RJbNonjJ wx-info",children:s.jsx(oh,{extraInfo:r})}):null]})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`wx-RJbNonjJ wx-content-item${T?"":"-fit"}`,children:A==="panels"?s.jsx(HA,{}):s.jsx(IA,{})}),T?s.jsx("div",{className:"wx-RJbNonjJ wx-info",children:s.jsx(oh,{extraInfo:r})}):null]})})})]})})]})})}const WA=n=>n.split("-").map(a=>a?a.charAt(0).toUpperCase()+a.slice(1):"").join("");function YA(n,a){const{type:r,ext:l}=n;if(r==="folder")return!1;let c;return r&&r!=="file"&&cx[r]?c=r:l?c=cx[l]?l:"file":c="unknown",`https://cdn.svar.dev/icons/filemanager/vivid/${a}/${c}.svg`}const KA=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=Vk,extraInfo:w=null,init:x=null,icons:b=YA,previews:j=null,...C}=n,k=u.useRef();k.current=C;const M=u.useMemo(()=>new Gk(Ob),[]),A=u.useMemo(()=>M.in,[M]),T=u.useRef(null);T.current===null&&(T.current=new Rb((F,V)=>{const _="on"+WA(F);k.current&&k.current[_]&&k.current[_](V)}),A.setNext(T.current));const R=u.useMemo(()=>({getState:M.getState.bind(M),getReactiveState:M.getReactive.bind(M),getStores:()=>({data:M}),exec:A.exec,setNext:F=>(T.current=T.current.setNext(F),T.current),intercept:A.intercept.bind(A),on:A.on.bind(A),detach:A.detach.bind(A),getFile:M.getFile.bind(M),serialize:M.serialize.bind(M),templates:{preview:j||(()=>null),icon:b==="simple"?(()=>null):b}}),[M,A]),P=u.useRef(0);return u.useEffect(()=>{if(!P.current)x&&x(R);else{const F=M.getState();M.init({data:r,mode:l,drive:c,preview:d,panels:m||F.panels||[],activePanel:p})}P.current++},[M,r,l,c,d,m,p,x,R]),P.current===0&&M.init({data:r,mode:l,drive:c,preview:d,panels:m||[],activePanel:p}),u.useImperativeHandle(a,()=>({...R}),[R]),s.jsx(Bn.Provider,{value:R,children:s.jsx(gp,{words:vp,optional:!0,children:s.jsx(LA,{children:s.jsx(VA,{readonly:v,menuOptions:g,extraInfo:w})})})})});function QA({fonts:n=!0,children:a}){return a?s.jsx(Yy,{fonts:n,children:a}):s.jsx(Yy,{fonts:n})}cp(Fa);function Sp(n,a){if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`Invalid Hub ${a} response.`);return n}function iu(n,a,r){const l=Sp(n,r);if(!Array.isArray(l[a]))throw new Error(`Invalid Hub ${r} response: ${a} must be an array.`);return l[a]}function XA(n,a,r){const l=Sp(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 ZA(n,a=!1){return iu(await We(`/api/remote/filesystem/roots${a?"?refresh=1":""}`,void 0,n),"roots","filesystem roots")}async function ch(n,a){const r=await We(`/api/remote/filesystem/entries?id=${encodeURIComponent(n)}`,void 0,a);return{folder:XA(r,"folder","filesystem entries"),entries:iu(r,"entries","filesystem entries")}}async function JA(n,a){return We("/api/remote/filesystem/selection/scan",{method:"POST",body:JSON.stringify({itemIds:n})},a)}async function eN(n,a,r,l){return We("/api/remote/files/from-hub",{method:"POST",body:JSON.stringify({itemIds:n,deviceIds:a,remoteDirectory:r})},l)}async function tN(n,a=!1){const r=await We(`/api/remote/files/jobs?active=${a?"1":"0"}`,void 0,n);return{jobs:iu(r,"jobs","file transfer jobs")}}async function nN(n,a){return We(`/api/remote/files/jobs/${encodeURIComponent(n)}`,void 0,a)}async function aN(n,a){return We(`/api/remote/files/jobs/${encodeURIComponent(n)}/cancel`,{method:"POST"},a)}async function ux(n){return iu(await We("/api/remote/filesystem/shared-folders",void 0,n),"folders","shared folders")}async function sN(n,a){return We("/api/remote/filesystem/shared-folders",{method:"POST",body:JSON.stringify({sourceId:n})},a)}async function iN(n,a,r){return We(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)},r)}async function rN(n,a){return We(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}`,{method:"DELETE"},a)}async function lN(n,a,r,l){const c=await We(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}/sync`,{method:"POST",body:JSON.stringify({deviceIds:a,remoteDirectory:r})},l),d=Sp(c,"shared folder sync");return{ok:d.ok===!0,jobs:iu(c,"jobs","shared folder sync"),files:Number(d.files||0),totalBytes:Number(d.totalBytes||0)}}function oN(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 dx(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 $d(n){return n.driveType==="network"?"network":n.driveType==="removable"?"removable":"local"}function cN(n){const a=n.filter(r=>$d(r)==="local");return a.find(r=>/\bC:/i.test(`${r.name} ${r.displayPath||""}`))||a[0]||n[0]||null}function uN({hubUrl:n,roots:a,loading:r,error:l,onRefreshRoots:c,onImportFiles:d,onImportFolder:m,onSelectionChange:p,onShareItem:v,onAddSyncFolder:g,onNotice:w}){const x=u.useRef(null),b=u.useRef("/"),j=u.useRef(0),C=u.useRef([]),k=u.useRef(new Map),[M,A]=u.useState(null),[T,R]=u.useState([]),[P,F]=u.useState([]),[V,_]=u.useState(0),[L,ne]=u.useState(null),[W,J]=u.useState(!1),[O,be]=u.useState(""),[re,K]=u.useState(new Set),I=a.find(ce=>ce.id===M)||null,ee=T[T.length-1]||null,G=I?ee?.svarPath||`/${I.name}`:null,q=G;u.useEffect(()=>{C.current=T,b.current=q||"/"},[q,T]);const oe=u.useMemo(()=>(k.current.clear(),!I||!q||T.length===0?[]:(T.forEach(ce=>k.current.set(ce.svarPath,ce.hubId)),[...T.map((ce,ve)=>({id:ce.svarPath,parent:ve===0?"/":T[ve-1].svarPath,type:"folder",name:ce.name,date:ce.modifiedAt?new Date(ce.modifiedAt):void 0,lazy:!1})),...P.map(ce=>{const ve=`${q}/${ce.name}`;return k.current.set(ve,ce.id),{id:ve,parent:q,name:ce.name,type:ce.type==="file"?"file":"folder",...ce.type==="file"?{size:ce.size}:{},date:ce.modifiedAt?new Date(ce.modifiedAt):void 0,lazy:ce.type!=="file"&&ce.hasChildren===!0,displayPath:ce.displayPath,locked:ce.locked,driveType:ce.driveType,totalBytes:ce.totalBytes,freeBytes:ce.freeBytes}})])),[I,P,q,T]),we=ce=>k.current.get(String(ce))||String(ce),Q=ce=>oN({...ce,id:we(String(ce.id)),parent:we(String(ce.parent))}),$=async(ce,ve)=>{const ke=ce[ce.length-1];if(!ke)return;const Ne=++j.current;J(!0),be("");try{const He=await ch(ke.hubId,n);if(Ne!==j.current)return;if(!Array.isArray(He.entries))throw new Error("Invalid Hub filesystem entries response.");const $e={...ke,displayPath:He.folder.displayPath||ke.displayPath,modifiedAt:He.folder.modifiedAt||ke.modifiedAt},Xe=[...ce.slice(0,-1),$e];C.current=Xe,R(Xe),F(He.entries),_(ye=>ye+1)}catch(He){if(Ne!==j.current)return;console.error("[LiveDesk FS] folder navigation failed",{folderId:ke.hubId,error:He}),be(He instanceof Error?`${ve}: ${He.message}`:`${ve}: Unable to read this folder.`)}finally{Ne===j.current&&J(!1)}},he=async ce=>{const ve={svarPath:`/${ce.name}`,hubId:ce.id,name:ce.name,displayPath:ce.displayPath,modifiedAt:ce.modifiedAt},ke=++j.current;A(ce.id),C.current=[ve],R([ve]),b.current=ve.svarPath,F([]),be(""),J(!0),ne(ce.id),K(Ne=>{const He=new Set(Ne);return He.delete(ce.id),He});try{const Ne=await ch(ce.id,n);if(ke!==j.current)return;if(!Array.isArray(Ne.entries))throw new Error("Invalid Hub filesystem entries response.");const He={...ve,displayPath:Ne.folder.displayPath||ve.displayPath,modifiedAt:Ne.folder.modifiedAt||ve.modifiedAt};C.current=[He],R([He]),F(Ne.entries),_($e=>$e+1)}catch(Ne){if(ke!==j.current)return;console.error("[LiveDesk FS] getEntries failed",{rootId:ce.id,error:Ne}),K(He=>new Set(He).add(ce.id)),be(Ne instanceof Error?`${ce.name}: ${Ne.message}`:`${ce.name}: Unable to read this drive.`),w(Ne instanceof Error?`${ce.name}: ${Ne.message}`:`${ce.name}: Unable to read this drive.`)}finally{ke===j.current&&(ne(null),J(!1))}},fe=ce=>{const ve=C.current;ce<0||ce>=ve.length||ce===ve.length-1||$(ve.slice(0,ce+1),ve[ce].name)},me=(ce,ve)=>{if(ce.type!=="folder")return;const ke=C.current,Ne=ke.findIndex($e=>$e.svarPath===ve);if(Ne<0)return;const He={svarPath:`${ve}/${ce.name}`,hubId:ce.id,name:ce.name,displayPath:ce.displayPath,modifiedAt:ce.modifiedAt};$([...ke.slice(0,Ne+1),He],ce.name)},Se=()=>fe(C.current.length-2),Be=ce=>{if(ce.key!=="Enter"&&ce.code!=="Enter"&&ce.code!=="NumpadEnter"||ce.target?.closest('button, input, textarea, [contenteditable="true"]'))return;const ke=x.current;if(!ke)return;const Ne=ke.getState().panels?.flatMap($e=>$e.selected||[])||[];if(Ne.length!==1)return;const He=ke.getFile(String(Ne[0]));He?.type==="folder"&&(ce.preventDefault(),ce.stopPropagation(),me(Q(He),String(He.parent||b.current)))};u.useEffect(()=>{const ce=a.find(ve=>ve.id===M)||cN(a);if(K(ve=>new Set([...ve].filter(ke=>a.some(Ne=>Ne.id===ke)))),!ce){A(null),C.current=[],R([]),F([]);return}he(ce)},[a]);const Oe=ce=>{x.current=ce,ce.on("request-data",async({id:ve})=>{const ke=String(ve),Ne=we(ke);try{const He=await ch(Ne,n);if(!Array.isArray(He.entries))throw new Error("Invalid Hub filesystem entries response.");const $e=He.entries.map(Xe=>{const ye=`${ke}/${Xe.name}`;return k.current.set(ye,Xe.id),{id:ye,parent:ke,name:Xe.name,type:Xe.type==="file"?"file":"folder",...Xe.type==="file"?{size:Xe.size}:{},date:Xe.modifiedAt?new Date(Xe.modifiedAt):void 0,lazy:Xe.type!=="file"&&Xe.hasChildren===!0,displayPath:Xe.displayPath,locked:Xe.locked,driveType:Xe.driveType,totalBytes:Xe.totalBytes,freeBytes:Xe.freeBytes}});await ce.exec("provide-data",{id:ke,data:$e})}catch(He){console.error("[LiveDesk FS] nested getEntries failed",{id:Ne,error:He}),w(He instanceof Error?He.message:"Unable to read this folder.")}}),ce.intercept("set-path",({id:ve})=>{const ke=String(ve),Ne=C.current.findIndex($e=>$e.svarPath===ke);if(Ne>=0)return fe(Ne),!1;const He=ce.getFile(ke);if(He?.type==="folder")return me(Q(He),String(He.parent||b.current)),!1}),ce.intercept("open-file",()=>!1),ce.on("select-file",()=>{window.setTimeout(()=>{const Ne=(ce.getState().panels?.flatMap(He=>He.selected||[])||[]).map(He=>ce.getFile(He)).filter(Boolean).map(He=>Q(He));p(Ne.map(He=>He.id),Ne)},0)})},ge=(ce,ve)=>{const ke=ve?Q(ve):null,Ne=()=>{const He=ke?.type==="file"?String(ve?.parent||b.current):String(ve?.id||b.current);x.current?.exec("request-data",{id:He})};return ce==="body"?[{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Ne},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>w("Select a file or folder to view its properties.")}]:ce==="multiselect"?[{id:"share",text:"Share to workstations",icon:"mdi mdi-share-variant",handler:()=>{(x.current?.getState().panels?.flatMap($e=>$e.selected||[])||[]).forEach($e=>{const Xe=x.current?.getFile($e);Xe&&v(Q(Xe))})}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Ne}]:ke?[{id:"share",text:"Share to workstations",icon:"mdi mdi-share-variant",handler:()=>v(ke)},...ke.type==="folder"?[{id:"sync",text:"Add folder to Sync",icon:"mdi mdi-folder-sync-outline",handler:()=>g(ke)}]:[],{id:"copy-path",text:"Copy path",icon:"mdi mdi-content-copy",handler:()=>{kl(ke.displayPath||ke.name)}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Ne},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>w(`${ke.name}
14
- ${ke.displayPath||""}`)}]:[]},Ze=async()=>{try{await c()}catch(ce){w(ce instanceof Error?ce.message:"Unable to refresh Hub drives.")}},Ke=[{id:"local",label:"Local drives",icon:Nl,roots:a.filter(ce=>$d(ce)==="local")},{id:"removable",label:"Removable drives",icon:XS,roots:a.filter(ce=>$d(ce)==="removable")},{id:"network",label:"Network drives",icon:np,roots:a.filter(ce=>$d(ce)==="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(Nl,{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(Kx,{size:16})}),s.jsx("button",{className:"icon-button",onClick:m,title:"Import folder from this browser",type:"button",children:s.jsx(ZS,{size:16})}),s.jsx("button",{className:"icon-button",onClick:()=>{Ze()},title:"Refresh drives",type:"button",children:s.jsx(Eo,{size:16})})]})]}),r?s.jsxs("div",{className:"hub-file-explorer-state",children:[s.jsx(Nl,{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(Nl,{size:15}),s.jsx("strong",{children:"This PC"})]}),Ke.map(ce=>ce.roots.length>0&&s.jsxs("section",{className:"hub-drive-group",children:[s.jsxs("h3",{children:[s.jsx(ce.icon,{size:13}),ce.label]}),s.jsx("div",{className:"hub-drive-list",children:ce.roots.map(ve=>{const ke=ce.icon,Ne=re.has(ve.id)||ve.locked===!0;return s.jsxs("button",{className:`hub-drive-item ${M===ve.id?"active":""} ${Ne?"unavailable":""}`,onClick:()=>{he(ve)},"aria-pressed":M===ve.id,type:"button",children:[s.jsx("span",{className:"hub-drive-item-icon",children:s.jsx(ke,{size:16})}),s.jsxs("span",{className:"hub-drive-item-copy",children:[s.jsx("strong",{children:ve.name}),s.jsx("small",{children:ve.displayPath||ve.name}),s.jsxs("em",{children:[dx(ve.freeBytes||0)," free / ",dx(ve.totalBytes||0)]})]}),L===ve.id?s.jsx(ci,{className:"hub-drive-item-status spin",size:15}):Ne?s.jsx(ly,{className:"hub-drive-item-status",size:15}):null]},ve.id)})})]},ce.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:T.map((ce,ve)=>s.jsxs("span",{className:"hub-file-explorer-breadcrumb-item",children:[ve>0&&s.jsx(ap,{size:13,"aria-hidden":"true"}),s.jsx("button",{className:`hub-file-explorer-breadcrumb ${ve===T.length-1?"current":""}`,onClick:()=>fe(ve),"aria-current":ve===T.length-1?"location":void 0,type:"button",children:ce.name})]},ce.svarPath))}),s.jsxs("div",{className:"hub-file-explorer-navigation-actions",children:[W&&s.jsx(ci,{className:"hub-file-explorer-loading-icon spin",size:15,"aria-label":"Loading folder"}),s.jsx("button",{className:"icon-button",onClick:Se,disabled:T.length<=1||W,title:"Back to parent folder",type:"button",children:s.jsx(Gx,{size:16})})]})]}),O&&s.jsxs("div",{className:"hub-file-explorer-folder-error",role:"alert",children:[s.jsx(ly,{size:15}),s.jsx("span",{children:O})]}),s.jsx("div",{className:"hub-file-explorer-svar",onKeyDownCapture:Be,children:s.jsx(QA,{fonts:!1,children:s.jsx(KA,{data:oe,panels:G?[{path:G,selected:[]}]:void 0,readonly:!0,mode:"table",preview:!1,init:Oe,icons:"simple",menuOptions:ge},`${I?.id||"no-root"}:${V}`)})})]})]})]})}class dN 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(rf,{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(Eo,{size:15})," Retry"]})]}):this.props.children}}function fN(n){return n.deviceName||n.hostname||n.deviceId}function mN({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(Jc,{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:fN(m)}),s.jsxs("small",{children:["Slot ",m.slotNumber?String(m.slotNumber).padStart(3,"0"):"-"," / ",m.platform||"unknown OS"]})]}),s.jsx(_n,{size:17,"aria-hidden":"true"})]},m.deviceId)})})]})}function hN(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 pN({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(Od,{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(Od,{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(Od,{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 / ",hN(g.totalBytes)," · ",g.lastSyncedAt?`Last sync ${ab(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(Eo,{size:14})," Sync now"]}),s.jsx("button",{className:"icon-button",onClick:()=>p(g),title:"Remove sync folder",type:"button",children:s.jsx(ep,{size:15})})]},g.id))})]})}function gN(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(Xc,{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(mN,{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(ko,{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(Xc,{size:17})," Share selected"]}),s.jsxs("button",{className:"file-share-secondary-button",onClick:n.onAddSync,disabled:!n.canAddSync,type:"button",children:[s.jsx(ko,{size:16})," Add selected folder to Sync"]})]}):s.jsx(pN,{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 vN(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 fx(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 mx(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 hx(n){return["completed","partially-failed","failed","cancelled"].includes(n)}function yN({hubUrl:n,devices:a,localFeatureAccess:r,upgradeNotice:l,remoteDirectory:c,onRemoteDirectoryChange:d,targetMode:m,selectedTargetIds:p,onTargetModeChange:v,onTargetToggle:g,filePickerRef:w,folderPickerRef:x,onBrowserFileImport:b,onBrowserFolderImport:j,onNotice:C,onTransferChange:k}){const M=Array.isArray(a)?a:[],[A,T]=u.useState([]),[R,P]=u.useState(!0),[F,V]=u.useState(""),[_,L]=u.useState([]),[ne,W]=u.useState([]),[J,O]=u.useState(null),[be,re]=u.useState(!1),[K,I]=u.useState([]),[ee,G]=u.useState(!0),[q,oe]=u.useState(!1),[we,Q]=u.useState("send"),[$,he]=u.useState([]),fe=u.useRef(new Set),me=u.useMemo(()=>m==="all"?M.map(ae=>ae.deviceId):p.filter(ae=>M.some(Te=>Te.deviceId===ae)),[M,p,m]),Se=$.find(ae=>!hx(ae.state)),Be=ne.length===1&&ne[0].type==="folder"?ne[0]:null,Oe=ne.length===0?"Select files or folders from the Hub explorer.":be?"Calculating selection size...":J?`${J.files} files, ${J.folders} folders · ${vN(J.totalBytes)}`:`${ne.length} item${ne.length===1?"":"s"} selected`,ge=ae=>{k({id:ae.jobId,state:ae.state,progress:fx(ae),message:mx(ae)})},Ze=u.useCallback(async()=>{const ae=await ZA(n,!0);return T(ae),V(""),ae},[n]),Ke=async()=>{try{const Te=(await tN(n,!0)).jobs||[],Pe=await Promise.all([...fe.current].map(async It=>{try{return await nN(It,n)}catch{return null}})),Je=[...Te,...Pe.filter(Boolean)],Mt=[...new Map(Je.map(It=>[It.jobId,It])).values()];he(Mt),Mt.forEach(ge),Mt.filter(It=>hx(It.state)).forEach(It=>fe.current.delete(It.jobId))}catch{}};u.useEffect(()=>{let ae=!0;P(!0),V(""),Promise.all([Ze(),ux(n).then(Pe=>{ae&&I(Pe)})]).catch(Pe=>{ae&&(V(Pe instanceof Error?"Hub file system is unavailable. Make sure LiveDesk Hub is running on this computer.":"Hub file system is unavailable."),C(Pe instanceof Error?Pe.message:"Hub file system is unavailable."))}).finally(()=>{ae&&(P(!1),G(!1))}),Ke();const Te=window.setInterval(()=>{Ke()},800);return()=>{ae=!1,window.clearInterval(Te)}},[n,Ze]),u.useEffect(()=>{if(_.length===0){O(null);return}let ae=!1;return re(!0),JA(_,n).then(Te=>{ae||O(Te)}).catch(Te=>{ae||C(Te instanceof Error?Te.message:"Unable to calculate selected size.")}).finally(()=>{ae||re(!1)}),()=>{ae=!0}},[n,_.join("|")]);const ce=(ae,Te)=>{L(ae),W(Te)},ve=ae=>{ae.forEach(Te=>fe.current.add(Te.jobId)),he(Te=>[...new Map([...Te,...ae].map(Pe=>[Pe.jobId,Pe])).values()]),ae.forEach(ge)},ke=async()=>{if(!r){C(l);return}if(_.length===0){C("Select files or folders from the Hub explorer.");return}if(me.length===0){C("Choose at least one connected workstation.");return}if(Se){C("A Hub transfer is already running.");return}try{const ae=await eN(_,me,c.trim(),n);fe.current.add(ae.jobId),C("Hub transfer queued."),await Ke()}catch(ae){C(ae instanceof Error?ae.message:"Unable to start Hub transfer.")}},Ne=async ae=>{const Te=ae||Be;if(!Te||Te.type!=="folder"){C("Select one folder to add it to Sync.");return}try{const Pe=await sN(Te.id,n);I(Je=>[...Je.filter(Mt=>Mt.id!==Pe.folder.id),Pe.folder]),Q("sync"),C(`${Te.name} is ready for Hub sync.`)}catch(Pe){C(Pe instanceof Error?Pe.message:"Unable to add the Hub folder to Sync.")}},He=async ae=>{if(me.length===0){C("Choose at least one connected workstation.");return}oe(!0),I(Te=>Te.map(Pe=>Pe.id===ae.id?{...Pe,status:"syncing"}:Pe));try{const Te=await lN(ae.id,me,c.trim(),n);ve(Te.jobs||[]),C(Te.jobs?.length?"Hub sync queued.":"No changed files to sync.");const Pe=await ux(n);I(Pe)}catch(Te){C(Te instanceof Error?Te.message:"Unable to sync the Hub folder."),I(Pe=>Pe.map(Je=>Je.id===ae.id?{...Je,status:"error",message:"Sync failed"}:Je))}finally{oe(!1)}},$e=async()=>{oe(!0);try{for(const ae of K)await He(ae)}finally{oe(!1)}},Xe=async ae=>{try{const Te=await iN(ae.id,{autoSync:!ae.autoSync},n);I(Pe=>Pe.map(Je=>Je.id===ae.id?Te.folder:Je))}catch(Te){C(Te instanceof Error?Te.message:"Unable to update auto sync.")}},ye=async ae=>{try{await rN(ae.id,n),I(Te=>Te.filter(Pe=>Pe.id!==ae.id))}catch(Te){C(Te instanceof Error?Te.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:ae=>{ae.currentTarget.files&&b(ae.currentTarget.files),ae.currentTarget.value=""}}),s.jsx("input",{ref:x,className:"hidden-file-input",type:"file",multiple:!0,webkitdirectory:"",directory:"",onChange:ae=>{ae.currentTarget.files&&j(ae.currentTarget.files),ae.currentTarget.value=""}}),s.jsx("div",{className:"file-share-workspace",children:s.jsxs(dN,{onRetry:()=>window.location.reload(),children:[s.jsx(uN,{hubUrl:n,roots:A,loading:R,error:F,onRefreshRoots:Ze,onImportFiles:()=>w.current?.click(),onImportFolder:()=>x.current?.click(),onSelectionChange:ce,onShareItem:ae=>{L([ae.id]),W([ae]),Q("send")},onAddSyncFolder:ae=>{L([ae.id]),W([ae]),Ne(ae)},onNotice:C}),s.jsx(gN,{devices:M,targetMode:m,selectedTargetIds:p,onTargetModeChange:v,onTargetToggle:g,remoteDirectory:c,onRemoteDirectoryChange:d,selectedEntries:ne,selectedSummary:Oe,canShare:r&&!Se&&_.length>0&&me.length>0&&!be,onShare:()=>{ke()},canAddSync:!!Be,onAddSync:()=>{Ne()},tab:we,onTabChange:Q,folders:K,foldersLoading:ee,syncBusy:q,onSyncAll:()=>{$e()},onSync:ae=>{He(ae)},onToggleAuto:ae=>{Xe(ae)},onRemove:ae=>{ye(ae)},onAddFolder:()=>{Ne()}})]})}),Se&&s.jsx("footer",{className:"file-share-workspace-footer",children:s.jsxs("span",{children:[mx(Se)," · ",fx(Se),"% ",s.jsx("button",{className:"icon-button",onClick:()=>{aN(Se.jobId,n).then(ae=>{he(Te=>Te.map(Pe=>Pe.jobId===ae.jobId?ae:Pe)),ge(ae)})},title:"Cancel transfer",type:"button",children:s.jsx(Sa,{size:14})})]})})]})}const xN=u.forwardRef(function({value:a,onChange:r,onSubmit:l,onOpenSuggestedTasks:c,suggestedOpen:d=!1,suggestedTaskCount:m,disabled:p=!1,placeholder:v="Ask LiveDesk to work across your machines...",compact:g=!1},w){return s.jsxs("form",{className:"agents-composer",onSubmit:x=>{x.preventDefault(),l()},children:[s.jsx("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(JS,{size:17})}),s.jsx("textarea",{ref:w,value:a,onChange:x=>r(x.target.value.slice(0,4e3)),placeholder:v,"aria-label":"Ask LiveDesk",rows:g?1:2,disabled:p}),s.jsxs("button",{className:"agents-run-button",type:"submit",disabled:p||!a.trim(),children:[p?s.jsx(ci,{className:"spin",size:16}):s.jsx(Xc,{size:16}),p?"Running":"Run"]})]})}),bN=["read","processControl","serviceControl","applicationControl","fileRead","fileWrite","fileDelete","shell","script","softwareInstall","network","systemPower","systemConfiguration","userAccount"];function tf(n){return n.deviceName?.trim()||n.hostname?.trim()||n.deviceId}function nf(n){return n.connected!==!0?!1:n.synthetic===!0?!0:!n.channels||n.channels.control===!0}function wN(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 CN(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:null}function Za(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Td(n){const a=Za(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 jN(n){const a=Za(n);return a===null?"":`${Math.round((a<=1?a:a/100)*100)}%`}function kN(n){return!n||/^(?:[\w .-]+ )?collected(?:\.)?$/i.test(n.trim())?"":n.trim()}function af(n,a){if(a.error)return a.error;const r=CN(a.data),l=kN(a.result||"");if(!r)return l||a.stage||a.status;if(n==="system.health"){const c=typeof r.machine=="string"?r.machine:"",d=Td(r.freeMemoryBytes),m=Td(r.totalMemoryBytes),p=Za(r.totalMemoryBytes)&&Za(r.freeMemoryBytes)!==null?`${Math.round(Za(r.freeMemoryBytes)/Za(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=Td(r.freeBytes),m=Za(r.totalBytes)&&Za(r.freeBytes)!==null?`${Math.round(Za(r.freeBytes)/Za(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=jN(r.usageRatio),m=Za(r.temperatureC)!==null?`${Math.round(Za(r.temperatureC))}°C`:"",p=Td(r.freeMemoryBytes);return[c,d&&`GPU ${d}`,m,p&&`${p} free`].filter(Boolean).join(" · ")||l||a.status}if(n==="process.list"){const c=Za(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 px(n,a){const r=af(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 AN({state:n,operation:a}){const r=n.status==="completed"?ui:n.status==="failed"||n.status==="cancelled"?Sa:n.status==="running"?ci:Qx,l=n.status==="running"?n.stage||"Working":n.status==="completed"?a?af(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 NN({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"),x=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=>px(n,R)),j=b.filter(R=>R.status==="completed").length,C=x.failed>0,k=b.length>0,M=a.filter(R=>g==="issues"?px(n,R):g==="running"?R.status==="running"||R.status==="queued":g==="completed"?R.status==="completed":g==="failed"?R.status==="failed":!0),A=k&&!m||r==="completed-with-failures"?"Completed with issues":r[0]?.toUpperCase()+r.slice(1),T=a.filter(R=>R.status==="completed").map(R=>af(n,R)).filter(Boolean).filter((R,P,F)=>F.indexOf(R)===P).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-${k?"completed-with-failures":r}`,children:A})]}),s.jsxs("div",{className:"agent-task-summary","aria-label":"Task summary",children:[s.jsxs("strong",{children:[x.total," targets"]}),s.jsxs("span",{className:"summary-completed",children:[x.completed," completed"]}),x.running>0&&s.jsxs("span",{className:"summary-running",children:[x.running," running"]}),x.queued>0&&s.jsxs("span",{children:[x.queued," queued"]}),C&&s.jsxs("span",{className:"summary-failed",children:[x.failed," failed"]}),j>0&&s.jsxs("span",{className:"summary-cancelled",children:[j," warning"]}),x.cancelled>0&&s.jsxs("span",{className:"summary-cancelled",children:[x.cancelled," cancelled"]})]}),T.length>0&&s.jsxs("div",{className:"agent-task-result-preview",title:T.join(" · "),children:[s.jsx("span",{children:"Result"}),T.join(" · ")]}),s.jsx("div",{className:"agent-target-chips","aria-label":"Target status overview",children:a.map((R,P)=>{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}: ${af(n,R)}`,"aria-label":`${P+1}. ${R.deviceName}: ${R.status}`,children:[s.jsx("b",{children:String(P+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(e0,{size:14}):s.jsx(Xx,{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:M.length>0?M.map(R=>s.jsx(AN,{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(t0,{size:14})," Cancel"]}),!m&&C&&c&&s.jsxs("button",{onClick:c,disabled:d,type:"button",children:[s.jsx(Gc,{size:14})," Retry failed"]})]})]})}function MN(n){try{return JSON.stringify(n,null,2).slice(0,6e3)}catch{return"{}"}}function TN({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:MN(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(Sa,{size:14})," Reject"]}),s.jsxs("button",{disabled:a,onClick:()=>r("once"),type:"button",children:[s.jsx(ui,{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(rf,{size:13})," Approval is bound to this run, tool, arguments, selected devices, and policy hash."]})]})}function EN(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 RN({items:n,onCancel:a,onRetry:r,busyBatchId:l,approvals:c,onApprove:d,onReject:m,busyApprovalId:p,progress:v,emptyTitle:g="Ask LiveDesk to work across your machines.",emptyBody:w="Start with a read-only request such as “모든 PC에서 ComfyUI가 실행 중인지 확인해줘”."}){const x=u.useRef(null),b=u.useRef(!0),j=u.useRef(""),C=n[n.length-1];return u.useLayoutEffect(()=>{const k=x.current;k&&(C?.type==="user"&&C.id!==j.current&&(b.current=!0),j.current=C?.id||"",b.current&&(k.scrollTop=k.scrollHeight))},[c,n,C?.id,C?.type,v?.message,v?.stage]),s.jsxs("section",{className:"agents-conversation","aria-live":"polite",ref:x,onScroll:k=>{const M=k.currentTarget;b.current=M.scrollHeight-M.scrollTop-M.clientHeight<72},children:[c.filter(k=>k.status==="pending").map(k=>s.jsx(TN,{approval:k,busy:p===k.approvalId,onApprove:M=>d(k,M),onReject:()=>m(k)},k.approvalId)),n.length===0&&s.jsxs("div",{className:"agents-empty-conversation",children:[s.jsx("strong",{children:g}),s.jsx("span",{children:w})]}),n.map(k=>{if(k.type==="task"){const M=k;return s.jsx(NN,{operation:M.operation,states:M.states,status:M.status,onCancel:()=>a(M.batchId,M.agentRunId),onRetry:()=>r(M.batchId),busy:l===M.batchId},M.id)}return s.jsxs("article",{className:`agents-message ${k.type}`,children:[s.jsx("span",{children:k.type==="user"?"You":"LiveDesk Agent"}),s.jsx("p",{children:k.text})]},k.id)}),v&&s.jsxs("article",{className:"agents-message agent agents-progress-message",role:"status",children:[s.jsxs("span",{children:[s.jsx(ci,{"aria-hidden":"true",size:15}),EN(v.stage)]}),s.jsx("p",{children:v.message})]})]})}const gx=["Recommended","Health & capacity","Processes & services","AI workloads","Files & configuration","Software & automation","Network & connectivity","Power & maintenance","Troubleshooting & recovery"],jn=["windows","macos","linux"],qr={"system.health":{label:"system health",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:jn},"gpu.status":{label:"GPU status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:jn},"disk.status":{label:"disk status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:jn},"process.list":{label:"process inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:jn},"service.status":{label:"service inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:jn},"diagnostics.collect":{label:"diagnostics collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:jn},"process.control":{label:"process control",permissionCategory:"processControl",readOnly:!1,risk:"high",supportedPlatforms:jn},"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:jn},"application.close":{label:"application close",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:jn},"file.read":{label:"file reading",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:jn},"file.write":{label:"file writing",permissionCategory:"fileWrite",readOnly:!1,risk:"high",supportedPlatforms:jn},"file.delete":{label:"file deletion",permissionCategory:"fileDelete",readOnly:!1,risk:"critical",supportedPlatforms:jn},"file.list":{label:"directory listing",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:jn},"command.run":{label:"command execution",permissionCategory:"shell",readOnly:!1,risk:"critical",supportedPlatforms:jn},"script.run":{label:"script execution",permissionCategory:"script",readOnly:!1,risk:"high",supportedPlatforms:jn},"software.install":{label:"software installation",permissionCategory:"softwareInstall",readOnly:!1,risk:"high",supportedPlatforms:jn},"network.status":{label:"network inspection",permissionCategory:"network",readOnly:!0,risk:"low",supportedPlatforms:jn},"system.power":{label:"power control",permissionCategory:"systemPower",readOnly:!1,risk:"critical",supportedPlatforms:jn},"system.configure":{label:"system configuration",permissionCategory:"systemConfiguration",readOnly:!1,risk:"critical",supportedPlatforms:jn},"logs.collect":{label:"log collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:jn}};new Set(Object.keys(qr));const DN={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","문제해결","복구","장애"]},vx=["low","medium","high","critical"];function LN(n){return n.reduce((a,r)=>{const l=qr[r].risk;return vx.indexOf(l)>vx.indexOf(a)?l:a},"low")}function _N(n){return jn.filter(a=>n.every(r=>qr[r].supportedPlatforms.includes(a)))}function Ue(n,a,r,l,c,d,m={}){const p=m.description||l,v=c.flatMap(w=>w.split(".")),g=[...new Set([...DN[a],...d,...v])];return{id:n,category:a,title:r,prompt:l,description:p,requiredOperations:c,risk:m.risk||LN(c),targetSupport:m.targetSupport||"single-or-multiple",supportedPlatforms:m.supportedPlatforms||_N(c),keywords:g,recommended:m.recommended??!1,enabled:!0}}const nw=[Ue("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}),Ue("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}),Ue("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}),Ue("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}),Ue("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}),Ue("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}),Ue("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}),Ue("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}),Ue("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","높은 사용량"]),Ue("health-uptime","Health & capacity","Review workstation uptime","Show uptime, boot time, and current system health for the target workstations.",["system.health"],["uptime","boot","가동시간"]),Ue("health-gpu-temperature","Health & capacity","Check GPU temperature","Check GPU temperature and thermal warnings on the current targets.",["gpu.status"],["thermal","temperature","발열"]),Ue("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"]),Ue("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","디스크"]),Ue("health-gpu-compare","Health & capacity","Compare GPU capacity","Compare GPU model, memory, temperature, and utilization across the current targets.",["gpu.status"],["compare","graphics","capacity"]),Ue("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","경고"]),Ue("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"]),Ue("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","실행 중"]),Ue("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"]),Ue("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"}),Ue("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"}),Ue("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"}),Ue("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"}),Ue("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","서비스 상태"]),Ue("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"}),Ue("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"]),Ue("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"}),Ue("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"}),Ue("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"]),Ue("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"]),Ue("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"}),Ue("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"]),Ue("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"}),Ue("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"}),Ue("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","구성"]),Ue("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"]),Ue("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"}),Ue("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"}),Ue("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"]),Ue("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"}),Ue("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"}),Ue("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"]}),Ue("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"]}),Ue("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"]}),Ue("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"}),Ue("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"}),Ue("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"}),Ue("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"]),Ue("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"}),Ue("network-adapter-status","Network & connectivity","Check network adapters","Show adapter state, address, and link information for the current targets.",["network.status"],["adapter","ethernet","wifi","네트워크 상태"]),Ue("network-disconnected","Network & connectivity","Find disconnected targets","Find current targets with disconnected or degraded network adapters.",["network.status"],["disconnected","offline","연결 끊김"]),Ue("network-link-speed","Network & connectivity","Check link speed","Report network link speed and duplex information for the current targets.",["network.status"],["speed","bandwidth","duplex"]),Ue("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"]),Ue("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"]),Ue("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"]),Ue("network-compare","Network & connectivity","Compare target connectivity","Compare adapter state, addresses, and link speed across the current targets.",["network.status"],["compare","inventory","connectivity"]),Ue("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"]),Ue("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"}),Ue("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"}),Ue("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"}),Ue("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"}),Ue("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"}),Ue("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"}),Ue("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"}),Ue("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"}),Ue("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"}),Ue("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"}),Ue("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"}),Ue("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"}),Ue("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"}),Ue("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"}),Ue("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"}),Ue("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","장애 보고서"])],uh={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 zN(n,a){return n==="safe-auto"?uh:n==="full-access"?{...uh,processControl:"allow",serviceControl:"allow",applicationControl:"allow",fileDelete:"allow",shell:"allow",script:"allow",softwareInstall:"allow",systemPower:"allow",systemConfiguration:"allow"}:n==="custom"&&a?a:{...uh,processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileWrite:"ask",network:"ask"}}function IN(n,a,r){const l=zN(a,r),c=n.requiredOperations.map(d=>l[qr[d].permissionCategory]);if(c.includes("deny")){const d=n.requiredOperations.find(m=>l[qr[m].permissionCategory]==="deny");return{state:"blocked",label:"Blocked",reason:`This task requires ${qr[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=>qr[d].readOnly)?{state:"read-only",label:"Read only"}:a==="full-access"?{state:"full-access",label:"Full Access"}:{state:"auto",label:"Auto allowed"}}function ON(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 HN(n,a,r){const l=new Set(r);return n.filter(c=>c.connected&&(a==="all"||a==="auto"||l.has(c.deviceId)))}function BN(n,a){const r=ON(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=>qr[c].readOnly):a.requiredOperations.every(c=>l.includes(c))}function aw(n,a,r,l,c,d){const m=IN(n,c,d),p=HN(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)),x=w.map(j=>j.deviceId),b=v.filter(j=>!x.includes(j));return w.length===0?{...g,unsupportedDeviceIds:b,reason:"No current target supports the required platform and client capabilities."}:{...g,available:!0,availableDeviceIds:x,unsupportedDeviceIds:b}}function FN(n,a,r,l,c,d){return n.filter(m=>m.enabled&&aw(m,a,r,l,c,d).available).length}const dh="livedesk.agentPromptRecent",fh="livedesk.agentPromptFavorites",PN={Recommended:Ds,"Health & capacity":bn,"Processes & services":r0,"AI workloads":Ah,"Files & configuration":i0,"Software & automation":Vd,"Network & connectivity":np,"Power & maintenance":Ht,"Troubleshooting & recovery":s0};function yx(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 Ed(n,a){try{window.localStorage.setItem(n,JSON.stringify(a))}catch{}}function mh(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 $N(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 UN(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 qN(n){return`permission-${n}`}function GN(n){return n==="low"?"Low risk":n==="medium"?"Medium risk":n==="high"?"High risk":"Critical risk"}function VN(n){return n==="windows"?"Windows":n==="macos"?"macOS":"Linux"}function WN({devices:n,targetMode:a,selectedIds:r,permissionMode:l,customCategories:c,onSelectPrompt:d,onClose:m}){const[p,v]=u.useState(""),[g,w]=u.useState("all"),[x,b]=u.useState(()=>yx(dh)),[j,C]=u.useState(()=>yx(fh)),[k,M]=u.useState(0),[A,T]=u.useState(""),R=u.useRef(null),P=u.useRef(null),F=u.useMemo(()=>nw.filter(K=>K.enabled),[]),V=u.useMemo(()=>new Map(F.map(K=>[K.id,aw(K,n,a,r,l,c)])),[c,n,l,r,a,F]),_=u.useMemo(()=>[...V.values()].filter(K=>K.available).length,[V]),L=u.useMemo(()=>n.filter(K=>K.connected&&(a==="all"||a==="auto"||r.includes(K.deviceId))).length,[n,r,a]),ne=u.useMemo(()=>{const K=F.filter(I=>UN(I,V.get(I.id),p));return g==="recent"?x.map(I=>K.find(ee=>ee.id===I)).filter(I=>!!I):g==="favorites"?j.map(I=>K.find(ee=>ee.id===I)).filter(I=>!!I):g==="all"?K:K.filter(I=>{const ee=V.get(I.id);return g==="read-only"?ee.state==="read-only":g==="auto"?ee.state==="auto":g==="approval"?ee.state==="approval":g==="full-access"?ee.state==="full-access":g==="available"?ee.available:g==="unavailable"?!ee.available:I.category===g})},[V,j,g,x,p,F]),W=u.useMemo(()=>g!=="all"?[{category:mh(g),templates:ne}]:gx.map(K=>({category:K,templates:ne.filter(I=>I.category===K)})).filter(K=>K.templates.length>0),[g,ne]);u.useEffect(()=>{M(K=>Math.min(K,Math.max(0,ne.length-1)))},[ne.length]),u.useEffect(()=>{Ed(dh,x)},[x]),u.useEffect(()=>{Ed(fh,j)},[j]),u.useEffect(()=>{P.current?.focus();const K=ee=>{ee.target instanceof Node&&!R.current?.contains(ee.target)&&m()},I=ee=>{ee.key==="Escape"&&(ee.preventDefault(),m())};return document.addEventListener("pointerdown",K),document.addEventListener("keydown",I),()=>{document.removeEventListener("pointerdown",K),document.removeEventListener("keydown",I)}},[m]);const J=K=>{const I=V.get(K.id);if(!I.available){T(I.reason||"This task is not available for the current targets and permission policy.");return}const ee=[K.id,...x.filter(G=>G!==K.id)].slice(0,10);b(ee),Ed(dh,ee),d(K.prompt),m()},O=K=>{C(I=>{const ee=I.includes(K)?I.filter(G=>G!==K):[K,...I];return Ed(fh,ee),ee})},be=K=>{K.key==="ArrowDown"?(K.preventDefault(),M(I=>Math.min(I+1,Math.max(0,ne.length-1)))):K.key==="ArrowUp"?(K.preventDefault(),M(I=>Math.max(I-1,0))):K.key==="Enter"&&ne[k]&&(K.preventDefault(),J(ne[k]))};let re=-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(Ds,{size:15})," Suggested tasks"]}),s.jsxs("small",{children:[_," 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(Sa,{size:16})})]}),s.jsxs("label",{className:"agents-suggested-search",children:[s.jsx(n0,{size:15,"aria-hidden":"true"}),s.jsx("input",{ref:P,value:p,onChange:K=>v(K.target.value),onKeyDown:be,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",...gx].map(K=>{const I=K==="recent"?Wx:K==="favorites"?Nh:K==="all"?Ds:K==="available"?_n:K==="unavailable"?a0:K==="read-only"||K==="auto"||K==="approval"||K==="full-access"?Ht:PN[K];return s.jsxs("button",{className:g===K?"active":"",type:"button",title:mh(K),"aria-label":mh(K),"aria-pressed":g===K,onClick:()=>{w(K),M(0),T("")},children:[s.jsx(I,{size:12})," ",$N(K)]},K)})}),A&&s.jsx("div",{className:"agents-suggested-notice",role:"status",children:A}),s.jsxs("div",{className:"agents-suggested-list",role:"listbox","aria-label":"Suggested tasks",children:[W.map(K=>s.jsxs("div",{className:"agents-suggested-group",children:[s.jsx("strong",{children:K.category}),K.templates.map(I=>{re+=1;const ee=re===k,G=j.includes(I.id),q=V.get(I.id),oe=q.availableDeviceIds.length+q.unsupportedDeviceIds.length||L,we=q.available?`Available on ${q.availableDeviceIds.length} of ${oe} target${oe===1?"":"s"}`:`Unavailable: ${q.reason||"not supported by the current targets"}`;return s.jsxs("div",{className:`agents-suggested-item ${ee?"active":""} ${q.available?"":"unavailable"}`,children:[s.jsxs("button",{className:"agents-suggested-prompt",type:"button",role:"option","aria-selected":ee,"aria-disabled":!q.available,onClick:()=>J(I),children:[s.jsx("span",{children:I.title}),s.jsx("small",{className:"agents-suggested-description",children:I.description}),s.jsxs("span",{className:"agents-suggested-meta",children:[s.jsx("em",{children:I.category}),s.jsx("em",{className:qN(q.state),children:q.label}),s.jsx("em",{className:`risk-${I.risk}`,children:GN(I.risk)}),s.jsx("em",{children:I.supportedPlatforms.map(VN).join(" · ")}),s.jsx("em",{className:q.available?"availability-ok":"availability-unavailable",children:we}),q.available&&q.unsupportedDeviceIds.length>0&&s.jsxs("em",{className:"availability-warning",children:["Unsupported on ",q.unsupportedDeviceIds.length]})]})]}),s.jsx("button",{className:`agents-suggested-favorite ${G?"favorite":""}`,type:"button","aria-label":G?`Remove ${I.title} from favorites`:`Add ${I.title} to favorites`,"aria-pressed":G,onClick:()=>O(I.id),children:s.jsx(Nh,{size:14,fill:G?"currentColor":"none"})})]},I.id)})]},K.category)),ne.length===0&&s.jsx("p",{className:"agents-suggested-empty",children:"No tasks match this search or current filter."})]})]})}function YN({devices:n,mode:a,selectedIds:r,onModeChange:l,onToggle:c,permissionMode:d,onPermissionModeChange:m}){const p=n.filter(nf),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(Jc,{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(ui,{size:14})," Selected ",v]}),s.jsxs("button",{className:a==="auto"?"active":"",onClick:()=>l("auto"),type:"button",children:[s.jsx(Ds,{size:14})," Auto"]}),s.jsxs("button",{type:"button",disabled:!0,title:"Saved workstation groups are coming next.",children:[s.jsx(Jc,{size:14})," Group ",s.jsx("small",{children:"Soon"})]})]}),s.jsxs("label",{className:`agents-permission-picker permission-${d}`,children:[s.jsx(rf,{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(Xx,{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=nf(g),x=a==="all"||a==="auto"?w:r.includes(g.deviceId);return s.jsxs("label",{className:`agents-target-option ${x?"selected":""} ${w?"":"offline"}`,children:[s.jsx("input",{type:"checkbox",checked:x,disabled:!w||a!=="selected",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:tf(g)}),s.jsx("small",{children:w?"Ready":g.connected?"Agent reconnecting":"Offline"})]}),x&&s.jsx(ui,{className:"agents-target-check",size:15,"aria-hidden":"true"})]},g.deviceId)})})]})}async function KN(n,a){return We("/api/settings/agent/plan",{method:"POST",body:JSON.stringify({instruction:a})},n)}async function QN(n,a){return We("/api/settings/agent/run",{method:"POST",body:JSON.stringify(a)},n)}async function XN(n,a){return We(`/api/settings/agent/runs/${encodeURIComponent(a)}`,void 0,n)}async function ZN(n,a){return We(`/api/settings/agent/runs/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})},n)}async function JN(n){return We("/api/settings/agent/runs/cancel-all",{method:"POST",body:JSON.stringify({})},n)}async function eM(n,a,r,l){return We(`/api/settings/agent/runs/${encodeURIComponent(a)}/approvals/${encodeURIComponent(r)}/approve`,{method:"POST",body:JSON.stringify({scope:l})},n)}async function tM(n,a,r,l="User rejected this action."){return We(`/api/settings/agent/runs/${encodeURIComponent(a)}/approvals/${encodeURIComponent(r)}/reject`,{method:"POST",body:JSON.stringify({reason:l})},n)}async function nM(n,a,r){return We(`/api/settings/agent/policies/${encodeURIComponent(a)}`,{method:"PUT",body:JSON.stringify({categories:r})},n)}async function aM(n,a){return We("/api/settings/agent/summary",{method:"POST",body:JSON.stringify(a)},n)}async function sM(n,a){return We("/api/remote/tasks",{method:"POST",body:JSON.stringify({instruction:a.instruction,deviceIds:a.deviceIds,operation:a.operation,targetQuery:a.targetQuery,approvalLevel:"read-only"})},n)}async function iM(n,a){return We(`/api/remote/tasks/${encodeURIComponent(a)}`,void 0,n)}async function rM(n,a){return We(`/api/remote/tasks/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})},n)}async function lM(n,a){return We(`/api/remote/tasks/${encodeURIComponent(a)}/retry`,{method:"POST",body:JSON.stringify({failedOnly:!0})},n)}function wl(n){return`${n}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Rd(n,a){const r=new Map(a.map(l=>[l.deviceId,tf(l)]));return n.results.map(l=>({deviceId:l.deviceId,deviceName:l.deviceName||r.get(l.deviceId)||l.deviceId,status:wN(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 oM(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 cM(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}
15
- ${l.map(p=>`${p.deviceName}는 ${p.error||"응답하지 않았습니다."}`).join(`
16
- `)}`:m}return l.length>0?`${r.length}대 완료, ${l.length}대 실패했습니다.`:`${r.length}대 작업이 완료되었습니다.`}const uM={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 dM(n){return n==="safe-auto"?"Safe Auto":n==="full-access"?"Full Access":n==="custom"?"Custom":"Ask"}function fM(n){return n.replace(/([A-Z])/g," $1").replace(/^./,a=>a.toUpperCase())}function mM(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 xx({hubUrl:n,devices:a,launchRequest:r,variant:l="page",selectedDeviceIds:c=[]}){const d=l==="dock",[m,p]=u.useState(d?c.length>0?"selected":"auto":"all"),[v,g]=u.useState(c),[w,x]=u.useState("auto"),[b,j]=u.useState(""),[C,k]=u.useState([]),[M,A]=u.useState(""),[T,R]=u.useState(""),[P,F]=u.useState(""),[V,_]=u.useState("safe-auto"),[L]=u.useState("custom-default"),[ne,W]=u.useState(uM),[J,O]=u.useState([]),[be,re]=u.useState(""),[K,I]=u.useState(!1),[ee,G]=u.useState(null),[q,oe]=u.useState(!1),[we,Q]=u.useState(""),[$,he]=u.useState(!1),[fe,me]=u.useState(null),Se=u.useRef(null),Be=u.useRef(new Set),Oe=u.useRef(new Set),ge=u.useRef(new Set),Ze=u.useMemo(()=>a.filter(nf).map(X=>X.deviceId),[a]),Ke=u.useMemo(()=>FN(nw,a,m,v,V,ne),[ne,a,V,v,m]);u.useEffect(()=>{d&&g(c)},[d,c]),u.useEffect(()=>{r?.deviceId&&(p("selected"),g([r.deviceId]),j(r.instruction),he(!1),window.requestAnimationFrame(()=>{Se.current?.focus(),Se.current?.setSelectionRange(r.instruction.length,r.instruction.length)}))},[r]);const ce=u.useCallback(X=>{const De=Rd(X,a);if(k(ze=>ze.map(Ae=>Ae.type==="task"&&Ae.batchId===X.batchId?{...Ae,states:oM(Ae.states,De),status:X.status}:Ae)),!["running","queued"].includes(X.status)&&!Be.current.has(X.batchId)){Be.current.add(X.batchId);const ze=wl("agent-summary");k(Ae=>[...Ae,{type:"agent",id:ze,text:cM(X,De)}]),X.operation&&aM(n,{instruction:X.instructionPreview,operation:X.operation,total:De.length,completed:De.filter(Ae=>Ae.status==="completed").length,failed:De.filter(Ae=>Ae.status==="failed").length,results:De.map(Ae=>({deviceName:Ae.deviceName,status:Ae.status,result:Ae.result,error:Ae.error}))}).then(Ae=>{!Ae.ok||!Ae.summary||k(et=>et.map(gt=>gt.type==="agent"&&gt.id===ze?{...gt,text:Ae.summary}:gt))}).catch(()=>{}),A(Ae=>Ae===X.batchId?"":Ae)}},[a,n]),ve=u.useCallback(async X=>{const De=await iM(n,X);return ce(De),De},[n,ce]),ke=u.useCallback((X,De)=>{ge.current.has(X.batchId)||(ge.current.add(X.batchId),k(ze=>[...ze,{type:"task",id:wl("task"),batchId:X.batchId,agentRunId:De,operation:X.operation||"diagnostics.collect",instruction:X.instructionPreview,states:Rd(X,a),status:X.status}])),ce(X)},[a,ce]),Ne=u.useCallback(async X=>{const De=await XN(n,X);for(const Ae of De.taskBatches||[])ke(Ae,X);O(De.approvals||[]);const ze=["running","queued","waiting-approval"].includes(De.status);if(me(ze?{runId:X,stage:De.stage||De.status,message:De.progressMessage||(De.status==="waiting-approval"?"Review the requested action to continue.":"Codex is preparing the answer.")}:Ae=>Ae?.runId===X?null:Ae),!ze&&!Oe.current.has(X)){Oe.current.add(X);const Ae=[De.error,De.errorMessage].filter(Boolean).join(" — "),et=De.finalResponse?.trim()||(De.status==="cancelled"?"Codex 작업을 취소했습니다.":Ae?`Codex 작업이 완료되지 않았습니다: ${Ae}`:"Codex 작업이 완료되었습니다.");k(gt=>[...gt,{type:De.status==="failed"?"error":"agent",id:wl("agent-run-result"),text:et}])}return De},[ke,n]);u.useEffect(()=>{if(!M)return;let X=!0;const De=async()=>{try{const Ae=await ve(M);X&&!["running","queued"].includes(Ae.status)&&A("")}catch(Ae){X&&Q(Ae instanceof Error?Ae.message:String(Ae))}};De();const ze=window.setInterval(()=>{De()},800);return()=>{X=!1,window.clearInterval(ze)}},[M,ve]),u.useEffect(()=>{if(!T)return;let X=!0;const De=async()=>{try{const Ae=await Ne(T);X&&!["running","queued","waiting-approval"].includes(Ae.status)&&(R(""),oe(!1))}catch(Ae){X&&Q(Ae instanceof Error?Ae.message:String(Ae))}};De();const ze=window.setInterval(()=>{De()},800);return()=>{X=!1,window.clearInterval(ze)}},[T,Ne]);const He=async(X="",De,ze=!1)=>{const Ae=(X||b).trim();if(!Ae||M||T)return;let et=null;const gt=De||(m==="all"||m==="auto"?Ze:v.filter(at=>Ze.includes(at)));if(gt.length===0){Q("Select at least one connected workstation.");return}if(V==="full-access"&&!q&&!ze){G({instruction:Ae,targetIds:gt});return}if(k(at=>[...at,{type:"user",id:wl("user"),text:Ae}]),j(""),he(!1),Q(""),gt.length===0){k(at=>[...at,{type:"error",id:wl("no-targets"),text:"연결된 대상 장비를 하나 이상 선택해 주세요."}]);return}const fa=w==="ask"?`Read-only request. Inspect and answer without changing workstation state.
17
-
18
- ${Ae}`:w==="plan"?`Plan only. Produce a safe execution plan, but do not change workstation state.
19
-
20
- ${Ae}`:w==="execute"?`Execute this request within the configured LiveDesk approval policy.
21
-
22
- ${Ae}`:Ae,$n=m==="auto"?`Auto target selection is enabled. Inspect the allowed workstations and use only the most suitable target or targets for this request.
23
-
24
- ${fa}`:fa;if(!et){try{if(V==="custom"){const qt=await nM(n,L,ne);if(!qt.ok)throw new Error(qt.error||"Custom Agent policy could not be saved.")}const at=await QN(n,{instruction:$n,deviceIds:gt,permissionMode:V,customPolicyId:L});if(!at.ok||!at.runId)throw new Error(at.error||"Codex Agent run could not be started.");O(at.approvals||[]),me({runId:at.runId,stage:at.stage||at.status||"queued",message:at.progressMessage||"Codex request queued on the Hub."}),R(at.runId);return}catch(at){try{const qt=await KN(n,$n);qt.ok&&qt.plan&&(et={operation:qt.plan.operation,query:qt.plan.targetQuery})}catch{k(qt=>[...qt,{type:"error",id:wl("unsupported"),text:mM(at)}])}}if(!et)return}try{const at=await sM(n,{instruction:$n,deviceIds:gt,operation:et.operation,targetQuery:et.query});if(!at.ok||!at.batch||!at.batchId)throw new Error(at.error||"작업을 만들지 못했습니다.");const qt={type:"task",id:wl("task"),batchId:at.batchId,operation:et.operation,instruction:Ae,states:Rd(at.batch,a),status:at.batch.status};ge.current.add(at.batchId),k(un=>[...un,qt]),A(at.batchId)}catch(at){Q(at instanceof Error?at.message:String(at))}},$e=async(X,De)=>{re(X.approvalId);try{const ze=await eM(n,X.runId,X.approvalId,De);if(!ze.ok)throw new Error(ze.error||"Agent approval could not be applied.");await Ne(X.runId)}catch(ze){Q(ze instanceof Error?ze.message:String(ze))}finally{re("")}},Xe=async X=>{re(X.approvalId);try{const De=await tM(n,X.runId,X.approvalId);if(!De.ok)throw new Error(De.error||"Agent approval could not be rejected.");await Ne(X.runId)}catch(De){Q(De instanceof Error?De.message:String(De))}finally{re("")}},ye=async(X,De)=>{F(X);try{if(De){const Ae=await ZN(n,De);for(const et of Ae.taskBatches||[])ce(et);R(et=>et===De?"":et),me(et=>et?.runId===De?null:et);return}const ze=await rM(n,X);ce(ze),A(Ae=>Ae===X?"":Ae)}catch(ze){Q(ze instanceof Error?ze.message:String(ze))}finally{F("")}},ae=async()=>{if(!(K||!M&&!T)){I(!0);try{const X=await JN(n);if(!X.ok)throw new Error(X.error||"모든 Agent 작업을 취소하지 못했습니다.");A(""),R(""),me(null),O([]),k(De=>De.map(ze=>ze.type==="task"&&["queued","running"].includes(ze.status)?{...ze,status:"cancelled",states:ze.states.map(Ae=>["queued","running"].includes(Ae.status)?{...Ae,status:"cancelled",stage:"Cancelled",error:"Cancelled by user."}:Ae)}:ze))}catch(X){Q(X instanceof Error?X.message:String(X))}finally{I(!1)}}},Te=async X=>{F(X);try{const De=await lM(n,X);if(!De.ok||!De.batch||!De.batchId)throw new Error(De.error||"재시도하지 못했습니다.");Be.current.delete(De.batchId),k(ze=>ze.map(Ae=>Ae.type==="task"&&Ae.batchId===X?{...Ae,batchId:De.batchId,states:Rd(De.batch,a),status:De.batch.status}:Ae)),A(De.batchId)}catch(De){Q(De instanceof Error?De.message:String(De))}finally{F("")}},Pe=X=>{j(X),he(!1),window.requestAnimationFrame(()=>Se.current?.focus())},Je=u.useMemo(()=>a.filter(nf),[a]),Mt=u.useMemo(()=>Je.filter(X=>v.includes(X.deviceId)),[Je,v]),It=m==="auto"?`Auto · ${Je.length} available`:m==="all"?`All ${Je.length} computers`:Mt.length===1?tf(Mt[0]):`${Mt.length} selected`,an=m==="auto"?"LiveDesk chooses the best computer for each task.":m==="all"?"The Agent may coordinate every connected computer.":Mt.length>0?Mt.map(tf).join(" · "):"Select one or more computers on the Wall.",mt=m==="selected"&&Mt.length===1?["Diagnose this computer","Analyze recent errors","Summarize running applications","Check disk and GPU capacity"]:m==="all"?["Compare all computer health","Find the busiest computer","Check disk capacity everywhere","Divide a task across computers"]:["Use the fastest computer","Find an idle computer","Choose the best GPU","Check all computer health"],Pn=m==="selected"?Mt.length>0?"What should this computer do?":"Choose a computer or use Auto.":m==="all"?"Use all your computers together.":"What should LiveDesk handle?",Kt=m==="auto"?"LiveDesk can inspect the available computers and choose the best target.":"Describe the outcome. LiveDesk will plan, request approval when needed, and show progress per computer.";return s.jsxs("section",{className:`agents-page ${d?"agents-dock-console":""}`,children:[d&&s.jsxs("header",{className:"agent-console-header",children:[s.jsxs("div",{className:"agent-console-title",children:[s.jsx("span",{className:"agent-console-mark",children:s.jsx(Ds,{size:16})}),s.jsxs("div",{children:[s.jsx("small",{children:"Live agent"}),s.jsx("strong",{children:"Agent Console"})]}),s.jsx("i",{children:"Ready"})]}),s.jsxs("section",{className:"agent-console-target","aria-label":"Agent target scope",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Target"}),s.jsx("strong",{children:It}),s.jsx("small",{children:an})]}),s.jsxs("div",{className:"agent-console-target-modes",children:[s.jsxs("button",{className:m==="selected"?"active":"",onClick:()=>p("selected"),type:"button",children:[s.jsx(ui,{size:12})," Selected"]}),s.jsxs("button",{className:m==="all"?"active":"",onClick:()=>p("all"),type:"button",children:[s.jsx(Jc,{size:12})," All"]}),s.jsxs("button",{type:"button",disabled:!0,title:"Saved workstation groups are coming next.",children:[s.jsx(Jc,{size:12})," Group"]}),s.jsxs("button",{className:m==="auto"?"active":"",onClick:()=>p("auto"),type:"button",children:[s.jsx(Ds,{size:12})," Auto"]})]})]}),s.jsx("div",{className:"agent-console-interaction-modes","aria-label":"Agent interaction mode",children:["auto","ask","plan","execute"].map(X=>s.jsxs("button",{className:w===X?"active":"",onClick:()=>x(X),type:"button",children:[X==="auto"?s.jsx(Ds,{size:12}):X==="execute"?s.jsx(Zt,{size:12}):null,X[0].toUpperCase()+X.slice(1)]},X))})]}),s.jsxs("div",{className:"agents-workspace",children:[(M||T)&&s.jsxs("div",{className:"agents-page-status",children:[s.jsxs("span",{children:[Ze.length," workstations · ",dM(V)]}),s.jsx("button",{type:"button",className:"agents-stop-all",onClick:()=>{ae()},disabled:K,children:K?"Stopping…":"Stop all"})]}),ee&&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(rf,{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:()=>G(null),children:"Cancel"}),s.jsx("button",{type:"button",className:"danger",onClick:()=>{const X=ee;G(null),oe(!0),He(X.instruction,X.targetIds,!0)},children:"Run with Full Access"})]})]})}),we&&s.jsx("div",{className:"agents-error",role:"alert",children:we}),s.jsx(RN,{items:C,onCancel:ye,onRetry:Te,busyBatchId:P,approvals:J,onApprove:$e,onReject:Xe,busyApprovalId:be,progress:fe,emptyTitle:d?Pn:void 0,emptyBody:d?Kt:void 0}),d&&C.length===0&&!fe&&s.jsx("div",{className:"agent-console-suggestions","aria-label":"Suggested Agent commands",children:mt.map(X=>s.jsx("button",{type:"button",onClick:()=>Pe(X),children:X},X))}),s.jsxs("div",{className:"agents-composer-shell",children:[$&&s.jsx(WN,{devices:a,targetMode:m,selectedIds:v,permissionMode:V,customCategories:ne,onSelectPrompt:Pe,onClose:()=>he(!1)}),s.jsx(xN,{ref:Se,value:b,onChange:j,onSubmit:()=>{He()},onOpenSuggestedTasks:()=>he(X=>!X),suggestedOpen:$,suggestedTaskCount:Ke,disabled:!!M||!!T,placeholder:d?"Tell LiveDesk what outcome you want...":void 0,compact:d})]})]}),!d&&s.jsxs("aside",{className:"agents-target-sidebar","aria-label":"Agent targets and permissions",children:[s.jsx(YN,{devices:a,mode:m,selectedIds:v,onModeChange:p,onToggle:X=>g(De=>De.includes(X)?De.filter(ze=>ze!==X):[...De,X]),permissionMode:V,onPermissionModeChange:X=>{_(X),X!=="full-access"&&oe(!1)}}),V==="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:bN.map(X=>s.jsxs("label",{children:[s.jsx("span",{children:fM(X)}),s.jsxs("select",{value:ne[X],onChange:De=>W(ze=>({...ze,[X]:De.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"})]})]},X))})]})]})]})}function sw(n){return{type:n.type,deviceIds:n.deviceIds,monitorIndex:n.monitorIndex,label:n.label}}async function iw(n){try{return(await n.json()).error||`${n.status} ${n.statusText}`}catch{return`${n.status} ${n.statusText}`}}async function rw(n,a,r){const l=encodeURIComponent(JSON.stringify({kind:a.kind,fileName:a.fileName,mimeType:n.type||"application/octet-stream",durationMs:a.durationMs,target:sw(a.target)})),c=await fetch(`${Kr(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 iw(c));return await c.json()}async function hM(n,a){return await We("/api/capture-sessions",{method:"POST",body:JSON.stringify({...n,target:sw(n.target)})},a)}async function pM(n,a,r,l){const c=await fetch(`${Kr(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 iw(c));return await c.json()}async function gM(n,a,r){return await We(`/api/capture-sessions/${encodeURIComponent(n)}/finalize`,{method:"POST",body:JSON.stringify({durationMs:a})},r)}async function bx(n,a){await We(`/api/capture-sessions/${encodeURIComponent(n)}`,{method:"DELETE"},a)}async function vM(n){return await We("/api/captures",void 0,n)}function wx(n,a){return`${Kr(a)}/api/captures/${encodeURIComponent(n)}/content`}async function yM(n,a){return await We(`/api/captures/${encodeURIComponent(n)}`,{method:"DELETE"},a)}function xM({hubUrl:n,onToast:a}){const[r,l]=u.useState([]),[c,d]=u.useState(!0),m=u.useCallback(async()=>{d(!0);try{l((await vM(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=wx(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(Eo,{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=wx(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(l0,{size:15})}),s.jsx("a",{className:"icon-button",title:"Download","aria-label":"Download",href:`${g}?download=1`,download:v.fileName,children:s.jsx(Xh,{size:15})}),s.jsx("button",{className:"icon-button",title:"Share","aria-label":"Share",onClick:()=>{p(v)},type:"button",children:s.jsx(o0,{size:15})}),s.jsx("button",{className:"icon-button danger",title:"Delete","aria-label":"Delete",onClick:()=>{window.confirm(`Delete ${v.fileName}?`)&&yM(v.id,n).then(()=>m()).catch(w=>a(w instanceof Error?w.message:String(w)))},type:"button",children:s.jsx(ep,{size:15})})]})]})]},v.id)})})]})}function Dd(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 Sx({controller:n,compact:a=!1,onFirstRollingUse:r,onError:l}){const{state:c,settings:d,videoSupported:m}=n,p=async x=>{try{await x()}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?
25
- Nothing is saved until you press Save Last 30s.`))&&n.setRollingEnabled(!0)},g=c.recording?`Stop recording · ${Dd(c.recordingStartedAt)}`:`Start recording · ${c.targetLabel}`,w=c.timelapse?`Stop timelapse · ${Dd(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(c0,{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(oy,{size:14,fill:"currentColor"}),s.jsx("span",{children:Dd(c.recordingStartedAt)})]}):s.jsx(Qx,{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(u0,{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(oy,{size:14,fill:"currentColor"}),s.jsx("span",{children:Dd(c.timelapseStartedAt)})]}):s.jsx(d0,{size:17})})]})}async function bM(n,a={}){const r=n.filter(x=>x.canvas&&x.canvas.width>0&&x.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 x=0;x<r.length;x+=1){const b=r[x],j=x%d,C=Math.floor(x/d),k=j*p,M=C*v,A=b.canvas,T=Math.min(p/A.width,v/A.height),R=Math.max(1,Math.floor(A.width*T)),P=Math.max(1,Math.floor(A.height*T)),F=k+Math.floor((p-R)/2),V=M+Math.floor((v-P)/2);w.drawImage(A,F,V,R,P),a.includeLabels!==!1&&(w.fillStyle="rgba(4, 10, 20, .74)",w.fillRect(k,M+v-28,p,28),w.fillStyle="#f8fafc",w.fillText(b.label,k+9,M+v-9))}return g}function wM(n){return n?.signature||"none"}function SM(n){return n?.label||"No capture target"}function Cx(n){return{...n,deviceIds:[...n.deviceIds],sourceCanvas:n.sourceCanvas||null}}function CM(){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 jM(n){return n.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function kM(n){return`LiveDesk_${n.type==="wall"||n.type==="selection"?"Wall":`${jM(n.label)}_Monitor-${Number(n.monitorIndex||0)+1}`}_${CM()}.png`}async function AM(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 rw(l,{kind:"screenshot",fileName:kM(a),target:a},r);try{await navigator.clipboard.write([new ClipboardItem({"image/png":l})])}catch{}return c.capture}function lw(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(a=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(a))||""}function NM(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 ow(n){if(typeof MediaRecorder>"u"||typeof n.canvas.captureStream!="function")throw new Error("This browser does not support video recording.");const a=lw();if(!a)throw new Error("This browser does not support WebM recording.");const r=n.kind||"recording",l=await hM({kind:r,fileName:NM(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=x=>{if(!x.data||x.data.size===0)return;const b=p++;w=w.then(()=>pM(l.sessionId,b,x.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(x=>{d.addEventListener("stop",()=>x(),{once:!0}),d.stop()}),c.getTracks().forEach(x=>x.stop()),await w,g)throw await bx(l.sessionId,n.hubUrl).catch(()=>{}),g;await gM(l.sessionId,Math.max(0,performance.now()-m),n.hubUrl)}},cancel:async()=>{v||(v=!0,d.stop(),c.getTracks().forEach(x=>x.stop()),await bx(l.sessionId,n.hubUrl).catch(()=>{}))}}}class MM{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=lw();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 rw(l,{kind:"last-30s",fileName:d,target:a,durationMs:Math.min(3e4,this.segments.length*1e3)},r)}}async function TM(n,a,r,l,c){const d=await ow({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 cw="livedesk.captureSettings";function EM(){const n={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const a=JSON.parse(localStorage.getItem(cw)||"null");return{...n,...a&&typeof a=="object"?a:{}}}catch{return n}}function RM(n){const[a,r]=u.useState(EM),[l,c]=u.useState(0),[d,m]=u.useState(0),[p,v]=u.useState(0),[g,w]=u.useState(!1),x=u.useRef(void 0),b=u.useRef(!1),j=u.useRef(""),C=u.useRef(null),k=u.useRef(null),M=u.useRef(null),A=u.useRef(null),T=u.useRef(new MM),R=n.sourceRegistry.resolveCurrentTarget(),P=wM(R),F=SM(R),V=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;u.useEffect(()=>{if(localStorage.setItem(cw,JSON.stringify(a)),!b.current)return;const G=JSON.stringify(a);G!==j.current&&(j.current=G,We("/api/settings",{method:"PATCH",body:JSON.stringify({revision:x.current,filesAudio:{rollingBufferEnabled:a.rollingEnabled,recordingQuality:a.recordingQuality,timelapseIntervalSeconds:a.timelapseIntervalSeconds,includeRemoteCursor:a.includeRemoteCursor}})},n.hubUrl).then(q=>{x.current=Number(q.revision||x.current||0)}).catch(()=>{}))},[n.hubUrl,a]),u.useEffect(()=>{let G=!0;return We("/api/settings",void 0,n.hubUrl).then(q=>{if(!G)return;const oe=q.settings?.filesAudio||{},we=typeof oe.rollingBufferEnabled=="boolean"?oe.rollingBufferEnabled:a.rollingEnabled,Q=oe.recordingQuality==="high"?"high":"standard",$=[5,10,30,60].includes(Number(oe.timelapseIntervalSeconds))?Number(oe.timelapseIntervalSeconds):a.timelapseIntervalSeconds,he=typeof oe.includeRemoteCursor=="boolean"?oe.includeRemoteCursor:a.includeRemoteCursor,fe={rollingEnabled:we,recordingQuality:Q,timelapseIntervalSeconds:$,includeRemoteCursor:he};x.current=Number(q.revision||0),j.current=JSON.stringify(fe),b.current=!0,r(fe)}).catch(()=>{b.current=!0}),()=>{G=!1}},[n.hubUrl]);const _=u.useCallback(async G=>{if(G.sourceCanvas&&G.sourceCanvas.width>0&&G.sourceCanvas.height>0)return{target:Cx(G),canvas:G.sourceCanvas,cleanup:()=>{}};const q=await n.sourceRegistry.composeWall(G.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let oe=!1;const we=window.setInterval(async()=>{if(oe)return;const Q=await n.sourceRegistry.composeWall(G.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0}).catch(()=>null);!Q||oe||((q.width!==Q.width||q.height!==Q.height)&&(q.width=Q.width,q.height=Q.height),q.getContext("2d")?.drawImage(Q,0,0))},100);return{target:Cx(G),canvas:q,cleanup:()=>{oe=!0,window.clearInterval(we)}}},[n.sourceRegistry]);u.useEffect(()=>{const G=T.current;if(!a.rollingEnabled||!R||!V){G.stop(),v(0);return}let q=!1,oe=null;return(async()=>{try{if(oe=await _(R),q)return;await G.start(oe.canvas,oe.target);const Q=window.setInterval(()=>v(Math.round(G.seconds)),500),$=()=>{window.clearInterval(Q),oe?.cleanup()};G.__cleanup=$}catch(Q){q||n.onToast(Q instanceof Error?Q.message:String(Q))}})(),()=>{q=!0,G.stop(),G.__cleanup?.(),G.__cleanup=void 0,v(0)}},[_,n.onToast,a.rollingEnabled,P,V]);const L=u.useCallback(G=>r(q=>({...q,rollingEnabled:G})),[]),ne=u.useCallback(G=>r(q=>({...q,recordingQuality:G})),[]),W=u.useCallback(G=>r(q=>({...q,timelapseIntervalSeconds:G})),[]),J=u.useCallback(async()=>{const G=n.sourceRegistry.resolveCurrentTarget();if(!G)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);let q=null;try{q=await _(G),await AM(q.canvas,q.target,n.hubUrl),n.onToast("Screenshot saved")}finally{q?.cleanup(),w(!1)}},[_,n.hubUrl,n.onToast,n.sourceRegistry]),O=u.useCallback(async()=>{if(M.current)throw new Error("Stop the timelapse before recording.");const G=n.sourceRegistry.resolveCurrentTarget();if(!G)throw new Error("화면이 준비된 후 다시 시도하세요.");const q=await _(G),oe=await ow({canvas:q.canvas,target:q.target,fps:G.type==="control"?30:15,hubUrl:n.hubUrl,onError:we=>n.onToast(we.message)});k.current=q.cleanup,C.current=oe,c(Date.now()),n.onToast("Recording started")},[_,n.hubUrl,n.onToast,n.sourceRegistry]),be=u.useCallback(async()=>{const G=C.current;if(G){w(!0);try{await G.stop(),n.onToast("Recording saved")}finally{C.current=null,k.current?.(),k.current=null,c(0),w(!1)}}},[n.onToast]),re=u.useCallback(async()=>{if(C.current||M.current)throw new Error("Last 30s is unavailable during a recording.");const G=n.sourceRegistry.resolveCurrentTarget();if(!G)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);try{await T.current.save(G,n.hubUrl),n.onToast("Last 30 seconds saved")}finally{w(!1)}},[n.hubUrl,n.onToast,n.sourceRegistry]),K=u.useCallback(async()=>{if(C.current)throw new Error("Stop the recording before starting a timelapse.");const G=n.sourceRegistry.resolveCurrentTarget();if(!G)throw new Error("화면이 준비된 후 다시 시도하세요.");const q=await _(G),oe=await TM(q.canvas,q.target,a.timelapseIntervalSeconds,n.hubUrl,we=>n.onToast(we.message));A.current=q.cleanup,M.current=oe,m(Date.now()),n.onToast("Timelapse started")},[_,n.hubUrl,n.onToast,n.sourceRegistry,a.timelapseIntervalSeconds]),I=u.useCallback(async()=>{const G=M.current;if(G){w(!0);try{await G.stop(),n.onToast("Timelapse saved")}finally{M.current=null,A.current?.(),A.current=null,m(0),w(!1)}}},[n.onToast]);return u.useEffect(()=>{const G=q=>{!C.current&&!M.current||(q.preventDefault(),q.returnValue="")};return window.addEventListener("beforeunload",G),()=>window.removeEventListener("beforeunload",G)},[]),u.useEffect(()=>()=>{T.current.stop(),C.current?.cancel(),M.current?.cancel(),k.current?.(),A.current?.()},[]),{state:u.useMemo(()=>({recording:!!C.current,recordingStartedAt:l,timelapse:!!M.current,timelapseStartedAt:d,bufferSeconds:p,bufferEnabled:a.rollingEnabled,busy:g,targetLabel:F}),[p,g,l,a.rollingEnabled,F,d]),settings:a,videoSupported:V,targetKey:P,setRollingEnabled:L,setRecordingQuality:ne,setTimelapseInterval:W,takeScreenshot:J,startRecording:O,stopRecording:be,saveLast30Seconds:re,startTimelapse:K,stopTimelapse:I}}const DM=120,LM=999,Pc=5,$c=30,_M=Number.POSITIVE_INFINITY,uw="livedesk.remoteDirectory",Uh="livedesk.localHubAccessEnabled",dw="livedesk.streamSettings",qh=16,fw="livedesk.controlStreamSettings",Gh=6,mw="livedesk.wallMonitorSelections",hw=1,hh=512*1024,Vh="".trim(),pw="".trim(),jx="livedesk-adsense-script",ph=!!Vh&&!!pw,zM=1e3/60,gh=1500,IM=650,OM=1800,HM=650,BM=2500,kx=1500,Ax=15e3,FM=6e4,Nx=240,PM=1024,$M=640,UM=360,Mx="Connected LiveDesk clients are updating in batches. Hub will restart after every target reconnects on the requested versions.",Ld="LiveDesk is replacing the Hub and verifying the requested version.",_d=5*6e4,qM=5e3;function $r({label:n,tooltip:a,disabled:r=!1,active:l=!1,danger:c=!1,pressed:d,onClick:m,children:p}){return s.jsx("span",{className:`manual-action-tooltip ${r?"disabled":""}`.trim(),"data-tooltip":a,children:s.jsx("button",{className:`manual-action ${l?"active":""} ${c?"danger":""}`.trim(),onClick:m,disabled:r,"aria-label":n,"aria-pressed":d,type:"button",children:p})})}function GM(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 Sl={free:{name:"Free",price:"$0",limit:Pc,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:_M,audience:"Business and studios",note:"Commercial use and larger workstation walls."}},gw={"mode1-jpeg":5,"mode3-h264-hw":30,"mode4-h264-atlas":20};function Tx(n,a){const r=m=>{const v=String(m||"").trim().replace(/^v/i,"").match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/);if(!v)return null;const g=v[4]?v[4].split(".").map(w=>/^\d+$/.test(w)?w.length>1&&w.startsWith("0")?Number.NaN:Number(w):w):[];return g.some(w=>typeof w=="number"&&!Number.isFinite(w))?null:{core:[Number(v[1]),Number(v[2]),Number(v[3])],prerelease:g}},l=r(n),c=r(a);if(!l||!c)return!1;for(let m=0;m<3;m+=1){if(l.core[m]>c.core[m])return!0;if(l.core[m]<c.core[m])return!1}if(l.prerelease.length===0||c.prerelease.length===0)return l.prerelease.length===0;const d=Math.max(l.prerelease.length,c.prerelease.length);for(let m=0;m<d;m+=1){const p=l.prerelease[m],v=c.prerelease[m];if(p===void 0||v===void 0)return v===void 0;if(p!==v){if(typeof p=="number"&&typeof v=="number")return p>v;if(typeof p=="number")return!1;if(typeof v=="number"||p>v)return!0;if(p<v)return!1}}return!0}function xs(n,a){return`${n}:${a}`}const wa={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:gw["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},Ha={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-software",fps:30,maxWidth:1920,maxHeight:1080,quality:75,showScreenStatus:!1};function vh(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 vw(n,a){n.push(a),n.length>Nx&&n.splice(0,n.length-Nx)}function Ex(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 Rx(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),vw(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 Dx(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 Lx(n){return!n||n.seqGapCount<=0?"none":`${n.seqGapCount} gaps / max ${n.maxSeqGap}`}function VM(n){return Number.isFinite(n)?String(n):"30+"}const Ud=[{id:"mode4-h264-atlas",label:"Mode 4",detail:"Hub H.264 Atlas"},{id:"mode3-h264-hw",label:"Mode 3",detail:"H.264 hardware"}],Wh=[{id:"prefer-software",label:"Software low latency"},{id:"prefer-hardware",label:"Hardware decode"},{id:"no-preference",label:"Browser auto"}],WM=[{id:"mode3-h264-hw",label:"Mode 3 - H.264 hardware"}],qd=[{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}],yh=qd.filter(n=>n.width>=1280),xh=[{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},{id:"640x360",label:"Crisp 640x360",width:640,height:360}],Cp=[1,2,5,8,12,20,30],YM=[20,30,60],_x=[45,60,75,90],zx={large:{maxWidth:1280,maxHeight:720},medium:{maxWidth:960,maxHeight:540},list:{maxWidth:640,maxHeight:360}},da={preserveConfiguredFpsDeviceCount:12,visibleRootMargin:"520px 0px 760px 0px",fallbackVisibleCounts:{large:12,medium:18,list:32},maxWallFramesPerSecond:di.maxDirectFramesPerSecond,maxWallBytesPerSecond:80*1024*1024,maxFrameGapMs:280,lowLoadFrameRatio:.58,lowLoadByteRatio:.52,downshiftCooldownMs:1800,recoveryCooldownMs:14e3,minFps:5},Ix=2200,KM=8e3,QM=3500,XM=7e3,ZM=2,JM=7e3,eT=2600,tT=4200,nT=750,aT=2,Ox=4200;function Hx(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 Ja(n){return n.deviceName||n.hostname||n.deviceId}function sT(){return"npx -y --prefer-online livedesk@latest client"}function iT(){return"npx -y --prefer-online livedesk@latest"}function rT(){try{return localStorage.getItem(uw)||""}catch{return""}}function lT(){try{return localStorage.getItem(Uh)==="1"}catch{return!1}}function wo(n){try{n?localStorage.setItem(Uh,"1"):localStorage.removeItem(Uh)}catch{}}function bs(n,a,r,l){const c=Number(n);return Number.isFinite(c)?Math.max(a,Math.min(r,Math.round(c))):l}function Yh(n){const a=String(n||"").trim();return Ud.some(r=>r.id===a)?a:wa.frameMode}function sf(n){const a=String(n||"").trim();return Wh.some(r=>r.id===a)?a:wa.h264DecodeAcceleration}function Kh(n){return n==="mode3-h264-hw"?n:Ha.frameMode}function yw(n){return gw[n]||12}function xw(n){return n==="mode3-h264-hw"?30:n==="mode4-h264-atlas"?20:30}function Qh(n,a){return bs(n,1,xw(a),yw(a))}function Ll(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function ba(n){const a=Ll(n.status),r=Ll(a.screens),l=Ll(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 Gr(n){const a=Number(n);return Number.isFinite(a)&&a>0?Math.floor(a):0}function oT(n){const a=Ll(n.status),l=[Ll(a.screens).displays,a.displays,a.monitors];for(const c of l)if(!(!Array.isArray(c)||c.length===0))return c.map(d=>Ll(d));return[]}function bw(n,a){const r=oT(n),l=r.find(v=>Number(v.index)===a)||r[a]||r[0]||{},c=Gr(l.width),d=Gr(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 cT(n){const a=ba(n);return Array.from({length:a},(r,l)=>bw(n,l))}function uT(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 ww(n,a){const r=bw(n,a);if(r.width>0&&r.height>0)return{width:r.width,height:r.height};const l=Ll(n.status),c=Gr(l.screenWidth||l.width),d=Gr(l.screenHeight||l.height);return c>0&&d>0?{width:c,height:d}:null}function Sw(n){if(!n)return null;const a=Gr(n.sourceWidth)||Gr(n.width),r=Gr(n.sourceHeight)||Gr(n.height);return a>0&&r>0?{width:a,height:r}:null}function dT(n,a,r){const d=((typeof a?.monitorIndex=="number"?Oa(a.monitorIndex,Math.max(1,a.monitorCount||1)):r)===r?Sw(a):null)||ww(n,r);return d?Math.max(.25,Math.min(4,d.width/d.height)):16/9}const zd=16/9;function Oa(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 fT(){try{const n=localStorage.getItem(mw);if(!n)return{};const a=JSON.parse(n),r=a&&typeof a=="object"&&!Array.isArray(a)?a.selections:void 0;if(Number(a?.version)!==hw||!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 mT(n){try{localStorage.setItem(mw,JSON.stringify({version:hw,selections:n}))}catch{}}function hT(){try{const n=JSON.parse(localStorage.getItem(dw)||"{}"),a=Number(n.version);if(![qh,15,14,13,12,11].includes(a))return wa;const r=Yh(n.frameMode),l=bs(n.maxWidth,320,3840,wa.maxWidth),c=bs(n.maxHeight,180,2160,wa.maxHeight),d=Number(n.atlasTileWidth),m=Number(n.atlasTileHeight),p=d>=640||m>=360?{width:640,height:360}:d>=480||m>=270?{width:480,height:270}:{width:320,height:180};return{frameMode:r,h264DecodeAcceleration:sf(n.h264DecodeAcceleration),fps:a<qh&&r==="mode3-h264-hw"?wa.fps:Qh(n.fps,r),maxWidth:l,maxHeight:c,atlasTileWidth:p.width,atlasTileHeight:p.height,atlasTileSizeMode:n.atlasTileSizeMode==="fixed"?"fixed":"auto",quality:bs(n.quality,20,95,wa.quality),autoStartLive:typeof n.autoStartLive=="boolean"?n.autoStartLive:wa.autoStartLive,showScreenStatus:typeof n.showScreenStatus=="boolean"?n.showScreenStatus:wa.showScreenStatus,visibleOnlyLive:typeof n.visibleOnlyLive=="boolean"?n.visibleOnlyLive:wa.visibleOnlyLive,adaptiveLoadShedding:typeof n.adaptiveLoadShedding=="boolean"?n.adaptiveLoadShedding:wa.adaptiveLoadShedding,adaptiveSizeByWall:typeof n.adaptiveSizeByWall=="boolean"?n.adaptiveSizeByWall:wa.adaptiveSizeByWall}}catch{return wa}}function pT(n){try{localStorage.setItem(dw,JSON.stringify({...n,version:qh}))}catch{}}function gT(){try{const n=JSON.parse(localStorage.getItem(fw)||"{}"),a=Number(n.version);if(![Gh,5,4,3,2,1].includes(a))return Ha;const r=bs(n.fps,20,60,Ha.fps),l=a<Gh;return{frameMode:l?Ha.frameMode:Kh(n.frameMode),h264DecodeAcceleration:l?Ha.h264DecodeAcceleration:sf(n.h264DecodeAcceleration),fps:l?Ha.fps:r,maxWidth:bs(n.maxWidth,1280,3840,Ha.maxWidth),maxHeight:bs(n.maxHeight,720,2160,Ha.maxHeight),quality:bs(n.quality,20,95,Ha.quality),showScreenStatus:typeof n.showScreenStatus=="boolean"?n.showScreenStatus:Ha.showScreenStatus}}catch{return Ha}}function vT(n){try{localStorage.setItem(fw,JSON.stringify({...n,version:Gh}))}catch{}}function bh(n,a){return n.length!==a.length?!1:n.every((r,l)=>r===a[l])}function wh(n){return[...new Set(n.filter(Boolean))].sort()}function yT(n){return da.fallbackVisibleCounts[n]||da.fallbackVisibleCounts.large}function xT(n,a,r){if(n.frameMode==="mode4-h264-atlas")return n.atlasTileSizeMode==="auto"?a==="large"?{maxWidth:640,maxHeight:360}:{maxWidth:320,maxHeight:180}:{maxWidth:n.atlasTileWidth,maxHeight:n.atlasTileHeight};if(!n.adaptiveSizeByWall)return{maxWidth:n.maxWidth,maxHeight:n.maxHeight};const l=zx[a]||zx.large;return{maxWidth:Math.min(n.maxWidth,l.maxWidth),maxHeight:Math.min(n.maxHeight,l.maxHeight)}}function bT(n,a=da.minFps){const r=[...Cp].sort((c,d)=>c-d),l=Math.max(a,Math.floor(n/2));return[...r].reverse().find(c=>c<n&&c>=a)||l}function wT(n,a){return[...Cp].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 Bx(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 Sh(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`${Bx(r)} / ${Bx(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 Fx(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 CT(n){return n===1?"middle":n===2?"right":"left"}function Px(n,...a){for(const r of a){const l=n?.[r];if(typeof l=="string"&&l.trim())return l.trim()}return""}function $x(n){const a=Number(n);return Number.isInteger(a)&&a>=1&&a<=LM?a:0}const jT={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function kT(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=jT[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 xn(n,...a){for(const r of a){const l=pf(n,r),c=Number(l);if(Number.isFinite(c))return c}}function es(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 AT(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 Ji(n){const a=Number(n);if(Number.isFinite(a))return Math.max(0,Math.min(1,a>1?a/100:a))}function Ch(n,a){if(!(typeof n!="number"||typeof a!="number"||!Number.isFinite(n)||!Number.isFinite(a)||n<=0))return Ji((n-Math.max(0,a))/n)}function So(n){return n===void 0?"-":`${Math.round(n*100)}%`}function jh(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 Cl(n,a=.92,r=.78){return n===void 0?"unknown":n>=a?"critical":n>=r?"warn":"good"}function NT(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 Id(n,a,r){const l=pf(n,`tools.${a}`),c=es(n,`tools.${a}.status`,`tooling.${a}.status`,`${a}.status`).toLowerCase(),d=AT(n,`tools.${a}.running`,`tooling.${a}.running`,`${a}.running`),m=es(n,`tools.${a}.version`,`tooling.${a}.version`,`${a}.version`),p=es(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 Cw(n){const a=n.status||{},r=xn(a,"cpu.cores","cpuCores","processorCount"),l=xn(a,"loadavg.0","cpu.load1"),c=Ji(xn(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=xn(a,"memory.totalBytes","totalMem"),m=xn(a,"memory.freeBytes","freeMem"),p=Ji(xn(a,"memory.usedRatio","memory.usedPct","usedMemRatio"))??Ch(d,m),v=xn(a,"disk.totalBytes","rootDisk.totalBytes","storage.totalBytes"),g=xn(a,"disk.freeBytes","rootDisk.freeBytes","storage.freeBytes"),w=Ji(xn(a,"disk.usedRatio","disk.usedPct","rootDisk.usedRatio","storage.usedRatio"))??Ch(v,g),x=xn(a,"thermal.cpuC","temperatureC","cpu.temperatureC","gpu.temperatureC"),b=Ji(xn(a,"gpu.usedRatio","gpu.usageRatio","gpu.usedPct","gpu.usagePct","gpu.percent","accelerators.gpu.usageRatio")),j=es(a,"gpu.name","gpu.model","accelerators.gpu.name"),C=xn(a,"gpu.memory.totalBytes","gpu.totalMemoryBytes","gpu.vramTotalBytes"),k=xn(a,"gpu.memory.freeBytes","gpu.freeMemoryBytes","gpu.vramFreeBytes"),M=Ji(xn(a,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??Ch(C,k),A=xn(a,"gpu.temperatureC","thermal.gpuC"),T=Ji(xn(a,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),R=es(a,"npu.name","npu.model","accelerators.npu.name"),P=xn(a,"npu.tops","npu.topsInt8","accelerators.npu.tops"),F=xn(a,"network.rxMbps","network.receiveMbps","network.downMbps"),V=xn(a,"network.txMbps","network.transmitMbps","network.upMbps"),_=xn(a,"network.latencyMs","network.rttMs"),L=Ji(xn(a,"network.usedRatio","network.usageRatio","network.saturationRatio")),ne=es(a,"network.link","network.interface","network.name"),W=Math.max(x??Number.NEGATIVE_INFINITY,A??Number.NEGATIVE_INFINITY),J=Number.isFinite(W)?W:void 0,O=J===void 0?void 0:Ji((J-35)/60),be=x!==void 0&&A!==void 0?`CPU ${Math.round(x)}° · GPU ${Math.round(A)}°`:x!==void 0?`CPU ${Math.round(x)}°`:A!==void 0?`GPU ${Math.round(A)}°`:"-",re=es(a,"workload.role","role","lane")||(Qc(n,"aiAssist")?"Agent worker":Qc(n,"taskDispatch")?"Task worker":"Local machine"),K=es(n.latestTask,"status")||es(a,"workload.status")||"idle",I=es(n.latestTask,"title","instructionPreview")||es(a,"workload.title"),ee=es(n.latestTask,"resultSummary","error","instructionPreview")||es(a,"workload.summary"),G=[Id(a,"ollama","Ollama"),Id(a,"lmStudio","LM Studio"),Id(a,"comfyui","ComfyUI"),Id(a,"stableDiffusion","Stable Diffusion")],q=G.some(fe=>fe.status!=="unknown"),oe=Date.parse(n.lastSeenAt||n.connectedAt||""),we=Number.isFinite(oe)?Date.now()-oe:0;let Q="online";n.connected?we>5*6e4?Q="stale":(x??0)>=86||(A??0)>=88||(c??0)>=.94||(b??0)>=.96||(M??0)>=.96||(T??0)>=.96||(p??0)>=.94||(w??0)>=.94||(_??0)>=200||K==="failed"?Q="critical":(x??0)>=78||(A??0)>=80||(c??0)>=.82||(b??0)>=.86||(M??0)>=.88||(T??0)>=.86||(p??0)>=.82||(w??0)>=.86||(_??0)>=80?Q="warn":(["queued","running","targeted"].includes(K)||G.some(fe=>fe.status==="busy"))&&(Q="busy"):Q="offline";const $=G.filter(fe=>fe.status==="online"||fe.status==="busy").length,he=[{id:"cpu",label:"CPU",value:So(c),detail:r?`${r} cores`:l!==void 0?`load ${l.toFixed(1)}`:"not reported",ratio:c,state:Cl(c,.92,.78)},{id:"memory",label:"RAM",value:So(p),detail:Sh(d,m),ratio:p,state:Cl(p,.92,.78)},{id:"disk",label:"DISK",value:So(w),detail:Sh(v,g),ratio:w,state:Cl(w,.92,.82)},{id:"gpu",label:"GPU",value:So(b),detail:j||(C&&k!==void 0?`${Uc(k)} VRAM free`:A!==void 0?`${Math.round(A)}C`:"not reported"),ratio:b,state:A!==void 0&&A>=88?"critical":A!==void 0&&A>=80?"warn":Cl(b,.96,.86)},{id:"vram",label:"VRAM",value:So(M),detail:Sh(C,k),ratio:M,state:Cl(M,.96,.88)},{id:"npu",label:"NPU",value:T!==void 0?So(T):P!==void 0?`${Math.round(P)} TOPS`:"-",detail:R||(P!==void 0?"neural engine":"not reported"),ratio:T,state:Cl(T,.96,.86)},{id:"temp",label:"TEMP",value:be,detail:$>0?`${$} local tools`:`uptime ${NT(xn(a,"uptimeSec"))}`,ratio:O,state:J===void 0?"unknown":J>=86?"critical":J>=78?"warn":"good"},{id:"network",label:"NET",value:jh(F)||(_!==void 0?`${Math.round(_)}ms`:ne||"-"),detail:jh(V)?`${jh(V)} up`:ne||"not reported",ratio:L,state:_!==void 0&&_>=200?"critical":_!==void 0&&_>=80?"warn":Cl(L,.9,.75)}];return{state:Q,label:kT(Q,he,K),role:re,taskLabel:I||(K==="idle"?"idle":K),taskStatus:K,taskSummary:ee,tools:q?G:G.map(fe=>({...fe,detail:"not reported"})),metrics:he}}const MT=[{id:"list",label:"List"},{id:"medium",label:"Small"},{id:"large",label:"Large"}],TT=[{id:"sync-server",label:"Hub",icon:Vr,accent:"blue",tooltip:"hub"},{id:"wall",label:"Wall",icon:Zc,accent:"blue",tooltip:"wall"},{id:"control",label:"Control",icon:Hd,accent:"red",tooltip:"control"},{id:"share-files",label:"Share Files",icon:Od,accent:"green",tooltip:"share-files"},{id:"agents",label:"Agents",icon:Bd,accent:"violet",tooltip:"agents"}],ET=[{id:"doc",label:"Doc",icon:Gd,accent:"amber"},{id:"support",label:"Support",icon:qc,accent:"violet"},{id:"pricing",label:"Pricing",icon:jo,accent:"green"}];function RT(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 mn(n){return RT(n).replaceAll("Sync Server","Hub").replace(/\bRemoteHub\b/g,"Hub client endpoint").replace(/\bManagers\b/g,"Hubs").replace(/\bManager\b/g,"Hub").replace(/\bmanager\b/g,"Hub").replace(/\bMANAGER\b/g,"HUB").replace(/매니저/g,"Hub")}function jl(n){return n.map(a=>mn(a))}function ca(n){return{languageName:n.languageName,languageLabel:n.languageLabel,eyebrow:n.eyebrow,title:mn(n.title),intro:mn(n.intro),sections:[{title:mn(n.managerTitle),body:mn(n.managerBody),points:jl(n.managerPoints)},{title:mn(n.clientTitle),body:mn(n.clientBody),points:jl(n.clientPoints)},{title:mn(n.syncTitle),body:mn(n.syncBody),points:jl(n.syncPoints)},...n.agentTitle&&n.agentBody&&n.agentPoints?[{title:mn(n.agentTitle),body:mn(n.agentBody),points:jl(n.agentPoints)}]:[],{title:mn(n.platformTitle),body:mn(n.platformBody),points:jl(n.platformPoints)}],sync:{title:mn(n.syncTitle),body:mn(n.syncBody),points:jl(n.syncPoints)},firewall:{title:mn(n.firewallTitle),body:mn(n.firewallBody),points:jl(n.firewallPoints)},commands:{title:mn(n.commandsTitle),body:mn(n.commandsBody),manager:mn(n.managerCommandLabel),primary:mn(n.clientCommandLabel),slot:mn(n.slotCommandLabel),manual:mn(n.manualCommandLabel)}}}const To={ko:ca({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, X11/XTEST 입력과 PipeWire/PulseAudio 기본 출력 오디오 캡처를 지원합니다."],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:ca({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, X11/XTEST input, and default-output audio capture through PipeWire or PulseAudio."],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:ca({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、X11/XTEST 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":ca({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 捕获、X11/XTEST 输入后端。音频尚未启用。"],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":ca({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、X11/XTEST 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:ca({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: runtime linux-x64, entrada X11/XTEST y audio de salida mediante PipeWire o PulseAudio."],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:ca({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, entrée X11/XTEST et audio de sortie via PipeWire ou PulseAudio."],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:ca({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, X11/XTEST Eingabe und Ausgangsaudio über PipeWire oder PulseAudio."],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":ca({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 X11/XTEST 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:ca({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 X11/XTEST. 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:ca({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 X11/XTEST 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:ca({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 X11/XTEST. 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:ca({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 และ X11/XTEST 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:ca({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, X11/XTEST input और PipeWire/PulseAudio output audio capture उपलब्ध हैं।"],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:ca({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 وX11/XTEST 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:ca({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 X11/XTEST 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ı"})},DT=Object.entries(To).map(([n,a])=>({id:n,label:a.languageName}));function LT(){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(To[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(To[l])return l}return"en"}function Ux({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")]})]})]})})}const _T=["cpu","gpu","memory","vram","network","disk","temp"];function zT({device:n,slotNumber:a,selected:r,updateIndicator:l,onSelect:c,onOpenControl:d}){const m=Cw(n),p=new Map(m.metrics.map(g=>[g.id,g])),v=l?.label||m.label;return s.jsxs("div",{className:`wall-device-list-row state-${m.state} ${r?"selected":""}`,role:"row","aria-selected":r,tabIndex:0,onClick:c,onDoubleClick:g=>{g.preventDefault(),d()},onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),c())},children:[s.jsxs("span",{className:"wall-device-name",role:"gridcell",children:[s.jsx("span",{className:"wall-device-icon","aria-hidden":"true",children:s.jsx(Zt,{size:17})}),s.jsxs("span",{children:[s.jsx("strong",{children:Ja(n)}),s.jsxs("small",{children:["Slot ",String(a).padStart(3,"0"),n.platform?` · ${n.platform}`:"",n.arch?` · ${n.arch}`:""]})]}),r&&s.jsx(ui,{size:16,strokeWidth:3,"aria-label":"Selected"})]}),s.jsxs("span",{className:`wall-device-list-status state-${m.state} ${l?`update-${l.state}`:""}`,role:"gridcell",title:l?.error||v,children:[s.jsx("i",{"aria-hidden":"true"}),s.jsx("strong",{children:v})]}),_T.map(g=>{const w=p.get(g);return s.jsxs("span",{className:`wall-device-list-metric state-${w?.state||"unknown"}`,role:"gridcell",title:w?`${w.label}: ${w.value} · ${w.detail}`:"Not reported",children:[s.jsx("strong",{children:w?.value||"-"}),s.jsx("small",{children:w?.detail||"not reported"}),w?.ratio!==void 0&&s.jsx("i",{style:{width:`${Math.round(w.ratio*100)}%`},"aria-hidden":"true"})]},g)})]})}function IT(n){if(!n)return!1;const a=String(n.platform||"").trim().toLowerCase();return er(a)&&n.capabilities?.screenRecordingPermission===!1}function er(n){const a=String(n||"").trim().toLowerCase();return a==="macos"||a==="darwin"||a==="mac"||a==="macosx"}function OT(n){const a=String(n||"").trim().toLowerCase();return a==="linux"||a.startsWith("linux ")}function qx(n){if(!n)return!1;const a=String(n.capabilities?.liveCaptureConcurrency||"").trim().toLowerCase();return a==="exclusive"?!0:a==="parallel"?!1:er(n.platform)}function kh({device:n,frame:a,selected:r,controlEnabled:l,showStatus:c,monitorIndex:d,monitorCount:m,onSelect:p,onFocusDevice:v,onOpenControl:g,onCycleMonitor:w,onCanvasReady:x,sendInput:b,updateIndicator:j,presentationReady:C,showPresentationSpinner:k=!1}){const M=u.useRef(null),A=u.useRef(null),T=u.useRef(0),R=u.useRef(null),P=Cw(n),F=["cpu","gpu","memory","vram"].map($=>P.metrics.find(he=>he.id===$)).filter($=>!!$),V=Oa(d,m),_=m>1,L=C??!!a,ne=IT(n)&&!L,W=k&&n.connected&&!L&&!ne,J=dT(n,a,V),O=J>=zd?100:J/zd*100,be=J>=zd?zd/J*100:100,re={"--screen-aspect":J.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,O)).toFixed(3)}%`,"--screen-content-height":`${Math.max(1,Math.min(100,be)).toFixed(3)}%`},K=u.useCallback($=>{M.current=$,x(n.deviceId,$)},[n.deviceId,x]),I=$=>{const he=$.currentTarget.getBoundingClientRect();return Ej($.clientX,$.clientY,he)},ee=$=>({shiftKey:$.shiftKey,ctrlKey:$.ctrlKey,altKey:$.altKey,metaKey:$.metaKey}),G=u.useCallback(()=>{R.current!==null&&(window.cancelAnimationFrame(R.current),R.current=null)},[]),q=u.useCallback(()=>{const $=A.current;if(!$)return;A.current=null;const he=Number($.input.normalizedX),fe=Number($.input.normalizedY);if(!Number.isFinite(he)||!Number.isFinite(fe))return;b(n.deviceId,{...$.input,normalizedX:he,normalizedY:fe})&&(T.current=performance.now())},[n.deviceId,b]),oe=u.useCallback(()=>{R.current===null&&(R.current=window.requestAnimationFrame(()=>{R.current=null,q()}))},[q]);u.useEffect(()=>()=>{G(),A.current=null},[G]);const we=($,he)=>{if(!l)return;const fe={type:he,monitorIndex:V,...I($),button:CT($.button),...ee($)};if(he==="pointermove"){const me=performance.now();A.current={input:fe},me-T.current>=zM&&(G(),q()),oe();return}A.current&&(G(),q()),b(n.deviceId,fe)},Q=u.useCallback($=>{const he=document.activeElement;he instanceof HTMLElement&&$.contains(he)&&he.classList.contains("monitor-cycle-button")&&he.blur()},[]);return s.jsx("article",{className:`device-tile ${r?"selected":""} ${n.connected?"online":"offline"}`,"data-live-device-id":n.deviceId,style:re,children:s.jsxs("div",{className:`tile-screen ${L?"has-frame":"is-empty"}`,role:"button",tabIndex:l?-1:0,"aria-pressed":r,onClick:$=>{$.target instanceof Element&&$.target.closest(".monitor-cycle")||l||p()},onKeyDown:$=>{$.target instanceof Element&&$.target.closest(".monitor-cycle")||l||($.key==="Enter"||$.key===" ")&&($.preventDefault(),p())},onDoubleClick:$=>{$.target instanceof Element&&$.target.closest(".monitor-cycle")||($.preventDefault(),g())},onPointerLeave:$=>Q($.currentTarget),children:[s.jsx("span",{className:`screen-content ${L?"has-frame":"is-empty"}`,children:s.jsx("canvas",{ref:K,className:`remote-canvas ${L?"has-frame":"is-empty"}`,tabIndex:l?0:-1,onPointerDown:$=>{l&&($.preventDefault(),$.stopPropagation(),v(),$.currentTarget.focus(),$.currentTarget.setPointerCapture($.pointerId),we($,"pointerdown"))},onPointerMove:$=>{l&&$.preventDefault(),we($,"pointermove")},onPointerLeave:$=>{l&&(we($,"pointermove"),G(),q())},onPointerUp:$=>{l&&($.preventDefault(),$.stopPropagation(),we($,"pointerup"),$.currentTarget.hasPointerCapture($.pointerId)&&$.currentTarget.releasePointerCapture($.pointerId))},onPointerCancel:$=>{$.currentTarget.hasPointerCapture($.pointerId)&&$.currentTarget.releasePointerCapture($.pointerId)},onWheel:$=>{l&&($.preventDefault(),b(n.deviceId,{type:"wheel",monitorIndex:V,...I($),deltaX:$.deltaX,deltaY:$.deltaY,...ee($)}))},onKeyDown:$=>{l&&($.preventDefault(),$.stopPropagation(),b(n.deviceId,{type:"keydown",monitorIndex:V,key:$.key,code:$.code,keyCode:$.keyCode||$.which||0,location:$.location,text:$.key.length===1?$.key:"",repeat:$.repeat,...ee($)}))},onKeyUp:$=>{l&&($.preventDefault(),$.stopPropagation(),b(n.deviceId,{type:"keyup",monitorIndex:V,key:$.key,code:$.code,keyCode:$.keyCode||$.which||0,location:$.location,text:$.key.length===1?$.key:"",repeat:!1,...ee($)}))},onContextMenu:$=>l&&$.preventDefault()})}),!L&&s.jsx("span",{className:"empty-screen",children:s.jsx(Zt,{size:26})}),W&&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"})]}),ne&&s.jsxs("span",{className:"wall-presentation-loading permission-required",role:"status","aria-live":"polite",children:[s.jsx(Ht,{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 state-${j.state}`,role:"status","aria-live":"polite",title:j.error||j.label,children:[j.state==="updated"?s.jsx(_n,{size:20,"aria-hidden":"true"}):j.state==="failed"?s.jsx(Sa,{size:22,"aria-hidden":"true"}):j.state==="offline"?s.jsx(El,{size:22,"aria-hidden":"true"}):s.jsx("span",{className:"wall-update-spinner","aria-hidden":"true"}),s.jsx("strong",{children:j.label}),j.error?s.jsx("small",{children:j.error}):null]}),c&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`tile-health-pill state-${P.state}`,children:P.label}),s.jsx("span",{className:"tile-metrics","aria-label":`${Ja(n)} status`,children:F.map($=>s.jsxs("span",{className:`tile-metric state-${$.state}`,children:[s.jsx("b",{children:$.label}),s.jsx("em",{children:$.value}),$.ratio!==void 0&&s.jsx("i",{style:{width:`${Math.round($.ratio*100)}%`}})]},$.id))})]}),_&&s.jsxs("span",{className:"monitor-cycle","aria-label":`${Ja(n)} display ${V+1} of ${m}`,onPointerDown:$=>$.stopPropagation(),onClick:$=>$.stopPropagation(),onDoubleClick:$=>$.stopPropagation(),children:[s.jsx("button",{className:"monitor-cycle-button previous",onClick:$=>{$.preventDefault(),$.stopPropagation(),w(-1),$.currentTarget.blur()},title:"Previous display",type:"button",children:s.jsx(Zx,{size:18})}),s.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",V+1,"/",m]}),s.jsx("button",{className:"monitor-cycle-button next",onClick:$=>{$.preventDefault(),$.stopPropagation(),w(1),$.currentTarget.blur()},title:"Next display",type:"button",children:s.jsx(ap,{size:18})})]}),r&&s.jsx("span",{className:"device-selection-check","aria-hidden":"true",children:s.jsx(ui,{size:23,strokeWidth:3.5})})]})})}function HT({visible:n}){return u.useEffect(()=>{if(!n||!ph)return;if(!document.getElementById(jx)){const r=document.createElement("script");r.id=jx,r.async=!0,r.crossOrigin="anonymous",r.src=`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${encodeURIComponent(Vh)}`,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 ${ph?"adsense-ready":"house-ad"}`,"aria-label":"Advertisement",children:[s.jsx("span",{className:"ad-label",children:"Advertisement"}),ph?s.jsx("ins",{className:"adsbygoogle livedesk-ad-unit",style:{display:"block"},"data-ad-client":Vh,"data-ad-slot":pw,"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 BT(){const{session:n,loading:a}=lj(),{target:r,error:l,refresh:c}=cj(n),d=u.useMemo(()=>{if(!r?.active)return null;const y=r.expires_at?Date.parse(r.expires_at):Number.POSITIVE_INFINITY;return Number.isFinite(y)&&y<=Date.now()?null:r},[r]),m=u.useMemo(()=>wy(d),[d]),p=u.useMemo(()=>m.length>0?[...new Set([...m,kn])]:[kn],[m]),[v,g]=u.useState(lT),w=u.useMemo(()=>p.some(y=>!!Wc(y)),[p]),x=!w||v,{status:b,devices:j,error:C,refresh:k,hubBaseUrl:M}=oj(p,x),{entitlement:A,licensed:T,loading:R,error:P,refresh:F}=uj(n),[V,_]=u.useState([]),[L,ne]=u.useState(""),[W,J]=u.useState(""),[O,be]=u.useState(""),[re,K]=u.useState(""),[I,ee]=u.useState(""),[G,q]=u.useState("idle"),[oe,we]=u.useState(!1),[Q,$]=u.useState(null),[he,fe]=u.useState(""),me=u.useRef("");me.current=re;const[Se,Be]=u.useState(!1),[Oe,ge]=u.useState(!1),Ze=u.useRef(""),Ke=u.useRef(new Map),ce=u.useRef(0),[ve,ke]=u.useState(""),[Ne,He]=u.useState(""),[$e,Xe]=u.useState(!1),ye=u.useRef(null),ae=u.useRef(null),[Te,Pe]=u.useState(null);u.useEffect(()=>{ve==="auth"&&n?.access_token&&ke("")},[ve,n?.access_token]);const[Je,Mt]=u.useState(""),[It,an]=u.useState(null),mt=u.useRef(null),Pn=u.useRef(0),Kt=u.useCallback((y,N,z)=>{const B=String(y||"").trim();if(Mt(B),mt.current!==null&&(window.clearTimeout(mt.current),mt.current=null),!B){an(null);return}const D=++Pn.current;if(an({id:D,message:B,tone:N}),!z)return;const ue=window.setTimeout(()=>{an(de=>de?.id===D?null:de),mt.current===ue&&(mt.current=null)},5e3);mt.current=ue},[]),X=u.useCallback((y,N="info")=>{Kt(y,N,!0)},[Kt]),De=u.useCallback(y=>{Kt(y,"progress",!1)},[Kt]);u.useEffect(()=>()=>{mt.current!==null&&window.clearTimeout(mt.current)},[]);const[ze,Ae]=u.useState(()=>typeof window<"u"&&window.location.pathname.startsWith("/support")?"support":"wall");u.useEffect(()=>{const y=()=>{Ae(window.location.pathname.startsWith("/support")?"support":N=>N==="support"?"wall":N)};return window.addEventListener("popstate",y),()=>window.removeEventListener("popstate",y)},[]);const[et,gt]=u.useState("large"),[Re,fa]=u.useState(LT),[$n,at]=u.useState(!1),[qt,un]=u.useState(!1),[ns,as]=u.useState(!1),[Zn,nr]=u.useState(rT),[Fe,zs]=u.useState(hT),[vt,hi]=u.useState(gT),[Jt,H]=u.useState(fT),[Le,lt]=u.useState(null),[hn,ss]=u.useState([]),[Dn,ma]=u.useState(Fe.fps),[te,Me]=u.useState(""),[Ge,ut]=u.useState(0),[sn,Gt]=u.useState(0),[nt,kt]=u.useState(()=>new Set),Bt=u.useRef(new Map),Qt=u.useRef(new Map),rn=u.useRef(new Map),Ot=u.useRef(new Map),Dt=u.useRef(new Map),Vt=u.useRef(new Map),ha=u.useRef(new Set),is=u.useRef(new Map),Lt=u.useRef(""),pn=u.useRef(""),ar=u.useRef(null),Pa=u.useRef(null),Ca=u.useRef(new Map),_l=u.useRef(null),sr=u.useRef(0),ir=u.useRef(new Map),[$a,ja]=u.useState({}),zl=u.useRef(new Map),[Lo,_o]=u.useState({}),[zo,Jn]=u.useState(!1),Io=u.useRef(null),dn=u.useRef(null),ea=u.useRef(0),Is=u.useRef(""),Ss=u.useRef(new Map),Ua=u.useRef(new Map),Qr=u.useRef(performance.now()),rr=u.useRef(new Map),qa=u.useRef(new Map),lr=u.useRef(new Map),or=u.useRef(new Map),Il=u.useRef(new Map),pi=u.useRef(0),Ol=u.useRef(0),Hl=u.useRef(0),gi=u.useRef(0),Ga=u.useRef(0),Bl=u.useRef(new Map),rs=u.useRef(new Map),[ka,pa]=u.useState(null),[ru,Xr]=u.useState(!1),[gf,Zr]=u.useState([]),[ta,Oo]=u.useState("all"),[ls,os]=u.useState([]),[lu,Ho]=u.useState(!1),[vf,Fl]=u.useState(!0),Jr=u.useRef(null),Bo=u.useRef(null),na=u.useRef(null),vi=u.useRef(null),Pl=u.useRef(!1),yi=u.useRef(!1),Fo=u.useRef(!1),xi=u.useRef(0),cs=u.useRef(0),Os=ze==="settings",el=ze==="pricing",Po=ze==="doc",ou=ze==="support",tl=ze==="share-files",$o=ze==="agents",$l=!Os&&!el&&!Po&&!ou&&!tl&&!$o,ot=ze==="control",ht=Fe.frameMode==="mode4-h264-atlas",ga=I||vt.frameMode,cr=ga!=="mode3-h264-hw"?Math.min(30,vt.fps):vt.fps,yf=j.find(y=>y.deviceId===W)?.platform,Uo=OT(yf)?{maxWidth:1280,maxHeight:720}:{maxWidth:3840,maxHeight:2160},Hs={maxWidth:Math.min(ga!=="mode3-h264-hw"?1920:3840,Uo.maxWidth,vt.maxWidth),maxHeight:Math.min(ga!=="mode3-h264-hw"?1080:2160,Uo.maxHeight,vt.maxHeight)};u.useEffect(()=>{if(b?.started){if(!n?.access_token){We("/api/remote/license",{method:"DELETE"},M).catch(()=>{});return}We("/api/remote/license/sync",{method:"POST",headers:{Authorization:`Bearer ${n.access_token}`}},M).catch(y=>{console.warn("[LiveDesk] Hub license sync failed",y)})}},[A?.updated_at,M,n?.access_token,b?.started]),u.useEffect(()=>{!n?.access_token||!b?.started||b.runtimeRole!=="hub"||!b.deviceId||(async()=>{try{const{data:y,error:N}=await ft.rpc("register_livedesk_device",{p_device_id:b.deviceId,p_device_name:b.deviceName||b.deviceId,p_role:"hub",p_assigned_hub_id:null,p_platform:navigator.platform||navigator.userAgent,p_os_version:navigator.userAgent,p_app_version:b.managerVersion||b.managerPackage||""}),z=Array.isArray(y)?y[0]:y;(N||z?.ok===!1)&&console.warn("[LiveDesk] Hub device role registration failed",N||z?.reason||"unknown-error")}catch(y){console.warn("[LiveDesk] Hub device role registration failed",y)}})()},[n?.access_token,b?.deviceId,b?.deviceName,b?.managerPackage,b?.managerVersion,b?.runtimeRole,b?.started]),u.useEffect(()=>{!n?.access_token||!n.refresh_token||!b?.started||b.runtimeRole!=="hub"||Fo.current||(Fo.current=!0,We("/api/auth/session",{method:"POST",body:JSON.stringify({accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:n.expires_at,user:{id:n.user.id,email:n.user.email}})},M||kn).then(y=>{y.hostTarget?.ok===!1&&console.warn("[LiveDesk] Hub host target publish is waiting for a valid Hub role:",y.hostTarget.error||"unknown-error"),k()}).catch(y=>{console.warn("[LiveDesk] Hub session sync failed:",y)}).finally(()=>{Fo.current=!1}))},[M,k,n?.access_token,n?.expires_at,n?.refresh_token,n?.user?.email,n?.user?.id,b?.runtimeRole,b?.started]);const it=u.useMemo(()=>j.filter(y=>y.connected),[j]),cu=ta==="all"?it.length:ls.filter(y=>it.some(N=>N.deviceId===y)).length,xf=u.useMemo(()=>it.reduce((y,N)=>Math.max(y,$x(N.slotNumber)),0),[it]),ur=Math.max(DM,it.length,xf),bi=u.useMemo(()=>{const y=Array(ur).fill(null),N=[];for(const z of it){const B=$x(z.slotNumber);B>0&&B<=ur&&!y[B-1]?y[B-1]=z:N.push(z)}for(const z of N){const B=y.findIndex(D=>!D);B<0?y.push(z):y[B]=z}return y},[it]),uu=u.useMemo(()=>bi.flatMap((y,N)=>y?[{device:y,slotNumber:N+1}]:[]),[bi]),qo=u.useMemo(()=>it.map(y=>y.deviceId),[it]),Bs=u.useMemo(()=>new Set(V),[V]),va=u.useMemo(()=>it.filter(y=>Bs.has(y.deviceId)),[it,Bs]),dr=u.useMemo(()=>j.find(y=>y.deviceId===L)||va[0]||null,[j,L,va]),Un=u.useMemo(()=>j.find(y=>y.deviceId===W)||null,[W,j]),Fs=Un?Oa(Jt[Un.deviceId],ba(Un)):0,_e=ot?Un:dr,du=u.useMemo(()=>new Set(ls),[ls]),bf=u.useMemo(()=>ta==="all"?it.map(y=>y.deviceId):it.filter(y=>du.has(y.deviceId)).map(y=>y.deviceId),[it,du,ta]),wf=_e?Qc(_e,"control"):!1,Go=er(_e?.platform)&&(_e?.capabilities?.controlPermission===!1||_e?.capabilities?.accessibilityPermission===!1),wi=_e?Qc(_e,"audio")||Qc(_e,"remoteAudio"):!1,fr=Array.isArray(_e?.capabilities?.agentTools)?_e.capabilities.agentTools.map(String):[],fu=fr.includes("system.power"),Vo=fr.includes("command.run"),Wt=T?A?.plan==="pro"?"pro":"ltd":"free",Wo=Sl[Wt],nl=Wo.limit,Si=u.useMemo(()=>{if(!Number.isFinite(nl))return new Set(it.map(N=>N.deviceId));const y=_e?[_e,...it.filter(N=>N.deviceId!==_e.deviceId)]:it;return new Set(y.slice(0,nl).map(N=>N.deviceId))},[nl,it,_e]),mr=!_e||Si.has(_e.deviceId),Sf=Wt==="free",en=mr,al=Wt==="ltd"?`Plus includes up to ${$c} workstations. Upgrade to Pro for commercial use and larger walls.`:`Free includes up to ${Pc} workstations. Upgrade to Plus for ${$c} devices and no ads.`,mu=Wt==="free",us=en&&!!_e&&wf,hr=en&&!!_e&&wi,Ps=u.useMemo(()=>bi.filter(y=>!!y?.connected).slice(0,yT(et)).map(y=>y.deviceId),[bi,et]),Ul=u.useMemo(()=>et==="list"?[]:ht?qo:Fe.visibleOnlyLive?hn.length>0?hn:Ps:qo,[Ps,ht,hn,Fe.visibleOnlyLive,qo,et]),aa=u.useMemo(()=>wh(Ul.filter(y=>Si.has(y))),[Si,Ul]),Cs=u.useMemo(()=>aa.filter(y=>y!==te),[aa,te]),sl=u.useMemo(()=>new Map(it.map(y=>[y.deviceId,y.platform])),[it]),Aa=Rj(ht,aa.length),sa=u.useMemo(()=>ht?Cs.filter(y=>Hc({mode4Enabled:ht,directMode4WallEnabled:Aa,isMac:er(sl.get(y))})==="atlas"):[],[Aa,ht,sl,Cs]),ia=u.useMemo(()=>Cs.filter(y=>Hc({mode4Enabled:ht,directMode4WallEnabled:Aa,isMac:er(sl.get(y))})==="direct"),[Aa,ht,sl,Cs]);u.useEffect(()=>{const y=new Set(aa);kt(N=>{let z=!1;const B=new Set;for(const D of N)y.has(D)?B.add(D):z=!0;return z?B:N})},[aa]);const hu=u.useMemo(()=>{const y=D=>it.find(ue=>ue.deviceId===D)||null,N=D=>Oa(Jt[D],y(D)?ba(y(D)):0),z=(D,ue=N(D))=>D===O&&(G==="connecting"||G==="active"||G==="warm")?Dt.current.get(D)||Qt.current.get(D)||null:ht?Ca.current.get(D)||Bt.current.get(D)||null:Bt.current.get(D)||null,B=(D,ue=N(D))=>{const de=y(D);return`${de?Ja(de):D} · Monitor ${ue+1}`};return{resolveCurrentTarget(){if(ot&&Un){const qe=Fs;return{type:"control",deviceIds:[Un.deviceId],monitorIndex:qe,label:`${Ja(Un)} · Monitor ${qe+1}`,sourceCanvas:z(Un.deviceId,qe),signature:`control:${Un.deviceId}:${qe}:${vt.frameMode}`}}const D=va.map(qe=>qe.deviceId).filter(qe=>Cs.includes(qe)),ue=dr&&Cs.includes(dr.deviceId)?dr.deviceId:"",de=D.length>0?D:ue?[ue]:Cs,Ie=D.length===0&&!ue;if(de.length===0)return null;if(de.length===1){const qe=de[0],Ve=N(qe);return{type:Ie?"wall":D.length>1?"selection":"device",deviceIds:de,monitorIndex:Ve,label:Ie?"Wall":B(qe,Ve),sourceCanvas:Ie?null:z(qe,Ve),signature:`${Ie?"wall":"device"}:${qe}:${Ve}:${ht?"atlas":"direct"}`}}return{type:D.length>1?"selection":"wall",deviceIds:de,label:D.length>1?`${de.length} selected workstations`:"Wall",sourceCanvas:null,signature:`${D.length>1?"selection":"wall"}:${de.join(",")}:${et}`}},getDeviceCanvas:z,composeWall(D,ue={}){return bM(D.map(de=>{const Ie=N(de);return{deviceId:de,label:B(de,Ie),canvas:z(de,Ie)}}),ue)}}},[it,Un,O,G,vt.frameMode,Bt,ht,Jt,Fs,va,ot,Cs,dr,et]),Yo=RM({hubUrl:M,sourceRegistry:hu,onToast:X}),pr=u.useMemo(()=>en&&O&&Si.has(O)&&(G==="connecting"||G==="active"||G==="warm")?[O]:[],[O,G,en,Si]),Cf=u.useMemo(()=>wh([...aa,...pr]),[pr,aa]),qn=u.useMemo(()=>xT(Fe,et),[Fe,et]),gr=Dj({mode4Enabled:ht,directMode4WallEnabled:Aa,adaptiveFps:Dn,directDeviceCount:ia.length}),Gn=u.useCallback((y,N,z)=>{if(y.width<=0||y.height<=0)return!1;const B=z?Math.min(1,z.maxWidth/y.width,z.maxHeight/y.height):1,D=Math.max(1,Math.round(y.width*B)),ue=Math.max(1,Math.round(y.height*B));(N.width!==D||N.height!==ue)&&(N.width=D,N.height=ue);const de=N.getContext("2d",{alpha:!1});return de?(de.imageSmoothingEnabled=!0,de.imageSmoothingQuality="high",de.drawImage(y,0,0,y.width,y.height,0,0,N.width,N.height),!0):!1},[]),ln=u.useCallback(y=>{y&&kt(N=>{if(N.has(y))return N;const z=new Set(N);return z.add(y),z})},[]),$s=u.useCallback(y=>{y&&kt(N=>{if(!N.has(y))return N;const z=new Set(N);return z.delete(y),z})},[]),Ci=u.useCallback((y,N)=>{if(!N||N.width<=0||N.height<=0)return!1;const z=document.createElement("canvas");return z.width=N.width,z.height=N.height,Gn(N,z)?(rn.current.set(y,z),ln(y),!0):!1},[ln,Gn]),js=u.useCallback(y=>{const N=Ot.current.get(y);N!==void 0&&(window.cancelAnimationFrame(N),Ot.current.delete(y))},[]),ji=u.useCallback(y=>{js(y),rn.current.delete(y)},[js]),il=u.useCallback((y,N)=>{js(y);const z=()=>{const B=rn.current.get(y),D=Bt.current.get(y)===N||Ca.current.get(y)===N;if(!B||!D){Ot.current.delete(y);return}Gn(B,N),Ot.current.set(y,window.requestAnimationFrame(z))};z()},[Gn,js]);u.useEffect(()=>()=>{for(const y of Ot.current.values())window.cancelAnimationFrame(y);Ot.current.clear()},[]);const Va=u.useCallback((y,N=!1)=>{if(!ha.current.has(y))return!1;const z=performance.now(),B=is.current.get(y)||0,D=Math.max(1,Math.min(di.controlWallReuseMaxFps,cr)),ue=cr>D?Math.max(0,1e3/D-2):0;if(!N&&z-B<ue)return!1;const de=Dt.current.get(y)||Qt.current.get(y),Ie=Bt.current.get(y)||Ca.current.get(y);return!de||!Ie||!Gn(de,Ie,qn)?!1:(is.current.set(y,z),ln(y),ji(y),!0)},[cr,qn,ln,Gn,ji]);u.useEffect(()=>{Lt.current=te},[te]);const pu=u.useCallback((y,N)=>{const z=Bt.current.get(y);if(z&&z!==N&&(js(y),Ci(y,z),Oc(z)),N){Bt.current.set(y,N);const B=rn.current.get(y);B&&Gn(B,N)&&(ln(y),il(y,N)),Va(y,!0);return}Bt.current.delete(y),rn.current.has(y)||$s(y)},[$s,il,ln,Gn,Va,Ci,js]),vr=u.useCallback((y,N)=>{const z=Qt.current.get(y);if(z&&z!==N&&Oc(z),N){Qt.current.set(y,N);const B=O===y&&oe?Dt.current.get(y):null;B&&Gn(B,N)&&y===W&&Jn(!0);return}Qt.current.delete(y)},[W,O,oe,Gn]),yr=u.useCallback((y,N,z)=>{const B=performance.now(),D=xs(y,z.deviceId);let ue=z;if(y==="control"&&z.visualChanged){const Ie=gj(z.deviceId),qe=Bl.current.get(z.deviceId)||0,Ve=Ie?B-Ie.sentAt:Number.POSITIVE_INFINITY;Ie&&Ie.inputSeq>qe&&Ve<=kx&&(ue={...z,inputFeedbackSeq:Ie.inputSeq,inputFeedbackMs:Math.max(0,Ve),inputFeedbackAt:B},Bl.current.set(z.deviceId,Ie.inputSeq))}Ua.current.set(D,B);const de=ir.current.get(D)||{totalFrames:0,totalChangedFrames:0,sampleFrames:0,sampleChangedFrames:0,sampleStartedAt:B,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleDecoderInputBase:0,sampleDecoderOutputBase:0};y==="control"&&ue.inputFeedbackMs===void 0&&de.lastInfo?.inputFeedbackMs!==void 0&&de.lastInfo.inputFeedbackAt!==void 0&&B-de.lastInfo.inputFeedbackAt<=kx&&(ue={...ue,inputFeedbackSeq:de.lastInfo.inputFeedbackSeq,inputFeedbackMs:de.lastInfo.inputFeedbackMs,inputFeedbackAt:de.lastInfo.inputFeedbackAt}),de.totalFrames+=1,de.sampleFrames+=1,Rx(de,B,ue.frameSeq),ue.visualChanged&&(de.totalChangedFrames+=1,de.sampleChangedFrames+=1),de.lastInfo=ue,ir.current.set(D,de)},[]),Us=u.useCallback((y,N)=>{yr("wall",y,N),y.kind==="live"&&(ln(y.deviceId),ji(y.deviceId));const z=oe&&O===y.deviceId;Lt.current!==y.deviceId&&!z&&(ha.current.delete(y.deviceId),is.current.delete(y.deviceId))},[O,oe,ln,yr,ji]),ql=u.useCallback((y,N)=>{yr("control",y,N),fe(ue=>ue&&"");const z=Dt.current.get(y.deviceId),B=Qt.current.get(y.deviceId);z&&z.width>0&&z.height>0&&(B&&Gn(z,B),Vt.current.set(y.deviceId,{...y,payload:new Uint8Array(0),byteLength:0}),ha.current.add(y.deviceId),y.deviceId===O&&(we(!0),q(ue=>ue==="connecting"?"active":ue)),Va(y.deviceId));const D=Io.current;!D||!GM(D,y)||Jn(!0)},[O,Gn,Va,yr]);u.useEffect(()=>{const y=window.setInterval(()=>{const N=performance.now(),z={};for(const[B,D]of ir.current.entries()){const ue=Math.max(1,N-D.sampleStartedAt);z[B]={totalFrames:D.totalFrames,totalChangedFrames:D.totalChangedFrames,framesPerSecond:D.sampleFrames*1e3/ue,changedFramesPerSecond:D.sampleChangedFrames*1e3/ue,averageIntervalMs:D.intervalCount>0?D.intervalSumMs/D.intervalCount:0,minIntervalMs:Number.isFinite(D.minIntervalMs)?D.minIntervalMs:0,maxIntervalMs:D.maxIntervalMs,p95IntervalMs:vh(D.intervalSamplesMs,.95),intervalCount:D.intervalCount,seqGapCount:D.seqGapCount,maxSeqGap:D.maxSeqGap,decoderInputFps:Math.max(0,(Number(D.lastInfo?.decoderInputCount||0)-D.sampleDecoderInputBase)*1e3/ue),decoderOutputFps:Math.max(0,(Number(D.lastInfo?.decoderOutputCount||0)-D.sampleDecoderOutputBase)*1e3/ue),sampleMs:ue,lastInfo:D.lastInfo},D.sampleDecoderInputBase=Number(D.lastInfo?.decoderInputCount||0),D.sampleDecoderOutputBase=Number(D.lastInfo?.decoderOutputCount||0),D.sampleChangedFrames=0,Ex(D,N)}ja(z)},1e3);return()=>window.clearInterval(y)},[]);const ki=u.useCallback((y,N)=>{const z=performance.now(),B=xs(y,N.deviceId);Ss.current.set(B,z),rs.current.delete(B),y==="control"?qa.current.delete(B):or.current.delete(B);const D=zl.current.get(B)||{totalFrames:0,sampleFrames:0,sampleStartedAt:z,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleBytes:0,sampleH264Frames:0,sampleTinyFrames:0,sampleRepeatedFrames:0,sourceSendIntervalsMs:[]};if(D.totalFrames+=1,D.sampleFrames+=1,D.sampleBytes+=Math.max(0,Number(N.byteLength||0)),String(N.frameMode||N.mode||N.codec||N.mimeType||"").toLowerCase().includes("h264")){D.sampleH264Frames+=1,Number(N.byteLength||0)<=PM&&(D.sampleTinyFrames+=1);const qe=String(N.contentHash||"");qe&&D.lastContentHash===qe&&(D.sampleRepeatedFrames+=1),D.lastContentHash=qe}const Ie=Number(N.agentSendGapMs||0);Ie>0&&Ie<1e3&&vw(D.sourceSendIntervalsMs,Ie),D.lastFrame=N,Rx(D,z,N.frameSeq),zl.current.set(B,D)},[]);u.useEffect(()=>{const y=window.setInterval(()=>{const N=performance.now(),z={};for(const[B,D]of zl.current.entries()){const ue=Math.max(1,N-D.sampleStartedAt);z[B]={totalFrames:D.totalFrames,framesPerSecond:D.sampleFrames*1e3/ue,averageIntervalMs:D.intervalCount>0?D.intervalSumMs/D.intervalCount:0,minIntervalMs:Number.isFinite(D.minIntervalMs)?D.minIntervalMs:0,maxIntervalMs:D.maxIntervalMs,p95IntervalMs:vh(D.intervalSamplesMs,.95),intervalCount:D.intervalCount,seqGapCount:D.seqGapCount,maxSeqGap:D.maxSeqGap,averageFrameBytes:D.sampleFrames>0?D.sampleBytes/D.sampleFrames:0,tinyFrameRatio:D.sampleH264Frames>0?D.sampleTinyFrames/D.sampleH264Frames:0,repeatedFrameRatio:D.sampleH264Frames>0?D.sampleRepeatedFrames/D.sampleH264Frames:0,sourceSendAverageMs:D.sourceSendIntervalsMs.length>0?D.sourceSendIntervalsMs.reduce((de,Ie)=>de+Ie,0)/D.sourceSendIntervalsMs.length:0,sourceSendP95Ms:vh(D.sourceSendIntervalsMs,.95),sourceSendSampleCount:D.sourceSendIntervalsMs.length,sampleMs:ue,lastFrame:D.lastFrame},D.sampleBytes=0,D.sampleH264Frames=0,D.sampleTinyFrames=0,D.sampleRepeatedFrames=0,D.sourceSendIntervalsMs.length=0,Ex(D,N)}_o(z)},1e3);return()=>window.clearInterval(y)},[]);const qs=u.useCallback(y=>{ki("wall",y);const N=Bt.current.get(y.deviceId);if(!N)return;const z=Lj(ht,Fe.h264DecodeAcceleration);nh(N,y,()=>Bt.current.get(y.deviceId)!==N,Us,z.acceleration,z.latencyMode).catch(()=>{})},[Us,ht,ki,Fe.h264DecodeAcceleration]),Ai=u.useCallback(y=>{ki("control",y);let N=Dt.current.get(y.deviceId);N||(N=document.createElement("canvas"),N.setAttribute("aria-hidden","true"),Dt.current.set(y.deviceId,N));const z=N,B=me.current;nh(z,y,()=>Dt.current.get(y.deviceId)!==z,ql,vt.h264DecodeAcceleration,"interactive").catch(D=>{me.current!==B||Dt.current.get(y.deviceId)!==z||O!==y.deviceId||fe(D instanceof Error?D.message:String(D||"Control H.264 decode failed"))})},[O,vt.h264DecodeAcceleration,ql,ki]),Ko=u.useCallback(y=>{const N=Pa.current;N&&N!==y&&Oc(N),Pa.current=y,pi.current=0,Ol.current=0,Hl.current=0,gi.current=0,Ga.current=0,sr.current=0},[]),Ni=u.useCallback(()=>{const y=new Set,N=Pa.current,z=_l.current;if(!N||!z||N.width<=0||N.height<=0||sr.current!==z.layoutVersion)return y;for(const B of z.tiles){const D=Ca.current.get(B.deviceId);if(!D||B.width<=0||B.height<=0)continue;const ue=Math.max(1,Math.round(B.width)),de=Math.max(1,Math.round(B.height)),Ie=$M,qe=UM;(D.width!==Ie||D.height!==qe)&&(D.width=Ie,D.height=qe);const Ve=D.getContext("2d",{alpha:!1});if(Ve){Ve.imageSmoothingEnabled=!0,Ve.imageSmoothingQuality="high";try{Ve.drawImage(N,Math.round(B.x),Math.round(B.y),ue,de,0,0,Ie,qe),y.add(B.deviceId)}catch{}}}return y},[]),Mi=u.useCallback((y,N)=>{if(N){Ca.current.set(y,N);const B=rn.current.get(y);B&&Gn(B,N)&&(ln(y),il(y,N)),window.requestAnimationFrame(()=>{Ni().has(y)&&ji(y)}),window.requestAnimationFrame(()=>Va(y,!0));return}const z=Ca.current.get(y);js(y),Ci(y,z),Ca.current.delete(y),rn.current.has(y)||$s(y)},[$s,il,ln,Ni,Gn,Va,Ci,ji,js]),Qo=u.useCallback((y,N)=>{Hl.current=performance.now(),sr.current=Number(y.layoutVersion||0),Ni();const z=_l.current?.tiles||[],B=z.length>0?Math.round(y.byteLength/z.length):y.byteLength;for(const D of z){const ue={...y,deviceId:D.deviceId,width:D.width,height:D.height,sourceWidth:D.width,sourceHeight:D.height,byteLength:B};Us(ue,{...N,deviceId:D.deviceId,width:D.width,height:D.height,byteLength:B}),Lt.current===D.deviceId&&Va(D.deviceId,!0)}},[Us,Ni,Va]),gu=u.useCallback(y=>{const N=performance.now();pi.current<=0&&(pi.current=N),Ol.current=N;const z=Pa.current;if(!z)return;const B=_l.current?.tiles||[],D=B.length>0?Math.round(y.byteLength/B.length):y.byteLength;for(const ue of B)ki("wall",{...y,deviceId:ue.deviceId,width:ue.width,height:ue.height,sourceWidth:ue.width,sourceHeight:ue.height,byteLength:D});nh(z,y,()=>Pa.current!==z,Qo).catch(()=>{})},[Qo,ki]),vu=u.useMemo(()=>({fps:gr,maxWidth:qn.maxWidth,maxHeight:qn.maxHeight,quality:Fe.quality,mode:ht?"mode3-h264-hw":Fe.frameMode,frameMode:ht?"mode3-h264-hw":Fe.frameMode,streamPurpose:"wall",monitorSelections:Jt,onFrame:qs}),[gr,qs,qn,ht,Jt,Fe]),yu=u.useCallback(y=>{if(y.deviceId!==O||y.streamPurpose!=="control"||y.monitorIndex!==Fs)return;const N=it.find(z=>z.deviceId===y.deviceId);!N?.sessionId||N.sessionId!==y.sessionId||($(y),q(z=>z==="connecting"?"active":z))},[it,O,Fs]);u.useEffect(()=>{$(null)},[O,re,ga,Fs]);const jf=u.useMemo(()=>({fps:cr,maxWidth:Hs.maxWidth,maxHeight:Hs.maxHeight,quality:vt.quality,mode:ga,frameMode:ga,streamPurpose:"control",forceRestart:re!=="",forceRestartToken:re,restartReason:re?"control-session-start":"",monitorSelections:Jt,onFrame:Ai,onStreamReady:yu}),[re,vt.quality,Ai,cr,ga,Hs.maxHeight,Hs.maxWidth,yu,Jt]),{frames:xu,state:xr,error:Xo,stats:ds,restartLive:ra}=Ly(ia,Fe.autoStartLive&&ia.length>0,M,vu),{frame:ks,layout:An,state:Gs,stats:Zo,refreshInputs:rl}=yj(sa,ht&&Fe.autoStartLive&&sa.length>0,M,{fps:di.atlasOutputFps,width:1920,height:1080,tileWidth:qn.maxWidth,tileHeight:qn.maxHeight,captureDeviceIds:sa,monitorSelections:Jt,onFrame:gu});u.useEffect(()=>{_l.current=An,An&&window.requestAnimationFrame(Ni)},[An,Ni]),u.useEffect(()=>{if(!ht||Gs!=="open"){pi.current=0,Ol.current=0,Hl.current=0;return}const y=window.setInterval(()=>{const N=Pa.current,z=performance.now();if(!N||document.visibilityState!=="visible"||z-Qr.current<gh)return;const B=Ol.current,D=pi.current;if(B<=0||D<=0||z-B>500)return;const ue=Hl.current||D,de=z-ue;if(de>=OM&&z-Ga.current>=BM){eh(N)&&(Ga.current=z,gi.current=z);return}de>=IM&&z-gi.current>=HM&&ej(N)&&(gi.current=z)},250);return()=>window.clearInterval(y)},[Gs,ht]);const{frames:br,state:ll,error:Wa,stats:bu,restartLive:Ti,reconnectLive:Ei}=Ly(pr,pr.length>0,M,jf),Gl=u.useMemo(()=>{const y=new Map(xu);if(ht&&ks&&sa.length>0){const N=new Map((An?.tiles||[]).map(B=>[B.deviceId,B])),z=Math.max(1,N.size);for(const B of sa){const D=N.get(B);D&&y.set(B,{...ks,deviceId:B,width:D.width,height:D.height,sourceWidth:D.width,sourceHeight:D.height,byteLength:Math.round(ks.byteLength/z)})}}for(const[N,z]of br.entries())y.set(N,z);for(const N of Ul){if(!ha.current.has(N)||y.has(N))continue;const z=Vt.current.get(N);z&&y.set(N,z)}return y},[ks,An,br,sa,ht,xu,Ul,sn]),Vn=ot&&pr.length>0?ll:sa.length>0?Gs:xr,ol=ot&&pr.length>0?bu:sa.length>0?Zo:ds;u.useCallback((y,N="browser-stale")=>{const z=ra(y,N),B=Ti(y,N);return z||B},[Ti,ra]),u.useEffect(()=>{ht&&sa.length>0&&!ot&&rl()},[sa.length,ht,rl,ot]);const Na=u.useCallback((y,N,z)=>{const B=N==="control"?Dt.current.get(y)||null:Bt.current.get(y)||null;if(!B||!eh(B))return!1;const D=performance.now();return Il.current.set(xs(N,y),D),!0},[]),cl=u.useCallback(y=>{if(ga!=="mode3-h264-hw"||!O||I)return!1;const N=it.find(Ie=>Ie.deviceId===O)||Un,z=String(N?.platform||"").toLowerCase();if(!["win32","windows","win32nt"].includes(z))return!1;const B="mode5-lzo-delta",D=xs("control",O),ue=performance.now();lr.current.set(D,ue),Ss.current.delete(D),Ua.current.delete(D),rr.current.delete(D),qa.current.delete(D),rs.current.delete(D),eh(Dt.current.get(O)||null),Ei([O],"control-decode-fallback"),ee(B),K(`control-${B}-fallback-${O}-${Date.now()}`),we(!1),Jn(!1);const de=y==="no first frame"||y==="control-first-frame-timeout";return fe(Ie=>Ie||(de?`Control frame transport timeout; retrying Control with Mode 5 (${y})`:`H.264 decode failed; retrying Control with Mode 5 (${y})`)),q("connecting"),!0},[it,Un,O,I,ga,Ei]);u.useEffect(()=>{const y=ot?Un:null;if(y){Io.current={deviceId:y.deviceId,monitorIndex:Fs,frameMode:ga,startedAtEpochMs:Date.now()},Jn(O===y.deviceId&&oe);return}Io.current=null,Jn(!1)},[Un?.sessionId,W,O,oe,ga,Fs,ot]);const Vs=u.useCallback(async y=>{const N=j.find(de=>de.deviceId===y),z=Hc({mode4Enabled:ht,directMode4WallEnabled:Aa,isMac:er(N?.platform)})==="atlas",B=Oa(Jt[y],N?ba(N):1),D=z?{fps:di.scalableAtlasInputFps,maxWidth:qn.maxWidth,maxHeight:qn.maxHeight,quality:60,mode:"mode2-lzo",frameMode:"mode2-lzo",streamPurpose:"atlas",monitorIndex:B}:{fps:ht&&!z?gr:Dn,maxWidth:qn.maxWidth,maxHeight:qn.maxHeight,quality:Fe.quality,mode:ht?"mode3-h264-hw":Fe.frameMode,frameMode:ht?"mode3-h264-hw":Fe.frameMode,streamPurpose:"wall",monitorIndex:B},ue=await We(`/api/remote/devices/${encodeURIComponent(y)}/live/start`,{method:"POST",body:JSON.stringify(D)},M);if(ue?.ok===!1)throw new Error(ue.error||"wall-stream-start-failed");return ue},[Dn,j,Aa,gr,qn.maxHeight,qn.maxWidth,M,ht,Jt,Fe.frameMode,Fe.quality]),fs=u.useCallback(async y=>{const N=j.find(D=>D.deviceId===y),z=Hc({mode4Enabled:ht,directMode4WallEnabled:Aa,isMac:er(N?.platform)})==="atlas",B=await We(`/api/remote/devices/${encodeURIComponent(y)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:z?"atlas":"wall",reason:"control-active"})},M);if(B?.ok===!1)throw new Error(B.error||"wall-stream-stop-failed");return B},[j,Aa,M,ht]),Ws=u.useCallback(async(y,N="control-session-stop")=>{const z=await We(`/api/remote/devices/${encodeURIComponent(y)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"control",reason:N})},M);if(z?.ok===!1)throw new Error(z.error||"control-stream-stop-failed");return z},[M]),Ri=u.useCallback(y=>{const N=Dt.current.get(y);N&&(rn.current.has(y)||Bt.current.has(y)||Ca.current.has(y)||Ci(y,N),Oc(N),Dt.current.delete(y));const z=Qt.current.get(y);z&&Oc(z),Vt.current.delete(y),ha.current.delete(y),is.current.delete(y)},[Ci]);u.useEffect(()=>{const y=W&&it.find(D=>D.deviceId===W)||null;if(!ot||!en||!y){Is.current&&(++ea.current,Is.current="");return}if(O===y.deviceId&&(G==="active"||G==="warm"||G==="connecting")){q(D=>D==="warm"?"active":D);return}if(Is.current===y.deviceId)return;const N=++ea.current,z=O;Is.current=y.deviceId,(async()=>{if(z){if(q("stopping"),await Ws(z,"control-session-switch").catch(()=>{}),N!==ea.current)return;const de=Lt.current;if(de&&de!==y.deviceId)try{await Vs(de)}catch(Ie){X(Ie instanceof Error?Ie.message:String(Ie))}finally{Lt.current===de&&(Lt.current="",Me(""))}if(N!==ea.current)return;Ri(z)}if(N!==ea.current)return;if(qx(y)){try{await fs(y.deviceId)}catch(de){N===ea.current&&(Is.current="",q("error"),X(de instanceof Error?de.message:String(de)));return}if(N!==ea.current){await Vs(y.deviceId).catch(()=>{});return}Lt.current=y.deviceId,Me(y.deviceId),ha.current.add(y.deviceId)}const D=xs("control",y.deviceId),ue=`control-session-${N}-${y.deviceId}`;lr.current.set(D,performance.now()),Ss.current.delete(D),Ua.current.delete(D),rs.current.delete(D),qa.current.delete(D),ee(""),fe(""),K(ue),be(y.deviceId),we(!1),q("connecting"),ea.current===N&&Is.current===y.deviceId&&(Is.current="")})()},[it,W,O,G,en,Ri,X,ot,Vs,Ws,fs]),u.useEffect(()=>{if(!O||it.some(z=>z.deviceId===O))return;const y=O,N=++ea.current;q("stopping"),Ws(y,"control-device-disconnected").catch(()=>{}).finally(()=>{N===ea.current&&(Ri(y),we(!1),K(""),ee(""),fe(""),be(z=>z===y?"":z),q("idle"))})},[it,O,Ri,Ws]);const Vl=qx(it.find(y=>y.deviceId===O));u.useEffect(()=>{if(dn.current!==null&&(window.clearTimeout(dn.current),dn.current=null),!O||G==="idle"||G==="stopping"||G==="error"||ot||ze==="wall"){O&&!ot&&ze==="wall"&&q(z=>z==="warm"||z==="active"?"active":z);return}q(z=>z==="idle"||z==="stopping"?z:"warm");const y=O,N=++ea.current;return dn.current=window.setTimeout(()=>{dn.current=null,q("stopping"),Ws(y,"control-session-warm-timeout").catch(()=>{}).finally(()=>{N===ea.current&&(Ri(y),we(!1),K(""),ee(""),fe(""),be(z=>z===y?"":z),q("idle"))})},FM),()=>{dn.current!==null&&(window.clearTimeout(dn.current),dn.current=null)}},[ze,O,G,Ri,ot,Ws]),u.useEffect(()=>()=>{dn.current!==null&&window.clearTimeout(dn.current)},[]),u.useEffect(()=>{const N=O&&(Vl&&(G==="connecting"||G==="active"||G==="warm"||G==="stopping")||oe&&(G==="active"||G==="warm"))?O:"";if(pn.current=N,ar.current)return;const z=async()=>{for(;;){const D=pn.current,ue=Lt.current;if(ue===D)return;if(ue){try{await Vs(ue)}catch(de){X(de instanceof Error?de.message:String(de))}finally{Lt.current===ue&&(Lt.current="",Me(""))}continue}if(!D)return;try{await fs(D)}catch(de){pn.current=Lt.current,X(de instanceof Error?de.message:String(de));return}Lt.current=D,Me(D),ha.current.add(D)}};let B;B=z().finally(()=>{ar.current===B&&(ar.current=null),Lt.current!==pn.current&&ut(D=>D+1)}),ar.current=B},[O,oe,G,Vl,ht,X,Vs,fs,Ge]);const Ys=O&&it.find(y=>y.deviceId===O)||null,Wn=!!(ot&&Se&&G==="active"&&Ys?.sessionId&&Q?.deviceId===Ys.deviceId&&Q.sessionId===Ys.sessionId&&Q.streamPurpose==="control"&&Q.commandId&&Q.captureGeneration>0&&Q.monitorIndex===Fs),{state:Ks,sendInput:Di,stats:ya,error:wr}=xj(us&&Wn,M),zn=u.useCallback((y,N)=>!Wn||!Ys||!Q||y!==Ys.deviceId?!1:Di(y,{...N,controlSessionId:Ys.sessionId,controlCommandId:Q.commandId,captureGeneration:Q.captureGeneration}),[Wn,Ys,Q,Di]),In=Wn&&Ks==="open",{state:Qs,lastFrame:Ya,stats:Xt,error:ms}=Mj(_e?.deviceId||"",hr&&Oe,M),ul=u.useRef(new Map);u.useEffect(()=>{const y=[["hub",C],["registry",l],["license",P],["wall-stream",Xo],["control-stream",Wa],["control-decode",he],["remote-input",wr],["remote-audio",ms]];for(const[N,z]of y){const B=String(z||"").trim();if(N==="hub"&&Le?.requiresHubRestart&&Le.stage==="updating"){ul.current.delete(N);continue}if(!B){ul.current.delete(N);continue}ul.current.get(N)!==B&&(ul.current.set(N,B),X(B))}},[ms,he,Wa,C,wr,P,l,X,Xo,Le]),u.useEffect(()=>{if(!ot||!Se||!us||!In||!_e)return;const y=(B,D)=>{const ue=B.target,de=ue?.tagName?.toLowerCase();ue?.isContentEditable||de==="input"||de==="textarea"||de==="select"||(B.preventDefault(),B.stopPropagation(),zn(_e.deviceId,{type:D,monitorIndex:Oa(Jt[_e.deviceId],ba(_e)),key:B.key,code:B.code,keyCode:B.keyCode||B.which||0,location:B.location,text:B.key.length===1?B.key:"",repeat:D==="keydown"?B.repeat:!1,shiftKey:B.shiftKey,ctrlKey:B.ctrlKey,altKey:B.altKey,metaKey:B.metaKey}))},N=B=>y(B,"keydown"),z=B=>y(B,"keyup");return window.addEventListener("keydown",N),window.addEventListener("keyup",z),()=>{window.removeEventListener("keydown",N),window.removeEventListener("keyup",z)}},[us,In,Se,Jt,_e,zn,ot]),u.useEffect(()=>{const y=()=>{document.visibilityState==="visible"&&(Qr.current=performance.now())};return document.addEventListener("visibilitychange",y),window.addEventListener("pageshow",y),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("pageshow",y)}},[]),u.useEffect(()=>{if(!O||G!=="connecting"&&G!=="active"&&G!=="warm"||ll!=="open")return;const y=O,N=xs("control",y),z=window.setInterval(()=>{const B=performance.now();if(document.visibilityState!=="visible"||B-Qr.current<gh)return;const D=Ss.current.get(N)||0,ue=Ua.current.get(N)||0,de=rr.current.get(N)||0,Ie=lr.current.get(N)||B;lr.current.has(N)||lr.current.set(N,Ie);const qe=D<=0,Ve=qe?B-Ie>KM:B-D>Ix,At=D>0&&(ue<=0||B-ue>Ix);if(!Ve&&At){const rt=Il.current.get(N)||0;B-rt>=Ox&&Na(y,"control","decoder-paint-stale");return}if(!Ve)return;const yt=qa.current.get(N)||0;if(yt>0){if(B-yt<XM)return;qa.current.delete(N)}const Yn=rs.current.get(N)||0;if(Yn>=ZM){if(cl(qe?"no first frame":"stale stream"))return;we(!1),Jn(!1),q("error");return}if(B-de<Hx(QM,Yn))return;Ti([y],qe?"control-first-frame-timeout":"control-receive-stale")&&(rr.current.set(N,B),qa.current.set(N,B),lr.current.set(N,B),rs.current.set(N,Yn+1))},650);return()=>window.clearInterval(z)},[ll,O,G,cl,Na,Ti]),u.useEffect(()=>{!he||ga!=="mode3-h264-hw"||cl(he)||(we(!1),Jn(!1),q("error"))},[he,ga,cl]),u.useEffect(()=>{!ot||!O||!Wa||q(y=>y==="error"?y:"error")},[Wa,O,ot]),u.useEffect(()=>{if(xr!=="open"||!Fe.autoStartLive||ia.length===0)return;const y=window.setInterval(()=>{const N=performance.now();if(document.visibilityState!=="visible"||N-Qr.current<gh)return;const z=1e3/Math.max(1,gr||Fe.fps||1),B=Math.max(eT,Math.ceil(z*4)),D=[];for(const ue of ia){if(D.length>=aT)break;const de=xs("wall",ue),Ie=Ss.current.get(de)||0,qe=Ie<=0,Ve=or.current.get(de)||N;if(or.current.has(de)||or.current.set(de,Ve),qe&&N-Ve<=JM)continue;const At=rr.current.get(de)||0,yt=Ua.current.get(de)||0,Yn=qe||N-Ie>B,Ea=!qe&&(yt<=0||N-yt>B);if(!Yn&&Ea){const Tt=Il.current.get(de)||0;N-Tt>=Ox&&Na(ue,"wall","decoder-paint-stale");continue}if(!Yn)continue;const rt=rs.current.get(de)||0;N-At>=Hx(tT,rt)&&D.push(ue)}if(D.length>0&&ra(D,D.some(ue=>(Ss.current.get(xs("wall",ue))||0)<=0)?"wall-first-frame-timeout":"wall-frame-stale"))for(const ue of D){const de=xs("wall",ue);rr.current.set(de,N),or.current.set(de,N),Ss.current.delete(de),Ua.current.delete(de),rs.current.set(de,(rs.current.get(de)||0)+1)}},nT);return()=>window.clearInterval(y)},[gr,ia,Na,ra,Fe.autoStartLive,Fe.fps,xr]),u.useEffect(()=>{ma(Fe.fps),xi.current=Date.now(),cs.current=0},[Fe.fps,Fe.frameMode,Fe.adaptiveLoadShedding]),u.useEffect(()=>{VC({h264DecodeAcceleration:Fe.h264DecodeAcceleration})},[Fe.h264DecodeAcceleration]),u.useEffect(()=>{if(!en||ot||et==="list"||!Fe.visibleOnlyLive){ss([]);return}const y=Jr.current;if(!y||typeof IntersectionObserver>"u"){ss(Ps);return}const N=Array.from(y.querySelectorAll("[data-live-device-id]"));if(N.length===0){ss([]);return}const z=new Map,B=()=>{const ue=wh(N.map(de=>String(de.dataset.liveDeviceId||"")).filter(de=>(z.get(de)||0)>0));ss(de=>bh(de,ue)?de:ue)},D=new IntersectionObserver(ue=>{for(const de of ue){const Ie=String(de.target.dataset.liveDeviceId||"");Ie&&z.set(Ie,de.isIntersecting?de.intersectionRatio||.01:0)}B()},{root:null,rootMargin:da.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return N.forEach(ue=>D.observe(ue)),B(),()=>D.disconnect()},[Ps,en,ot,bi,Fe.visibleOnlyLive,et]),u.useEffect(()=>{if(!Fe.adaptiveLoadShedding||!Fe.autoStartLive||ia.length===0)return;const y=Fe.fps;if(ia.length<=da.preserveConfiguredFpsDeviceCount){Dn!==y&&(ma(y),xi.current=Date.now(),cs.current=0);return}if(xr!=="open"||ds.sampleMs<500)return;const N=Date.now(),z=ia.length*Dn,B=ds.framesPerSecond,D=ds.bytesPerSecond,ue=Math.max(0,...ia.map(At=>Lo[xs("wall",At)]?.maxIntervalMs||0)),de=Math.max(0,...ia.map(At=>$a[xs("wall",At)]?.maxIntervalMs||0)),Ie=z>8&&B>0&&B<z*.72;if(B>da.maxWallFramesPerSecond||D>da.maxWallBytesPerSecond||ue>da.maxFrameGapMs||de>da.maxFrameGapMs||Ie){cs.current=0;const At=da.minFps;if(N-xi.current>=da.downshiftCooldownMs&&Dn>At){const yt=Math.max(At,bT(Dn,At));yt<Dn&&(ma(yt),xi.current=N)}return}const Ve=B<da.maxWallFramesPerSecond*da.lowLoadFrameRatio&&D<da.maxWallBytesPerSecond*da.lowLoadByteRatio;if(!Ve||Dn>=y){Ve||(cs.current=0);return}if(!cs.current){cs.current=N;return}if(N-cs.current>=da.recoveryCooldownMs){const At=Math.min(y,wT(Dn,y));At>Dn&&(ma(At),xi.current=N,cs.current=0)}},[Dn,ia.length,ia,$a,Lo,xr,ds.bytesPerSecond,ds.framesPerSecond,ds.lastUpdatedAt,ds.sampleMs,Fe.adaptiveLoadShedding,Fe.autoStartLive,Fe.frameMode,Fe.fps]),u.useEffect(()=>{const y=new URLSearchParams(window.location.search).get("checkout");if(y==="success"){X("Checkout returned. Waiting for Dodo confirmation."),F();const N=window.setInterval(()=>{F()},4e3),z=window.setTimeout(()=>{window.clearInterval(N)},45e3);return()=>{window.clearInterval(N),window.clearTimeout(z)}}y==="cancelled"&&X("Checkout cancelled.")},[F]),u.useEffect(()=>{!en&&Se&&Be(!1),!en&&Oe&&ge(!1)},[Oe,Se,en]),u.useEffect(()=>{const y=_e?.deviceId||"",N=Ze.current;if(Ze.current=y,!N||N===y)return;const z=++ce.current,B=y?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";y&&Oe&&Ke.current.set(y,B);let D=!0;return(async()=>{try{const de=Ke.current.get(N);if(Ke.current.delete(N),await We(`/api/remote/devices/${encodeURIComponent(N)}/audio/stop`,{method:"POST",body:JSON.stringify(de?{streamId:de}:{})},M),!D||z!==ce.current||!Oe||!y||!en||!wi)return;const Ie=await We(`/api/remote/devices/${encodeURIComponent(y)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:B,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},M);if(Ie.ok===!1)throw new Error(Ie.error||"Remote audio start failed.")}catch(de){D&&(Ke.current.delete(y),ge(!1),X(de instanceof Error?de.message:String(de)))}})(),()=>{D=!1}},[Oe,en,M,wi,_e?.deviceId]),u.useEffect(()=>{const y=it.map(B=>B.deviceId),N=new Set(y),z=new Map(it.map(B=>[B.deviceId,B]));_(B=>{const D=B.filter(ue=>N.has(ue));return bh(B,D)?B:D}),ne(B=>B&&N.has(B)?B:""),J(B=>B&&N.has(B)?B:""),H(B=>{let D=!1;const ue={};for(const[de,Ie]of Object.entries(B)){const qe=z.get(de);if(!qe){ue[de]=Ie;continue}const Ve=Oa(Ie,qe?ba(qe):1);ue[de]=Ve,Ve!==Ie&&(D=!0)}return D?ue:B}),os(B=>{const D=B.filter(ue=>N.has(ue));return bh(B,D)?B:D})},[it,ur]),u.useEffect(()=>{Zr([]),Fl(!1)},[Va]),u.useEffect(()=>{!tl||ta!=="selected"||ls.length>0||va.length===0||os(va.map(y=>y.deviceId))},[va,ls.length,ta,tl]),u.useEffect(()=>{try{localStorage.setItem(uw,Zn)}catch{}},[Zn]),u.useEffect(()=>{pT(Fe)},[Fe]),u.useEffect(()=>{vT(vt)},[vt]),u.useEffect(()=>{mT(Jt)},[Jt]);const dl=u.useCallback(async()=>{const y=new Set(p);y.add(kn);try{const ue=await We("/api/remote/status",void 0,kn);wy({endpoint:ue.agentEndpoint,endpoint_candidates:[...ue.agentEndpointCandidates||[],...ue.hostTargetEndpointCandidates||[]]}).forEach(de=>y.add(de))}catch{}const N=[...y].sort((ue,de)=>{const Ie=qe=>{const Ve=Wc(qe);return Ve==="local"?0:Ve==="loopback"?1:2};return Ie(ue)-Ie(de)||ue.localeCompare(de)});let z=!1,B="",D=!1;try{for(const ue of N){const de=Wc(ue);try{if(await We("/api/health",void 0,ue),de==="local")return g(!0),wo(!0),ue;de==="loopback"&&(z=!0,B=ue)}catch{de==="local"&&(D=!0)}}return z?(D&&X("LiveDesk Hub is reachable on this PC, but not through the LAN address yet. Restart LiveDesk Hub to bind 5179 on the network."),g(!0),wo(!0),B||kn):(g(!1),wo(!1),"")}catch{return g(!1),wo(!1),""}},[p]),Li=async()=>{if(ke("auth"),un(!1),await dl(),window.liveDesk?.auth?.signInWithGoogle){const z=await window.liveDesk.auth.signInWithGoogle();z?.ok===!1&&(X(z.error||"LiveDesk could not open the system browser for Google sign-in."),ke(""));return}const{data:y,error:N}=await ft.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}/callback`}});N&&(X(N.message),ke(""))},wu=async()=>{ke("auth"),un(!1),await ft.auth.signOut(),(await window.liveDesk?.auth?.persistSession?.(null))?.runtimeCleared===!1?X("Signed out locally. The LiveDesk runtime could not be reached to clear its session."):window.liveDesk?.auth?.persistSession||await We("/api/auth/session",{method:"DELETE"},kn).catch(()=>{}),ke("")};u.useEffect(()=>{if(!qt)return;const y=z=>{z.target instanceof Element&&(z.target.closest(".account-popover, .rail-account")||un(!1))},N=z=>{z.key==="Escape"&&un(!1)};return window.addEventListener("pointerdown",y),window.addEventListener("keydown",N),()=>{window.removeEventListener("pointerdown",y),window.removeEventListener("keydown",N)}},[qt]);const wn=u.useCallback(async(y={})=>{const N=y.silent===!0,z=y.takeover===!0,B=y.requestLocalAccess===!0;if(!n?.user){N||X("Sign in before publishing this host.","error");return}if(!yi.current){yi.current=!0,N||(ke("host"),De("Hub · 1/4 · Checking the local runtime…"));try{const ue=(B?await dl():"")||M||kn;if(!(b||await We("/api/remote/status",void 0,ue)).started)throw new Error("Start LiveDesk on this computer before syncing the server.");N||De("Hub · 2/4 · Sending the signed-in session to the Hub…");const Ie=await We("/api/auth/session",{method:"POST",body:JSON.stringify({accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:n.expires_at,user:{id:n.user.id,email:n.user.email}})},ue);if(!Ie.ok||!Ie.authenticated)throw new Error(Ie.error||"hub-session-sync-failed");N||De("Hub · 3/4 · Claiming the Hub role and publishing its endpoint…");const qe=await We("/api/hub/sync",{method:"POST",body:JSON.stringify({takeover:z})},ue);if(!qe.ok)throw new Error(qe.error||"host-target-failed");if(!N){De("Hub · 4/4 · Verifying the endpoint and lease renewal…");const Ve=await We("/api/hub/status",void 0,ue);if(!Ve.hostTargetActive)throw new Error(Ve.hostTargetLease?.lastError||"host-target-not-active-after-sync");const At=Ve.hostTargetEndpoint||Ve.agentEndpoint||"endpoint ready",yt=Number(Ve.connectedDeviceCount||0),Yn=yt>0?`${yt} client${yt===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";X(`Hub ready · ${At} · lease auto-renewal active. ${Yn}`,"success"),(B||w)&&(g(!0),wo(!0)),k()}c()}catch(D){if(!N){const ue=D instanceof Error?D.message:String(D);ue.includes("local network access")&&(g(!1),wo(!1)),X(`Hub setup failed · ${ue}`,"error")}}finally{yi.current=!1,N||ke("")}}},[M,w,k,c,dl,n,X,De,b]),_t=u.useCallback((y=!0)=>{ve!=="host"&&(Xe(!1),y&&window.requestAnimationFrame(()=>ae.current?.focus()))},[ve]),xt=u.useCallback(()=>{ve!=="host"&&(ae.current=document.activeElement instanceof HTMLElement?document.activeElement:null,un(!1),Xe(!0))},[ve]),Xs=u.useCallback(()=>{Xe(!1),wn({takeover:!0,requestLocalAccess:!0})},[wn]);u.useEffect(()=>{if(!$e)return;const y=window.requestAnimationFrame(()=>ye.current?.focus()),N=B=>{B.target instanceof Element&&B.target.closest(".client-hub-switch-popover, .hub-sync-trigger")||_t(!1)},z=B=>{B.key==="Escape"&&_t()};return window.addEventListener("pointerdown",N),window.addEventListener("keydown",z),()=>{window.cancelAnimationFrame(y),window.removeEventListener("pointerdown",N),window.removeEventListener("keydown",z)}},[_t,$e]);const Ma=u.useCallback(async()=>{if(!(!b?.update?.canApply||ve==="update")){ke("update");try{const y=await We("/api/update/apply",{method:"POST",body:JSON.stringify({})},M||kn);if(!y.ok)throw new Error(y.error||"LiveDesk update could not be started.");const N=[...new Set((y.targets||[]).map(D=>String(D.deviceId||"").trim()).filter(Boolean))],z=!!(y.managerUpdateAvailable||y.clientPackageUpdateAvailable),B=y.state==="hub-restart-requested"?Date.now():void 0;(N.length>0||z)&&lt({operationId:String(y.operationId||`wall-update-${Date.now()}`),targetIds:N,stage:y.state==="clients-updated"?"updated":"updating",requiresHubRestart:z,initialHostInstanceId:String(b.hostInstanceId||""),targetManagerVersion:String(y.latestVersion||b.update?.latestVersion||""),targetClientVersion:String(y.latestClientVersion||b.update?.latestClientVersion||""),restartRequestedAt:B,restartDeadlineAt:B?B+_d:void 0}),De(y.state==="hub-restart-requested"?Ld:Mx),k()}catch(y){X(y instanceof Error?y.message:String(y),"error")}finally{ke("")}}},[ve,M,k,X,De,b]);u.useEffect(()=>{const y=Le,N=b?.update;if(!y||y.stage!=="updating"||!N)return;const z=N.restartResult?.operationId===y.operationId?N.restartResult:null;if(z?.outcome==="restored"){const qe=z.error||`The requested Hub ${z.targetVersion||y.targetManagerVersion||"version"} failed verification.`;lt(Ve=>Ve?.operationId===y.operationId?{...Ve,stage:"restored",error:qe}:Ve),X(`LiveDesk update did not complete. Hub ${z.fallbackVersion||z.appVersion||"the previous version"} was restored. ${qe}`,"error");return}if(z?.outcome==="failed"){const qe=z.error||"No verified LiveDesk Hub replacement could be started.";lt(Ve=>Ve?.operationId===y.operationId?{...Ve,stage:"failed",error:qe}:Ve),X(`LiveDesk Hub update failed. ${qe}`,"error");return}if(N.operationId===y.operationId&&N.state==="failed"){const qe=N.error||"LiveDesk update failed before the Hub replacement completed.";lt(Ve=>Ve?.operationId===y.operationId?{...Ve,stage:"failed",error:qe}:Ve),X(qe,"error");return}if(N.operationId===y.operationId){if(N.state==="hub-restart-requested"&&!y.restartDeadlineAt){const qe=Date.now();lt(Ve=>Ve?.operationId===y.operationId?{...Ve,restartRequestedAt:qe,restartDeadlineAt:qe+_d}:Ve),De(Ld)}!y.requiresHubRestart&&N.state==="clients-updated"&&(lt(qe=>qe?.operationId===y.operationId?{...qe,stage:"updated"}:qe),X("LiveDesk clients updated and reconnected successfully.","success"));return}if(!y.requiresHubRestart)return;const B=b.started===!0&&(!y.initialHostInstanceId||b.hostInstanceId&&b.hostInstanceId!==y.initialHostInstanceId),D=!!N.checkedAt,ue=Tx(N.currentVersion,y.targetManagerVersion),de=!y.targetClientVersion||Tx(N.currentClientVersion,y.targetClientVersion),Ie=D&&N.state==="idle"&&N.updateAvailable===!1&&ue&&de;B&&Ie&&(lt(qe=>qe?.operationId===y.operationId?{...qe,stage:"updated"}:qe),X(`LiveDesk Hub ${N.currentVersion||z?.appVersion||y.targetManagerVersion} restarted and passed version verification.`,"success"))},[X,De,b,Le]),u.useEffect(()=>{const y=Le;if(!y||y.stage!=="updating"||!y.requiresHubRestart||y.restartDeadlineAt)return;const N=()=>{const B=Date.now();lt(D=>D?.operationId===y.operationId&&D.stage==="updating"&&!D.restartDeadlineAt?{...D,restartRequestedAt:B,restartDeadlineAt:B+_d}:D),De(Ld)};if(b?.update?.state==="hub-restart-requested"){N();return}if(!C)return;const z=window.setTimeout(N,qM);return()=>window.clearTimeout(z)},[C,De,b?.update?.state,Le]),u.useEffect(()=>{const y=Le;if(!y||y.stage!=="updating"||!y.requiresHubRestart||!y.restartDeadlineAt)return;const N=Math.max(0,y.restartDeadlineAt-Date.now()),z=y.operationId,B=window.setTimeout(()=>{const D=`LiveDesk Hub did not return and verify ${y.targetManagerVersion||"the requested version"} within ${Math.round(_d/6e4)} minutes. Check the Hub terminal or restart log, then run livedesk@latest manually if the Hub is still offline.`;lt(ue=>ue?.operationId===z&&ue.stage==="updating"?{...ue,stage:"failed",error:D}:ue),X(D,"error")},N);return()=>window.clearTimeout(B)},[X,Le]),u.useEffect(()=>{if(!Le||Le.stage!=="updated")return;const y=Le.operationId,N=window.setTimeout(()=>{lt(z=>z?.operationId===y?null:z)},8e3);return()=>window.clearTimeout(N)},[Le]),u.useEffect(()=>{if(Je!==Mx&&Je!==Ld)return;const y=b?.update;if(String(y?.state||"")==="failed"){X(y?.error||"LiveDesk update failed.","error");return}Le?.stage==="updated"&&X("")},[Je,X,b?.update?.error,b?.update?.state,Le?.stage]);const Jo=u.useCallback(async()=>{if(!ve){ke("pin");try{const N=await We("/api/remote/pairing-pin",{method:"POST"},M||kn);if(!N.ok)throw new Error(N.error||"pin-rotation-failed");await k(),X("New PIN published.")}catch(y){X(y instanceof Error?y.message:String(y))}finally{ke("")}}},[ve,M,k]),hs=u.useCallback(y=>{y&&(ne(y),_(N=>N.includes(y)?N:[...N,y]))},[]),Wl=u.useCallback(y=>{if(!y)return;const N=Bs.has(y);ne(z=>N?z===y?"":z:y),_(z=>N?z.filter(B=>B!==y):z.includes(y)?z:[...z,y])},[Bs]),Sr=u.useCallback(()=>{_([]),ne("")},[Gn]),_i=u.useCallback(()=>{_(it.map(y=>y.deviceId)),ne("")},[it]),As=u.useCallback((y,N)=>{const z=it.find(D=>D.deviceId===y);if(!z)return;const B=ba(z);B<=1||(H(D=>{const de=(Oa(D[y],B)+N+B)%B;return{...D,[y]:de}}),ot&&(Jn(!1),J(y)))},[it,ot]);u.useEffect(()=>{const y=N=>{if(ot&&Se&&us)return;const z=N.target,B=z?.tagName?.toLowerCase();z?.isContentEditable||B==="input"||B==="textarea"||B==="select"||((N.ctrlKey||N.metaKey)&&N.key.toLowerCase()==="a"&&(N.preventDefault(),_i()),N.key==="Escape"&&Sr())};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[us,Sr,Se,_i,ot]);const ec=(y,N)=>{const z=it.find(D=>D.deviceId===y),B=Oa(N,z?ba(z):1);H(D=>({...D,[y]:B})),ot?(Jn(!1),J(y)):hs(y)},Ns=async y=>{if(Jn(!1),J(y),Ae("control"),!Si.has(y)){Be(!1),X(al);return}const N=it.find(B=>B.deviceId===y);if(er(N?.platform)&&(N?.capabilities?.controlPermission===!1||N?.capabilities?.accessibilityPermission===!1)){Be(!1),X("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts LiveDesk, then restart the Mac client.","error");return}Be(!0),X(`Opening remote control${N?` for ${Ja(N)}`:""}.`,"success")},tc=async()=>{if(!_e){X("Select a workstation before playing audio.");return}if(!en){X(al);return}if(!wi){X("Selected workstation does not report remote audio support yet.");return}if(Ne)return;const y=!Oe,N=y?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:Ke.current.get(_e.deviceId);y&&N?Ke.current.set(_e.deviceId,N):y||Ke.current.delete(_e.deviceId),He("audio"),ge(y);try{await We(`/api/remote/devices/${encodeURIComponent(_e.deviceId)}/audio/${y?"start":"stop"}`,{method:"POST",body:JSON.stringify({...N?{streamId:N}:{},mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},M),X(`${y?"Audio started":"Audio stopped"} for ${Ja(_e)}.`,"success")}catch(z){y&&Ke.current.delete(_e.deviceId),ge(!1),X(z instanceof Error?z.message:String(z),"error")}finally{He("")}},zi=y=>{const N=y instanceof Error?y.message:String(y);return/remote-actions-disabled|allowAgent-blocked-by-settings/i.test(N)?"Remote actions are off. Turn on Settings > Agent > Enable AI Agent first.":/power-actions-disabled/i.test(N)?"Power actions are off. Turn on Settings > Agent > Allow power actions first.":/agent-tool-capability-unavailable|unsupported-agent-operation/i.test(N)?"This workstation needs a newer LiveDesk Client for power actions.":/device-not-connected|404 device-not-found/i.test(N)?"The workstation disconnected before the action could be sent.":N},Ta=async y=>{if(!_e||Ne)return;const N=_e,B={lock:"Lock",sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[y];if(!(y!=="lock"&&!window.confirm(`${B} ${Ja(N)}? Unsaved work on that computer may be lost.`))){He(y),X(`Sending ${B.toLowerCase()} request to ${Ja(N)}...`);try{const D=await We(`/api/remote/devices/${encodeURIComponent(N.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:y})},M);if(!D.ok)throw new Error(D.error||"The remote action could not be sent.");X(`${B} request sent to ${Ja(N)}.`,"success"),k()}catch(D){X(zi(D),"error")}finally{He("")}}},Zs=()=>{_e&&(Pe({id:Date.now(),deviceId:_e.deviceId,instruction:"Run command "}),Be(!1),Ae("agents"),X(`Command runner opened for ${Ja(_e)}.`))},ps=async(y,N,z="files")=>{const B=y.filter(Ie=>Ie.file.size>=0);if(B.length===0)return{files:0,bytes:0};if(!en)throw new Error(al);if(N.length===0)throw new Error("Select at least one connected workstation.");const D=crypto.randomUUID(),ue=B.reduce((Ie,qe)=>Ie+qe.file.size,0);let de=0;pa({id:D,status:"reading",progress:1,message:`Preparing ${B.length} ${z}`});try{for(let Ie=0;Ie<B.length;Ie+=1){const qe=B[Ie],Ve=qe.file,At=Math.max(1,Math.ceil(Ve.size/hh));for(let yt=0;yt<At;yt+=1){const Yn=yt*hh,Ea=Math.min(Ve.size,Yn+hh),rt=Ve.size===0?new ArrayBuffer(0):await Ve.slice(Yn,Ea).arrayBuffer(),Tt=yt===At-1;pa({id:D,status:"sending",progress:Math.max(2,Math.min(98,Math.round(de/Math.max(1,ue)*96))),message:`${Ie+1}/${B.length} ${qe.relativePath}`});const tn=await We("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:D,deviceIds:N,remoteDirectory:Zn.trim(),name:Ve.name,relativePath:qe.relativePath,size:Ve.size,type:Ve.type,lastModified:Ve.lastModified,offset:Yn,totalBytes:Ve.size,final:Tt,dataBase64:ST(rt)})},M);if(!tn.ok||tn.queued!==N.length)throw new Error(tn.error||`file-chunk-not-queued-${tn.queued}/${N.length}`);de+=rt.byteLength,await new Promise(ao=>window.setTimeout(ao,0))}}return pa({id:D,status:"queued",progress:100,message:`Sent ${B.length} file${B.length===1?"":"s"} to ${N.length} workstation${N.length===1?"":"s"}`}),window.setTimeout(()=>{pa(Ie=>Ie?.id===D&&Ie.status==="queued"?null:Ie)},4500),{files:B.length,bytes:ue}}catch(Ie){throw pa({id:D,status:"failed",progress:100,message:Ie instanceof Error?Ie.message:String(Ie)}),Ie}},Yl=async y=>{const N=va.length>0?va.map(z=>z.deviceId):_e?[_e.deviceId]:[];try{await ps(Fx(y),N)}catch(z){X(z instanceof Error?z.message:String(z))}},Kl=async y=>{try{await ps(Fx(y),bf)}catch(N){X(N instanceof Error?N.message:String(N))}};u.useEffect(()=>{Pl.current=!1},[]);const Cr=y=>{y.preventDefault(),y.stopPropagation(),Xr(!1),Yl(y.dataTransfer.files)},Ii=async(y="ltd")=>{if(!n){X("Sign in with Google before checkout.");return}if(T&&y===Wt){X("LiveDesk license is already active.");return}if(T&&Wt==="pro"){X("LiveDesk Pro is already active.");return}ke("checkout");try{const{data:N,error:z}=await ft.functions.invoke("dodo-checkout",{body:{plan:y}});if(z)throw z;if(!N?.checkout_url)throw new Error("Checkout function did not return a checkout URL.");window.location.assign(N.checkout_url)}catch(N){X(N instanceof Error?N.message:String(N)),ke("")}},la=sT(),gn=iT(),Ql=it.length,Xl=Cf.filter(y=>Gl.has(y)).length,nc=Vn==="open"&&ol.sampleMs>0?`${ol.framesPerSecond.toFixed(1)} fps`:Vn,Ee=_e?ot?br.get(_e.deviceId):Gl.get(_e.deviceId):void 0,Zl=_e?Oa(Jt[_e.deviceId],ba(_e)):0,fn=_e?cT(_e):[],ac=typeof Ee?.monitorIndex=="number"?Oa(Ee.monitorIndex,Math.max(1,Ee.monitorCount||1)):Zl,Oi=(Ee&&ac===Zl?Sw(Ee):null)||(_e?ww(_e,Zl):null);Oi&&`${Oi.width}${Oi.height}`;const jr=_e?xs(ot?"control":"wall",_e.deviceId):"",on=jr?Lo[jr]:void 0,Nn=jr?$a[jr]:void 0,bt=Nn?.lastInfo,Su=on&&on.sampleMs>0?`${on.framesPerSecond.toFixed(1)} fps`:"waiting";on&&`${on.totalFrames}${Su}`,Nn&&Nn.sampleMs>0&&`${Nn.framesPerSecond.toFixed(1)}`,Nn&&Nn.sampleMs>0&&`${Nn.changedFramesPerSecond.toFixed(1)}`,bt&&(`${bt.frameSeq}${bt.decoderLabel}${bt.queueSize}${bt.renderQueueSize}${bt.droppedForLatency}${bt.decoderFlushCount}${bt.decoderTimestampFallbacks}${bt.decoderInputCount}${bt.decoderOutputCount}`,bt.visualChanged),bt&&`${Math.round(bt.queuedForMs)}${Math.round(bt.decodedForMs)}${Math.round(bt.scheduledForMs)}${bt.drawMs.toFixed(1)}`,bt?.targetPaintIntervalMs&&`${bt.targetPaintIntervalMs.toFixed(1)}${(1e3/bt.targetPaintIntervalMs).toFixed(1)}`,Nn&&`${Nn.decoderInputFps.toFixed(1)}${Nn.decoderOutputFps.toFixed(1)}`,bt?.canvasPresentation,bt&&`${bt.interactiveBufferWaitCount}${Math.round(bt.interactiveBufferWaitMs)}${bt.interactiveQueueDrainCount}`,on&&(Ee?.frameMode==="mode5-lzo-delta"?`${Uc(on.averageFrameBytes)}${Ee.deltaVisualTileCount||0}${Ee.deltaRefreshTileCount||0}${Ee.deltaTotalTiles||0}`:`${Uc(on.averageFrameBytes)}${Math.round(on.tinyFrameRatio*100)}${Math.round(on.repeatedFrameRatio*100)}`),on&&on.sourceSendSampleCount>0&&`${on.sourceSendAverageMs.toFixed(1)}${on.sourceSendP95Ms.toFixed(1)}`,Dx(on),Dx(Nn),on&&Nn&&`${Lx(on)}${Lx(Nn)}`,Ee?Ee.frameMode||Ee.mode||Ee.codec||Ee.mimeType:ot?vt.frameMode:Fe.frameMode,ot?vt.frameMode:Fe.frameMode,Ee?`${Ee.width}${Ee.height}${Uc(Ee.byteLength)}`:ot?`${Hs.maxWidth}${Hs.maxHeight}`:`${Fe.maxWidth}${Fe.maxHeight}`,Ee&&`${Ee.isKeyFrame?"key":String(Ee.chunkType||"delta")}`,Ee&&Ee.monitorCount&&((Ee.monitorIndex??0)+1,`${Ee.monitorCount}`),Ee&&[`src ${Math.round(Ee.sourceGapMs||0)}ms`,`gap ${Math.round(Ee.agentSendGapMs||0)}ms`,`tx ${Math.round(Ee.agentSendDurationMs||0)}ms`,`pace ${Math.round(Ee.agentPaceMs||0)}ms`,`queue ${Math.round(Ee.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(Ee.agentFrameAgeMs||0)}ms`,Ee.browserReceivedEpochMs&&Ee.receivedAt?`hub ${Math.max(0,Math.round(Ee.browserReceivedEpochMs-Date.parse(Ee.receivedAt)))}ms`:"",Ee.browserReceivedEpochMs&&Ee.hubPacketEpochMs?`sock ${Math.max(0,Math.round(Ee.browserReceivedEpochMs-Ee.hubPacketEpochMs))}ms`:"",Ee.droppedByAgent?`drop ${Ee.droppedByAgent}`:"",Ee.hubIngressDropped?`ingress-drop ${Ee.hubIngressDropped}`:"",Ee.hubClientDropped?`ws-drop ${Ee.hubClientDropped}`:"",Ee.captureStageMs?`capture ${Math.round(Ee.captureStageMs)}ms`:"",Ee.requestedFps?`req ${Math.round(Ee.requestedFps)}fps`:"",Ee.effectiveFps?`eff ${Math.round(Ee.effectiveFps)}fps`:"",Ee.captureAverageMs?`avg ${Math.round(Ee.captureAverageMs)}ms`:"",Ee.captureP95Ms?`p95 ${Math.round(Ee.captureP95Ms)}ms`:"",Ee.slowFrameCount?`slow ${Math.round(Ee.slowFrameCount)}`:"",Ee.captureHelperRestarts?`helper ${Math.round(Ee.captureHelperRestarts)}`:"",Ee.convertMs?`rgb565 ${Math.round(Ee.convertMs)}ms`:"",Ee.compressMs?`lzo ${Math.round(Ee.compressMs)}ms`:"",Ee.captureSourceSerial?`cap #${Ee.captureSourceSerial}`:"",Ee.captureSourceSkipped?`cap skip ${Ee.captureSourceSkipped}`:"",Ee.frameMode==="mode5-lzo-delta"?`tiles ${Ee.deltaVisualTileCount||0}+${Ee.deltaRefreshTileCount||0}/${Ee.deltaTotalTiles||0}@${Ee.deltaTileSize||0}`:"",Ee.platformProfile||Ee.hardwareEncoder||"-",Ee.atlasComposeMs?`atlas ${Ee.atlasComposeMs.toFixed(1)}ms`:"",Ee.atlasPoolStarved?`pool ${Ee.atlasPoolStarved}`:"",Ee.atlasTileCount?`tiles ${Ee.atlasReadyTiles||0}/${Ee.atlasTileCount}`:"",Ee.atlasInputRevision?`input #${Ee.atlasInputRevision}`:"",Ee.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(Ee.atlasSourceMaxAgeMs)}ms`:"",bt?.inputFeedbackMs!==void 0&&bt.inputFeedbackAt!==void 0&&performance.now()-bt.inputFeedbackAt<=Ax?`feedback ${Math.round(bt.inputFeedbackMs)}ms`:"",Ee.contentHash?`enc ${Ee.contentHash.slice(0,6)}`:"",bt?.visualHash?`pix ${bt.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "),Ks==="open"&&[`${ya.sentPerSecond.toFixed(1)} hz`,ya.lastInputSeq>0?`rtt ${Math.round(ya.lastRoundTripMs)}ms`:"",ya.lastInputSeq>0?`apply ${ya.lastAgentApplyMs.toFixed(1)}ms`:"",ya.droppedPerSecond>0?`drop ${ya.droppedPerSecond.toFixed(1)}/s`:"",ya.bufferedAmount>0?`buf ${Uc(ya.bufferedAmount)}`:"",ya.lastInputType||"ready"].filter(Boolean).join(" / "),bt?.inputFeedbackMs!==void 0&&bt.inputFeedbackAt!==void 0&&performance.now()-bt.inputFeedbackAt<=Ax&&`${Math.round(bt.inputFeedbackMs)}${bt.inputFeedbackSeq||0}`,Oe&&[Qs,`context ${Xt.audioContextState}`,`queue ${Math.round(Xt.queuedMs)}ms`,`last ${Math.round(Xt.lastPacketAgeMs)}ms`,`accepted ${Math.round(Xt.lastAcceptedAgeMs)}ms`,`process ${Math.round(Xt.localProcessingAgeMs)}ms`,`remote ${Math.round(Xt.browserAgeMs)}/${Math.round(Xt.captureAgeMs)}ms`,`heartbeat ${Math.round(Xt.captureStatusAgeMs)}ms`,`capture ${Xt.captureAlive&&Xt.helperAlive?"alive":"down"}`,`drop ${Xt.drops}`,`resync ${Xt.resyncs}`,`restart ${Xt.automaticRestarts}`,Xt.pendingDecodes>0?`decode ${Xt.pendingDecodes}`:"",Ya?`#${Ya.frameSeq}`:"waiting"].filter(Boolean).join(" / "),Ee&&`${Ee.frameSeq}${ab(Ee.receivedAt||Ee.capturedAt)}`;const kr=Math.max(0,ol.bytesPerSecond*8/1e6),sc=ks?.atlasReadyTiles??Xl,Ms=ks?.atlasTileCount??Xl,ic=sc===Ms?`${Ms} tiles`:`${sc}/${Ms} tiles`,eo=sa.length>0;ot?`${nc}${kr.toFixed(kr>=10?0:1)}`:eo?`${ic}${nc}${kr.toFixed(kr>=10?0:1)}`:`${Xl}${nc}${kr.toFixed(kr>=10?0:1)}`;const rc=C?"offline":b?.started?"online":"starting",Js=va.length,lc=ot?_e?Ja(_e):"No workstation":Js===0?"No workstation":Js>1?`${Js} selected`:_e?Ja(_e):"No workstation",to=ot?[_e?.deviceId].filter(y=>!!y):va.map(y=>y.deviceId),Mn=To[Re]||To.en,fl=Mn.sync||To.en.sync,oc=a||R?"checking":T?Wt==="pro"?"Pro LTD active":`Plus LTD ${it.length}/${$c}`:Sf?`Free ${it.length}/${Pc}`:`Upgrade ${it.length}/${Pc}`,Hi=Wt==="pro"?"Pro active":ve==="checkout"?"Opening":Wt==="ltd"?"Pro $199":"Plus $79",Cu=T?Wt==="pro"?"Pro active":"Upgrade to Pro LTD":n?ve==="checkout"?"Opening checkout":Wt==="ltd"?"Buy Pro LTD":"Buy Plus LTD":ve==="auth"?"Opening Google":"Sign in to buy",ju=Wt==="pro"||ve==="checkout"||ve==="auth"||a||R,Bi=n?.user?.user_metadata,ei=Px(Bi,"avatar_url","picture"),ti=Px(Bi,"full_name","name")||n?.user?.email||"Google",Nr=ti.slice(0,1).toUpperCase(),no=b?.started?"Local app ready":"Start LiveDesk",ku=r?.active?"Published":n?"Not published":"Sign in required",Fi=/^\d{6}$/.test(b?.pairingPin||"")?b?.pairingPin:"------",Au=qd.find(y=>y.width===Fe.maxWidth&&y.height===Fe.maxHeight)?.id||`${Fe.maxWidth}x${Fe.maxHeight}`,ni=Fe.atlasTileSizeMode==="auto"?"auto":xh.find(y=>y.width===Fe.atlasTileWidth&&y.height===Fe.atlasTileHeight)?.id||"320x180",cc=yh.find(y=>y.width===vt.maxWidth&&y.height===vt.maxHeight)?.id||`${vt.maxWidth}x${vt.maxHeight}`,uc=Ud.find(y=>y.id===Fe.frameMode)||Ud[0],Sn=y=>{zs(N=>{const z=y.frameMode?Yh(y.frameMode):N.frameMode,B=y.frameMode!==void 0&&z!==N.frameMode;return{...N,...y,frameMode:z,fps:Qh(y.fps??(B?yw(z):N.fps),z)}})},ai=y=>{const N=qd.find(z=>z.id===y);N&&Sn({maxWidth:N.width,maxHeight:N.height})},ml=y=>{if(y==="auto"){Sn({atlasTileSizeMode:"auto"});return}const N=xh.find(z=>z.id===y);!N?.width||!N?.height||Sn({atlasTileSizeMode:"fixed",atlasTileWidth:N.width,atlasTileHeight:N.height})},si=y=>{y.frameMode!==void 0&&(ee(""),fe("")),hi(N=>{const z=y.frameMode?Kh(y.frameMode):N.frameMode,B=y.frameMode!==void 0&&z!==N.frameMode,D=y.fps??(B?30:N.fps),ue=y.maxWidth??N.maxWidth,de=y.maxHeight??N.maxHeight;return{...N,...y,frameMode:z,fps:bs(D,20,z==="mode3-h264-hw"?60:30,z==="mode3-h264-hw"?60:30),maxWidth:z==="mode3-h264-hw"?ue:Math.min(1920,ue),maxHeight:z==="mode3-h264-hw"?de:Math.min(1080,de)}})},dc=y=>{const N=yh.find(z=>z.id===y);N&&si({maxWidth:N.width,maxHeight:N.height})},Pi=y=>{if(typeof window<"u"&&(y==="support"?window.history.pushState({},"","/support"):ze==="support"&&window.history.pushState({},"","/")),y==="control"){const N=Un||dr;if(N&&(Jn(!1),J(N.deviceId)),Ae(y),!en){Be(!1),X(al);return}Be(!0);return}y==="agents"&&Pe(null),y==="wall"&&Gt(N=>N+1),Ae(y),Be(!1)},gs=ve==="update"||Le?.stage==="updating"||["dispatching","waiting-for-clients","hub-restart-requested"].includes(b?.update?.state||""),Nu=!!(b?.update?.updateAvailable&&b.update.canApply||gs||!b&&Le),ii=mC(Re),ri=u.useCallback(y=>{if(!Le?.targetIds.includes(y))return;if(Le.stage==="updated")return{state:"updated",label:"Updated"};if(Le.stage==="restored"||Le.stage==="failed")return{state:"failed",label:Le.stage==="restored"?"Update restored":"Update failed",error:Le.error};const N=b?.update?.operationId===Le.operationId?b.update.targets?.find(z=>z.deviceId===y):void 0;switch(N?.state){case"completed":return{state:"updated",label:"Updated"};case"failed":return{state:"failed",label:"Update failed",error:N.error||b?.update?.error};case"pending-offline":return{state:"offline",label:"Waiting for reconnect"};case"queued":return{state:"queued",label:"Queued"};case"waiting":return N.candidateSince?{state:"updating",label:"Verifying restart..."}:{state:"updating",label:"Restarting..."};default:return{state:"updating",label:"Verifying..."}}},[b?.update,Le]);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(sb,{size:25})}),s.jsx("nav",{className:"rail-tools",children:TT.map(y=>{const N=y.icon,z=Wd(y.tooltip,Re);return s.jsxs("button",{className:`rail-tool ${y.id==="sync-server"?"sync-server hub-sync-trigger":""} ${ze===y.id?"active":""} accent-${y.accent}`,onClick:()=>y.id==="sync-server"?xt():Pi(y.id),"data-tooltip":y.id==="sync-server"&&$e?void 0:Eh(y.label,y.tooltip,Re),"aria-label":`${y.label}. ${z}`,type:"button",disabled:y.id==="sync-server"&&ve==="host","aria-busy":y.id==="sync-server"&&ve==="host","aria-expanded":y.id==="sync-server"?$e:void 0,"aria-haspopup":y.id==="sync-server"?"dialog":void 0,"aria-controls":y.id==="sync-server"&&$e?"hub-sync-popover":void 0,children:[y.id==="sync-server"&&ve==="host"?s.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):s.jsx(N,{size:19}),s.jsx("span",{children:y.id==="sync-server"&&ve==="host"?"Syncing…":y.label})]},y.id)})}),s.jsxs("div",{className:"rail-footer",children:[ET.map(y=>{const N=y.icon;return s.jsxs("button",{className:`rail-tool compact ${ze===y.id?"active":""} accent-${y.accent}`,onClick:()=>Pi(y.id),title:y.label,type:"button",children:[s.jsx(N,{size:18}),s.jsx("span",{children:y.label})]},y.id)}),s.jsxs("button",{className:`rail-tool compact local-settings ${Os?"active":""}`,onClick:()=>{Ae("settings"),typeof window<"u"&&window.history.pushState({},"","/"),un(!1),Be(!1),at(!1)},title:"Settings",type:"button",children:[s.jsx(Zh,{size:18}),s.jsx("span",{children:"Settings"})]}),s.jsxs("button",{className:`rail-account ${n?"signed-in":""}`,onClick:()=>{un(y=>!y)},disabled:a||ve==="auth","aria-expanded":qt,title:n?`Account: ${n.user?.email||ti}`:"Sign in with Google",type:"button",children:[n?ei?s.jsx("img",{src:ei,alt:ti,referrerPolicy:"no-referrer"}):s.jsx("span",{className:"avatar-fallback",children:Nr}):s.jsx(Tl,{size:18}),s.jsx("span",{children:n?"Account":"Google"})]}),qt&&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:n&&ei?s.jsx("img",{src:ei,alt:ti,referrerPolicy:"no-referrer"}):n?s.jsx("span",{children:Nr}):s.jsx(Tl,{size:18})}),s.jsxs("div",{children:[s.jsx("strong",{children:n?ti:"Account"}),s.jsx("p",{children:n?.user?.email||"Not signed in"})]})]}),s.jsxs("dl",{className:"account-popover-facts",children:[s.jsx("dt",{children:"User"}),s.jsx("dd",{children:n?.user?.email||"Not signed in"}),s.jsx("dt",{children:"Network"}),s.jsx("dd",{children:no}),s.jsx("dt",{children:"Access"}),s.jsx("dd",{children:ku}),s.jsx("dt",{children:"Plan"}),s.jsx("dd",{children:oc}),s.jsx("dt",{children:"Ads"}),s.jsx("dd",{children:Wt==="free"?"Standard banner":"Removed"})]}),n?s.jsxs("button",{className:"account-popover-action",onClick:wu,disabled:ve==="auth",type:"button",children:[s.jsx(Vx,{size:16}),"Logout"]}):s.jsxs("button",{className:"account-popover-action primary",onClick:Li,disabled:ve==="auth",type:"button",children:[s.jsx(Tl,{size:16}),"Sign in with Google"]})]})]})]}),$e&&s.jsxs("section",{id:"hub-sync-popover",className:"client-hub-switch-popover hub-sync-popover",role:"dialog","aria-modal":"false","aria-labelledby":"hub-sync-title","aria-describedby":"hub-sync-description hub-sync-notice",children:[s.jsxs("header",{className:"client-hub-switch-head",children:[s.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:s.jsx(Vr,{size:19})}),s.jsx("span",{className:"client-hub-switch-eyebrow",children:ii.eyebrow}),s.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>_t(),"aria-label":ii.closeLabel,children:s.jsx(Sa,{size:17})})]}),s.jsx("h2",{id:"hub-sync-title",children:ii.title}),s.jsx("p",{id:"hub-sync-description",children:ii.description}),s.jsxs("p",{id:"hub-sync-notice",className:"client-hub-switch-notice",children:[s.jsx(Ht,{size:16,"aria-hidden":"true"}),s.jsx("span",{children:ii.restartNotice})]}),s.jsxs("div",{className:"client-hub-switch-actions",children:[s.jsx("button",{type:"button",onClick:()=>_t(),children:ii.cancel}),s.jsxs("button",{ref:ye,className:"primary",type:"button",onClick:Xs,disabled:ve==="host",children:[s.jsx(Vr,{size:16}),ii.confirm]})]})]}),s.jsxs("section",{className:`desk-stage ${$l&&!$n?"dock-open":""} ${ot?"control-stage":""} ${$o?"agents-stage":""}`,children:[s.jsxs("header",{className:"topbar",children:[s.jsxs("div",{className:"brand",children:[s.jsx("span",{className:"brand-mark",children:s.jsx(bn,{size:18})}),s.jsxs("div",{className:"brand-copy",children:[s.jsx("h1",{children:"LiveDesk"}),s.jsx("p",{children:"Control wall for local machines"})]}),Nu?s.jsxs("button",{className:"topbar-update-button",onClick:()=>{Ma()},title:Le?.error||`Update LiveDesk to ${b?.update?.latestVersion||Le?.targetManagerVersion||"latest"}`,"aria-label":gs?"LiveDesk update in progress":`Update LiveDesk to ${b?.update?.latestVersion||Le?.targetManagerVersion||"latest"}`,type:"button",disabled:gs||!b?.update?.canApply,"aria-busy":gs,children:[gs?s.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):s.jsx(Xh,{size:19,"aria-hidden":"true"}),gs&&b?.update?.targetCount?s.jsxs("span",{className:"topbar-update-count","aria-hidden":"true",children:[b.update.completedCount||0,"/",b.update.targetCount]}):null]}):null]}),s.jsxs("div",{className:"topbar-tray",children:[tl&&!ot&&s.jsxs("div",{className:"file-share-top-route","aria-label":"File distribution route",children:[s.jsxs("div",{children:[s.jsx(Nl,{size:17}),s.jsxs("span",{children:[s.jsx("small",{children:"Source"}),s.jsx("strong",{children:"LiveDesk Hub"})]})]}),s.jsx(np,{size:15}),s.jsx(f0,{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:[cu," workstation",cu===1?"":"s"]}),s.jsx("em",{children:Zn.trim()||"Desktop/LiveDeskFiles"})]})]})]}),$l&&!ot&&s.jsxs("div",{className:"top-actions",children:[s.jsx(Sx,{controller:Yo,onError:X}),s.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),s.jsx("div",{className:"segmented-control","aria-label":"Wall view",children:MT.map(y=>s.jsx("button",{className:et===y.id?"active":"",onClick:()=>gt(y.id),type:"button",children:y.label},y.id))})]}),ot&&s.jsx("div",{className:"top-actions",children:s.jsx(Sx,{controller:Yo,onError:X})})]})]}),Po?s.jsxs("section",{className:"doc-page",lang:Re,dir:Re==="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(Gd,{size:16}),Mn.eyebrow]}),s.jsx("h2",{children:Mn.title}),s.jsx("p",{children:Mn.intro})]}),s.jsxs("label",{className:"doc-language-picker",children:[s.jsxs("span",{children:[s.jsx(m0,{size:17}),Mn.languageLabel]}),s.jsx("select",{value:Re,onChange:y=>fa(y.target.value),children:DT.map(y=>s.jsx("option",{value:y.id,children:y.label},y.id))})]})]}),s.jsx("section",{className:"doc-grid",children:Mn.sections.map((y,N)=>{const B=[Vr,Bd,Um,Ht,El][N]||Gd;return s.jsxs("article",{className:"doc-card",children:[s.jsx("div",{className:"doc-card-icon",children:s.jsx(B,{size:19})}),s.jsxs("div",{children:[s.jsx("h3",{children:y.title}),s.jsx("p",{children:y.body}),s.jsx("ul",{children:y.points.map(D=>s.jsx("li",{children:D},D))})]})]},y.title)})}),fl&&s.jsxs("section",{className:"doc-sync",children:[s.jsxs("div",{className:"doc-sync-head",children:[s.jsx(Um,{size:20}),s.jsxs("div",{children:[s.jsx("h3",{children:fl.title}),s.jsx("p",{children:fl.body})]})]}),s.jsx("ul",{children:fl.points.map(y=>s.jsx("li",{children:y},y))})]}),s.jsxs("section",{className:"doc-firewall",children:[s.jsxs("div",{className:"doc-firewall-head",children:[s.jsx(Ht,{size:20}),s.jsxs("div",{children:[s.jsx("h3",{children:Mn.firewall.title}),s.jsx("p",{children:Mn.firewall.body})]})]}),s.jsx("ul",{children:Mn.firewall.points.map(y=>s.jsx("li",{children:y},y))})]}),s.jsxs("section",{className:"doc-command-panel",children:[s.jsxs("div",{className:"doc-command-head",children:[s.jsx(Bd,{size:20}),s.jsxs("div",{children:[s.jsx("h3",{children:Mn.commands.title}),s.jsx("p",{children:Mn.commands.body})]})]}),s.jsxs("div",{className:"doc-command-list",children:[Mn.commands.manager&&s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:Mn.commands.manager}),s.jsx("code",{children:gn}),s.jsx("button",{className:"icon-button",onClick:()=>kl(gn),title:"Copy command",type:"button",children:s.jsx(yl,{size:16})})]}),s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:Mn.commands.primary}),s.jsx("code",{children:la}),s.jsx("button",{className:"icon-button",onClick:()=>kl(la),title:"Copy command",type:"button",children:s.jsx(yl,{size:16})})]}),s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:Mn.commands.slot}),s.jsx("code",{children:`${la} 3`}),s.jsx("button",{className:"icon-button",onClick:()=>kl(`${la} 3`),title:"Copy command",type:"button",children:s.jsx(yl,{size:16})})]})]})]})]}):$o?s.jsx(xx,{hubUrl:M,devices:j,launchRequest:Te}):tl?s.jsx(yN,{hubUrl:M,devices:it,localFeatureAccess:en,upgradeNotice:al,remoteDirectory:Zn,onRemoteDirectoryChange:nr,targetMode:ta,selectedTargetIds:ls,onTargetModeChange:Oo,onTargetToggle:y=>os(N=>N.includes(y)?N.filter(z=>z!==y):[...N,y]),filePickerRef:na,folderPickerRef:vi,onBrowserFileImport:y=>{Kl(y)},onBrowserFolderImport:y=>{Kl(y)},onNotice:X,onTransferChange:y=>{if(!y){pa(null);return}const N=y.state==="failed"||y.state==="partially-failed"||y.state==="cancelled"?"failed":y.state==="completed"?"queued":y.state==="sending"?"sending":"reading";pa({id:y.id,status:N,progress:y.progress,message:y.message}),["completed","partially-failed","failed","cancelled"].includes(y.state)&&window.setTimeout(()=>pa(z=>z?.id===y.id?null:z),4500)}}):ou?s.jsx(eb,{session:n,currentProductKey:"livedesk",appVersion:"",onSignIn:Li}):Os?s.jsx(zj,{hubUrl:M,runtimeRole:b?.runtimeRole||"hub",runtimeDeviceId:b?.deviceId||"",sessionAccessToken:n?.access_token||"",pin:s.jsxs(Ij,{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:Fi}),s.jsxs("button",{className:"text-button ghost compact",onClick:Jo,disabled:!b?.started||ve==="pin",type:"button",children:[s.jsx(Rs,{size:15}),ve==="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:rc})]}),s.jsx("span",{className:`settings-status-dot state-${rc}`})]}),s.jsxs("dl",{className:"settings-facts",children:[s.jsx("dt",{children:"Address"}),s.jsx("dd",{children:M||"-"}),s.jsx("dt",{children:"Connected workstations"}),s.jsxs("dd",{children:[Ql,"/",ur]}),s.jsx("dt",{children:"Sync access"}),s.jsx("dd",{children:b?.started?"Local app ready":"Start Hub first"}),s.jsx("dt",{children:"Plan"}),s.jsx("dd",{children:oc})]}),s.jsxs("div",{className:"settings-action-row",children:[s.jsxs("button",{className:"text-button primary",onClick:()=>wn({takeover:!0,requestLocalAccess:!0}),disabled:!n||ve==="host",type:"button",children:[ve==="host"?s.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):s.jsx(Um,{size:16}),ve==="host"?"Syncing…":"Sync access"]}),s.jsxs("button",{className:"text-button buy",onClick:()=>Ii(Wt==="ltd"?"pro":"ltd"),disabled:ve==="checkout"||Wt==="pro",type:"button",children:[s.jsx(jo,{size:16}),Hi]})]})]})]}),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(ko,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Remote folder"}),s.jsx("input",{value:Zn,onChange:y=>nr(y.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),s.jsx("p",{className:"settings-help",children:"Blank uses Desktop/LiveDeskFiles on each workstation."})]})]}),wall:s.jsx(Oj,{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(Zc,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Frame mode"}),s.jsx("select",{value:Fe.frameMode,onChange:y=>Sn({frameMode:Yh(y.target.value)}),children:Ud.map(y=>s.jsxs("option",{value:y.id,children:[y.label," - ",y.detail]},y.id))})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"H.264 decode"}),s.jsx("select",{value:Fe.h264DecodeAcceleration,onChange:y=>Sn({h264DecodeAcceleration:sf(y.target.value)}),children:Wh.map(y=>s.jsx("option",{value:y.id,children:y.label},y.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:Fe.fps,onChange:y=>Sn({fps:Qh(y.target.value,Fe.frameMode)}),children:Cp.filter(y=>y<=xw(Fe.frameMode)).map(y=>s.jsx("option",{value:y,children:y},y))})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:ht?"Atlas tile":"Resolution"}),s.jsx("select",{value:ht?ni:Au,onChange:y=>ht?ml(y.target.value):ai(y.target.value),children:(ht?xh:qd).map(y=>s.jsx("option",{value:y.id,children:y.label},y.id))})]})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Quality"}),s.jsx("select",{value:Fe.quality,onChange:y=>Sn({quality:bs(y.target.value,20,95,wa.quality)}),children:_x.map(y=>s.jsx("option",{value:y,children:y},y))})]})]}),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(bn,{size:20})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Fe.autoStartLive,onChange:y=>Sn({autoStartLive:y.target.checked})}),s.jsx("span",{children:"Auto live on connected screens"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Fe.visibleOnlyLive,onChange:y=>Sn({visibleOnlyLive:y.target.checked})}),s.jsx("span",{children:"Stream visible tiles first"})]}),!ht&&s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Fe.adaptiveSizeByWall,onChange:y=>Sn({adaptiveSizeByWall:y.target.checked})}),s.jsx("span",{children:"Fit stream size to Wall"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Fe.adaptiveLoadShedding,onChange:y=>Sn({adaptiveLoadShedding:y.target.checked})}),s.jsx("span",{children:"Reduce FPS under load"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Fe.showScreenStatus,onChange:y=>Sn({showScreenStatus:y.target.checked})}),s.jsx("span",{children:"Screen status overlay"})]}),s.jsxs("div",{className:"settings-summary",children:[s.jsx("span",{children:uc.label}),s.jsxs("strong",{children:[qn.maxWidth,"x",qn.maxHeight," / ",Dn,"fps"]})]}),s.jsxs("button",{className:"settings-reset",onClick:()=>zs(wa),type:"button",children:[s.jsx(Gc,{size:15})," Reset Wall settings"]})]})]})}),control:s.jsx(Hj,{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(Hd,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Frame mode"}),s.jsx("select",{value:vt.frameMode,onChange:y=>si({frameMode:Kh(y.target.value)}),children:WM.map(y=>s.jsx("option",{value:y.id,children:y.label},y.id))})]}),vt.frameMode==="mode3-h264-hw"&&s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"H.264 decode"}),s.jsx("select",{value:vt.h264DecodeAcceleration,onChange:y=>si({h264DecodeAcceleration:sf(y.target.value)}),children:Wh.map(y=>s.jsx("option",{value:y.id,children:y.label},y.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:vt.fps,onChange:y=>si({fps:bs(y.target.value,20,60,Ha.fps)}),children:YM.filter(y=>vt.frameMode==="mode3-h264-hw"||y<=30).map(y=>s.jsx("option",{value:y,children:y},y))})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Resolution"}),s.jsx("select",{value:cc,onChange:y=>dc(y.target.value),children:yh.filter(y=>vt.frameMode==="mode3-h264-hw"||y.width<=1920).map(y=>s.jsx("option",{value:y.id,children:y.label},y.id))})]})]}),vt.frameMode==="mode3-h264-hw"&&s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Quality"}),s.jsx("select",{value:vt.quality,onChange:y=>si({quality:bs(y.target.value,20,95,Ha.quality)}),children:_x.map(y=>s.jsx("option",{value:y,children:y},y))})]})]}),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:vt.showScreenStatus,onChange:y=>si({showScreenStatus:y.target.checked})}),s.jsx("span",{children:"Screen status overlay"})]}),s.jsxs("div",{className:"settings-summary control",children:[s.jsx("span",{children:vt.frameMode==="mode5-lzo-delta"?"Mode 5 tile delta":"Mode 3 H.264"}),s.jsxs("strong",{children:[Hs.maxWidth,"x",Hs.maxHeight," / ",cr,"fps"]})]}),s.jsxs("button",{className:"settings-reset",onClick:()=>hi(Ha),type:"button",children:[s.jsx(Gc,{size:15})," Reset Control settings"]})]})]})}),agent:s.jsx(Bj,{hubUrl:M}),captureGallery:s.jsx(xM,{hubUrl:M,onToast:X}),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(yl,{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:la}),s.jsx("button",{className:"icon-button",onClick:()=>kl(la),title:"Copy client command",type:"button",children:s.jsx(yl,{size:16})})]}),s.jsxs("div",{className:"settings-command-row",children:[s.jsx("span",{children:"Slot example"}),s.jsx("code",{children:`${la} 3`}),s.jsx("button",{className:"icon-button",onClick:()=>kl(`${la} 3`),title:"Copy slot command",type:"button",children:s.jsx(yl,{size:16})})]}),s.jsxs("div",{className:"settings-command-row",children:[s.jsx("span",{children:"Hub"}),s.jsx("code",{children:gn}),s.jsx("button",{className:"icon-button",onClick:()=>kl(gn),title:"Copy Hub command",type:"button",children:s.jsx(yl,{size:16})})]})]})]})}):el?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(Nh,{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:()=>Pi("wall"),title:"Close pricing",type:"button",children:s.jsx(Sa,{size:18})})]}),s.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[s.jsx("span",{children:"Current plan"}),s.jsx("strong",{children:Wo.name}),s.jsxs("small",{children:[it.length,"/",VM(nl)," connected devices"]})]}),s.jsxs("div",{className:"pricing-cards","aria-label":"LiveDesk plans",children:[s.jsxs("article",{className:`pricing-plan-card ${Wt==="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:Sl.free.audience}),s.jsx("h3",{children:"Monitor your local wall"}),s.jsx("p",{children:Sl.free.note}),s.jsxs("ul",{children:[s.jsxs("li",{children:[s.jsx(_n,{size:16})," Up to ",Pc," devices"]}),s.jsxs("li",{children:[s.jsx(_n,{size:16})," Live view and local control"]}),s.jsxs("li",{children:[s.jsx(_n,{size:16})," Standard ad-supported banner"]})]}),s.jsx("span",{className:"pricing-current-label",children:Wt==="free"?"Current plan":"Included for everyone"})]}),s.jsxs("article",{className:`pricing-plan-card featured ${Wt==="ltd"?"current":""}`,children:[s.jsxs("div",{className:"pricing-plan-topline",children:[s.jsxs("span",{className:"pricing-plan-badge plus",children:[s.jsx(h0,{size:14})," Plus"]}),s.jsx("strong",{children:"$5"})]}),s.jsx("p",{className:"pricing-plan-audience",children:Sl.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(_n,{size:16})," Up to ",$c," devices"]}),s.jsxs("li",{children:[s.jsx(_n,{size:16})," No standard ad banner"]}),s.jsxs("li",{children:[s.jsx(_n,{size:16})," ",Sl.ltd.ltd]})]}),s.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>Ii("ltd"):Li,disabled:Wt!=="free"||ve==="checkout"||ve==="auth"||a||R,type:"button",children:[s.jsx(jo,{size:16}),Wt==="free"?n?"Choose Plus":"Sign in for Plus":"Plus active"]})]}),s.jsxs("article",{className:`pricing-plan-card pro ${Wt==="pro"?"current":""}`,children:[s.jsxs("div",{className:"pricing-plan-topline",children:[s.jsxs("span",{className:"pricing-plan-badge pro",children:[s.jsx(Ht,{size:14})," Pro"]}),s.jsx("strong",{children:"$15"})]}),s.jsx("p",{className:"pricing-plan-audience",children:Sl.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(_n,{size:16})," 30+ workstation walls"]}),s.jsxs("li",{children:[s.jsx(_n,{size:16})," Commercial use included"]}),s.jsxs("li",{children:[s.jsx(_n,{size:16})," ",Sl.pro.ltd]})]}),s.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>Ii("pro"):Li,disabled:Wt==="pro"||ve==="checkout"||ve==="auth"||a||R,type:"button",children:[s.jsx(jo,{size:16}),Wt==="pro"?"Pro active":n?"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(Hd,{size:17}),s.jsx("span",{children:"Focused control"}),s.jsx("strong",{children:"Local-first"})]}),s.jsxs("div",{children:[s.jsx(cy,{size:17}),s.jsx("span",{children:"Remote audio"}),s.jsx("strong",{children:"Available"})]}),s.jsxs("div",{children:[s.jsx(ko,{size:17}),s.jsx("span",{children:"File transfer"}),s.jsx("strong",{children:"Included"})]})]}),s.jsxs("p",{className:"pricing-note",children:[s.jsx(_n,{size:15})," Commercial use requires Pro. Plus LTD is for personal, creator, and homelab use."]}),s.jsxs("button",{className:"pricing-primary-cta",onClick:n?()=>Ii(Wt==="ltd"?"pro":"ltd"):Li,disabled:ju,type:"button",children:[s.jsx(jo,{size:18}),Cu]})]}):s.jsx(s.Fragment,{children:s.jsxs("section",{className:`monitor-layout ${$n?"dock-collapsed":""}`,children:[s.jsxs("section",{ref:Jr,className:`screen-wall-panel ${ru?"drop-active":""}`,onClick:y=>{y.currentTarget===y.target&&Sr()},onDragEnter:y=>{y.preventDefault(),Xr(!0)},onDragOver:y=>{y.preventDefault(),y.dataTransfer.dropEffect="copy"},onDragLeave:y=>{y.currentTarget===y.target&&Xr(!1)},onDrop:Cr,children:[sa.length>0&&s.jsx("canvas",{ref:Ko,className:"atlas-source-canvas",width:An?.width||1920,height:An?.height||1080,"aria-hidden":"true"}),ot?s.jsx("section",{className:"control-focus",children:s.jsxs("div",{className:"control-wall",children:[_e&&fn.length>1&&s.jsx("div",{className:"control-monitor-tabs","aria-label":"Select monitor",children:fn.map(y=>s.jsxs("button",{className:y.index===Zl?"active":"",onClick:()=>ec(_e.deviceId,y.index),title:uT(y),type:"button",children:[s.jsx("span",{children:y.name||`Display ${y.index+1}`}),y.width>0&&y.height>0&&s.jsxs("small",{children:[y.width,"x",y.height]})]},y.index))}),_e?s.jsx(kh,{device:_e,frame:Ee,selected:!1,controlEnabled:us&&Se&&In,showStatus:vt.showScreenStatus,monitorIndex:Oa(Jt[_e.deviceId],ba(_e)),monitorCount:ba(_e),onSelect:()=>{},onFocusDevice:()=>J(_e.deviceId),onOpenControl:()=>Ns(_e.deviceId),onCycleMonitor:y=>As(_e.deviceId,y),onCanvasReady:vr,sendInput:zn,presentationReady:zo},_e.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."})]}),_e&&Go&&s.jsxs("div",{className:"control-connection-overlay",role:"alert",children:[s.jsx(Ht,{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."})]}),_e&&!Go&&!zo&&s.jsxs("div",{className:"control-connection-overlay",role:"status","aria-live":"polite",children:[G!=="error"&&s.jsx("span",{className:"control-connection-spinner","aria-hidden":"true"}),s.jsx("strong",{children:G==="error"?"Connection failed":"Connecting"}),s.jsx("small",{children:G==="error"?"See the notification for details. Reopen Control to retry.":Wa||he?"Control stream is recovering. See the notification for details.":Vn==="open"?"Preparing the first control frame":"Opening the Control stream"})]})]})}):et==="list"?s.jsxs("div",{className:"wall-device-list",role:"grid","aria-label":"Computer status list",children:[s.jsxs("div",{className:"wall-device-list-head",role:"row",children:[s.jsx("span",{role:"columnheader",children:"Computer"}),s.jsx("span",{role:"columnheader",children:"Status"}),s.jsx("span",{role:"columnheader",children:"CPU"}),s.jsx("span",{role:"columnheader",children:"GPU"}),s.jsx("span",{role:"columnheader",children:"RAM"}),s.jsx("span",{role:"columnheader",children:"VRAM"}),s.jsx("span",{role:"columnheader",children:"Network"}),s.jsx("span",{role:"columnheader",children:"HDD"}),s.jsx("span",{role:"columnheader",children:"Temp"})]}),uu.length>0?uu.map(({device:y,slotNumber:N})=>s.jsx(zT,{device:y,slotNumber:N,selected:Bs.has(y.deviceId),updateIndicator:ri(y.deviceId),onSelect:()=>Wl(y.deviceId),onOpenControl:()=>Ns(y.deviceId)},y.deviceId)):s.jsxs("div",{className:"wall-device-list-empty",children:[s.jsx(Zt,{size:24,"aria-hidden":"true"}),s.jsx("strong",{children:"No connected computers"})]})]}):ht?s.jsx("div",{className:`screen-wall atlas-slot-wall size-${et}`,onClick:y=>{y.currentTarget===y.target&&Sr()},children:bi.map((y,N)=>y?s.jsx(kh,{device:y,frame:Gl.get(y.deviceId),selected:Bs.has(y.deviceId),controlEnabled:!1,showStatus:Fe.showScreenStatus,monitorIndex:Oa(Jt[y.deviceId],ba(y)),monitorCount:ba(y),onSelect:()=>Wl(y.deviceId),onFocusDevice:()=>hs(y.deviceId),onOpenControl:()=>Ns(y.deviceId),onCycleMonitor:z=>As(y.deviceId,z),onCanvasReady:Hc({mode4Enabled:ht,directMode4WallEnabled:Aa,isMac:er(y.platform)})==="direct"?pu:Mi,sendInput:zn,updateIndicator:ri(y.deviceId),presentationReady:Fe.autoStartLive&&aa.includes(y.deviceId)?nt.has(y.deviceId):void 0,showPresentationSpinner:Fe.autoStartLive&&aa.includes(y.deviceId)},y.deviceId):s.jsx(Ux,{index:N},`slot-${N}`))}):s.jsx("div",{className:`screen-wall size-${et}`,onClick:y=>{y.currentTarget===y.target&&Sr()},children:bi.map((y,N)=>y?s.jsx(kh,{device:y,frame:Gl.get(y.deviceId),selected:Bs.has(y.deviceId),controlEnabled:us&&Se&&In&&_e?.deviceId===y.deviceId,showStatus:Fe.showScreenStatus,monitorIndex:Oa(Jt[y.deviceId],ba(y)),monitorCount:ba(y),onSelect:()=>Wl(y.deviceId),onFocusDevice:()=>hs(y.deviceId),onOpenControl:()=>Ns(y.deviceId),onCycleMonitor:z=>As(y.deviceId,z),onCanvasReady:pu,sendInput:zn,updateIndicator:ri(y.deviceId),presentationReady:Fe.autoStartLive&&aa.includes(y.deviceId)?nt.has(y.deviceId):void 0,showPresentationSpinner:Fe.autoStartLive&&aa.includes(y.deviceId)},y.deviceId):s.jsx(Ux,{index:N},`slot-${N}`))}),s.jsx(HT,{visible:mu&&!ot})]}),!Os&&s.jsxs("aside",{className:`right-dock actions-mode ${$n?"collapsed":""}`,"aria-label":"LiveDesk tools",children:[s.jsx("button",{className:"dock-toggle",onClick:()=>at(y=>!y),"aria-label":$n?"Show control panel":"Hide control panel",title:$n?"Show control panel":"Hide control panel",type:"button",children:$n?s.jsx(Zx,{size:18}):s.jsx(ap,{size:18})}),!$n&&s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"action-dock",children:[s.jsx("input",{ref:Bo,className:"hidden-file-input",type:"file",multiple:!0,onChange:y=>{y.currentTarget.files&&Yl(y.currentTarget.files),y.currentTarget.value=""}}),s.jsxs("div",{className:"manual-action-bar",role:"toolbar","aria-label":"Manual workstation controls",children:[s.jsx($r,{label:"Control",tooltip:_e?Go?"Allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client.":us?In?"Keyboard and mouse control is ready":"Waiting for the current Control capture session":"Remote control is not available on this workstation":"Select a workstation to use Control",onClick:()=>{if(_e){if(ot&&Se){Be(!1),X("Remote control paused. Screen viewing stays on.");return}Ns(_e.deviceId)}},disabled:!us||!!Ne,active:Se,pressed:ot&&Se,children:s.jsx(Hd,{size:17})}),s.jsx($r,{label:"Audio",tooltip:_e?wi?Oe?"Stop hearing this workstation":"Hear this workstation":"Audio is not available on this workstation":"Select a workstation to use Audio",onClick:()=>{tc()},disabled:!hr||!!Ne,active:Oe,pressed:Oe,children:Ne==="audio"?s.jsx(ci,{className:"spin",size:17}):s.jsx(cy,{size:17})}),s.jsx($r,{label:"Send files",tooltip:va.length===0&&!ot?"Select one or more workstations to send files":_e?"Choose files and send them to the selected workstation":"Select a workstation to send files",onClick:()=>{X(`Choose files to send to ${lc}.`),Bo.current?.click()},disabled:!!Ne||!en||(ot?!_e:va.length===0),children:s.jsx(ko,{size:17})}),s.jsx($r,{label:"Run command",tooltip:_e?Vo?"Run command":"Command runner is not available on this workstation":"Select a workstation to run a command",onClick:Zs,disabled:!_e||!en||!!Ne||!Vo,children:s.jsx(Bd,{size:17})}),s.jsx($r,{label:"Restart",tooltip:_e?fu?"Restart workstation":"Restart is not available on this workstation":"Select a workstation to restart",onClick:()=>{Ta("restart")},disabled:!_e||!en||!!Ne||!fu,children:Ne==="restart"?s.jsx(ci,{className:"spin",size:17}):s.jsx(Gc,{size:17})}),s.jsx($r,{label:"Lock",tooltip:_e?"Lock workstation":"Select a workstation to lock",onClick:()=>{Ta("lock")},disabled:!_e||!en||!!Ne,children:Ne==="lock"?s.jsx(ci,{className:"spin",size:17}):s.jsx(Rs,{size:17})}),s.jsx($r,{label:"Sleep",tooltip:_e?"Put workstation to sleep":"Select a workstation to put to sleep",onClick:()=>{Ta("sleep")},disabled:!_e||!en||!!Ne,children:Ne==="sleep"?s.jsx(ci,{className:"spin",size:17}):s.jsx(p0,{size:17})}),s.jsx($r,{label:"Shut down",tooltip:_e?"Shut down workstation":"Select a workstation to shut down",onClick:()=>{Ta("shutdown")},disabled:!_e||!en||!!Ne,danger:!0,children:Ne==="shutdown"?s.jsx(ci,{className:"spin",size:17}):s.jsx(g0,{size:17})})]})]}),s.jsx(xx,{hubUrl:M,devices:j,variant:"dock",selectedDeviceIds:to})]})]})]})})]}),ka&&s.jsxs("aside",{className:`transfer-bar state-${ka.status}`,"aria-live":"polite",children:[s.jsx("span",{className:"transfer-bar-icon","aria-hidden":"true",children:ka.status==="queued"?s.jsx(_n,{size:18}):ka.status==="failed"?s.jsx(Sa,{size:18}):s.jsx(Kx,{size:18})}),s.jsxs("div",{className:"transfer-bar-copy",children:[s.jsx("p",{children:ka.message}),s.jsx("div",{className:"transfer-bar-track",children:s.jsx("span",{style:{width:`${Math.max(0,Math.min(100,ka.progress))}%`}})})]}),s.jsxs("strong",{children:[Math.max(0,Math.min(100,ka.progress)),"%"]})]}),It&&s.jsxs("aside",{className:`livedesk-toast tone-${It.tone}`,role:It.tone==="error"?"alert":"status","aria-live":It.tone==="error"?"assertive":"polite","aria-busy":It.tone==="progress",children:[It.tone==="progress"&&s.jsx("span",{className:"livedesk-toast-spinner","aria-hidden":"true"}),s.jsx("span",{children:It.message}),s.jsx("button",{className:"livedesk-toast-close",onClick:()=>X(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:s.jsx(Sa,{size:15})})]})]})}function FT(){if(typeof window>"u")return[];const n=window.location.origin;return window.location.port==="5179"?[n]:["http://127.0.0.1:5179"]}function PT(){const[a,r]=u.useState(null);return u.useEffect(()=>{let l=!1,c=!1;const d=async()=>{for(const v of FT())try{const g=await fetch(`${v}/api/runtime`,{cache:"no-store"});if(!g.ok)continue;const x=(await g.json()).role==="hub"?"hub":"client";c=!0,l||r(x);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(CC,{}):s.jsx(BT,{}):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..."})]})}j0.createRoot(document.getElementById("root")).render(s.jsx(u.StrictMode,{children:s.jsx(PT,{})}));