livedesk 0.1.440 → 0.1.441

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 +1,25 @@
1
- import{r as r0,a as u,M as _u,S as Wn,R as Sc,B as i0,P as fh,X as Na,b as Bu,C as Ir,F as dy,L as Ti,A as lx,c as l0,d as fy,E as my,T as o0,D as xp,e as Zn,f as c0,g as ox,h as u0,i as d0,j as zr,k as Ta,l as Tf,m as Iu,n as wp,o as mo,p as cx,q as ho,s as ux,t as dx,u as Yh,v as f0,w as m0,H as co,W as $f,x as h0,y as p0,z as gc,K as fx,G as Kh,I as yl,J as mx,N as g0,O as v0,Q as y0,U as Sp,V as Cp,Y as b0,Z as kp,_ as x0,$ as jp,a0 as hx,a1 as w0,a2 as Lr,a3 as hy,a4 as Ap,a5 as Bf,a6 as Pu,a7 as Sf,a8 as S0,a9 as px,aa as C0,ab as gx,ac as k0,ad as j0,ae as Qh,af as vx,ag as A0,ah as M0,ai as N0,aj as T0,ak as R0,al as E0,am as py,an as D0,ao as L0,ap as _0,aq as I0,ar as Xh,as as Zh,at as z0,au as O0,av as gy,aw as mh,ax as H0,ay as vy,az as yx,aA as F0,aB as $0,aC as B0,aD as P0}from"./icons-BIyRF-ou.js";import{r as bx}from"./react-C7a9r614.js";import{c as U0}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 i(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=i(c);fetch(c.href,d)}})();var hh={exports:{}},Cu={};var yy;function q0(){if(yy)return Cu;yy=1;var n=Symbol.for("react.transitional.element"),a=Symbol.for("react.fragment");function i(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 h in c)h!=="key"&&(d[h]=c[h])}else d=c;return c=d.ref,{$$typeof:n,type:l,key:m,ref:c!==void 0?c:null,props:d}}return Cu.Fragment=a,Cu.jsx=i,Cu.jsxs=i,Cu}var by;function G0(){return by||(by=1,hh.exports=q0()),hh.exports}var r=G0(),ph={exports:{}},ku={},gh={exports:{}},vh={};var xy;function V0(){return xy||(xy=1,(function(n){function a(z,se){var W=z.length;z.push(se);e:for(;0<W;){var O=W-1>>>1,le=z[O];if(0<c(le,se))z[O]=se,z[W]=le,W=O;else break e}}function i(z){return z.length===0?null:z[0]}function l(z){if(z.length===0)return null;var se=z[0],W=z.pop();if(W!==se){z[0]=W;e:for(var O=0,le=z.length,ce=le>>>1;O<ce;){var K=2*(O+1)-1,be=z[K],he=K+1,fe=z[he];if(0>c(be,W))he<le&&0>c(fe,be)?(z[O]=fe,z[he]=W,O=he):(z[O]=be,z[K]=W,O=K);else if(he<le&&0>c(fe,W))z[O]=fe,z[he]=W,O=he;else break e}}return se}function c(z,se){var W=z.sortIndex-se.sortIndex;return W!==0?W:z.id-se.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,h=m.now();n.unstable_now=function(){return m.now()-h}}var g=[],y=[],x=1,b=null,w=3,A=!1,j=!1,k=!1,N=!1,M=typeof setTimeout=="function"?setTimeout:null,T=typeof clearTimeout=="function"?clearTimeout:null,D=typeof setImmediate<"u"?setImmediate:null;function F(z){for(var se=i(y);se!==null;){if(se.callback===null)l(y);else if(se.startTime<=z)l(y),se.sortIndex=se.expirationTime,a(g,se);else break;se=i(y)}}function $(z){if(k=!1,F(z),!j)if(i(g)!==null)j=!0,G||(G=!0,H());else{var se=i(y);se!==null&&Z($,se.startTime-z)}}var G=!1,L=-1,Q=5,q=-1;function P(){return N?!0:!(n.unstable_now()-q<Q)}function Y(){if(N=!1,G){var z=n.unstable_now();q=z;var se=!0;try{e:{j=!1,k&&(k=!1,T(L),L=-1),A=!0;var W=w;try{t:{for(F(z),b=i(g);b!==null&&!(b.expirationTime>z&&P());){var O=b.callback;if(typeof O=="function"){b.callback=null,w=b.priorityLevel;var le=O(b.expirationTime<=z);if(z=n.unstable_now(),typeof le=="function"){b.callback=le,F(z),se=!0;break t}b===i(g)&&l(g),F(z)}else l(g);b=i(g)}if(b!==null)se=!0;else{var ce=i(y);ce!==null&&Z($,ce.startTime-z),se=!1}}break e}finally{b=null,w=W,A=!1}se=void 0}}finally{se?H():G=!1}}}var H;if(typeof D=="function")H=function(){D(Y)};else if(typeof MessageChannel<"u"){var ye=new MessageChannel,de=ye.port2;ye.port1.onmessage=Y,H=function(){de.postMessage(null)}}else H=function(){M(Y,0)};function Z(z,se){L=M(function(){z(n.unstable_now())},se)}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(z){z.callback=null},n.unstable_forceFrameRate=function(z){0>z||125<z?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):Q=0<z?Math.floor(1e3/z):5},n.unstable_getCurrentPriorityLevel=function(){return w},n.unstable_next=function(z){switch(w){case 1:case 2:case 3:var se=3;break;default:se=w}var W=w;w=se;try{return z()}finally{w=W}},n.unstable_requestPaint=function(){N=!0},n.unstable_runWithPriority=function(z,se){switch(z){case 1:case 2:case 3:case 4:case 5:break;default:z=3}var W=w;w=z;try{return se()}finally{w=W}},n.unstable_scheduleCallback=function(z,se,W){var O=n.unstable_now();switch(typeof W=="object"&&W!==null?(W=W.delay,W=typeof W=="number"&&0<W?O+W:O):W=O,z){case 1:var le=-1;break;case 2:le=250;break;case 5:le=1073741823;break;case 4:le=1e4;break;default:le=5e3}return le=W+le,z={id:x++,callback:se,priorityLevel:z,startTime:W,expirationTime:le,sortIndex:-1},W>O?(z.sortIndex=W,a(y,z),i(g)===null&&z===i(y)&&(k?(T(L),L=-1):k=!0,Z($,W-O))):(z.sortIndex=le,a(g,z),j||A||(j=!0,G||(G=!0,H()))),z},n.unstable_shouldYield=P,n.unstable_wrapCallback=function(z){var se=w;return function(){var W=w;w=se;try{return z.apply(this,arguments)}finally{w=W}}}})(vh)),vh}var wy;function W0(){return wy||(wy=1,gh.exports=V0()),gh.exports}var Sy;function Y0(){if(Sy)return ku;Sy=1;var n=W0(),a=r0(),i=bx();function l(e){var t="https://react.dev/errors/"+e;if(1<arguments.length){t+="?args[]="+encodeURIComponent(arguments[1]);for(var s=2;s<arguments.length;s++)t+="&args[]="+encodeURIComponent(arguments[s])}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,s=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,(t.flags&4098)!==0&&(s=t.return),e=t.return;while(e)}return t.tag===3?s: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 h(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 g(e){if(d(e)!==e)throw Error(l(188))}function y(e){var t=e.alternate;if(!t){if(t=d(e),t===null)throw Error(l(188));return t!==e?null:e}for(var s=e,o=t;;){var f=s.return;if(f===null)break;var p=f.alternate;if(p===null){if(o=f.return,o!==null){s=o;continue}break}if(f.child===p.child){for(p=f.child;p;){if(p===s)return g(f),e;if(p===o)return g(f),t;p=p.sibling}throw Error(l(188))}if(s.return!==o.return)s=f,o=p;else{for(var S=!1,R=f.child;R;){if(R===s){S=!0,s=f,o=p;break}if(R===o){S=!0,o=f,s=p;break}R=R.sibling}if(!S){for(R=p.child;R;){if(R===s){S=!0,s=p,o=f;break}if(R===o){S=!0,o=p,s=f;break}R=R.sibling}if(!S)throw Error(l(189))}}if(s.alternate!==o)throw Error(l(190))}if(s.tag!==3)throw Error(l(188));return s.stateNode.current===s?e:t}function x(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e;for(e=e.child;e!==null;){if(t=x(e),t!==null)return t;e=e.sibling}return null}var b=Object.assign,w=Symbol.for("react.element"),A=Symbol.for("react.transitional.element"),j=Symbol.for("react.portal"),k=Symbol.for("react.fragment"),N=Symbol.for("react.strict_mode"),M=Symbol.for("react.profiler"),T=Symbol.for("react.consumer"),D=Symbol.for("react.context"),F=Symbol.for("react.forward_ref"),$=Symbol.for("react.suspense"),G=Symbol.for("react.suspense_list"),L=Symbol.for("react.memo"),Q=Symbol.for("react.lazy"),q=Symbol.for("react.activity"),P=Symbol.for("react.memo_cache_sentinel"),Y=Symbol.iterator;function H(e){return e===null||typeof e!="object"?null:(e=Y&&e[Y]||e["@@iterator"],typeof e=="function"?e:null)}var ye=Symbol.for("react.client.reference");function de(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===ye?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case k:return"Fragment";case M:return"Profiler";case N:return"StrictMode";case $:return"Suspense";case G:return"SuspenseList";case q:return"Activity"}if(typeof e=="object")switch(e.$$typeof){case j:return"Portal";case D:return e.displayName||"Context";case T:return(e._context.displayName||"Context")+".Consumer";case F:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case L:return t=e.displayName||null,t!==null?t:de(e.type)||"Memo";case Q:t=e._payload,e=e._init;try{return de(e(t))}catch{}}return null}var Z=Array.isArray,z=a.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,se=i.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,W={pending:!1,data:null,method:null,action:null},O=[],le=-1;function ce(e){return{current:e}}function K(e){0>le||(e.current=O[le],O[le]=null,le--)}function be(e,t){le++,O[le]=e.current,e.current=t}var he=ce(null),fe=ce(null),ee=ce(null),we=ce(null);function Me(e,t){switch(be(ee,t),be(fe,e),be(he,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?_v(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=_v(t),e=Iv(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}K(he),be(he,e)}function He(){K(he),K(fe),K(ee)}function ne(e){e.memoizedState!==null&&be(we,e);var t=he.current,s=Iv(t,e.type);t!==s&&(be(fe,e),be(he,s))}function qe(e){fe.current===e&&(K(he),K(fe)),we.current===e&&(K(we),bu._currentValue=W)}var mt,J;function Ce(e){if(mt===void 0)try{throw Error()}catch(s){var t=s.stack.trim().match(/\n( *(at )?)/);mt=t&&t[1]||"",J=-1<s.stack.indexOf(`
1
+ import{r as r0,a as u,M as _u,S as Vn,R as Sc,B as i0,P as fh,X as Na,b as Bu,C as Ir,F as dy,L as Ti,A as lx,c as l0,d as fy,E as my,T as o0,D as xp,e as Xn,f as c0,g as ox,h as u0,i as d0,j as zr,k as Ta,l as Tf,m as Iu,n as wp,o as mo,p as cx,q as ho,s as ux,t as dx,u as Yh,v as f0,w as m0,H as co,W as $f,x as h0,y as p0,z as gc,K as fx,G as Kh,I as yl,J as mx,N as g0,O as v0,Q as y0,U as Sp,V as Cp,Y as b0,Z as kp,_ as x0,$ as jp,a0 as hx,a1 as w0,a2 as Lr,a3 as hy,a4 as Ap,a5 as Bf,a6 as Pu,a7 as Sf,a8 as S0,a9 as px,aa as C0,ab as gx,ac as k0,ad as j0,ae as Qh,af as vx,ag as A0,ah as M0,ai as N0,aj as T0,ak as R0,al as E0,am as py,an as D0,ao as L0,ap as _0,aq as I0,ar as Xh,as as Zh,at as z0,au as O0,av as gy,aw as mh,ax as H0,ay as vy,az as yx,aA as F0,aB as $0,aC as B0,aD as P0}from"./icons-BIyRF-ou.js";import{r as bx}from"./react-C7a9r614.js";import{c as U0}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 i(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=i(c);fetch(c.href,d)}})();var hh={exports:{}},Cu={};var yy;function q0(){if(yy)return Cu;yy=1;var n=Symbol.for("react.transitional.element"),a=Symbol.for("react.fragment");function i(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 h in c)h!=="key"&&(d[h]=c[h])}else d=c;return c=d.ref,{$$typeof:n,type:l,key:m,ref:c!==void 0?c:null,props:d}}return Cu.Fragment=a,Cu.jsx=i,Cu.jsxs=i,Cu}var by;function G0(){return by||(by=1,hh.exports=q0()),hh.exports}var r=G0(),ph={exports:{}},ku={},gh={exports:{}},vh={};var xy;function V0(){return xy||(xy=1,(function(n){function a(z,se){var W=z.length;z.push(se);e:for(;0<W;){var O=W-1>>>1,le=z[O];if(0<c(le,se))z[O]=se,z[W]=le,W=O;else break e}}function i(z){return z.length===0?null:z[0]}function l(z){if(z.length===0)return null;var se=z[0],W=z.pop();if(W!==se){z[0]=W;e:for(var O=0,le=z.length,ce=le>>>1;O<ce;){var Q=2*(O+1)-1,be=z[Q],he=Q+1,fe=z[he];if(0>c(be,W))he<le&&0>c(fe,be)?(z[O]=fe,z[he]=W,O=he):(z[O]=be,z[Q]=W,O=Q);else if(he<le&&0>c(fe,W))z[O]=fe,z[he]=W,O=he;else break e}}return se}function c(z,se){var W=z.sortIndex-se.sortIndex;return W!==0?W:z.id-se.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,h=m.now();n.unstable_now=function(){return m.now()-h}}var g=[],y=[],x=1,b=null,w=3,A=!1,j=!1,k=!1,N=!1,M=typeof setTimeout=="function"?setTimeout:null,T=typeof clearTimeout=="function"?clearTimeout:null,D=typeof setImmediate<"u"?setImmediate:null;function F(z){for(var se=i(y);se!==null;){if(se.callback===null)l(y);else if(se.startTime<=z)l(y),se.sortIndex=se.expirationTime,a(g,se);else break;se=i(y)}}function $(z){if(k=!1,F(z),!j)if(i(g)!==null)j=!0,q||(q=!0,H());else{var se=i(y);se!==null&&Z($,se.startTime-z)}}var q=!1,L=-1,Y=5,G=-1;function P(){return N?!0:!(n.unstable_now()-G<Y)}function K(){if(N=!1,q){var z=n.unstable_now();G=z;var se=!0;try{e:{j=!1,k&&(k=!1,T(L),L=-1),A=!0;var W=w;try{t:{for(F(z),b=i(g);b!==null&&!(b.expirationTime>z&&P());){var O=b.callback;if(typeof O=="function"){b.callback=null,w=b.priorityLevel;var le=O(b.expirationTime<=z);if(z=n.unstable_now(),typeof le=="function"){b.callback=le,F(z),se=!0;break t}b===i(g)&&l(g),F(z)}else l(g);b=i(g)}if(b!==null)se=!0;else{var ce=i(y);ce!==null&&Z($,ce.startTime-z),se=!1}}break e}finally{b=null,w=W,A=!1}se=void 0}}finally{se?H():q=!1}}}var H;if(typeof D=="function")H=function(){D(K)};else if(typeof MessageChannel<"u"){var ye=new MessageChannel,de=ye.port2;ye.port1.onmessage=K,H=function(){de.postMessage(null)}}else H=function(){M(K,0)};function Z(z,se){L=M(function(){z(n.unstable_now())},se)}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(z){z.callback=null},n.unstable_forceFrameRate=function(z){0>z||125<z?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):Y=0<z?Math.floor(1e3/z):5},n.unstable_getCurrentPriorityLevel=function(){return w},n.unstable_next=function(z){switch(w){case 1:case 2:case 3:var se=3;break;default:se=w}var W=w;w=se;try{return z()}finally{w=W}},n.unstable_requestPaint=function(){N=!0},n.unstable_runWithPriority=function(z,se){switch(z){case 1:case 2:case 3:case 4:case 5:break;default:z=3}var W=w;w=z;try{return se()}finally{w=W}},n.unstable_scheduleCallback=function(z,se,W){var O=n.unstable_now();switch(typeof W=="object"&&W!==null?(W=W.delay,W=typeof W=="number"&&0<W?O+W:O):W=O,z){case 1:var le=-1;break;case 2:le=250;break;case 5:le=1073741823;break;case 4:le=1e4;break;default:le=5e3}return le=W+le,z={id:x++,callback:se,priorityLevel:z,startTime:W,expirationTime:le,sortIndex:-1},W>O?(z.sortIndex=W,a(y,z),i(g)===null&&z===i(y)&&(k?(T(L),L=-1):k=!0,Z($,W-O))):(z.sortIndex=le,a(g,z),j||A||(j=!0,q||(q=!0,H()))),z},n.unstable_shouldYield=P,n.unstable_wrapCallback=function(z){var se=w;return function(){var W=w;w=se;try{return z.apply(this,arguments)}finally{w=W}}}})(vh)),vh}var wy;function W0(){return wy||(wy=1,gh.exports=V0()),gh.exports}var Sy;function Y0(){if(Sy)return ku;Sy=1;var n=W0(),a=r0(),i=bx();function l(e){var t="https://react.dev/errors/"+e;if(1<arguments.length){t+="?args[]="+encodeURIComponent(arguments[1]);for(var s=2;s<arguments.length;s++)t+="&args[]="+encodeURIComponent(arguments[s])}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,s=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,(t.flags&4098)!==0&&(s=t.return),e=t.return;while(e)}return t.tag===3?s: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 h(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 g(e){if(d(e)!==e)throw Error(l(188))}function y(e){var t=e.alternate;if(!t){if(t=d(e),t===null)throw Error(l(188));return t!==e?null:e}for(var s=e,o=t;;){var f=s.return;if(f===null)break;var p=f.alternate;if(p===null){if(o=f.return,o!==null){s=o;continue}break}if(f.child===p.child){for(p=f.child;p;){if(p===s)return g(f),e;if(p===o)return g(f),t;p=p.sibling}throw Error(l(188))}if(s.return!==o.return)s=f,o=p;else{for(var S=!1,R=f.child;R;){if(R===s){S=!0,s=f,o=p;break}if(R===o){S=!0,o=f,s=p;break}R=R.sibling}if(!S){for(R=p.child;R;){if(R===s){S=!0,s=p,o=f;break}if(R===o){S=!0,o=p,s=f;break}R=R.sibling}if(!S)throw Error(l(189))}}if(s.alternate!==o)throw Error(l(190))}if(s.tag!==3)throw Error(l(188));return s.stateNode.current===s?e:t}function x(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e;for(e=e.child;e!==null;){if(t=x(e),t!==null)return t;e=e.sibling}return null}var b=Object.assign,w=Symbol.for("react.element"),A=Symbol.for("react.transitional.element"),j=Symbol.for("react.portal"),k=Symbol.for("react.fragment"),N=Symbol.for("react.strict_mode"),M=Symbol.for("react.profiler"),T=Symbol.for("react.consumer"),D=Symbol.for("react.context"),F=Symbol.for("react.forward_ref"),$=Symbol.for("react.suspense"),q=Symbol.for("react.suspense_list"),L=Symbol.for("react.memo"),Y=Symbol.for("react.lazy"),G=Symbol.for("react.activity"),P=Symbol.for("react.memo_cache_sentinel"),K=Symbol.iterator;function H(e){return e===null||typeof e!="object"?null:(e=K&&e[K]||e["@@iterator"],typeof e=="function"?e:null)}var ye=Symbol.for("react.client.reference");function de(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===ye?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case k:return"Fragment";case M:return"Profiler";case N:return"StrictMode";case $:return"Suspense";case q:return"SuspenseList";case G:return"Activity"}if(typeof e=="object")switch(e.$$typeof){case j:return"Portal";case D:return e.displayName||"Context";case T:return(e._context.displayName||"Context")+".Consumer";case F:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case L:return t=e.displayName||null,t!==null?t:de(e.type)||"Memo";case Y:t=e._payload,e=e._init;try{return de(e(t))}catch{}}return null}var Z=Array.isArray,z=a.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,se=i.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,W={pending:!1,data:null,method:null,action:null},O=[],le=-1;function ce(e){return{current:e}}function Q(e){0>le||(e.current=O[le],O[le]=null,le--)}function be(e,t){le++,O[le]=e.current,e.current=t}var he=ce(null),fe=ce(null),ee=ce(null),Se=ce(null);function Ne(e,t){switch(be(ee,t),be(fe,e),be(he,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?_v(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=_v(t),e=Iv(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}Q(he),be(he,e)}function Fe(){Q(he),Q(fe),Q(ee)}function ne(e){e.memoizedState!==null&&be(Se,e);var t=he.current,s=Iv(t,e.type);t!==s&&(be(fe,e),be(he,s))}function Pe(e){fe.current===e&&(Q(he),Q(fe)),Se.current===e&&(Q(Se),bu._currentValue=W)}var mt,J;function ke(e){if(mt===void 0)try{throw Error()}catch(s){var t=s.stack.trim().match(/\n( *(at )?)/);mt=t&&t[1]||"",J=-1<s.stack.indexOf(`
2
2
  at`)?" (<anonymous>)":-1<s.stack.indexOf("@")?"@unknown:0:0":""}return`
3
- `+mt+e+J}var Le=!1;function Fe(e,t){if(!e||Le)return"";Le=!0;var s=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var o={DetermineComponentFrameRoot:function(){try{if(t){var ke=function(){throw Error()};if(Object.defineProperty(ke.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ke,[])}catch(ge){var me=ge}Reflect.construct(e,[],ke)}else{try{ke.call()}catch(ge){me=ge}e.call(ke.prototype)}}else{try{throw Error()}catch(ge){me=ge}(ke=e())&&typeof ke.catch=="function"&&ke.catch(function(){})}}catch(ge){if(ge&&me&&typeof ge.stack=="string")return[ge.stack,me.stack]}return[null,null]}};o.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var f=Object.getOwnPropertyDescriptor(o.DetermineComponentFrameRoot,"name");f&&f.configurable&&Object.defineProperty(o.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var p=o.DetermineComponentFrameRoot(),S=p[0],R=p[1];if(S&&R){var V=S.split(`
3
+ `+mt+e+J}var Le=!1;function Be(e,t){if(!e||Le)return"";Le=!0;var s=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var o={DetermineComponentFrameRoot:function(){try{if(t){var Ce=function(){throw Error()};if(Object.defineProperty(Ce.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Ce,[])}catch(ge){var me=ge}Reflect.construct(e,[],Ce)}else{try{Ce.call()}catch(ge){me=ge}e.call(Ce.prototype)}}else{try{throw Error()}catch(ge){me=ge}(Ce=e())&&typeof Ce.catch=="function"&&Ce.catch(function(){})}}catch(ge){if(ge&&me&&typeof ge.stack=="string")return[ge.stack,me.stack]}return[null,null]}};o.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var f=Object.getOwnPropertyDescriptor(o.DetermineComponentFrameRoot,"name");f&&f.configurable&&Object.defineProperty(o.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var p=o.DetermineComponentFrameRoot(),S=p[0],R=p[1];if(S&&R){var V=S.split(`
4
4
  `),ue=R.split(`
5
5
  `);for(f=o=0;o<V.length&&!V[o].includes("DetermineComponentFrameRoot");)o++;for(;f<ue.length&&!ue[f].includes("DetermineComponentFrameRoot");)f++;if(o===V.length||f===ue.length)for(o=V.length-1,f=ue.length-1;1<=o&&0<=f&&V[o]!==ue[f];)f--;for(;1<=o&&0<=f;o--,f--)if(V[o]!==ue[f]){if(o!==1||f!==1)do if(o--,f--,0>f||V[o]!==ue[f]){var xe=`
6
- `+V[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{Le=!1,Error.prepareStackTrace=s}return(s=e?e.displayName||e.name:"")?Ce(s):""}function _e(e,t){switch(e.tag){case 26:case 27:case 5:return Ce(e.type);case 16:return Ce("Lazy");case 13:return e.child!==t&&t!==null?Ce("Suspense Fallback"):Ce("Suspense");case 19:return Ce("SuspenseList");case 0:case 15:return Fe(e.type,!1);case 11:return Fe(e.type.render,!1);case 1:return Fe(e.type,!0);case 31:return Ce("Activity");default:return""}}function Xe(e){try{var t="",s=null;do t+=_e(e,s),s=e,e=e.return;while(e);return t}catch(o){return`
6
+ `+V[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{Le=!1,Error.prepareStackTrace=s}return(s=e?e.displayName||e.name:"")?ke(s):""}function _e(e,t){switch(e.tag){case 26:case 27:case 5:return ke(e.type);case 16:return ke("Lazy");case 13:return e.child!==t&&t!==null?ke("Suspense Fallback"):ke("Suspense");case 19:return ke("SuspenseList");case 0:case 15:return Be(e.type,!1);case 11:return Be(e.type.render,!1);case 1:return Be(e.type,!0);case 31:return ke("Activity");default:return""}}function Qe(e){try{var t="",s=null;do t+=_e(e,s),s=e,e=e.return;while(e);return t}catch(o){return`
7
7
  Error generating stack: `+o.message+`
8
- `+o.stack}}var We=Object.prototype.hasOwnProperty,Ze=n.unstable_scheduleCallback,dt=n.unstable_cancelCallback,U=n.unstable_shouldYield,ve=n.unstable_requestPaint,Ae=n.unstable_now,Be=n.unstable_getCurrentPriorityLevel,ft=n.unstable_ImmediatePriority,it=n.unstable_UserBlockingPriority,yt=n.unstable_NormalPriority,ot=n.unstable_LowPriority,kt=n.unstable_IdlePriority,pe=n.log,De=n.unstable_setDisableYieldValue,$e=null,je=null;function ct(e){if(typeof pe=="function"&&De(e),je&&typeof je.setStrictMode=="function")try{je.setStrictMode($e,e)}catch{}}var bt=Math.clz32?Math.clz32:zn,ze=Math.log,aa=Math.LN2;function zn(e){return e>>>=0,e===0?32:31-(ze(e)/aa|0)|0}var nt=256,Ot=262144,Nn=4194304;function pa(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 Oe(e,t,s){var o=e.pendingLanes;if(o===0)return 0;var f=0,p=e.suspendedLanes,S=e.pingedLanes;e=e.warmLanes;var R=o&134217727;return R!==0?(o=R&~p,o!==0?f=pa(o):(S&=R,S!==0?f=pa(S):s||(s=R&~e,s!==0&&(f=pa(s))))):(R=o&~p,R!==0?f=pa(R):S!==0?f=pa(S):s||(s=o&~e,s!==0&&(f=pa(s)))),f===0?0:t!==0&&t!==f&&(t&p)===0&&(p=f&-f,s=t&-t,p>=s||p===32&&(s&4194048)!==0)?t:f}function wn(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function On(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 ws(){var e=Nn;return Nn<<=1,(Nn&62914560)===0&&(Nn=4194304),e}function pn(e){for(var t=[],s=0;31>s;s++)t.push(e);return t}function qs(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function Yn(e,t,s,o,f,p){var S=e.pendingLanes;e.pendingLanes=s,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=s,e.entangledLanes&=s,e.errorRecoveryDisabledLanes&=s,e.shellSuspendCounter=0;var R=e.entanglements,V=e.expirationTimes,ue=e.hiddenUpdates;for(s=S&~s;0<s;){var xe=31-bt(s),ke=1<<xe;R[xe]=0,V[xe]=-1;var me=ue[xe];if(me!==null)for(ue[xe]=null,xe=0;xe<me.length;xe++){var ge=me[xe];ge!==null&&(ge.lane&=-536870913)}s&=~ke}o!==0&&Gs(e,o,0),p!==0&&f===0&&e.tag!==0&&(e.suspendedLanes|=p&~(S&~t))}function Gs(e,t,s){e.pendingLanes|=t,e.suspendedLanes&=~t;var o=31-bt(t);e.entangledLanes|=t,e.entanglements[o]=e.entanglements[o]|1073741824|s&261930}function B(e,t){var s=e.entangledLanes|=t;for(e=e.entanglements;s;){var o=31-bt(s),f=1<<o;f&t|e[o]&t&&(e[o]|=t),s&=~f}}function Ke(e,t){var s=t&-t;return s=(s&42)!==0?1:ht(s),(s&(e.suspendedLanes|t))!==0?0:s}function ht(e){switch(e){case 2:e=1;break;case 8:e=4;break;case 32:e=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:e=128;break;case 268435456:e=134217728;break;default:e=0}return e}function fn(e){return e&=-e,2<e?8<e?(e&134217727)!==0?32:268435456:8:2}function Fa(){var e=se.p;return e!==0?e:(e=window.event,e===void 0?32:sy(e.type))}function Di(e,t){var s=se.p;try{return se.p=e,t()}finally{se.p=s}}var Ss=Math.random().toString(36).slice(2),re="__reactFiber$"+Ss,Te="__reactProps$"+Ss,Pe="__reactContainer$"+Ss,vt="__reactEvents$"+Ss,qt="__reactListeners$"+Ss,Yt="__reactHandles$"+Ss,st="__reactResources$"+Ss,Mt="__reactMarker$"+Ss;function sa(e){delete e[re],delete e[Te],delete e[vt],delete e[qt],delete e[Yt]}function Hn(e){var t=e[re];if(t)return t;for(var s=e.parentNode;s;){if(t=s[Pe]||s[re]){if(s=t.alternate,t.child!==null||s!==null&&s.child!==null)for(e=Pv(e);e!==null;){if(s=e[re])return s;e=Pv(e)}return t}e=s,s=e.parentNode}return null}function gn(e){if(e=e[re]||e[Pe]){var t=e.tag;if(t===5||t===6||t===13||t===31||t===26||t===27||t===3)return e}return null}function nn(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e.stateNode;throw Error(l(33))}function Ye(e){var t=e[st];return t||(t=e[st]={hoistableStyles:new Map,hoistableScripts:new Map}),t}function At(e){e[Mt]=!0}var Vs=new Set,zt={};function Sn(e,t){Tn(e,t),Tn(e+"Capture",t)}function Tn(e,t){for(zt[e]=t,e=0;e<t.length;e++)Vs.add(t[e])}var go=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"),Nt={},ga={};function Mc(e){return We.call(ga,e)?!0:We.call(Nt,e)?!1:go.test(e)?ga[e]=!0:(Nt[e]=!0,!1)}function Fr(e,t,s){if(Mc(t))if(s===null)e.removeAttribute(t);else{switch(typeof s){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,""+s)}}function Fn(e,t,s){if(s===null)e.removeAttribute(t);else{switch(typeof s){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(t);return}e.setAttribute(t,""+s)}}function $a(e,t,s,o){if(o===null)e.removeAttribute(s);else{switch(typeof o){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(s);return}e.setAttributeNS(t,s,""+o)}}function Kn(e){switch(typeof e){case"bigint":case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Qu(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Qf(e,t,s){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,p=o.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return f.call(this)},set:function(S){s=""+S,p.call(this,S)}}),Object.defineProperty(e,t,{enumerable:o.enumerable}),{getValue:function(){return s},setValue:function(S){s=""+S},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Nc(e){if(!e._valueTracker){var t=Qu(e)?"checked":"value";e._valueTracker=Qf(e,t,""+e[t])}}function Xu(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var s=t.getValue(),o="";return e&&(o=Qu(e)?e.checked?"true":"false":e.value),e=o,e!==s?(t.setValue(e),!0):!1}function Sl(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 Xf=/[\n"\\]/g;function Ba(e){return e.replace(Xf,function(t){return"\\"+t.charCodeAt(0).toString(16)+" "})}function vo(e,t,s,o,f,p,S,R){e.name="",S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"?e.type=S:e.removeAttribute("type"),t!=null?S==="number"?(t===0&&e.value===""||e.value!=t)&&(e.value=""+Kn(t)):e.value!==""+Kn(t)&&(e.value=""+Kn(t)):S!=="submit"&&S!=="reset"||e.removeAttribute("value"),t!=null?$n(e,S,Kn(t)):s!=null?$n(e,S,Kn(s)):o!=null&&e.removeAttribute("value"),f==null&&p!=null&&(e.defaultChecked=!!p),f!=null&&(e.checked=f&&typeof f!="function"&&typeof f!="symbol"),R!=null&&typeof R!="function"&&typeof R!="symbol"&&typeof R!="boolean"?e.name=""+Kn(R):e.removeAttribute("name")}function Li(e,t,s,o,f,p,S,R){if(p!=null&&typeof p!="function"&&typeof p!="symbol"&&typeof p!="boolean"&&(e.type=p),t!=null||s!=null){if(!(p!=="submit"&&p!=="reset"||t!=null)){Nc(e);return}s=s!=null?""+Kn(s):"",t=t!=null?""+Kn(t):s,R||t===e.value||(e.value=t),e.defaultValue=t}o=o??f,o=typeof o!="function"&&typeof o!="symbol"&&!!o,e.checked=R?e.checked:!!o,e.defaultChecked=!!o,S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"&&(e.name=S),Nc(e)}function $n(e,t,s){t==="number"&&Sl(e.ownerDocument)===e||e.defaultValue===""+s||(e.defaultValue=""+s)}function Ra(e,t,s,o){if(e=e.options,t){t={};for(var f=0;f<s.length;f++)t["$"+s[f]]=!0;for(s=0;s<e.length;s++)f=t.hasOwnProperty("$"+e[s].value),e[s].selected!==f&&(e[s].selected=f),f&&o&&(e[s].defaultSelected=!0)}else{for(s=""+Kn(s),t=null,f=0;f<e.length;f++){if(e[f].value===s){e[f].selected=!0,o&&(e[f].defaultSelected=!0);return}t!==null||e[f].disabled||(t=e[f])}t!==null&&(t.selected=!0)}}function Ws(e,t,s){if(t!=null&&(t=""+Kn(t),t!==e.value&&(e.value=t),s==null)){e.defaultValue!==t&&(e.defaultValue=t);return}e.defaultValue=s!=null?""+Kn(s):""}function $r(e,t,s,o){if(t==null){if(o!=null){if(s!=null)throw Error(l(92));if(Z(o)){if(1<o.length)throw Error(l(93));o=o[0]}s=o}s==null&&(s=""),t=s}s=Kn(t),e.defaultValue=s,o=e.textContent,o===s&&o!==""&&o!==null&&(e.value=o),Nc(e)}function Cn(e,t){if(t){var s=e.firstChild;if(s&&s===e.lastChild&&s.nodeType===3){s.nodeValue=t;return}}e.textContent=t}var Cl=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 Ys(e,t,s){var o=t.indexOf("--")===0;s==null||typeof s=="boolean"||s===""?o?e.setProperty(t,""):t==="float"?e.cssFloat="":e[t]="":o?e.setProperty(t,s):typeof s!="number"||s===0||Cl.has(t)?t==="float"?e.cssFloat=s:e[t]=(""+s).trim():e[t]=s+"px"}function kl(e,t,s){if(t!=null&&typeof t!="object")throw Error(l(62));if(e=e.style,s!=null){for(var o in s)!s.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)&&s[f]!==o&&Ys(e,f,o)}else for(var p in t)t.hasOwnProperty(p)&&Ys(e,p,t[p])}function Br(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 os=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"]]),Zu=/^[\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 Pr(e){return Zu.test(""+e)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":e}function ra(){}var Cs=null;function _i(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var vr=null,Ks=null;function jl(e){var t=gn(e);if(t&&(e=t.stateNode)){var s=e[Te]||null;e:switch(e=t.stateNode,t.type){case"input":if(vo(e,s.value,s.defaultValue,s.defaultValue,s.checked,s.defaultChecked,s.type,s.name),t=s.name,s.type==="radio"&&t!=null){for(s=e;s.parentNode;)s=s.parentNode;for(s=s.querySelectorAll('input[name="'+Ba(""+t)+'"][type="radio"]'),t=0;t<s.length;t++){var o=s[t];if(o!==e&&o.form===e.form){var f=o[Te]||null;if(!f)throw Error(l(90));vo(o,f.value,f.defaultValue,f.defaultValue,f.checked,f.defaultChecked,f.type,f.name)}}for(t=0;t<s.length;t++)o=s[t],o.form===e.form&&Xu(o)}break e;case"textarea":Ws(e,s.value,s.defaultValue);break e;case"select":t=s.value,t!=null&&Ra(e,!!s.multiple,t,!1)}}}var yo=!1;function Al(e,t,s){if(yo)return e(t,s);yo=!0;try{var o=e(t);return o}finally{if(yo=!1,(vr!==null||Ks!==null)&&(Nd(),vr&&(t=vr,e=Ks,Ks=vr=null,jl(t),e)))for(t=0;t<e.length;t++)jl(e[t])}}function yr(e,t){var s=e.stateNode;if(s===null)return null;var o=s[Te]||null;if(o===null)return null;s=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(s&&typeof s!="function")throw Error(l(231,t,typeof s));return s}var ks=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),bo=!1;if(ks)try{var ia={};Object.defineProperty(ia,"passive",{get:function(){bo=!0}}),window.addEventListener("test",ia,ia),window.removeEventListener("test",ia,ia)}catch{bo=!1}var js=null,Pa=null,va=null;function la(){if(va)return va;var e,t=Pa,s=t.length,o,f="value"in js?js.value:js.textContent,p=f.length;for(e=0;e<s&&t[e]===f[e];e++);var S=s-e;for(o=1;o<=S&&t[s-o]===f[p-o];o++);return va=f.slice(e,1<o?1-o:void 0)}function Ml(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 Nl(){return!0}function Tt(){return!1}function Zt(e){function t(s,o,f,p,S){this._reactName=s,this._targetInst=f,this.type=o,this.nativeEvent=p,this.target=S,this.currentTarget=null;for(var R in e)e.hasOwnProperty(R)&&(s=e[R],this[R]=s?s(p):p[R]);return this.isDefaultPrevented=(p.defaultPrevented!=null?p.defaultPrevented:p.returnValue===!1)?Nl:Tt,this.isPropagationStopped=Tt,this}return b(t.prototype,{preventDefault:function(){this.defaultPrevented=!0;var s=this.nativeEvent;s&&(s.preventDefault?s.preventDefault():typeof s.returnValue!="unknown"&&(s.returnValue=!1),this.isDefaultPrevented=Nl)},stopPropagation:function(){var s=this.nativeEvent;s&&(s.stopPropagation?s.stopPropagation():typeof s.cancelBubble!="unknown"&&(s.cancelBubble=!0),this.isPropagationStopped=Nl)},persist:function(){},isPersistent:Nl}),t}var Ea={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Qs=Zt(Ea),Xs=b({},Ea,{view:0,detail:0}),br=Zt(Xs),Zs,Ii,As,Ms=b({},Xs,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:ed,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!==As&&(As&&e.type==="mousemove"?(Zs=e.screenX-As.screenX,Ii=e.screenY-As.screenY):Ii=Zs=0,As=e),Zs)},movementY:function(e){return"movementY"in e?e.movementY:Ii}}),xr=Zt(Ms),zi=b({},Ms,{dataTransfer:0}),xo=Zt(zi),Tl=b({},Xs,{relatedTarget:0}),Oi=Zt(Tl),wo=b({},Ea,{animationName:0,elapsedTime:0,pseudoElement:0}),So=Zt(wo),Tc=b({},Ea,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),Ju=Zt(Tc),Js=b({},Ea,{data:0}),cs=Zt(Js),Ur={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},wr={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"},Zf={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Rc(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):(e=Zf[e])?!!t[e]:!1}function ed(){return Rc}var Jf=b({},Xs,{key:function(e){if(e.key){var t=Ur[e.key]||e.key;if(t!=="Unidentified")return t}return e.type==="keypress"?(e=Ml(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?wr[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:ed,charCode:function(e){return e.type==="keypress"?Ml(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?Ml(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),Hi=Zt(Jf),em=b({},Ms,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),qr=Zt(em),Ec=b({},Xs,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:ed}),Wp=Zt(Ec),Yp=b({},Ea,{propertyName:0,elapsedTime:0,pseudoElement:0}),Kp=Zt(Yp),tm=b({},Ms,{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}),td=Zt(tm),nd=b({},Ea,{newState:0,oldState:0}),nm=Zt(nd),am=[9,13,27,32],Dc=ks&&"CompositionEvent"in window,Gr=null;ks&&"documentMode"in document&&(Gr=document.documentMode);var Lc=ks&&"TextEvent"in window&&!Gr,Fi=ks&&(!Dc||Gr&&8<Gr&&11>=Gr),er=" ",Rl=!1;function _c(e,t){switch(e){case"keyup":return am.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Ic(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Vr=!1;function El(e,t){switch(e){case"compositionend":return Ic(t);case"keypress":return t.which!==32?null:(Rl=!0,er);case"textInput":return e=t.data,e===er&&Rl?null:e;default:return null}}function zc(e,t){if(Vr)return e==="compositionend"||!Dc&&_c(e,t)?(e=la(),va=Pa=js=null,Vr=!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 Fi&&t.locale!=="ko"?null:t.data;default:return null}}var Dl={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 pt(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t==="input"?!!Dl[e.type]:t==="textarea"}function Rt(e,t,s,o){vr?Ks?Ks.push(o):Ks=[o]:vr=o,t=Id(t,"onChange"),0<t.length&&(s=new Qs("onChange","change",null,s,o),e.push({event:s,listeners:t}))}var Bn=null,tr=null;function sm(e){Nv(e,0)}function Ll(e){var t=nn(e);if(Xu(t))return e}function Wr(e,t){if(e==="change")return t}var lt=!1;if(ks){var Co;if(ks){var Oc="oninput"in document;if(!Oc){var ko=document.createElement("div");ko.setAttribute("oninput","return;"),Oc=typeof ko.oninput=="function"}Co=Oc}else Co=!1;lt=Co&&(!document.documentMode||9<document.documentMode)}function Sr(){Bn&&(Bn.detachEvent("onpropertychange",Hc),tr=Bn=null)}function Hc(e){if(e.propertyName==="value"&&Ll(tr)){var t=[];Rt(t,tr,e,_i(e)),Al(sm,t)}}function Fc(e,t,s){e==="focusin"?(Sr(),Bn=t,tr=s,Bn.attachEvent("onpropertychange",Hc)):e==="focusout"&&Sr()}function Yr(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return Ll(tr)}function Da(e,t){if(e==="click")return Ll(t)}function $i(e,t){if(e==="input"||e==="change")return Ll(t)}function oa(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var an=typeof Object.is=="function"?Object.is:oa;function Ee(e,t){if(an(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;var s=Object.keys(e),o=Object.keys(t);if(s.length!==o.length)return!1;for(o=0;o<s.length;o++){var f=s[o];if(!We.call(t,f)||!an(e[f],t[f]))return!1}return!0}function $c(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function ad(e,t){var s=$c(e);e=0;for(var o;s;){if(s.nodeType===3){if(o=e+s.textContent.length,e<=t&&o>=t)return{node:s,offset:t-e};e=o}e:{for(;s;){if(s.nextSibling){s=s.nextSibling;break e}s=s.parentNode}s=void 0}s=$c(s)}}function sd(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?sd(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function jo(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Sl(e.document);t instanceof e.HTMLIFrameElement;){try{var s=typeof t.contentWindow.location.href=="string"}catch{s=!1}if(s)e=t.contentWindow;else break;t=Sl(e.document)}return t}function Kr(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 Qp=ks&&"documentMode"in document&&11>=document.documentMode,Qr=null,un=null,Bi=null,Pi=!1;function Xr(e,t,s){var o=s.window===s?s.document:s.nodeType===9?s:s.ownerDocument;Pi||Qr==null||Qr!==Sl(o)||(o=Qr,"selectionStart"in o&&Kr(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}),Bi&&Ee(Bi,o)||(Bi=o,o=Id(un,"onSelect"),0<o.length&&(t=new Qs("onSelect","select",null,t,s),e.push({event:t,listeners:o}),t.target=Qr)))}function Zr(e,t){var s={};return s[e.toLowerCase()]=t.toLowerCase(),s["Webkit"+e]="webkit"+t,s["Moz"+e]="moz"+t,s}var Ui={animationend:Zr("Animation","AnimationEnd"),animationiteration:Zr("Animation","AnimationIteration"),animationstart:Zr("Animation","AnimationStart"),transitionrun:Zr("Transition","TransitionRun"),transitionstart:Zr("Transition","TransitionStart"),transitioncancel:Zr("Transition","TransitionCancel"),transitionend:Zr("Transition","TransitionEnd")},Kt={},Jr={};ks&&(Jr=document.createElement("div").style,"AnimationEvent"in window||(delete Ui.animationend.animation,delete Ui.animationiteration.animation,delete Ui.animationstart.animation),"TransitionEvent"in window||delete Ui.transitionend.transition);function ei(e){if(Kt[e])return Kt[e];if(!Ui[e])return e;var t=Ui[e],s;for(s in t)if(t.hasOwnProperty(s)&&s in Jr)return Kt[e]=t[s];return e}var Ns=ei("animationend"),Bc=ei("animationiteration"),qi=ei("animationstart"),Pc=ei("transitionrun"),Ao=ei("transitionstart"),Mo=ei("transitioncancel"),Ua=ei("transitionend"),nr=new Map,Gi="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(" ");Gi.push("scrollEnd");function vn(e,t){nr.set(e,t),Sn(t,[e])}var Pn=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)},sn=[],Vi=0,No=0;function ar(){for(var e=Vi,t=No=Vi=0;t<e;){var s=sn[t];sn[t++]=null;var o=sn[t];sn[t++]=null;var f=sn[t];sn[t++]=null;var p=sn[t];if(sn[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}p!==0&&Ro(s,f,p)}}function To(e,t,s,o){sn[Vi++]=e,sn[Vi++]=t,sn[Vi++]=s,sn[Vi++]=o,No|=o,e.lanes|=o,e=e.alternate,e!==null&&(e.lanes|=o)}function La(e,t,s,o){return To(e,t,s,o),Rn(e)}function _a(e,t){return To(e,null,null,t),Rn(e)}function Ro(e,t,s){e.lanes|=s;var o=e.alternate;o!==null&&(o.lanes|=s);for(var f=!1,p=e.return;p!==null;)p.childLanes|=s,o=p.alternate,o!==null&&(o.childLanes|=s),p.tag===22&&(e=p.stateNode,e===null||e._visibility&1||(f=!0)),e=p,p=p.return;return e.tag===3?(p=e.stateNode,f&&t!==null&&(f=31-bt(s),e=p.hiddenUpdates,o=e[f],o===null?e[f]=[t]:o.push(t),t.lane=s|536870912),p):null}function Rn(e){if(50<fu)throw fu=0,zm=null,Error(l(185));for(var t=e.return;t!==null;)e=t,t=e.return;return e.tag===3?e.stateNode:null}var ca={};function Eo(e,t,s,o){this.tag=e,this.key=s,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=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 En(e,t,s,o){return new Eo(e,t,s,o)}function Ts(e){return e=e.prototype,!(!e||!e.isReactComponent)}function ya(e,t){var s=e.alternate;return s===null?(s=En(e.tag,t,e.key,e.mode),s.elementType=e.elementType,s.type=e.type,s.stateNode=e.stateNode,s.alternate=e,e.alternate=s):(s.pendingProps=t,s.type=e.type,s.flags=0,s.subtreeFlags=0,s.deletions=null),s.flags=e.flags&65011712,s.childLanes=e.childLanes,s.lanes=e.lanes,s.child=e.child,s.memoizedProps=e.memoizedProps,s.memoizedState=e.memoizedState,s.updateQueue=e.updateQueue,t=e.dependencies,s.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},s.sibling=e.sibling,s.index=e.index,s.ref=e.ref,s.refCleanup=e.refCleanup,s}function _l(e,t){e.flags&=65011714;var s=e.alternate;return s===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=s.childLanes,e.lanes=s.lanes,e.child=s.child,e.subtreeFlags=0,e.deletions=null,e.memoizedProps=s.memoizedProps,e.memoizedState=s.memoizedState,e.updateQueue=s.updateQueue,e.type=s.type,t=s.dependencies,e.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext}),e}function qa(e,t,s,o,f,p){var S=0;if(o=e,typeof e=="function")Ts(e)&&(S=1);else if(typeof e=="string")S=WS(e,s,he.current)?26:e==="html"||e==="head"||e==="body"?27:5;else e:switch(e){case q:return e=En(31,s,t,f),e.elementType=q,e.lanes=p,e;case k:return Cr(s.children,f,p,t);case N:S=8,f|=24;break;case M:return e=En(12,s,t,f|2),e.elementType=M,e.lanes=p,e;case $:return e=En(13,s,t,f),e.elementType=$,e.lanes=p,e;case G:return e=En(19,s,t,f),e.elementType=G,e.lanes=p,e;default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case D:S=10;break e;case T:S=9;break e;case F:S=11;break e;case L:S=14;break e;case Q:S=16,o=null;break e}S=29,s=Error(l(130,e===null?"null":typeof e,"")),o=null}return t=En(S,s,t,f),t.elementType=e,t.type=o,t.lanes=p,t}function Cr(e,t,s,o){return e=En(7,e,o,t),e.lanes=s,e}function Uc(e,t,s){return e=En(6,e,null,t),e.lanes=s,e}function Il(e){var t=En(18,null,null,0);return t.stateNode=e,t}function Wi(e,t,s){return t=En(4,e.children!==null?e.children:[],e.key,t),t.lanes=s,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}var qc=new WeakMap;function Un(e,t){if(typeof e=="object"&&e!==null){var s=qc.get(e);return s!==void 0?s:(t={value:e,source:t,stack:Xe(t)},qc.set(e,t),t)}return{value:e,source:t,stack:Xe(t)}}var ti=[],ni=0,Do=null,Rs=0,Ga=[],Ia=0,kr=null,Es=1,us="";function Va(e,t){ti[ni++]=Rs,ti[ni++]=Do,Do=e,Rs=t}function rd(e,t,s){Ga[Ia++]=Es,Ga[Ia++]=us,Ga[Ia++]=kr,kr=e;var o=Es;e=us;var f=32-bt(o)-1;o&=~(1<<f),s+=1;var p=32-bt(t)+f;if(30<p){var S=f-f%5;p=(o&(1<<S)-1).toString(32),o>>=S,f-=S,Es=1<<32-bt(t)+f|s<<f|o,us=p+e}else Es=1<<p|s<<f|o,us=e}function Lo(e){e.return!==null&&(Va(e,1),rd(e,1,0))}function ai(e){for(;e===Do;)Do=ti[--ni],ti[ni]=null,Rs=ti[--ni],ti[ni]=null;for(;e===kr;)kr=Ga[--Ia],Ga[Ia]=null,us=Ga[--Ia],Ga[Ia]=null,Es=Ga[--Ia],Ga[Ia]=null}function Gc(e,t){Ga[Ia++]=Es,Ga[Ia++]=us,Ga[Ia++]=kr,Es=t.id,us=t.overflow,kr=e}var rn=null,Gt=null,wt=!1,ba=null,xa=!1,Vc=Error(l(519));function sr(e){var t=Error(l(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw Ki(Un(t,e)),Vc}function zl(e){var t=e.stateNode,s=e.type,o=e.memoizedProps;switch(t[re]=e,t[Te]=o,s){case"dialog":Lt("cancel",t),Lt("close",t);break;case"iframe":case"object":case"embed":Lt("load",t);break;case"video":case"audio":for(s=0;s<hu.length;s++)Lt(hu[s],t);break;case"source":Lt("error",t);break;case"img":case"image":case"link":Lt("error",t),Lt("load",t);break;case"details":Lt("toggle",t);break;case"input":Lt("invalid",t),Li(t,o.value,o.defaultValue,o.checked,o.defaultChecked,o.type,o.name,!0);break;case"select":Lt("invalid",t);break;case"textarea":Lt("invalid",t),$r(t,o.value,o.defaultValue,o.children)}s=o.children,typeof s!="string"&&typeof s!="number"&&typeof s!="bigint"||t.textContent===""+s||o.suppressHydrationWarning===!0||Dv(t.textContent,s)?(o.popover!=null&&(Lt("beforetoggle",t),Lt("toggle",t)),o.onScroll!=null&&Lt("scroll",t),o.onScrollEnd!=null&&Lt("scrollend",t),o.onClick!=null&&(t.onclick=ra),t=!0):t=!1,t||sr(e,!0)}function _o(e){for(rn=e.return;rn;)switch(rn.tag){case 5:case 31:case 13:xa=!1;return;case 27:case 3:xa=!0;return;default:rn=rn.return}}function Ds(e){if(e!==rn)return!1;if(!wt)return _o(e),wt=!0,!1;var t=e.tag,s;if((s=t!==3&&t!==27)&&((s=t===5)&&(s=e.type,s=!(s!=="form"&&s!=="button")||Xm(e.type,e.memoizedProps)),s=!s),s&&Gt&&sr(e),_o(e),t===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(l(317));Gt=Bv(e)}else if(t===31){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(l(317));Gt=Bv(e)}else t===27?(t=Gt,ol(e.type)?(e=nh,nh=null,Gt=e):Gt=t):Gt=rn?$s(e.stateNode.nextSibling):null;return!0}function si(){Gt=rn=null,wt=!1}function Yi(){var e=ba;return e!==null&&(ns===null?ns=e:ns.push.apply(ns,e),ba=null),e}function Ki(e){ba===null?ba=[e]:ba.push(e)}var ri=ce(null),rr=null,Wa=null;function ds(e,t,s){be(ri,t._currentValue),t._currentValue=s}function Ya(e){e._currentValue=ri.current,K(ri)}function ir(e,t,s){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===s)break;e=e.return}}function Io(e,t,s,o){var f=e.child;for(f!==null&&(f.return=e);f!==null;){var p=f.dependencies;if(p!==null){var S=f.child;p=p.firstContext;e:for(;p!==null;){var R=p;p=f;for(var V=0;V<t.length;V++)if(R.context===t[V]){p.lanes|=s,R=p.alternate,R!==null&&(R.lanes|=s),ir(p.return,s,e),o||(S=null);break e}p=R.next}}else if(f.tag===18){if(S=f.return,S===null)throw Error(l(341));S.lanes|=s,p=S.alternate,p!==null&&(p.lanes|=s),ir(S,s,e),S=null}else S=f.child;if(S!==null)S.return=f;else for(S=f;S!==null;){if(S===e){S=null;break}if(f=S.sibling,f!==null){f.return=S.return,S=f;break}S=S.return}f=S}}function ii(e,t,s,o){e=null;for(var f=t,p=!1;f!==null;){if(!p){if((f.flags&524288)!==0)p=!0;else if((f.flags&262144)!==0)break}if(f.tag===10){var S=f.alternate;if(S===null)throw Error(l(387));if(S=S.memoizedProps,S!==null){var R=f.type;an(f.pendingProps.value,S.value)||(e!==null?e.push(R):e=[R])}}else if(f===we.current){if(S=f.alternate,S===null)throw Error(l(387));S.memoizedState.memoizedState!==f.memoizedState.memoizedState&&(e!==null?e.push(bu):e=[bu])}f=f.return}e!==null&&Io(t,e,s,o),t.flags|=262144}function lr(e){for(e=e.firstContext;e!==null;){if(!an(e.context._currentValue,e.memoizedValue))return!0;e=e.next}return!1}function Ka(e){rr=e,Wa=null,e=e.dependencies,e!==null&&(e.firstContext=null)}function ln(e){return li(rr,e)}function za(e,t){return rr===null&&Ka(e),li(e,t)}function li(e,t){var s=t._currentValue;if(t={context:t,memoizedValue:s,next:null},Wa===null){if(e===null)throw Error(l(308));Wa=t,e.dependencies={lanes:0,firstContext:t},e.flags|=524288}else Wa=Wa.next=t;return s}var id=typeof AbortController<"u"?AbortController:function(){var e=[],t=this.signal={aborted:!1,addEventListener:function(s,o){e.push(o)}};this.abort=function(){t.aborted=!0,e.forEach(function(s){return s()})}},zo=n.unstable_scheduleCallback,jr=n.unstable_NormalPriority,kn={$$typeof:D,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function Oo(){return{controller:new id,data:new Map,refCount:0}}function or(e){e.refCount--,e.refCount===0&&zo(jr,function(){e.controller.abort()})}var Ar=null,Ol=0,oi=0,ua=null;function ld(e,t){if(Ar===null){var s=Ar=[];Ol=0,oi=Pm(),ua={status:"pending",value:void 0,then:function(o){s.push(o)}}}return Ol++,t.then(Ho,Ho),t}function Ho(){if(--Ol===0&&Ar!==null){ua!==null&&(ua.status="fulfilled");var e=Ar;Ar=null,oi=0,ua=null;for(var t=0;t<e.length;t++)(0,e[t])()}}function Wc(e,t){var s=[],o={status:"pending",value:null,reason:null,then:function(f){s.push(f)}};return e.then(function(){o.status="fulfilled",o.value=t;for(var f=0;f<s.length;f++)(0,s[f])(t)},function(f){for(o.status="rejected",o.reason=f,f=0;f<s.length;f++)(0,s[f])(void 0)}),o}var Fo=z.S;z.S=function(e,t){nv=Ae(),typeof t=="object"&&t!==null&&typeof t.then=="function"&&ld(e,t),Fo!==null&&Fo(e,t)};var cr=ce(null);function $o(){var e=cr.current;return e!==null?e:tn.pooledCache}function Mr(e,t){t===null?be(cr,cr.current):be(cr,t.pool)}function Ls(){var e=$o();return e===null?null:{parent:kn._currentValue,pool:e}}var Nr=Error(l(460)),Yc=Error(l(474)),Hl=Error(l(542)),Dn={then:function(){}};function Kc(e){return e=e.status,e==="fulfilled"||e==="rejected"}function Fl(e,t,s){switch(s=e[s],s===void 0?e.push(t):s!==t&&(t.then(ra,ra),t=s),t.status){case"fulfilled":return t.value;case"rejected":throw e=t.reason,Bo(e),e;default:if(typeof t.status=="string")t.then(ra,ra);else{if(e=tn,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,Bo(e),e}throw Tr=t,Nr}}function _s(e){try{var t=e._init;return t(e._payload)}catch(s){throw s!==null&&typeof s=="object"&&typeof s.then=="function"?(Tr=s,Nr):s}}var Tr=null;function Qi(){if(Tr===null)throw Error(l(459));var e=Tr;return Tr=null,e}function Bo(e){if(e===Nr||e===Hl)throw Error(l(483))}var Is=null,$l=0;function Bl(e){var t=$l;return $l+=1,Is===null&&(Is=[]),Fl(Is,e,t)}function ur(e,t){t=t.props.ref,e.ref=t!==void 0?t:null}function Po(e,t){throw t.$$typeof===w?Error(l(525)):(e=Object.prototype.toString.call(t),Error(l(31,e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)))}function od(e){function t(ae,X){if(e){var oe=ae.deletions;oe===null?(ae.deletions=[X],ae.flags|=16):oe.push(X)}}function s(ae,X){if(!e)return null;for(;X!==null;)t(ae,X),X=X.sibling;return null}function o(ae){for(var X=new Map;ae!==null;)ae.key!==null?X.set(ae.key,ae):X.set(ae.index,ae),ae=ae.sibling;return X}function f(ae,X){return ae=ya(ae,X),ae.index=0,ae.sibling=null,ae}function p(ae,X,oe){return ae.index=oe,e?(oe=ae.alternate,oe!==null?(oe=oe.index,oe<X?(ae.flags|=67108866,X):oe):(ae.flags|=67108866,X)):(ae.flags|=1048576,X)}function S(ae){return e&&ae.alternate===null&&(ae.flags|=67108866),ae}function R(ae,X,oe,Se){return X===null||X.tag!==6?(X=Uc(oe,ae.mode,Se),X.return=ae,X):(X=f(X,oe),X.return=ae,X)}function V(ae,X,oe,Se){var rt=oe.type;return rt===k?xe(ae,X,oe.props.children,Se,oe.key):X!==null&&(X.elementType===rt||typeof rt=="object"&&rt!==null&&rt.$$typeof===Q&&_s(rt)===X.type)?(X=f(X,oe.props),ur(X,oe),X.return=ae,X):(X=qa(oe.type,oe.key,oe.props,null,ae.mode,Se),ur(X,oe),X.return=ae,X)}function ue(ae,X,oe,Se){return X===null||X.tag!==4||X.stateNode.containerInfo!==oe.containerInfo||X.stateNode.implementation!==oe.implementation?(X=Wi(oe,ae.mode,Se),X.return=ae,X):(X=f(X,oe.children||[]),X.return=ae,X)}function xe(ae,X,oe,Se,rt){return X===null||X.tag!==7?(X=Cr(oe,ae.mode,Se,rt),X.return=ae,X):(X=f(X,oe),X.return=ae,X)}function ke(ae,X,oe){if(typeof X=="string"&&X!==""||typeof X=="number"||typeof X=="bigint")return X=Uc(""+X,ae.mode,oe),X.return=ae,X;if(typeof X=="object"&&X!==null){switch(X.$$typeof){case A:return oe=qa(X.type,X.key,X.props,null,ae.mode,oe),ur(oe,X),oe.return=ae,oe;case j:return X=Wi(X,ae.mode,oe),X.return=ae,X;case Q:return X=_s(X),ke(ae,X,oe)}if(Z(X)||H(X))return X=Cr(X,ae.mode,oe,null),X.return=ae,X;if(typeof X.then=="function")return ke(ae,Bl(X),oe);if(X.$$typeof===D)return ke(ae,za(ae,X),oe);Po(ae,X)}return null}function me(ae,X,oe,Se){var rt=X!==null?X.key:null;if(typeof oe=="string"&&oe!==""||typeof oe=="number"||typeof oe=="bigint")return rt!==null?null:R(ae,X,""+oe,Se);if(typeof oe=="object"&&oe!==null){switch(oe.$$typeof){case A:return oe.key===rt?V(ae,X,oe,Se):null;case j:return oe.key===rt?ue(ae,X,oe,Se):null;case Q:return oe=_s(oe),me(ae,X,oe,Se)}if(Z(oe)||H(oe))return rt!==null?null:xe(ae,X,oe,Se,null);if(typeof oe.then=="function")return me(ae,X,Bl(oe),Se);if(oe.$$typeof===D)return me(ae,X,za(ae,oe),Se);Po(ae,oe)}return null}function ge(ae,X,oe,Se,rt){if(typeof Se=="string"&&Se!==""||typeof Se=="number"||typeof Se=="bigint")return ae=ae.get(oe)||null,R(X,ae,""+Se,rt);if(typeof Se=="object"&&Se!==null){switch(Se.$$typeof){case A:return ae=ae.get(Se.key===null?oe:Se.key)||null,V(X,ae,Se,rt);case j:return ae=ae.get(Se.key===null?oe:Se.key)||null,ue(X,ae,Se,rt);case Q:return Se=_s(Se),ge(ae,X,oe,Se,rt)}if(Z(Se)||H(Se))return ae=ae.get(oe)||null,xe(X,ae,Se,rt,null);if(typeof Se.then=="function")return ge(ae,X,oe,Bl(Se),rt);if(Se.$$typeof===D)return ge(ae,X,oe,za(X,Se),rt);Po(X,Se)}return null}function Qe(ae,X,oe,Se){for(var rt=null,Ht=null,Je=X,jt=X=0,It=null;Je!==null&&jt<oe.length;jt++){Je.index>jt?(It=Je,Je=null):It=Je.sibling;var Ft=me(ae,Je,oe[jt],Se);if(Ft===null){Je===null&&(Je=It);break}e&&Je&&Ft.alternate===null&&t(ae,Je),X=p(Ft,X,jt),Ht===null?rt=Ft:Ht.sibling=Ft,Ht=Ft,Je=It}if(jt===oe.length)return s(ae,Je),wt&&Va(ae,jt),rt;if(Je===null){for(;jt<oe.length;jt++)Je=ke(ae,oe[jt],Se),Je!==null&&(X=p(Je,X,jt),Ht===null?rt=Je:Ht.sibling=Je,Ht=Je);return wt&&Va(ae,jt),rt}for(Je=o(Je);jt<oe.length;jt++)It=ge(Je,ae,jt,oe[jt],Se),It!==null&&(e&&It.alternate!==null&&Je.delete(It.key===null?jt:It.key),X=p(It,X,jt),Ht===null?rt=It:Ht.sibling=It,Ht=It);return e&&Je.forEach(function(ml){return t(ae,ml)}),wt&&Va(ae,jt),rt}function ut(ae,X,oe,Se){if(oe==null)throw Error(l(151));for(var rt=null,Ht=null,Je=X,jt=X=0,It=null,Ft=oe.next();Je!==null&&!Ft.done;jt++,Ft=oe.next()){Je.index>jt?(It=Je,Je=null):It=Je.sibling;var ml=me(ae,Je,Ft.value,Se);if(ml===null){Je===null&&(Je=It);break}e&&Je&&ml.alternate===null&&t(ae,Je),X=p(ml,X,jt),Ht===null?rt=ml:Ht.sibling=ml,Ht=ml,Je=It}if(Ft.done)return s(ae,Je),wt&&Va(ae,jt),rt;if(Je===null){for(;!Ft.done;jt++,Ft=oe.next())Ft=ke(ae,Ft.value,Se),Ft!==null&&(X=p(Ft,X,jt),Ht===null?rt=Ft:Ht.sibling=Ft,Ht=Ft);return wt&&Va(ae,jt),rt}for(Je=o(Je);!Ft.done;jt++,Ft=oe.next())Ft=ge(Je,ae,jt,Ft.value,Se),Ft!==null&&(e&&Ft.alternate!==null&&Je.delete(Ft.key===null?jt:Ft.key),X=p(Ft,X,jt),Ht===null?rt=Ft:Ht.sibling=Ft,Ht=Ft);return e&&Je.forEach(function(s0){return t(ae,s0)}),wt&&Va(ae,jt),rt}function Xt(ae,X,oe,Se){if(typeof oe=="object"&&oe!==null&&oe.type===k&&oe.key===null&&(oe=oe.props.children),typeof oe=="object"&&oe!==null){switch(oe.$$typeof){case A:e:{for(var rt=oe.key;X!==null;){if(X.key===rt){if(rt=oe.type,rt===k){if(X.tag===7){s(ae,X.sibling),Se=f(X,oe.props.children),Se.return=ae,ae=Se;break e}}else if(X.elementType===rt||typeof rt=="object"&&rt!==null&&rt.$$typeof===Q&&_s(rt)===X.type){s(ae,X.sibling),Se=f(X,oe.props),ur(Se,oe),Se.return=ae,ae=Se;break e}s(ae,X);break}else t(ae,X);X=X.sibling}oe.type===k?(Se=Cr(oe.props.children,ae.mode,Se,oe.key),Se.return=ae,ae=Se):(Se=qa(oe.type,oe.key,oe.props,null,ae.mode,Se),ur(Se,oe),Se.return=ae,ae=Se)}return S(ae);case j:e:{for(rt=oe.key;X!==null;){if(X.key===rt)if(X.tag===4&&X.stateNode.containerInfo===oe.containerInfo&&X.stateNode.implementation===oe.implementation){s(ae,X.sibling),Se=f(X,oe.children||[]),Se.return=ae,ae=Se;break e}else{s(ae,X);break}else t(ae,X);X=X.sibling}Se=Wi(oe,ae.mode,Se),Se.return=ae,ae=Se}return S(ae);case Q:return oe=_s(oe),Xt(ae,X,oe,Se)}if(Z(oe))return Qe(ae,X,oe,Se);if(H(oe)){if(rt=H(oe),typeof rt!="function")throw Error(l(150));return oe=rt.call(oe),ut(ae,X,oe,Se)}if(typeof oe.then=="function")return Xt(ae,X,Bl(oe),Se);if(oe.$$typeof===D)return Xt(ae,X,za(ae,oe),Se);Po(ae,oe)}return typeof oe=="string"&&oe!==""||typeof oe=="number"||typeof oe=="bigint"?(oe=""+oe,X!==null&&X.tag===6?(s(ae,X.sibling),Se=f(X,oe),Se.return=ae,ae=Se):(s(ae,X),Se=Uc(oe,ae.mode,Se),Se.return=ae,ae=Se),S(ae)):s(ae,X)}return function(ae,X,oe,Se){try{$l=0;var rt=Xt(ae,X,oe,Se);return Is=null,rt}catch(Je){if(Je===Nr||Je===Hl)throw Je;var Ht=En(29,Je,null,ae.mode);return Ht.lanes=Se,Ht.return=ae,Ht}}}var ci=od(!0),cd=od(!1),zs=!1;function Pl(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function ui(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 dr(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Os(e,t,s){var o=e.updateQueue;if(o===null)return null;if(o=o.shared,(Pt&2)!==0){var f=o.pending;return f===null?t.next=t:(t.next=f.next,f.next=t),o.pending=t,t=Rn(e),Ro(e,null,s),t}return To(e,o,t,s),Rn(e)}function Ul(e,t,s){if(t=t.updateQueue,t!==null&&(t=t.shared,(s&4194048)!==0)){var o=t.lanes;o&=e.pendingLanes,s|=o,t.lanes=s,B(e,s)}}function di(e,t){var s=e.updateQueue,o=e.alternate;if(o!==null&&(o=o.updateQueue,s===o)){var f=null,p=null;if(s=s.firstBaseUpdate,s!==null){do{var S={lane:s.lane,tag:s.tag,payload:s.payload,callback:null,next:null};p===null?f=p=S:p=p.next=S,s=s.next}while(s!==null);p===null?f=p=t:p=p.next=t}else f=p=t;s={baseState:o.baseState,firstBaseUpdate:f,lastBaseUpdate:p,shared:o.shared,callbacks:o.callbacks},e.updateQueue=s;return}e=s.lastBaseUpdate,e===null?s.firstBaseUpdate=t:e.next=t,s.lastBaseUpdate=t}var Qc=!1;function ql(){if(Qc){var e=ua;if(e!==null)throw e}}function Gl(e,t,s,o){Qc=!1;var f=e.updateQueue;zs=!1;var p=f.firstBaseUpdate,S=f.lastBaseUpdate,R=f.shared.pending;if(R!==null){f.shared.pending=null;var V=R,ue=V.next;V.next=null,S===null?p=ue:S.next=ue,S=V;var xe=e.alternate;xe!==null&&(xe=xe.updateQueue,R=xe.lastBaseUpdate,R!==S&&(R===null?xe.firstBaseUpdate=ue:R.next=ue,xe.lastBaseUpdate=V))}if(p!==null){var ke=f.baseState;S=0,xe=ue=V=null,R=p;do{var me=R.lane&-536870913,ge=me!==R.lane;if(ge?(_t&me)===me:(o&me)===me){me!==0&&me===oi&&(Qc=!0),xe!==null&&(xe=xe.next={lane:0,tag:R.tag,payload:R.payload,callback:null,next:null});e:{var Qe=e,ut=R;me=t;var Xt=s;switch(ut.tag){case 1:if(Qe=ut.payload,typeof Qe=="function"){ke=Qe.call(Xt,ke,me);break e}ke=Qe;break e;case 3:Qe.flags=Qe.flags&-65537|128;case 0:if(Qe=ut.payload,me=typeof Qe=="function"?Qe.call(Xt,ke,me):Qe,me==null)break e;ke=b({},ke,me);break e;case 2:zs=!0}}me=R.callback,me!==null&&(e.flags|=64,ge&&(e.flags|=8192),ge=f.callbacks,ge===null?f.callbacks=[me]:ge.push(me))}else ge={lane:me,tag:R.tag,payload:R.payload,callback:R.callback,next:null},xe===null?(ue=xe=ge,V=ke):xe=xe.next=ge,S|=me;if(R=R.next,R===null){if(R=f.shared.pending,R===null)break;ge=R,R=ge.next,ge.next=null,f.lastBaseUpdate=ge,f.shared.pending=null}}while(!0);xe===null&&(V=ke),f.baseState=V,f.firstBaseUpdate=ue,f.lastBaseUpdate=xe,p===null&&(f.shared.lanes=0),al|=S,e.lanes=S,e.memoizedState=ke}}function Uo(e,t){if(typeof e!="function")throw Error(l(191,e));e.call(t)}function Xc(e,t){var s=e.callbacks;if(s!==null)for(e.callbacks=null,e=0;e<s.length;e++)Uo(s[e],t)}var fi=ce(null),Vl=ce(0);function ud(e,t){e=ki,be(Vl,e),be(fi,t),ki=e|t.baseLanes}function Wl(){be(Vl,ki),be(fi,fi.current)}function Xi(){ki=Vl.current,K(fi),K(Vl)}var wa=ce(null),Sa=null;function Hs(e){var t=e.alternate;be(yn,yn.current&1),be(wa,e),Sa===null&&(t===null||fi.current!==null||t.memoizedState!==null)&&(Sa=e)}function Ie(e){be(yn,yn.current),be(wa,e),Sa===null&&(Sa=e)}function Yl(e){e.tag===22?(be(yn,yn.current),be(wa,e),Sa===null&&(Sa=e)):fr()}function fr(){be(yn,yn.current),be(wa,wa.current)}function Oa(e){K(wa),Sa===e&&(Sa=null),K(yn)}var yn=ce(0);function Zi(e){for(var t=e;t!==null;){if(t.tag===13){var s=t.memoizedState;if(s!==null&&(s=s.dehydrated,s===null||eh(s)||th(s)))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 Qa=0,et=null,St=null,at=null,qo=!1,fs=!1,Xa=!1,Kl=0,Ji=0,mi=null,Ql=0;function Jt(){throw Error(l(321))}function Zc(e,t){if(t===null)return!1;for(var s=0;s<t.length&&s<e.length;s++)if(!an(e[s],t[s]))return!1;return!0}function Go(e,t,s,o,f,p){return Qa=p,et=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,z.H=e===null||e.memoizedState===null?mg:dm,Xa=!1,p=s(o,f),Xa=!1,fs&&(p=dd(t,s,o,f)),Vo(e),p}function Vo(e){z.H=au;var t=St!==null&&St.next!==null;if(Qa=0,at=St=et=null,qo=!1,Ji=0,mi=null,t)throw Error(l(300));e===null||Ln||(e=e.dependencies,e!==null&&lr(e)&&(Ln=!0))}function dd(e,t,s,o){et=e;var f=0;do{if(fs&&(mi=null),Ji=0,fs=!1,25<=f)throw Error(l(301));if(f+=1,at=St=null,e.updateQueue!=null){var p=e.updateQueue;p.lastEffect=null,p.events=null,p.stores=null,p.memoCache!=null&&(p.memoCache.index=0)}z.H=hg,p=t(s,o)}while(fs);return p}function rm(){var e=z.H,t=e.useState()[0];return t=typeof t.then=="function"?Yo(t):t,e=e.useState()[0],(St!==null?St.memoizedState:null)!==e&&(et.flags|=1024),t}function Xl(){var e=Kl!==0;return Kl=0,e}function Jc(e,t,s){t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~s}function eu(e){if(qo){for(e=e.memoizedState;e!==null;){var t=e.queue;t!==null&&(t.pending=null),e=e.next}qo=!1}Qa=0,at=St=et=null,fs=!1,Ji=Kl=0,mi=null}function $t(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return at===null?et.memoizedState=at=e:at=at.next=e,at}function on(){if(St===null){var e=et.alternate;e=e!==null?e.memoizedState:null}else e=St.next;var t=at===null?et.memoizedState:at.next;if(t!==null)at=t,St=e;else{if(e===null)throw et.alternate===null?Error(l(467)):Error(l(310));St=e,e={memoizedState:St.memoizedState,baseState:St.baseState,baseQueue:St.baseQueue,queue:St.queue,next:null},at===null?et.memoizedState=at=e:at=at.next=e}return at}function Wo(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function Yo(e){var t=Ji;return Ji+=1,mi===null&&(mi=[]),e=Fl(mi,e,t),t=et,(at===null?t.memoizedState:at.next)===null&&(t=t.alternate,z.H=t===null||t.memoizedState===null?mg:dm),e}function Ko(e){if(e!==null&&typeof e=="object"){if(typeof e.then=="function")return Yo(e);if(e.$$typeof===D)return ln(e)}throw Error(l(438,String(e)))}function tu(e){var t=null,s=et.updateQueue;if(s!==null&&(t=s.memoCache),t==null){var o=et.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}),s===null&&(s=Wo(),et.updateQueue=s),s.memoCache=t,s=t.data[t.index],s===void 0)for(s=t.data[t.index]=Array(e),o=0;o<e;o++)s[o]=P;return t.index++,s}function Fs(e,t){return typeof t=="function"?t(e):t}function hi(e){var t=on();return pi(t,St,e)}function pi(e,t,s){var o=e.queue;if(o===null)throw Error(l(311));o.lastRenderedReducer=s;var f=e.baseQueue,p=o.pending;if(p!==null){if(f!==null){var S=f.next;f.next=p.next,p.next=S}t.baseQueue=f=p,o.pending=null}if(p=e.baseState,f===null)e.memoizedState=p;else{t=f.next;var R=S=null,V=null,ue=t,xe=!1;do{var ke=ue.lane&-536870913;if(ke!==ue.lane?(_t&ke)===ke:(Qa&ke)===ke){var me=ue.revertLane;if(me===0)V!==null&&(V=V.next={lane:0,revertLane:0,gesture:null,action:ue.action,hasEagerState:ue.hasEagerState,eagerState:ue.eagerState,next:null}),ke===oi&&(xe=!0);else if((Qa&me)===me){ue=ue.next,me===oi&&(xe=!0);continue}else ke={lane:0,revertLane:ue.revertLane,gesture:null,action:ue.action,hasEagerState:ue.hasEagerState,eagerState:ue.eagerState,next:null},V===null?(R=V=ke,S=p):V=V.next=ke,et.lanes|=me,al|=me;ke=ue.action,Xa&&s(p,ke),p=ue.hasEagerState?ue.eagerState:s(p,ke)}else me={lane:ke,revertLane:ue.revertLane,gesture:ue.gesture,action:ue.action,hasEagerState:ue.hasEagerState,eagerState:ue.eagerState,next:null},V===null?(R=V=me,S=p):V=V.next=me,et.lanes|=ke,al|=ke;ue=ue.next}while(ue!==null&&ue!==t);if(V===null?S=p:V.next=R,!an(p,e.memoizedState)&&(Ln=!0,xe&&(s=ua,s!==null)))throw s;e.memoizedState=p,e.baseState=S,e.baseQueue=V,o.lastRenderedState=p}return f===null&&(o.lanes=0),[e.memoizedState,o.dispatch]}function Qo(e){var t=on(),s=t.queue;if(s===null)throw Error(l(311));s.lastRenderedReducer=e;var o=s.dispatch,f=s.pending,p=t.memoizedState;if(f!==null){s.pending=null;var S=f=f.next;do p=e(p,S.action),S=S.next;while(S!==f);an(p,t.memoizedState)||(Ln=!0),t.memoizedState=p,t.baseQueue===null&&(t.baseState=p),s.lastRenderedState=p}return[p,o]}function fd(e,t,s){var o=et,f=on(),p=wt;if(p){if(s===void 0)throw Error(l(407));s=s()}else s=t();var S=!an((St||f).memoizedState,s);if(S&&(f.memoizedState=s,Ln=!0),f=f.queue,el(Xo.bind(null,o,f,e),[e]),f.getSnapshot!==t||S||at!==null&&at.memoizedState.tag&1){if(o.flags|=2048,en(9,{destroy:void 0},hd.bind(null,o,f,s,t),null),tn===null)throw Error(l(349));p||(Qa&127)!==0||md(o,t,s)}return s}function md(e,t,s){e.flags|=16384,e={getSnapshot:t,value:s},t=et.updateQueue,t===null?(t=Wo(),et.updateQueue=t,t.stores=[e]):(s=t.stores,s===null?t.stores=[e]:s.push(e))}function hd(e,t,s,o){t.value=s,t.getSnapshot=o,gi(t)&&pd(e)}function Xo(e,t,s){return s(function(){gi(t)&&pd(e)})}function gi(e){var t=e.getSnapshot;e=e.value;try{var s=t();return!an(e,s)}catch{return!0}}function pd(e){var t=_a(e,2);t!==null&&as(t,e,2)}function mr(e){var t=$t();if(typeof e=="function"){var s=e;if(e=s(),Xa){ct(!0);try{s()}finally{ct(!1)}}}return t.memoizedState=t.baseState=e,t.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Fs,lastRenderedState:e},t}function Zo(e,t,s,o){return e.baseState=s,pi(e,St,typeof o=="function"?o:Fs)}function v(e,t,s,o,f){if(gd(e))throw Error(l(485));if(e=t.action,e!==null){var p={payload:f,action:e,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(S){p.listeners.push(S)}};z.T!==null?s(!0):p.isTransition=!1,o(p),s=t.pending,s===null?(p.next=t.pending=p,C(t,p)):(p.next=s.next,t.pending=s.next=p)}}function C(e,t){var s=t.action,o=t.payload,f=e.state;if(t.isTransition){var p=z.T,S={};z.T=S;try{var R=s(f,o),V=z.S;V!==null&&V(S,R),E(e,t,R)}catch(ue){_(e,t,ue)}finally{p!==null&&S.types!==null&&(p.types=S.types),z.T=p}}else try{p=s(f,o),E(e,t,p)}catch(ue){_(e,t,ue)}}function E(e,t,s){s!==null&&typeof s=="object"&&typeof s.then=="function"?s.then(function(o){I(e,t,o)},function(o){return _(e,t,o)}):I(e,t,s)}function I(e,t,s){t.status="fulfilled",t.value=s,te(t),e.state=s,t=e.pending,t!==null&&(s=t.next,s===t?e.pending=null:(s=s.next,t.next=s,C(e,s)))}function _(e,t,s){var o=e.pending;if(e.pending=null,o!==null){o=o.next;do t.status="rejected",t.reason=s,te(t),t=t.next;while(t!==o)}e.action=null}function te(e){e=e.listeners;for(var t=0;t<e.length;t++)(0,e[t])()}function ie(e,t){return t}function Ne(e,t){if(wt){var s=tn.formState;if(s!==null){e:{var o=et;if(wt){if(Gt){t:{for(var f=Gt,p=xa;f.nodeType!==8;){if(!p){f=null;break t}if(f=$s(f.nextSibling),f===null){f=null;break t}}p=f.data,f=p==="F!"||p==="F"?f:null}if(f){Gt=$s(f.nextSibling),o=f.data==="F!";break e}}sr(o)}o=!1}o&&(t=s[0])}}return s=$t(),s.memoizedState=s.baseState=t,o={pending:null,lanes:0,dispatch:null,lastRenderedReducer:ie,lastRenderedState:t},s.queue=o,s=ug.bind(null,et,o),o.dispatch=s,o=mr(!1),p=um.bind(null,et,!1,o.queue),o=$t(),f={state:t,dispatch:null,action:e,pending:null},o.queue=f,s=v.bind(null,et,f,p,s),f.dispatch=s,o.memoizedState=e,[t,s,!1]}function Re(e){var t=on();return Ue(t,St,e)}function Ue(e,t,s){if(t=pi(e,t,ie)[0],e=hi(Fs)[0],typeof t=="object"&&t!==null&&typeof t.then=="function")try{var o=Yo(t)}catch(S){throw S===Nr?Hl:S}else o=t;t=on();var f=t.queue,p=f.dispatch;return s!==t.memoizedState&&(et.flags|=2048,en(9,{destroy:void 0},Bt.bind(null,f,s),null)),[o,p,e]}function Bt(e,t){e.action=t}function xt(e){var t=on(),s=St;if(s!==null)return Ue(t,s,e);on(),t=t.memoizedState,s=on();var o=s.queue.dispatch;return s.memoizedState=e,[t,o,!1]}function en(e,t,s,o){return e={tag:e,create:s,deps:o,inst:t,next:null},t=et.updateQueue,t===null&&(t=Wo(),et.updateQueue=t),s=t.lastEffect,s===null?t.lastEffect=e.next=e:(o=s.next,s.next=e,e.next=o,t.lastEffect=e),e}function Ca(){return on().memoizedState}function Qn(e,t,s,o){var f=$t();et.flags|=e,f.memoizedState=en(1|t,{destroy:void 0},s,o===void 0?null:o)}function Za(e,t,s,o){var f=on();o=o===void 0?null:o;var p=f.memoizedState.inst;St!==null&&o!==null&&Zc(o,St.memoizedState.deps)?f.memoizedState=en(t,p,s,o):(et.flags|=e,f.memoizedState=en(1|t,p,s,o))}function vi(e,t){Qn(8390656,8,e,t)}function el(e,t){Za(2048,8,e,t)}function Zw(e){et.flags|=4;var t=et.updateQueue;if(t===null)t=Wo(),et.updateQueue=t,t.events=[e];else{var s=t.events;s===null?t.events=[e]:s.push(e)}}function Xp(e){var t=on().memoizedState;return Zw({ref:t,nextImpl:e}),function(){if((Pt&2)!==0)throw Error(l(440));return t.impl.apply(void 0,arguments)}}function Zp(e,t){return Za(4,2,e,t)}function Jp(e,t){return Za(4,4,e,t)}function eg(e,t){if(typeof t=="function"){e=e();var s=t(e);return function(){typeof s=="function"?s():t(null)}}if(t!=null)return e=e(),t.current=e,function(){t.current=null}}function tg(e,t,s){s=s!=null?s.concat([e]):null,Za(4,4,eg.bind(null,t,e),s)}function im(){}function ng(e,t){var s=on();t=t===void 0?null:t;var o=s.memoizedState;return t!==null&&Zc(t,o[1])?o[0]:(s.memoizedState=[e,t],e)}function ag(e,t){var s=on();t=t===void 0?null:t;var o=s.memoizedState;if(t!==null&&Zc(t,o[1]))return o[0];if(o=e(),Xa){ct(!0);try{e()}finally{ct(!1)}}return s.memoizedState=[o,t],o}function lm(e,t,s){return s===void 0||(Qa&1073741824)!==0&&(_t&261930)===0?e.memoizedState=t:(e.memoizedState=s,e=sv(),et.lanes|=e,al|=e,s)}function sg(e,t,s,o){return an(s,t)?s:fi.current!==null?(e=lm(e,s,o),an(e,t)||(Ln=!0),e):(Qa&42)===0||(Qa&1073741824)!==0&&(_t&261930)===0?(Ln=!0,e.memoizedState=s):(e=sv(),et.lanes|=e,al|=e,t)}function rg(e,t,s,o,f){var p=se.p;se.p=p!==0&&8>p?p:8;var S=z.T,R={};z.T=R,um(e,!1,t,s);try{var V=f(),ue=z.S;if(ue!==null&&ue(R,V),V!==null&&typeof V=="object"&&typeof V.then=="function"){var xe=Wc(V,o);nu(e,t,xe,ps(e))}else nu(e,t,o,ps(e))}catch(ke){nu(e,t,{then:function(){},status:"rejected",reason:ke},ps())}finally{se.p=p,S!==null&&R.types!==null&&(S.types=R.types),z.T=S}}function Jw(){}function om(e,t,s,o){if(e.tag!==5)throw Error(l(476));var f=ig(e).queue;rg(e,f,t,W,s===null?Jw:function(){return lg(e),s(o)})}function ig(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:W,baseState:W,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Fs,lastRenderedState:W},next:null};var s={};return t.next={memoizedState:s,baseState:s,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Fs,lastRenderedState:s},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function lg(e){var t=ig(e);t.next===null&&(t=e.alternate.memoizedState),nu(e,t.next.queue,{},ps())}function cm(){return ln(bu)}function og(){return on().memoizedState}function cg(){return on().memoizedState}function eS(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var s=ps();e=dr(s);var o=Os(t,e,s);o!==null&&(as(o,t,s),Ul(o,t,s)),t={cache:Oo()},e.payload=t;return}t=t.return}}function tS(e,t,s){var o=ps();s={lane:o,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null},gd(e)?dg(t,s):(s=La(e,t,s,o),s!==null&&(as(s,e,o),fg(s,t,o)))}function ug(e,t,s){var o=ps();nu(e,t,s,o)}function nu(e,t,s,o){var f={lane:o,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null};if(gd(e))dg(t,f);else{var p=e.alternate;if(e.lanes===0&&(p===null||p.lanes===0)&&(p=t.lastRenderedReducer,p!==null))try{var S=t.lastRenderedState,R=p(S,s);if(f.hasEagerState=!0,f.eagerState=R,an(R,S))return To(e,t,f,0),tn===null&&ar(),!1}catch{}if(s=La(e,t,f,o),s!==null)return as(s,e,o),fg(s,t,o),!0}return!1}function um(e,t,s,o){if(o={lane:2,revertLane:Pm(),gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null},gd(e)){if(t)throw Error(l(479))}else t=La(e,s,o,2),t!==null&&as(t,e,2)}function gd(e){var t=e.alternate;return e===et||t!==null&&t===et}function dg(e,t){fs=qo=!0;var s=e.pending;s===null?t.next=t:(t.next=s.next,s.next=t),e.pending=t}function fg(e,t,s){if((s&4194048)!==0){var o=t.lanes;o&=e.pendingLanes,s|=o,t.lanes=s,B(e,s)}}var au={readContext:ln,use:Ko,useCallback:Jt,useContext:Jt,useEffect:Jt,useImperativeHandle:Jt,useLayoutEffect:Jt,useInsertionEffect:Jt,useMemo:Jt,useReducer:Jt,useRef:Jt,useState:Jt,useDebugValue:Jt,useDeferredValue:Jt,useTransition:Jt,useSyncExternalStore:Jt,useId:Jt,useHostTransitionStatus:Jt,useFormState:Jt,useActionState:Jt,useOptimistic:Jt,useMemoCache:Jt,useCacheRefresh:Jt};au.useEffectEvent=Jt;var mg={readContext:ln,use:Ko,useCallback:function(e,t){return $t().memoizedState=[e,t===void 0?null:t],e},useContext:ln,useEffect:vi,useImperativeHandle:function(e,t,s){s=s!=null?s.concat([e]):null,Qn(4194308,4,eg.bind(null,t,e),s)},useLayoutEffect:function(e,t){return Qn(4194308,4,e,t)},useInsertionEffect:function(e,t){Qn(4,2,e,t)},useMemo:function(e,t){var s=$t();t=t===void 0?null:t;var o=e();if(Xa){ct(!0);try{e()}finally{ct(!1)}}return s.memoizedState=[o,t],o},useReducer:function(e,t,s){var o=$t();if(s!==void 0){var f=s(t);if(Xa){ct(!0);try{s(t)}finally{ct(!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=tS.bind(null,et,e),[o.memoizedState,e]},useRef:function(e){var t=$t();return e={current:e},t.memoizedState=e},useState:function(e){e=mr(e);var t=e.queue,s=ug.bind(null,et,t);return t.dispatch=s,[e.memoizedState,s]},useDebugValue:im,useDeferredValue:function(e,t){var s=$t();return lm(s,e,t)},useTransition:function(){var e=mr(!1);return e=rg.bind(null,et,e.queue,!0,!1),$t().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,s){var o=et,f=$t();if(wt){if(s===void 0)throw Error(l(407));s=s()}else{if(s=t(),tn===null)throw Error(l(349));(_t&127)!==0||md(o,t,s)}f.memoizedState=s;var p={value:s,getSnapshot:t};return f.queue=p,vi(Xo.bind(null,o,p,e),[e]),o.flags|=2048,en(9,{destroy:void 0},hd.bind(null,o,p,s,t),null),s},useId:function(){var e=$t(),t=tn.identifierPrefix;if(wt){var s=us,o=Es;s=(o&~(1<<32-bt(o)-1)).toString(32)+s,t="_"+t+"R_"+s,s=Kl++,0<s&&(t+="H"+s.toString(32)),t+="_"}else s=Ql++,t="_"+t+"r_"+s.toString(32)+"_";return e.memoizedState=t},useHostTransitionStatus:cm,useFormState:Ne,useActionState:Ne,useOptimistic:function(e){var t=$t();t.memoizedState=t.baseState=e;var s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return t.queue=s,t=um.bind(null,et,!0,s),s.dispatch=t,[e,t]},useMemoCache:tu,useCacheRefresh:function(){return $t().memoizedState=eS.bind(null,et)},useEffectEvent:function(e){var t=$t(),s={impl:e};return t.memoizedState=s,function(){if((Pt&2)!==0)throw Error(l(440));return s.impl.apply(void 0,arguments)}}},dm={readContext:ln,use:Ko,useCallback:ng,useContext:ln,useEffect:el,useImperativeHandle:tg,useInsertionEffect:Zp,useLayoutEffect:Jp,useMemo:ag,useReducer:hi,useRef:Ca,useState:function(){return hi(Fs)},useDebugValue:im,useDeferredValue:function(e,t){var s=on();return sg(s,St.memoizedState,e,t)},useTransition:function(){var e=hi(Fs)[0],t=on().memoizedState;return[typeof e=="boolean"?e:Yo(e),t]},useSyncExternalStore:fd,useId:og,useHostTransitionStatus:cm,useFormState:Re,useActionState:Re,useOptimistic:function(e,t){var s=on();return Zo(s,St,e,t)},useMemoCache:tu,useCacheRefresh:cg};dm.useEffectEvent=Xp;var hg={readContext:ln,use:Ko,useCallback:ng,useContext:ln,useEffect:el,useImperativeHandle:tg,useInsertionEffect:Zp,useLayoutEffect:Jp,useMemo:ag,useReducer:Qo,useRef:Ca,useState:function(){return Qo(Fs)},useDebugValue:im,useDeferredValue:function(e,t){var s=on();return St===null?lm(s,e,t):sg(s,St.memoizedState,e,t)},useTransition:function(){var e=Qo(Fs)[0],t=on().memoizedState;return[typeof e=="boolean"?e:Yo(e),t]},useSyncExternalStore:fd,useId:og,useHostTransitionStatus:cm,useFormState:xt,useActionState:xt,useOptimistic:function(e,t){var s=on();return St!==null?Zo(s,St,e,t):(s.baseState=e,[e,s.queue.dispatch])},useMemoCache:tu,useCacheRefresh:cg};hg.useEffectEvent=Xp;function fm(e,t,s,o){t=e.memoizedState,s=s(o,t),s=s==null?t:b({},t,s),e.memoizedState=s,e.lanes===0&&(e.updateQueue.baseState=s)}var mm={enqueueSetState:function(e,t,s){e=e._reactInternals;var o=ps(),f=dr(o);f.payload=t,s!=null&&(f.callback=s),t=Os(e,f,o),t!==null&&(as(t,e,o),Ul(t,e,o))},enqueueReplaceState:function(e,t,s){e=e._reactInternals;var o=ps(),f=dr(o);f.tag=1,f.payload=t,s!=null&&(f.callback=s),t=Os(e,f,o),t!==null&&(as(t,e,o),Ul(t,e,o))},enqueueForceUpdate:function(e,t){e=e._reactInternals;var s=ps(),o=dr(s);o.tag=2,t!=null&&(o.callback=t),t=Os(e,o,s),t!==null&&(as(t,e,s),Ul(t,e,s))}};function pg(e,t,s,o,f,p,S){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(o,p,S):t.prototype&&t.prototype.isPureReactComponent?!Ee(s,o)||!Ee(f,p):!0}function gg(e,t,s,o){e=t.state,typeof t.componentWillReceiveProps=="function"&&t.componentWillReceiveProps(s,o),typeof t.UNSAFE_componentWillReceiveProps=="function"&&t.UNSAFE_componentWillReceiveProps(s,o),t.state!==e&&mm.enqueueReplaceState(t,t.state,null)}function Zl(e,t){var s=t;if("ref"in t){s={};for(var o in t)o!=="ref"&&(s[o]=t[o])}if(e=e.defaultProps){s===t&&(s=b({},s));for(var f in e)s[f]===void 0&&(s[f]=e[f])}return s}function vg(e){Pn(e)}function yg(e){console.error(e)}function bg(e){Pn(e)}function vd(e,t){try{var s=e.onUncaughtError;s(t.value,{componentStack:t.stack})}catch(o){setTimeout(function(){throw o})}}function xg(e,t,s){try{var o=e.onCaughtError;o(s.value,{componentStack:s.stack,errorBoundary:t.tag===1?t.stateNode:null})}catch(f){setTimeout(function(){throw f})}}function hm(e,t,s){return s=dr(s),s.tag=3,s.payload={element:null},s.callback=function(){vd(e,t)},s}function wg(e){return e=dr(e),e.tag=3,e}function Sg(e,t,s,o){var f=s.type.getDerivedStateFromError;if(typeof f=="function"){var p=o.value;e.payload=function(){return f(p)},e.callback=function(){xg(t,s,o)}}var S=s.stateNode;S!==null&&typeof S.componentDidCatch=="function"&&(e.callback=function(){xg(t,s,o),typeof f!="function"&&(sl===null?sl=new Set([this]):sl.add(this));var R=o.stack;this.componentDidCatch(o.value,{componentStack:R!==null?R:""})})}function nS(e,t,s,o,f){if(s.flags|=32768,o!==null&&typeof o=="object"&&typeof o.then=="function"){if(t=s.alternate,t!==null&&ii(t,s,f,!0),s=wa.current,s!==null){switch(s.tag){case 31:case 13:return Sa===null?Td():s.alternate===null&&bn===0&&(bn=3),s.flags&=-257,s.flags|=65536,s.lanes=f,o===Dn?s.flags|=16384:(t=s.updateQueue,t===null?s.updateQueue=new Set([o]):t.add(o),Fm(e,o,f)),!1;case 22:return s.flags|=65536,o===Dn?s.flags|=16384:(t=s.updateQueue,t===null?(t={transitions:null,markerInstances:null,retryQueue:new Set([o])},s.updateQueue=t):(s=t.retryQueue,s===null?t.retryQueue=new Set([o]):s.add(o)),Fm(e,o,f)),!1}throw Error(l(435,s.tag))}return Fm(e,o,f),Td(),!1}if(wt)return t=wa.current,t!==null?((t.flags&65536)===0&&(t.flags|=256),t.flags|=65536,t.lanes=f,o!==Vc&&(e=Error(l(422),{cause:o}),Ki(Un(e,s)))):(o!==Vc&&(t=Error(l(423),{cause:o}),Ki(Un(t,s))),e=e.current.alternate,e.flags|=65536,f&=-f,e.lanes|=f,o=Un(o,s),f=hm(e.stateNode,o,f),di(e,f),bn!==4&&(bn=2)),!1;var p=Error(l(520),{cause:o});if(p=Un(p,s),du===null?du=[p]:du.push(p),bn!==4&&(bn=2),t===null)return!0;o=Un(o,s),s=t;do{switch(s.tag){case 3:return s.flags|=65536,e=f&-f,s.lanes|=e,e=hm(s.stateNode,o,e),di(s,e),!1;case 1:if(t=s.type,p=s.stateNode,(s.flags&128)===0&&(typeof t.getDerivedStateFromError=="function"||p!==null&&typeof p.componentDidCatch=="function"&&(sl===null||!sl.has(p))))return s.flags|=65536,f&=-f,s.lanes|=f,f=wg(f),Sg(f,e,s,o),di(s,f),!1}s=s.return}while(s!==null);return!1}var pm=Error(l(461)),Ln=!1;function da(e,t,s,o){t.child=e===null?cd(t,null,s,o):ci(t,e.child,s,o)}function Cg(e,t,s,o,f){s=s.render;var p=t.ref;if("ref"in o){var S={};for(var R in o)R!=="ref"&&(S[R]=o[R])}else S=o;return Ka(t),o=Go(e,t,s,S,p,f),R=Xl(),e!==null&&!Ln?(Jc(e,t,f),yi(e,t,f)):(wt&&R&&Lo(t),t.flags|=1,da(e,t,o,f),t.child)}function kg(e,t,s,o,f){if(e===null){var p=s.type;return typeof p=="function"&&!Ts(p)&&p.defaultProps===void 0&&s.compare===null?(t.tag=15,t.type=p,jg(e,t,p,o,f)):(e=qa(s.type,null,o,t,t.mode,f),e.ref=t.ref,e.return=t,t.child=e)}if(p=e.child,!Cm(e,f)){var S=p.memoizedProps;if(s=s.compare,s=s!==null?s:Ee,s(S,o)&&e.ref===t.ref)return yi(e,t,f)}return t.flags|=1,e=ya(p,o),e.ref=t.ref,e.return=t,t.child=e}function jg(e,t,s,o,f){if(e!==null){var p=e.memoizedProps;if(Ee(p,o)&&e.ref===t.ref)if(Ln=!1,t.pendingProps=o=p,Cm(e,f))(e.flags&131072)!==0&&(Ln=!0);else return t.lanes=e.lanes,yi(e,t,f)}return gm(e,t,s,o,f)}function Ag(e,t,s,o){var f=o.children,p=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(p=p!==null?p.baseLanes|s:s,e!==null){for(o=t.child=e.child,f=0;o!==null;)f=f|o.lanes|o.childLanes,o=o.sibling;o=f&~p}else o=0,t.child=null;return Mg(e,t,p,s,o)}if((s&536870912)!==0)t.memoizedState={baseLanes:0,cachePool:null},e!==null&&Mr(t,p!==null?p.cachePool:null),p!==null?ud(t,p):Wl(),Yl(t);else return o=t.lanes=536870912,Mg(e,t,p!==null?p.baseLanes|s:s,s,o)}else p!==null?(Mr(t,p.cachePool),ud(t,p),fr(),t.memoizedState=null):(e!==null&&Mr(t,null),Wl(),fr());return da(e,t,f,s),t.child}function su(e,t){return e!==null&&e.tag===22||t.stateNode!==null||(t.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),t.sibling}function Mg(e,t,s,o,f){var p=$o();return p=p===null?null:{parent:kn._currentValue,pool:p},t.memoizedState={baseLanes:s,cachePool:p},e!==null&&Mr(t,null),Wl(),Yl(t),e!==null&&ii(e,t,o,!0),t.childLanes=f,null}function yd(e,t){return t=xd({mode:t.mode,children:t.children},e.mode),t.ref=e.ref,e.child=t,t.return=e,t}function Ng(e,t,s){return ci(t,e.child,null,s),e=yd(t,t.pendingProps),e.flags|=2,Oa(t),t.memoizedState=null,e}function aS(e,t,s){var o=t.pendingProps,f=(t.flags&128)!==0;if(t.flags&=-129,e===null){if(wt){if(o.mode==="hidden")return e=yd(t,o),t.lanes=536870912,su(null,e);if(Ie(t),(e=Gt)?(e=$v(e,xa),e=e!==null&&e.data==="&"?e:null,e!==null&&(t.memoizedState={dehydrated:e,treeContext:kr!==null?{id:Es,overflow:us}:null,retryLane:536870912,hydrationErrors:null},s=Il(e),s.return=t,t.child=s,rn=t,Gt=null)):e=null,e===null)throw sr(t);return t.lanes=536870912,null}return yd(t,o)}var p=e.memoizedState;if(p!==null){var S=p.dehydrated;if(Ie(t),f)if(t.flags&256)t.flags&=-257,t=Ng(e,t,s);else if(t.memoizedState!==null)t.child=e.child,t.flags|=128,t=null;else throw Error(l(558));else if(Ln||ii(e,t,s,!1),f=(s&e.childLanes)!==0,Ln||f){if(o=tn,o!==null&&(S=Ke(o,s),S!==0&&S!==p.retryLane))throw p.retryLane=S,_a(e,S),as(o,e,S),pm;Td(),t=Ng(e,t,s)}else e=p.treeContext,Gt=$s(S.nextSibling),rn=t,wt=!0,ba=null,xa=!1,e!==null&&Gc(t,e),t=yd(t,o),t.flags|=4096;return t}return e=ya(e.child,{mode:o.mode,children:o.children}),e.ref=t.ref,t.child=e,e.return=t,e}function bd(e,t){var s=t.ref;if(s===null)e!==null&&e.ref!==null&&(t.flags|=4194816);else{if(typeof s!="function"&&typeof s!="object")throw Error(l(284));(e===null||e.ref!==s)&&(t.flags|=4194816)}}function gm(e,t,s,o,f){return Ka(t),s=Go(e,t,s,o,void 0,f),o=Xl(),e!==null&&!Ln?(Jc(e,t,f),yi(e,t,f)):(wt&&o&&Lo(t),t.flags|=1,da(e,t,s,f),t.child)}function Tg(e,t,s,o,f,p){return Ka(t),t.updateQueue=null,s=dd(t,o,s,f),Vo(e),o=Xl(),e!==null&&!Ln?(Jc(e,t,p),yi(e,t,p)):(wt&&o&&Lo(t),t.flags|=1,da(e,t,s,p),t.child)}function Rg(e,t,s,o,f){if(Ka(t),t.stateNode===null){var p=ca,S=s.contextType;typeof S=="object"&&S!==null&&(p=ln(S)),p=new s(o,p),t.memoizedState=p.state!==null&&p.state!==void 0?p.state:null,p.updater=mm,t.stateNode=p,p._reactInternals=t,p=t.stateNode,p.props=o,p.state=t.memoizedState,p.refs={},Pl(t),S=s.contextType,p.context=typeof S=="object"&&S!==null?ln(S):ca,p.state=t.memoizedState,S=s.getDerivedStateFromProps,typeof S=="function"&&(fm(t,s,S,o),p.state=t.memoizedState),typeof s.getDerivedStateFromProps=="function"||typeof p.getSnapshotBeforeUpdate=="function"||typeof p.UNSAFE_componentWillMount!="function"&&typeof p.componentWillMount!="function"||(S=p.state,typeof p.componentWillMount=="function"&&p.componentWillMount(),typeof p.UNSAFE_componentWillMount=="function"&&p.UNSAFE_componentWillMount(),S!==p.state&&mm.enqueueReplaceState(p,p.state,null),Gl(t,o,p,f),ql(),p.state=t.memoizedState),typeof p.componentDidMount=="function"&&(t.flags|=4194308),o=!0}else if(e===null){p=t.stateNode;var R=t.memoizedProps,V=Zl(s,R);p.props=V;var ue=p.context,xe=s.contextType;S=ca,typeof xe=="object"&&xe!==null&&(S=ln(xe));var ke=s.getDerivedStateFromProps;xe=typeof ke=="function"||typeof p.getSnapshotBeforeUpdate=="function",R=t.pendingProps!==R,xe||typeof p.UNSAFE_componentWillReceiveProps!="function"&&typeof p.componentWillReceiveProps!="function"||(R||ue!==S)&&gg(t,p,o,S),zs=!1;var me=t.memoizedState;p.state=me,Gl(t,o,p,f),ql(),ue=t.memoizedState,R||me!==ue||zs?(typeof ke=="function"&&(fm(t,s,ke,o),ue=t.memoizedState),(V=zs||pg(t,s,V,o,me,ue,S))?(xe||typeof p.UNSAFE_componentWillMount!="function"&&typeof p.componentWillMount!="function"||(typeof p.componentWillMount=="function"&&p.componentWillMount(),typeof p.UNSAFE_componentWillMount=="function"&&p.UNSAFE_componentWillMount()),typeof p.componentDidMount=="function"&&(t.flags|=4194308)):(typeof p.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=o,t.memoizedState=ue),p.props=o,p.state=ue,p.context=S,o=V):(typeof p.componentDidMount=="function"&&(t.flags|=4194308),o=!1)}else{p=t.stateNode,ui(e,t),S=t.memoizedProps,xe=Zl(s,S),p.props=xe,ke=t.pendingProps,me=p.context,ue=s.contextType,V=ca,typeof ue=="object"&&ue!==null&&(V=ln(ue)),R=s.getDerivedStateFromProps,(ue=typeof R=="function"||typeof p.getSnapshotBeforeUpdate=="function")||typeof p.UNSAFE_componentWillReceiveProps!="function"&&typeof p.componentWillReceiveProps!="function"||(S!==ke||me!==V)&&gg(t,p,o,V),zs=!1,me=t.memoizedState,p.state=me,Gl(t,o,p,f),ql();var ge=t.memoizedState;S!==ke||me!==ge||zs||e!==null&&e.dependencies!==null&&lr(e.dependencies)?(typeof R=="function"&&(fm(t,s,R,o),ge=t.memoizedState),(xe=zs||pg(t,s,xe,o,me,ge,V)||e!==null&&e.dependencies!==null&&lr(e.dependencies))?(ue||typeof p.UNSAFE_componentWillUpdate!="function"&&typeof p.componentWillUpdate!="function"||(typeof p.componentWillUpdate=="function"&&p.componentWillUpdate(o,ge,V),typeof p.UNSAFE_componentWillUpdate=="function"&&p.UNSAFE_componentWillUpdate(o,ge,V)),typeof p.componentDidUpdate=="function"&&(t.flags|=4),typeof p.getSnapshotBeforeUpdate=="function"&&(t.flags|=1024)):(typeof p.componentDidUpdate!="function"||S===e.memoizedProps&&me===e.memoizedState||(t.flags|=4),typeof p.getSnapshotBeforeUpdate!="function"||S===e.memoizedProps&&me===e.memoizedState||(t.flags|=1024),t.memoizedProps=o,t.memoizedState=ge),p.props=o,p.state=ge,p.context=V,o=xe):(typeof p.componentDidUpdate!="function"||S===e.memoizedProps&&me===e.memoizedState||(t.flags|=4),typeof p.getSnapshotBeforeUpdate!="function"||S===e.memoizedProps&&me===e.memoizedState||(t.flags|=1024),o=!1)}return p=o,bd(e,t),o=(t.flags&128)!==0,p||o?(p=t.stateNode,s=o&&typeof s.getDerivedStateFromError!="function"?null:p.render(),t.flags|=1,e!==null&&o?(t.child=ci(t,e.child,null,f),t.child=ci(t,null,s,f)):da(e,t,s,f),t.memoizedState=p.state,e=t.child):e=yi(e,t,f),e}function Eg(e,t,s,o){return si(),t.flags|=256,da(e,t,s,o),t.child}var vm={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function ym(e){return{baseLanes:e,cachePool:Ls()}}function bm(e,t,s){return e=e!==null?e.childLanes&~s:0,t&&(e|=hs),e}function Dg(e,t,s){var o=t.pendingProps,f=!1,p=(t.flags&128)!==0,S;if((S=p)||(S=e!==null&&e.memoizedState===null?!1:(yn.current&2)!==0),S&&(f=!0,t.flags&=-129),S=(t.flags&32)!==0,t.flags&=-33,e===null){if(wt){if(f?Hs(t):fr(),(e=Gt)?(e=$v(e,xa),e=e!==null&&e.data!=="&"?e:null,e!==null&&(t.memoizedState={dehydrated:e,treeContext:kr!==null?{id:Es,overflow:us}:null,retryLane:536870912,hydrationErrors:null},s=Il(e),s.return=t,t.child=s,rn=t,Gt=null)):e=null,e===null)throw sr(t);return th(e)?t.lanes=32:t.lanes=536870912,null}var R=o.children;return o=o.fallback,f?(fr(),f=t.mode,R=xd({mode:"hidden",children:R},f),o=Cr(o,f,s,null),R.return=t,o.return=t,R.sibling=o,t.child=R,o=t.child,o.memoizedState=ym(s),o.childLanes=bm(e,S,s),t.memoizedState=vm,su(null,o)):(Hs(t),xm(t,R))}var V=e.memoizedState;if(V!==null&&(R=V.dehydrated,R!==null)){if(p)t.flags&256?(Hs(t),t.flags&=-257,t=wm(e,t,s)):t.memoizedState!==null?(fr(),t.child=e.child,t.flags|=128,t=null):(fr(),R=o.fallback,f=t.mode,o=xd({mode:"visible",children:o.children},f),R=Cr(R,f,s,null),R.flags|=2,o.return=t,R.return=t,o.sibling=R,t.child=o,ci(t,e.child,null,s),o=t.child,o.memoizedState=ym(s),o.childLanes=bm(e,S,s),t.memoizedState=vm,t=su(null,o));else if(Hs(t),th(R)){if(S=R.nextSibling&&R.nextSibling.dataset,S)var ue=S.dgst;S=ue,o=Error(l(419)),o.stack="",o.digest=S,Ki({value:o,source:null,stack:null}),t=wm(e,t,s)}else if(Ln||ii(e,t,s,!1),S=(s&e.childLanes)!==0,Ln||S){if(S=tn,S!==null&&(o=Ke(S,s),o!==0&&o!==V.retryLane))throw V.retryLane=o,_a(e,o),as(S,e,o),pm;eh(R)||Td(),t=wm(e,t,s)}else eh(R)?(t.flags|=192,t.child=e.child,t=null):(e=V.treeContext,Gt=$s(R.nextSibling),rn=t,wt=!0,ba=null,xa=!1,e!==null&&Gc(t,e),t=xm(t,o.children),t.flags|=4096);return t}return f?(fr(),R=o.fallback,f=t.mode,V=e.child,ue=V.sibling,o=ya(V,{mode:"hidden",children:o.children}),o.subtreeFlags=V.subtreeFlags&65011712,ue!==null?R=ya(ue,R):(R=Cr(R,f,s,null),R.flags|=2),R.return=t,o.return=t,o.sibling=R,t.child=o,su(null,o),o=t.child,R=e.child.memoizedState,R===null?R=ym(s):(f=R.cachePool,f!==null?(V=kn._currentValue,f=f.parent!==V?{parent:V,pool:V}:f):f=Ls(),R={baseLanes:R.baseLanes|s,cachePool:f}),o.memoizedState=R,o.childLanes=bm(e,S,s),t.memoizedState=vm,su(e.child,o)):(Hs(t),s=e.child,e=s.sibling,s=ya(s,{mode:"visible",children:o.children}),s.return=t,s.sibling=null,e!==null&&(S=t.deletions,S===null?(t.deletions=[e],t.flags|=16):S.push(e)),t.child=s,t.memoizedState=null,s)}function xm(e,t){return t=xd({mode:"visible",children:t},e.mode),t.return=e,e.child=t}function xd(e,t){return e=En(22,e,null,t),e.lanes=0,e}function wm(e,t,s){return ci(t,e.child,null,s),e=xm(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function Lg(e,t,s){e.lanes|=t;var o=e.alternate;o!==null&&(o.lanes|=t),ir(e.return,t,s)}function Sm(e,t,s,o,f,p){var S=e.memoizedState;S===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:o,tail:s,tailMode:f,treeForkCount:p}:(S.isBackwards=t,S.rendering=null,S.renderingStartTime=0,S.last=o,S.tail=s,S.tailMode=f,S.treeForkCount=p)}function _g(e,t,s){var o=t.pendingProps,f=o.revealOrder,p=o.tail;o=o.children;var S=yn.current,R=(S&2)!==0;if(R?(S=S&1|2,t.flags|=128):S&=1,be(yn,S),da(e,t,o,s),o=wt?Rs:0,!R&&e!==null&&(e.flags&128)!==0)e:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&Lg(e,s,t);else if(e.tag===19)Lg(e,s,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(s=t.child,f=null;s!==null;)e=s.alternate,e!==null&&Zi(e)===null&&(f=s),s=s.sibling;s=f,s===null?(f=t.child,t.child=null):(f=s.sibling,s.sibling=null),Sm(t,!1,f,s,p,o);break;case"backwards":case"unstable_legacy-backwards":for(s=null,f=t.child,t.child=null;f!==null;){if(e=f.alternate,e!==null&&Zi(e)===null){t.child=f;break}e=f.sibling,f.sibling=s,s=f,f=e}Sm(t,!0,s,null,p,o);break;case"together":Sm(t,!1,null,null,void 0,o);break;default:t.memoizedState=null}return t.child}function yi(e,t,s){if(e!==null&&(t.dependencies=e.dependencies),al|=t.lanes,(s&t.childLanes)===0)if(e!==null){if(ii(e,t,s,!1),(s&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,s=ya(e,e.pendingProps),t.child=s,s.return=t;e.sibling!==null;)e=e.sibling,s=s.sibling=ya(e,e.pendingProps),s.return=t;s.sibling=null}return t.child}function Cm(e,t){return(e.lanes&t)!==0?!0:(e=e.dependencies,!!(e!==null&&lr(e)))}function sS(e,t,s){switch(t.tag){case 3:Me(t,t.stateNode.containerInfo),ds(t,kn,e.memoizedState.cache),si();break;case 27:case 5:ne(t);break;case 4:Me(t,t.stateNode.containerInfo);break;case 10:ds(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?(Hs(t),t.flags|=128,null):(s&t.child.childLanes)!==0?Dg(e,t,s):(Hs(t),e=yi(e,t,s),e!==null?e.sibling:null);Hs(t);break;case 19:var f=(e.flags&128)!==0;if(o=(s&t.childLanes)!==0,o||(ii(e,t,s,!1),o=(s&t.childLanes)!==0),f){if(o)return _g(e,t,s);t.flags|=128}if(f=t.memoizedState,f!==null&&(f.rendering=null,f.tail=null,f.lastEffect=null),be(yn,yn.current),o)break;return null;case 22:return t.lanes=0,Ag(e,t,s,t.pendingProps);case 24:ds(t,kn,e.memoizedState.cache)}return yi(e,t,s)}function Ig(e,t,s){if(e!==null)if(e.memoizedProps!==t.pendingProps)Ln=!0;else{if(!Cm(e,s)&&(t.flags&128)===0)return Ln=!1,sS(e,t,s);Ln=(e.flags&131072)!==0}else Ln=!1,wt&&(t.flags&1048576)!==0&&rd(t,Rs,t.index);switch(t.lanes=0,t.tag){case 16:e:{var o=t.pendingProps;if(e=_s(t.elementType),t.type=e,typeof e=="function")Ts(e)?(o=Zl(e,o),t.tag=1,t=Rg(null,t,e,o,s)):(t.tag=0,t=gm(null,t,e,o,s));else{if(e!=null){var f=e.$$typeof;if(f===F){t.tag=11,t=Cg(null,t,e,o,s);break e}else if(f===L){t.tag=14,t=kg(null,t,e,o,s);break e}}throw t=de(e)||e,Error(l(306,t,""))}}return t;case 0:return gm(e,t,t.type,t.pendingProps,s);case 1:return o=t.type,f=Zl(o,t.pendingProps),Rg(e,t,o,f,s);case 3:e:{if(Me(t,t.stateNode.containerInfo),e===null)throw Error(l(387));o=t.pendingProps;var p=t.memoizedState;f=p.element,ui(e,t),Gl(t,o,null,s);var S=t.memoizedState;if(o=S.cache,ds(t,kn,o),o!==p.cache&&Io(t,[kn],s,!0),ql(),o=S.element,p.isDehydrated)if(p={element:o,isDehydrated:!1,cache:S.cache},t.updateQueue.baseState=p,t.memoizedState=p,t.flags&256){t=Eg(e,t,o,s);break e}else if(o!==f){f=Un(Error(l(424)),t),Ki(f),t=Eg(e,t,o,s);break e}else for(e=t.stateNode.containerInfo,e.nodeType===9?e=e.body:e=e.nodeName==="HTML"?e.ownerDocument.body:e,Gt=$s(e.firstChild),rn=t,wt=!0,ba=null,xa=!0,s=cd(t,null,o,s),t.child=s;s;)s.flags=s.flags&-3|4096,s=s.sibling;else{if(si(),o===f){t=yi(e,t,s);break e}da(e,t,o,s)}t=t.child}return t;case 26:return bd(e,t),e===null?(s=Vv(t.type,null,t.pendingProps,null))?t.memoizedState=s:wt||(s=t.type,e=t.pendingProps,o=zd(ee.current).createElement(s),o[re]=t,o[Te]=e,fa(o,s,e),At(o),t.stateNode=o):t.memoizedState=Vv(t.type,e.memoizedProps,t.pendingProps,e.memoizedState),null;case 27:return ne(t),e===null&&wt&&(o=t.stateNode=Uv(t.type,t.pendingProps,ee.current),rn=t,xa=!0,f=Gt,ol(t.type)?(nh=f,Gt=$s(o.firstChild)):Gt=f),da(e,t,t.pendingProps.children,s),bd(e,t),e===null&&(t.flags|=4194304),t.child;case 5:return e===null&&wt&&((f=o=Gt)&&(o=_S(o,t.type,t.pendingProps,xa),o!==null?(t.stateNode=o,rn=t,Gt=$s(o.firstChild),xa=!1,f=!0):f=!1),f||sr(t)),ne(t),f=t.type,p=t.pendingProps,S=e!==null?e.memoizedProps:null,o=p.children,Xm(f,p)?o=null:S!==null&&Xm(f,S)&&(t.flags|=32),t.memoizedState!==null&&(f=Go(e,t,rm,null,null,s),bu._currentValue=f),bd(e,t),da(e,t,o,s),t.child;case 6:return e===null&&wt&&((e=s=Gt)&&(s=IS(s,t.pendingProps,xa),s!==null?(t.stateNode=s,rn=t,Gt=null,e=!0):e=!1),e||sr(t)),null;case 13:return Dg(e,t,s);case 4:return Me(t,t.stateNode.containerInfo),o=t.pendingProps,e===null?t.child=ci(t,null,o,s):da(e,t,o,s),t.child;case 11:return Cg(e,t,t.type,t.pendingProps,s);case 7:return da(e,t,t.pendingProps,s),t.child;case 8:return da(e,t,t.pendingProps.children,s),t.child;case 12:return da(e,t,t.pendingProps.children,s),t.child;case 10:return o=t.pendingProps,ds(t,t.type,o.value),da(e,t,o.children,s),t.child;case 9:return f=t.type._context,o=t.pendingProps.children,Ka(t),f=ln(f),o=o(f),t.flags|=1,da(e,t,o,s),t.child;case 14:return kg(e,t,t.type,t.pendingProps,s);case 15:return jg(e,t,t.type,t.pendingProps,s);case 19:return _g(e,t,s);case 31:return aS(e,t,s);case 22:return Ag(e,t,s,t.pendingProps);case 24:return Ka(t),o=ln(kn),e===null?(f=$o(),f===null&&(f=tn,p=Oo(),f.pooledCache=p,p.refCount++,p!==null&&(f.pooledCacheLanes|=s),f=p),t.memoizedState={parent:o,cache:f},Pl(t),ds(t,kn,f)):((e.lanes&s)!==0&&(ui(e,t),Gl(t,null,null,s),ql()),f=e.memoizedState,p=t.memoizedState,f.parent!==o?(f={parent:o,cache:o},t.memoizedState=f,t.lanes===0&&(t.memoizedState=t.updateQueue.baseState=f),ds(t,kn,o)):(o=p.cache,ds(t,kn,o),o!==f.cache&&Io(t,[kn],s,!0))),da(e,t,t.pendingProps.children,s),t.child;case 29:throw t.pendingProps}throw Error(l(156,t.tag))}function bi(e){e.flags|=4}function km(e,t,s,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(ov())e.flags|=8192;else throw Tr=Dn,Yc}else e.flags&=-16777217}function zg(e,t){if(t.type!=="stylesheet"||(t.state.loading&4)!==0)e.flags&=-16777217;else if(e.flags|=16777216,!Xv(t))if(ov())e.flags|=8192;else throw Tr=Dn,Yc}function wd(e,t){t!==null&&(e.flags|=4),e.flags&16384&&(t=e.tag!==22?ws():536870912,e.lanes|=t,nc|=t)}function ru(e,t){if(!wt)switch(e.tailMode){case"hidden":t=e.tail;for(var s=null;t!==null;)t.alternate!==null&&(s=t),t=t.sibling;s===null?e.tail=null:s.sibling=null;break;case"collapsed":s=e.tail;for(var o=null;s!==null;)s.alternate!==null&&(o=s),s=s.sibling;o===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:o.sibling=null}}function cn(e){var t=e.alternate!==null&&e.alternate.child===e.child,s=0,o=0;if(t)for(var f=e.child;f!==null;)s|=f.lanes|f.childLanes,o|=f.subtreeFlags&65011712,o|=f.flags&65011712,f.return=e,f=f.sibling;else for(f=e.child;f!==null;)s|=f.lanes|f.childLanes,o|=f.subtreeFlags,o|=f.flags,f.return=e,f=f.sibling;return e.subtreeFlags|=o,e.childLanes=s,t}function rS(e,t,s){var o=t.pendingProps;switch(ai(t),t.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return cn(t),null;case 1:return cn(t),null;case 3:return s=t.stateNode,o=null,e!==null&&(o=e.memoizedState.cache),t.memoizedState.cache!==o&&(t.flags|=2048),Ya(kn),He(),s.pendingContext&&(s.context=s.pendingContext,s.pendingContext=null),(e===null||e.child===null)&&(Ds(t)?bi(t):e===null||e.memoizedState.isDehydrated&&(t.flags&256)===0||(t.flags|=1024,Yi())),cn(t),null;case 26:var f=t.type,p=t.memoizedState;return e===null?(bi(t),p!==null?(cn(t),zg(t,p)):(cn(t),km(t,f,null,o,s))):p?p!==e.memoizedState?(bi(t),cn(t),zg(t,p)):(cn(t),t.flags&=-16777217):(e=e.memoizedProps,e!==o&&bi(t),cn(t),km(t,f,e,o,s)),null;case 27:if(qe(t),s=ee.current,f=t.type,e!==null&&t.stateNode!=null)e.memoizedProps!==o&&bi(t);else{if(!o){if(t.stateNode===null)throw Error(l(166));return cn(t),null}e=he.current,Ds(t)?zl(t):(e=Uv(f,o,s),t.stateNode=e,bi(t))}return cn(t),null;case 5:if(qe(t),f=t.type,e!==null&&t.stateNode!=null)e.memoizedProps!==o&&bi(t);else{if(!o){if(t.stateNode===null)throw Error(l(166));return cn(t),null}if(p=he.current,Ds(t))zl(t);else{var S=zd(ee.current);switch(p){case 1:p=S.createElementNS("http://www.w3.org/2000/svg",f);break;case 2:p=S.createElementNS("http://www.w3.org/1998/Math/MathML",f);break;default:switch(f){case"svg":p=S.createElementNS("http://www.w3.org/2000/svg",f);break;case"math":p=S.createElementNS("http://www.w3.org/1998/Math/MathML",f);break;case"script":p=S.createElement("div"),p.innerHTML="<script><\/script>",p=p.removeChild(p.firstChild);break;case"select":p=typeof o.is=="string"?S.createElement("select",{is:o.is}):S.createElement("select"),o.multiple?p.multiple=!0:o.size&&(p.size=o.size);break;default:p=typeof o.is=="string"?S.createElement(f,{is:o.is}):S.createElement(f)}}p[re]=t,p[Te]=o;e:for(S=t.child;S!==null;){if(S.tag===5||S.tag===6)p.appendChild(S.stateNode);else if(S.tag!==4&&S.tag!==27&&S.child!==null){S.child.return=S,S=S.child;continue}if(S===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=p;e:switch(fa(p,f,o),f){case"button":case"input":case"select":case"textarea":o=!!o.autoFocus;break e;case"img":o=!0;break e;default:o=!1}o&&bi(t)}}return cn(t),km(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,s),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==o&&bi(t);else{if(typeof o!="string"&&t.stateNode===null)throw Error(l(166));if(e=ee.current,Ds(t)){if(e=t.stateNode,s=t.memoizedProps,o=null,f=rn,f!==null)switch(f.tag){case 27:case 5:o=f.memoizedProps}e[re]=t,e=!!(e.nodeValue===s||o!==null&&o.suppressHydrationWarning===!0||Dv(e.nodeValue,s)),e||sr(t,!0)}else e=zd(e).createTextNode(o),e[re]=t,t.stateNode=e}return cn(t),null;case 31:if(s=t.memoizedState,e===null||e.memoizedState!==null){if(o=Ds(t),s!==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[re]=t}else si(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;cn(t),e=!1}else s=Yi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=s),e=!0;if(!e)return t.flags&256?(Oa(t),t):(Oa(t),null);if((t.flags&128)!==0)throw Error(l(558))}return cn(t),null;case 13:if(o=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(f=Ds(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[re]=t}else si(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;cn(t),f=!1}else f=Yi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=f),f=!0;if(!f)return t.flags&256?(Oa(t),t):(Oa(t),null)}return Oa(t),(t.flags&128)!==0?(t.lanes=s,t):(s=o!==null,e=e!==null&&e.memoizedState!==null,s&&(o=t.child,f=null,o.alternate!==null&&o.alternate.memoizedState!==null&&o.alternate.memoizedState.cachePool!==null&&(f=o.alternate.memoizedState.cachePool.pool),p=null,o.memoizedState!==null&&o.memoizedState.cachePool!==null&&(p=o.memoizedState.cachePool.pool),p!==f&&(o.flags|=2048)),s!==e&&s&&(t.child.flags|=8192),wd(t,t.updateQueue),cn(t),null);case 4:return He(),e===null&&Vm(t.stateNode.containerInfo),cn(t),null;case 10:return Ya(t.type),cn(t),null;case 19:if(K(yn),o=t.memoizedState,o===null)return cn(t),null;if(f=(t.flags&128)!==0,p=o.rendering,p===null)if(f)ru(o,!1);else{if(bn!==0||e!==null&&(e.flags&128)!==0)for(e=t.child;e!==null;){if(p=Zi(e),p!==null){for(t.flags|=128,ru(o,!1),e=p.updateQueue,t.updateQueue=e,wd(t,e),t.subtreeFlags=0,e=s,s=t.child;s!==null;)_l(s,e),s=s.sibling;return be(yn,yn.current&1|2),wt&&Va(t,o.treeForkCount),t.child}e=e.sibling}o.tail!==null&&Ae()>Ad&&(t.flags|=128,f=!0,ru(o,!1),t.lanes=4194304)}else{if(!f)if(e=Zi(p),e!==null){if(t.flags|=128,f=!0,e=e.updateQueue,t.updateQueue=e,wd(t,e),ru(o,!0),o.tail===null&&o.tailMode==="hidden"&&!p.alternate&&!wt)return cn(t),null}else 2*Ae()-o.renderingStartTime>Ad&&s!==536870912&&(t.flags|=128,f=!0,ru(o,!1),t.lanes=4194304);o.isBackwards?(p.sibling=t.child,t.child=p):(e=o.last,e!==null?e.sibling=p:t.child=p,o.last=p)}return o.tail!==null?(e=o.tail,o.rendering=e,o.tail=e.sibling,o.renderingStartTime=Ae(),e.sibling=null,s=yn.current,be(yn,f?s&1|2:s&1),wt&&Va(t,o.treeForkCount),e):(cn(t),null);case 22:case 23:return Oa(t),Xi(),o=t.memoizedState!==null,e!==null?e.memoizedState!==null!==o&&(t.flags|=8192):o&&(t.flags|=8192),o?(s&536870912)!==0&&(t.flags&128)===0&&(cn(t),t.subtreeFlags&6&&(t.flags|=8192)):cn(t),s=t.updateQueue,s!==null&&wd(t,s.retryQueue),s=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(s=e.memoizedState.cachePool.pool),o=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(o=t.memoizedState.cachePool.pool),o!==s&&(t.flags|=2048),e!==null&&K(cr),null;case 24:return s=null,e!==null&&(s=e.memoizedState.cache),t.memoizedState.cache!==s&&(t.flags|=2048),Ya(kn),cn(t),null;case 25:return null;case 30:return null}throw Error(l(156,t.tag))}function iS(e,t){switch(ai(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ya(kn),He(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return qe(t),null;case 31:if(t.memoizedState!==null){if(Oa(t),t.alternate===null)throw Error(l(340));si()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(Oa(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(l(340));si()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return K(yn),null;case 4:return He(),null;case 10:return Ya(t.type),null;case 22:case 23:return Oa(t),Xi(),e!==null&&K(cr),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Ya(kn),null;case 25:return null;default:return null}}function Og(e,t){switch(ai(t),t.tag){case 3:Ya(kn),He();break;case 26:case 27:case 5:qe(t);break;case 4:He();break;case 31:t.memoizedState!==null&&Oa(t);break;case 13:Oa(t);break;case 19:K(yn);break;case 10:Ya(t.type);break;case 22:case 23:Oa(t),Xi(),e!==null&&K(cr);break;case 24:Ya(kn)}}function iu(e,t){try{var s=t.updateQueue,o=s!==null?s.lastEffect:null;if(o!==null){var f=o.next;s=f;do{if((s.tag&e)===e){o=void 0;var p=s.create,S=s.inst;o=p(),S.destroy=o}s=s.next}while(s!==f)}}catch(R){Wt(t,t.return,R)}}function tl(e,t,s){try{var o=t.updateQueue,f=o!==null?o.lastEffect:null;if(f!==null){var p=f.next;o=p;do{if((o.tag&e)===e){var S=o.inst,R=S.destroy;if(R!==void 0){S.destroy=void 0,f=t;var V=s,ue=R;try{ue()}catch(xe){Wt(f,V,xe)}}}o=o.next}while(o!==p)}}catch(xe){Wt(t,t.return,xe)}}function Hg(e){var t=e.updateQueue;if(t!==null){var s=e.stateNode;try{Xc(t,s)}catch(o){Wt(e,e.return,o)}}}function Fg(e,t,s){s.props=Zl(e.type,e.memoizedProps),s.state=e.memoizedState;try{s.componentWillUnmount()}catch(o){Wt(e,t,o)}}function lu(e,t){try{var s=e.ref;if(s!==null){switch(e.tag){case 26:case 27:case 5:var o=e.stateNode;break;case 30:o=e.stateNode;break;default:o=e.stateNode}typeof s=="function"?e.refCleanup=s(o):s.current=o}}catch(f){Wt(e,t,f)}}function Rr(e,t){var s=e.ref,o=e.refCleanup;if(s!==null)if(typeof o=="function")try{o()}catch(f){Wt(e,t,f)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof s=="function")try{s(null)}catch(f){Wt(e,t,f)}else s.current=null}function $g(e){var t=e.type,s=e.memoizedProps,o=e.stateNode;try{e:switch(t){case"button":case"input":case"select":case"textarea":s.autoFocus&&o.focus();break e;case"img":s.src?o.src=s.src:s.srcSet&&(o.srcset=s.srcSet)}}catch(f){Wt(e,e.return,f)}}function jm(e,t,s){try{var o=e.stateNode;NS(o,e.type,s,t),o[Te]=t}catch(f){Wt(e,e.return,f)}}function Bg(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&ol(e.type)||e.tag===4}function Am(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Bg(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&&ol(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 Mm(e,t,s){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?(s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s).insertBefore(e,t):(t=s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s,t.appendChild(e),s=s._reactRootContainer,s!=null||t.onclick!==null||(t.onclick=ra));else if(o!==4&&(o===27&&ol(e.type)&&(s=e.stateNode,t=null),e=e.child,e!==null))for(Mm(e,t,s),e=e.sibling;e!==null;)Mm(e,t,s),e=e.sibling}function Sd(e,t,s){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?s.insertBefore(e,t):s.appendChild(e);else if(o!==4&&(o===27&&ol(e.type)&&(s=e.stateNode),e=e.child,e!==null))for(Sd(e,t,s),e=e.sibling;e!==null;)Sd(e,t,s),e=e.sibling}function Pg(e){var t=e.stateNode,s=e.memoizedProps;try{for(var o=e.type,f=t.attributes;f.length;)t.removeAttributeNode(f[0]);fa(t,o,s),t[re]=e,t[Te]=s}catch(p){Wt(e,e.return,p)}}var xi=!1,_n=!1,Nm=!1,Ug=typeof WeakSet=="function"?WeakSet:Set,Xn=null;function lS(e,t){if(e=e.containerInfo,Km=Ud,e=jo(e),Kr(e)){if("selectionStart"in e)var s={start:e.selectionStart,end:e.selectionEnd};else e:{s=(s=e.ownerDocument)&&s.defaultView||window;var o=s.getSelection&&s.getSelection();if(o&&o.rangeCount!==0){s=o.anchorNode;var f=o.anchorOffset,p=o.focusNode;o=o.focusOffset;try{s.nodeType,p.nodeType}catch{s=null;break e}var S=0,R=-1,V=-1,ue=0,xe=0,ke=e,me=null;t:for(;;){for(var ge;ke!==s||f!==0&&ke.nodeType!==3||(R=S+f),ke!==p||o!==0&&ke.nodeType!==3||(V=S+o),ke.nodeType===3&&(S+=ke.nodeValue.length),(ge=ke.firstChild)!==null;)me=ke,ke=ge;for(;;){if(ke===e)break t;if(me===s&&++ue===f&&(R=S),me===p&&++xe===o&&(V=S),(ge=ke.nextSibling)!==null)break;ke=me,me=ke.parentNode}ke=ge}s=R===-1||V===-1?null:{start:R,end:V}}else s=null}s=s||{start:0,end:0}}else s=null;for(Qm={focusedElem:e,selectionRange:s},Ud=!1,Xn=t;Xn!==null;)if(t=Xn,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Xn=e;else for(;Xn!==null;){switch(t=Xn,p=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(s=0;s<e.length;s++)f=e[s],f.ref.impl=f.nextImpl;break;case 11:case 15:break;case 1:if((e&1024)!==0&&p!==null){e=void 0,s=t,f=p.memoizedProps,p=p.memoizedState,o=s.stateNode;try{var Qe=Zl(s.type,f);e=o.getSnapshotBeforeUpdate(Qe,p),o.__reactInternalSnapshotBeforeUpdate=e}catch(ut){Wt(s,s.return,ut)}}break;case 3:if((e&1024)!==0){if(e=t.stateNode.containerInfo,s=e.nodeType,s===9)Jm(e);else if(s===1)switch(e.nodeName){case"HEAD":case"HTML":case"BODY":Jm(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,Xn=e;break}Xn=t.return}}function qg(e,t,s){var o=s.flags;switch(s.tag){case 0:case 11:case 15:Si(e,s),o&4&&iu(5,s);break;case 1:if(Si(e,s),o&4)if(e=s.stateNode,t===null)try{e.componentDidMount()}catch(S){Wt(s,s.return,S)}else{var f=Zl(s.type,t.memoizedProps);t=t.memoizedState;try{e.componentDidUpdate(f,t,e.__reactInternalSnapshotBeforeUpdate)}catch(S){Wt(s,s.return,S)}}o&64&&Hg(s),o&512&&lu(s,s.return);break;case 3:if(Si(e,s),o&64&&(e=s.updateQueue,e!==null)){if(t=null,s.child!==null)switch(s.child.tag){case 27:case 5:t=s.child.stateNode;break;case 1:t=s.child.stateNode}try{Xc(e,t)}catch(S){Wt(s,s.return,S)}}break;case 27:t===null&&o&4&&Pg(s);case 26:case 5:Si(e,s),t===null&&o&4&&$g(s),o&512&&lu(s,s.return);break;case 12:Si(e,s);break;case 31:Si(e,s),o&4&&Wg(e,s);break;case 13:Si(e,s),o&4&&Yg(e,s),o&64&&(e=s.memoizedState,e!==null&&(e=e.dehydrated,e!==null&&(s=gS.bind(null,s),zS(e,s))));break;case 22:if(o=s.memoizedState!==null||xi,!o){t=t!==null&&t.memoizedState!==null||_n,f=xi;var p=_n;xi=o,(_n=t)&&!p?Ci(e,s,(s.subtreeFlags&8772)!==0):Si(e,s),xi=f,_n=p}break;case 30:break;default:Si(e,s)}}function Gg(e){var t=e.alternate;t!==null&&(e.alternate=null,Gg(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&sa(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 dn=null,Ja=!1;function wi(e,t,s){for(s=s.child;s!==null;)Vg(e,t,s),s=s.sibling}function Vg(e,t,s){if(je&&typeof je.onCommitFiberUnmount=="function")try{je.onCommitFiberUnmount($e,s)}catch{}switch(s.tag){case 26:_n||Rr(s,t),wi(e,t,s),s.memoizedState?s.memoizedState.count--:s.stateNode&&(s=s.stateNode,s.parentNode.removeChild(s));break;case 27:_n||Rr(s,t);var o=dn,f=Ja;ol(s.type)&&(dn=s.stateNode,Ja=!1),wi(e,t,s),gu(s.stateNode),dn=o,Ja=f;break;case 5:_n||Rr(s,t);case 6:if(o=dn,f=Ja,dn=null,wi(e,t,s),dn=o,Ja=f,dn!==null)if(Ja)try{(dn.nodeType===9?dn.body:dn.nodeName==="HTML"?dn.ownerDocument.body:dn).removeChild(s.stateNode)}catch(p){Wt(s,t,p)}else try{dn.removeChild(s.stateNode)}catch(p){Wt(s,t,p)}break;case 18:dn!==null&&(Ja?(e=dn,Hv(e.nodeType===9?e.body:e.nodeName==="HTML"?e.ownerDocument.body:e,s.stateNode),uc(e)):Hv(dn,s.stateNode));break;case 4:o=dn,f=Ja,dn=s.stateNode.containerInfo,Ja=!0,wi(e,t,s),dn=o,Ja=f;break;case 0:case 11:case 14:case 15:tl(2,s,t),_n||tl(4,s,t),wi(e,t,s);break;case 1:_n||(Rr(s,t),o=s.stateNode,typeof o.componentWillUnmount=="function"&&Fg(s,t,o)),wi(e,t,s);break;case 21:wi(e,t,s);break;case 22:_n=(o=_n)||s.memoizedState!==null,wi(e,t,s),_n=o;break;default:wi(e,t,s)}}function Wg(e,t){if(t.memoizedState===null&&(e=t.alternate,e!==null&&(e=e.memoizedState,e!==null))){e=e.dehydrated;try{uc(e)}catch(s){Wt(t,t.return,s)}}}function Yg(e,t){if(t.memoizedState===null&&(e=t.alternate,e!==null&&(e=e.memoizedState,e!==null&&(e=e.dehydrated,e!==null))))try{uc(e)}catch(s){Wt(t,t.return,s)}}function oS(e){switch(e.tag){case 31:case 13:case 19:var t=e.stateNode;return t===null&&(t=e.stateNode=new Ug),t;case 22:return e=e.stateNode,t=e._retryCache,t===null&&(t=e._retryCache=new Ug),t;default:throw Error(l(435,e.tag))}}function Cd(e,t){var s=oS(e);t.forEach(function(o){if(!s.has(o)){s.add(o);var f=vS.bind(null,e,o);o.then(f,f)}})}function es(e,t){var s=t.deletions;if(s!==null)for(var o=0;o<s.length;o++){var f=s[o],p=e,S=t,R=S;e:for(;R!==null;){switch(R.tag){case 27:if(ol(R.type)){dn=R.stateNode,Ja=!1;break e}break;case 5:dn=R.stateNode,Ja=!1;break e;case 3:case 4:dn=R.stateNode.containerInfo,Ja=!0;break e}R=R.return}if(dn===null)throw Error(l(160));Vg(p,S,f),dn=null,Ja=!1,p=f.alternate,p!==null&&(p.return=null),f.return=null}if(t.subtreeFlags&13886)for(t=t.child;t!==null;)Kg(t,e),t=t.sibling}var hr=null;function Kg(e,t){var s=e.alternate,o=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:es(t,e),ts(e),o&4&&(tl(3,e,e.return),iu(3,e),tl(5,e,e.return));break;case 1:es(t,e),ts(e),o&512&&(_n||s===null||Rr(s,s.return)),o&64&&xi&&(e=e.updateQueue,e!==null&&(o=e.callbacks,o!==null&&(s=e.shared.hiddenCallbacks,e.shared.hiddenCallbacks=s===null?o:s.concat(o))));break;case 26:var f=hr;if(es(t,e),ts(e),o&512&&(_n||s===null||Rr(s,s.return)),o&4){var p=s!==null?s.memoizedState:null;if(o=e.memoizedState,s===null)if(o===null)if(e.stateNode===null){e:{o=e.type,s=e.memoizedProps,f=f.ownerDocument||f;t:switch(o){case"title":p=f.getElementsByTagName("title")[0],(!p||p[Mt]||p[re]||p.namespaceURI==="http://www.w3.org/2000/svg"||p.hasAttribute("itemprop"))&&(p=f.createElement(o),f.head.insertBefore(p,f.querySelector("head > title"))),fa(p,o,s),p[re]=e,At(p),o=p;break e;case"link":var S=Kv("link","href",f).get(o+(s.href||""));if(S){for(var R=0;R<S.length;R++)if(p=S[R],p.getAttribute("href")===(s.href==null||s.href===""?null:s.href)&&p.getAttribute("rel")===(s.rel==null?null:s.rel)&&p.getAttribute("title")===(s.title==null?null:s.title)&&p.getAttribute("crossorigin")===(s.crossOrigin==null?null:s.crossOrigin)){S.splice(R,1);break t}}p=f.createElement(o),fa(p,o,s),f.head.appendChild(p);break;case"meta":if(S=Kv("meta","content",f).get(o+(s.content||""))){for(R=0;R<S.length;R++)if(p=S[R],p.getAttribute("content")===(s.content==null?null:""+s.content)&&p.getAttribute("name")===(s.name==null?null:s.name)&&p.getAttribute("property")===(s.property==null?null:s.property)&&p.getAttribute("http-equiv")===(s.httpEquiv==null?null:s.httpEquiv)&&p.getAttribute("charset")===(s.charSet==null?null:s.charSet)){S.splice(R,1);break t}}p=f.createElement(o),fa(p,o,s),f.head.appendChild(p);break;default:throw Error(l(468,o))}p[re]=e,At(p),o=p}e.stateNode=o}else Qv(f,e.type,e.stateNode);else e.stateNode=Yv(f,o,e.memoizedProps);else p!==o?(p===null?s.stateNode!==null&&(s=s.stateNode,s.parentNode.removeChild(s)):p.count--,o===null?Qv(f,e.type,e.stateNode):Yv(f,o,e.memoizedProps)):o===null&&e.stateNode!==null&&jm(e,e.memoizedProps,s.memoizedProps)}break;case 27:es(t,e),ts(e),o&512&&(_n||s===null||Rr(s,s.return)),s!==null&&o&4&&jm(e,e.memoizedProps,s.memoizedProps);break;case 5:if(es(t,e),ts(e),o&512&&(_n||s===null||Rr(s,s.return)),e.flags&32){f=e.stateNode;try{Cn(f,"")}catch(Qe){Wt(e,e.return,Qe)}}o&4&&e.stateNode!=null&&(f=e.memoizedProps,jm(e,f,s!==null?s.memoizedProps:f)),o&1024&&(Nm=!0);break;case 6:if(es(t,e),ts(e),o&4){if(e.stateNode===null)throw Error(l(162));o=e.memoizedProps,s=e.stateNode;try{s.nodeValue=o}catch(Qe){Wt(e,e.return,Qe)}}break;case 3:if(Fd=null,f=hr,hr=Od(t.containerInfo),es(t,e),hr=f,ts(e),o&4&&s!==null&&s.memoizedState.isDehydrated)try{uc(t.containerInfo)}catch(Qe){Wt(e,e.return,Qe)}Nm&&(Nm=!1,Qg(e));break;case 4:o=hr,hr=Od(e.stateNode.containerInfo),es(t,e),ts(e),hr=o;break;case 12:es(t,e),ts(e);break;case 31:es(t,e),ts(e),o&4&&(o=e.updateQueue,o!==null&&(e.updateQueue=null,Cd(e,o)));break;case 13:es(t,e),ts(e),e.child.flags&8192&&e.memoizedState!==null!=(s!==null&&s.memoizedState!==null)&&(jd=Ae()),o&4&&(o=e.updateQueue,o!==null&&(e.updateQueue=null,Cd(e,o)));break;case 22:f=e.memoizedState!==null;var V=s!==null&&s.memoizedState!==null,ue=xi,xe=_n;if(xi=ue||f,_n=xe||V,es(t,e),_n=xe,xi=ue,ts(e),o&8192)e:for(t=e.stateNode,t._visibility=f?t._visibility&-2:t._visibility|1,f&&(s===null||V||xi||_n||Jl(e)),s=null,t=e;;){if(t.tag===5||t.tag===26){if(s===null){V=s=t;try{if(p=V.stateNode,f)S=p.style,typeof S.setProperty=="function"?S.setProperty("display","none","important"):S.display="none";else{R=V.stateNode;var ke=V.memoizedProps.style,me=ke!=null&&ke.hasOwnProperty("display")?ke.display:null;R.style.display=me==null||typeof me=="boolean"?"":(""+me).trim()}}catch(Qe){Wt(V,V.return,Qe)}}}else if(t.tag===6){if(s===null){V=t;try{V.stateNode.nodeValue=f?"":V.memoizedProps}catch(Qe){Wt(V,V.return,Qe)}}}else if(t.tag===18){if(s===null){V=t;try{var ge=V.stateNode;f?Fv(ge,!0):Fv(V.stateNode,!1)}catch(Qe){Wt(V,V.return,Qe)}}}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;s===t&&(s=null),t=t.return}s===t&&(s=null),t.sibling.return=t.return,t=t.sibling}o&4&&(o=e.updateQueue,o!==null&&(s=o.retryQueue,s!==null&&(o.retryQueue=null,Cd(e,s))));break;case 19:es(t,e),ts(e),o&4&&(o=e.updateQueue,o!==null&&(e.updateQueue=null,Cd(e,o)));break;case 30:break;case 21:break;default:es(t,e),ts(e)}}function ts(e){var t=e.flags;if(t&2){try{for(var s,o=e.return;o!==null;){if(Bg(o)){s=o;break}o=o.return}if(s==null)throw Error(l(160));switch(s.tag){case 27:var f=s.stateNode,p=Am(e);Sd(e,p,f);break;case 5:var S=s.stateNode;s.flags&32&&(Cn(S,""),s.flags&=-33);var R=Am(e);Sd(e,R,S);break;case 3:case 4:var V=s.stateNode.containerInfo,ue=Am(e);Mm(e,ue,V);break;default:throw Error(l(161))}}catch(xe){Wt(e,e.return,xe)}e.flags&=-3}t&4096&&(e.flags&=-4097)}function Qg(e){if(e.subtreeFlags&1024)for(e=e.child;e!==null;){var t=e;Qg(t),t.tag===5&&t.flags&1024&&t.stateNode.reset(),e=e.sibling}}function Si(e,t){if(t.subtreeFlags&8772)for(t=t.child;t!==null;)qg(e,t.alternate,t),t=t.sibling}function Jl(e){for(e=e.child;e!==null;){var t=e;switch(t.tag){case 0:case 11:case 14:case 15:tl(4,t,t.return),Jl(t);break;case 1:Rr(t,t.return);var s=t.stateNode;typeof s.componentWillUnmount=="function"&&Fg(t,t.return,s),Jl(t);break;case 27:gu(t.stateNode);case 26:case 5:Rr(t,t.return),Jl(t);break;case 22:t.memoizedState===null&&Jl(t);break;case 30:Jl(t);break;default:Jl(t)}e=e.sibling}}function Ci(e,t,s){for(s=s&&(t.subtreeFlags&8772)!==0,t=t.child;t!==null;){var o=t.alternate,f=e,p=t,S=p.flags;switch(p.tag){case 0:case 11:case 15:Ci(f,p,s),iu(4,p);break;case 1:if(Ci(f,p,s),o=p,f=o.stateNode,typeof f.componentDidMount=="function")try{f.componentDidMount()}catch(ue){Wt(o,o.return,ue)}if(o=p,f=o.updateQueue,f!==null){var R=o.stateNode;try{var V=f.shared.hiddenCallbacks;if(V!==null)for(f.shared.hiddenCallbacks=null,f=0;f<V.length;f++)Uo(V[f],R)}catch(ue){Wt(o,o.return,ue)}}s&&S&64&&Hg(p),lu(p,p.return);break;case 27:Pg(p);case 26:case 5:Ci(f,p,s),s&&o===null&&S&4&&$g(p),lu(p,p.return);break;case 12:Ci(f,p,s);break;case 31:Ci(f,p,s),s&&S&4&&Wg(f,p);break;case 13:Ci(f,p,s),s&&S&4&&Yg(f,p);break;case 22:p.memoizedState===null&&Ci(f,p,s),lu(p,p.return);break;case 30:break;default:Ci(f,p,s)}t=t.sibling}}function Tm(e,t){var s=null;e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(s=e.memoizedState.cachePool.pool),e=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(e=t.memoizedState.cachePool.pool),e!==s&&(e!=null&&e.refCount++,s!=null&&or(s))}function Rm(e,t){e=null,t.alternate!==null&&(e=t.alternate.memoizedState.cache),t=t.memoizedState.cache,t!==e&&(t.refCount++,e!=null&&or(e))}function pr(e,t,s,o){if(t.subtreeFlags&10256)for(t=t.child;t!==null;)Xg(e,t,s,o),t=t.sibling}function Xg(e,t,s,o){var f=t.flags;switch(t.tag){case 0:case 11:case 15:pr(e,t,s,o),f&2048&&iu(9,t);break;case 1:pr(e,t,s,o);break;case 3:pr(e,t,s,o),f&2048&&(e=null,t.alternate!==null&&(e=t.alternate.memoizedState.cache),t=t.memoizedState.cache,t!==e&&(t.refCount++,e!=null&&or(e)));break;case 12:if(f&2048){pr(e,t,s,o),e=t.stateNode;try{var p=t.memoizedProps,S=p.id,R=p.onPostCommit;typeof R=="function"&&R(S,t.alternate===null?"mount":"update",e.passiveEffectDuration,-0)}catch(V){Wt(t,t.return,V)}}else pr(e,t,s,o);break;case 31:pr(e,t,s,o);break;case 13:pr(e,t,s,o);break;case 23:break;case 22:p=t.stateNode,S=t.alternate,t.memoizedState!==null?p._visibility&2?pr(e,t,s,o):ou(e,t):p._visibility&2?pr(e,t,s,o):(p._visibility|=2,Jo(e,t,s,o,(t.subtreeFlags&10256)!==0||!1)),f&2048&&Tm(S,t);break;case 24:pr(e,t,s,o),f&2048&&Rm(t.alternate,t);break;default:pr(e,t,s,o)}}function Jo(e,t,s,o,f){for(f=f&&((t.subtreeFlags&10256)!==0||!1),t=t.child;t!==null;){var p=e,S=t,R=s,V=o,ue=S.flags;switch(S.tag){case 0:case 11:case 15:Jo(p,S,R,V,f),iu(8,S);break;case 23:break;case 22:var xe=S.stateNode;S.memoizedState!==null?xe._visibility&2?Jo(p,S,R,V,f):ou(p,S):(xe._visibility|=2,Jo(p,S,R,V,f)),f&&ue&2048&&Tm(S.alternate,S);break;case 24:Jo(p,S,R,V,f),f&&ue&2048&&Rm(S.alternate,S);break;default:Jo(p,S,R,V,f)}t=t.sibling}}function ou(e,t){if(t.subtreeFlags&10256)for(t=t.child;t!==null;){var s=e,o=t,f=o.flags;switch(o.tag){case 22:ou(s,o),f&2048&&Tm(o.alternate,o);break;case 24:ou(s,o),f&2048&&Rm(o.alternate,o);break;default:ou(s,o)}t=t.sibling}}var cu=8192;function ec(e,t,s){if(e.subtreeFlags&cu)for(e=e.child;e!==null;)Zg(e,t,s),e=e.sibling}function Zg(e,t,s){switch(e.tag){case 26:ec(e,t,s),e.flags&cu&&e.memoizedState!==null&&YS(s,hr,e.memoizedState,e.memoizedProps);break;case 5:ec(e,t,s);break;case 3:case 4:var o=hr;hr=Od(e.stateNode.containerInfo),ec(e,t,s),hr=o;break;case 22:e.memoizedState===null&&(o=e.alternate,o!==null&&o.memoizedState!==null?(o=cu,cu=16777216,ec(e,t,s),cu=o):ec(e,t,s));break;default:ec(e,t,s)}}function Jg(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 uu(e){var t=e.deletions;if((e.flags&16)!==0){if(t!==null)for(var s=0;s<t.length;s++){var o=t[s];Xn=o,tv(o,e)}Jg(e)}if(e.subtreeFlags&10256)for(e=e.child;e!==null;)ev(e),e=e.sibling}function ev(e){switch(e.tag){case 0:case 11:case 15:uu(e),e.flags&2048&&tl(9,e,e.return);break;case 3:uu(e);break;case 12:uu(e);break;case 22:var t=e.stateNode;e.memoizedState!==null&&t._visibility&2&&(e.return===null||e.return.tag!==13)?(t._visibility&=-3,kd(e)):uu(e);break;default:uu(e)}}function kd(e){var t=e.deletions;if((e.flags&16)!==0){if(t!==null)for(var s=0;s<t.length;s++){var o=t[s];Xn=o,tv(o,e)}Jg(e)}for(e=e.child;e!==null;){switch(t=e,t.tag){case 0:case 11:case 15:tl(8,t,t.return),kd(t);break;case 22:s=t.stateNode,s._visibility&2&&(s._visibility&=-3,kd(t));break;default:kd(t)}e=e.sibling}}function tv(e,t){for(;Xn!==null;){var s=Xn;switch(s.tag){case 0:case 11:case 15:tl(8,s,t);break;case 23:case 22:if(s.memoizedState!==null&&s.memoizedState.cachePool!==null){var o=s.memoizedState.cachePool.pool;o!=null&&o.refCount++}break;case 24:or(s.memoizedState.cache)}if(o=s.child,o!==null)o.return=s,Xn=o;else e:for(s=e;Xn!==null;){o=Xn;var f=o.sibling,p=o.return;if(Gg(o),o===s){Xn=null;break e}if(f!==null){f.return=p,Xn=f;break e}Xn=p}}}var cS={getCacheForType:function(e){var t=ln(kn),s=t.data.get(e);return s===void 0&&(s=e(),t.data.set(e,s)),s},cacheSignal:function(){return ln(kn).controller.signal}},uS=typeof WeakMap=="function"?WeakMap:Map,Pt=0,tn=null,Dt=null,_t=0,Vt=0,ms=null,nl=!1,tc=!1,Em=!1,ki=0,bn=0,al=0,eo=0,Dm=0,hs=0,nc=0,du=null,ns=null,Lm=!1,jd=0,nv=0,Ad=1/0,Md=null,sl=null,qn=0,rl=null,ac=null,ji=0,_m=0,Im=null,av=null,fu=0,zm=null;function ps(){return(Pt&2)!==0&&_t!==0?_t&-_t:z.T!==null?Pm():Fa()}function sv(){if(hs===0)if((_t&536870912)===0||wt){var e=Ot;Ot<<=1,(Ot&3932160)===0&&(Ot=262144),hs=e}else hs=536870912;return e=wa.current,e!==null&&(e.flags|=32),hs}function as(e,t,s){(e===tn&&(Vt===2||Vt===9)||e.cancelPendingCommit!==null)&&(sc(e,0),il(e,_t,hs,!1)),qs(e,s),((Pt&2)===0||e!==tn)&&(e===tn&&((Pt&2)===0&&(eo|=s),bn===4&&il(e,_t,hs,!1)),Er(e))}function rv(e,t,s){if((Pt&6)!==0)throw Error(l(327));var o=!s&&(t&127)===0&&(t&e.expiredLanes)===0||wn(e,t),f=o?mS(e,t):Hm(e,t,!0),p=o;do{if(f===0){tc&&!o&&il(e,t,0,!1);break}else{if(s=e.current.alternate,p&&!dS(s)){f=Hm(e,t,!1),p=!1;continue}if(f===2){if(p=t,e.errorRecoveryDisabledLanes&p)var S=0;else S=e.pendingLanes&-536870913,S=S!==0?S:S&536870912?536870912:0;if(S!==0){t=S;e:{var R=e;f=du;var V=R.current.memoizedState.isDehydrated;if(V&&(sc(R,S).flags|=256),S=Hm(R,S,!1),S!==2){if(Em&&!V){R.errorRecoveryDisabledLanes|=p,eo|=p,f=4;break e}p=ns,ns=f,p!==null&&(ns===null?ns=p:ns.push.apply(ns,p))}f=S}if(p=!1,f!==2)continue}}if(f===1){sc(e,0),il(e,t,0,!0);break}e:{switch(o=e,p=f,p){case 0:case 1:throw Error(l(345));case 4:if((t&4194048)!==t)break;case 6:il(o,t,hs,!nl);break e;case 2:ns=null;break;case 3:case 5:break;default:throw Error(l(329))}if((t&62914560)===t&&(f=jd+300-Ae(),10<f)){if(il(o,t,hs,!nl),Oe(o,0,!0)!==0)break e;ji=t,o.timeoutHandle=zv(iv.bind(null,o,s,ns,Md,Lm,t,hs,eo,nc,nl,p,"Throttled",-0,0),f);break e}iv(o,s,ns,Md,Lm,t,hs,eo,nc,nl,p,null,-0,0)}}break}while(!0);Er(e)}function iv(e,t,s,o,f,p,S,R,V,ue,xe,ke,me,ge){if(e.timeoutHandle=-1,ke=t.subtreeFlags,ke&8192||(ke&16785408)===16785408){ke={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:ra},Zg(t,p,ke);var Qe=(p&62914560)===p?jd-Ae():(p&4194048)===p?nv-Ae():0;if(Qe=KS(ke,Qe),Qe!==null){ji=p,e.cancelPendingCommit=Qe(hv.bind(null,e,t,p,s,o,f,S,R,V,xe,ke,null,me,ge)),il(e,p,S,!ue);return}}hv(e,t,p,s,o,f,S,R,V)}function dS(e){for(var t=e;;){var s=t.tag;if((s===0||s===11||s===15)&&t.flags&16384&&(s=t.updateQueue,s!==null&&(s=s.stores,s!==null)))for(var o=0;o<s.length;o++){var f=s[o],p=f.getSnapshot;f=f.value;try{if(!an(p(),f))return!1}catch{return!1}}if(s=t.child,t.subtreeFlags&16384&&s!==null)s.return=t,t=s;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 il(e,t,s,o){t&=~Dm,t&=~eo,e.suspendedLanes|=t,e.pingedLanes&=~t,o&&(e.warmLanes|=t),o=e.expirationTimes;for(var f=t;0<f;){var p=31-bt(f),S=1<<p;o[p]=-1,f&=~S}s!==0&&Gs(e,s,t)}function Nd(){return(Pt&6)===0?(mu(0),!1):!0}function Om(){if(Dt!==null){if(Vt===0)var e=Dt.return;else e=Dt,Wa=rr=null,eu(e),Is=null,$l=0,e=Dt;for(;e!==null;)Og(e.alternate,e),e=e.return;Dt=null}}function sc(e,t){var s=e.timeoutHandle;s!==-1&&(e.timeoutHandle=-1,ES(s)),s=e.cancelPendingCommit,s!==null&&(e.cancelPendingCommit=null,s()),ji=0,Om(),tn=e,Dt=s=ya(e.current,null),_t=t,Vt=0,ms=null,nl=!1,tc=wn(e,t),Em=!1,nc=hs=Dm=eo=al=bn=0,ns=du=null,Lm=!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-bt(o),p=1<<f;t|=e[f],o&=~p}return ki=t,ar(),s}function lv(e,t){et=null,z.H=au,t===Nr||t===Hl?(t=Qi(),Vt=3):t===Yc?(t=Qi(),Vt=4):Vt=t===pm?8:t!==null&&typeof t=="object"&&typeof t.then=="function"?6:1,ms=t,Dt===null&&(bn=1,vd(e,Un(t,e.current)))}function ov(){var e=wa.current;return e===null?!0:(_t&4194048)===_t?Sa===null:(_t&62914560)===_t||(_t&536870912)!==0?e===Sa:!1}function cv(){var e=z.H;return z.H=au,e===null?au:e}function uv(){var e=z.A;return z.A=cS,e}function Td(){bn=4,nl||(_t&4194048)!==_t&&wa.current!==null||(tc=!0),(al&134217727)===0&&(eo&134217727)===0||tn===null||il(tn,_t,hs,!1)}function Hm(e,t,s){var o=Pt;Pt|=2;var f=cv(),p=uv();(tn!==e||_t!==t)&&(Md=null,sc(e,t)),t=!1;var S=bn;e:do try{if(Vt!==0&&Dt!==null){var R=Dt,V=ms;switch(Vt){case 8:Om(),S=6;break e;case 3:case 2:case 9:case 6:wa.current===null&&(t=!0);var ue=Vt;if(Vt=0,ms=null,rc(e,R,V,ue),s&&tc){S=0;break e}break;default:ue=Vt,Vt=0,ms=null,rc(e,R,V,ue)}}fS(),S=bn;break}catch(xe){lv(e,xe)}while(!0);return t&&e.shellSuspendCounter++,Wa=rr=null,Pt=o,z.H=f,z.A=p,Dt===null&&(tn=null,_t=0,ar()),S}function fS(){for(;Dt!==null;)dv(Dt)}function mS(e,t){var s=Pt;Pt|=2;var o=cv(),f=uv();tn!==e||_t!==t?(Md=null,Ad=Ae()+500,sc(e,t)):tc=wn(e,t);e:do try{if(Vt!==0&&Dt!==null){t=Dt;var p=ms;t:switch(Vt){case 1:Vt=0,ms=null,rc(e,t,p,1);break;case 2:case 9:if(Kc(p)){Vt=0,ms=null,fv(t);break}t=function(){Vt!==2&&Vt!==9||tn!==e||(Vt=7),Er(e)},p.then(t,t);break e;case 3:Vt=7;break e;case 4:Vt=5;break e;case 7:Kc(p)?(Vt=0,ms=null,fv(t)):(Vt=0,ms=null,rc(e,t,p,7));break;case 5:var S=null;switch(Dt.tag){case 26:S=Dt.memoizedState;case 5:case 27:var R=Dt;if(S?Xv(S):R.stateNode.complete){Vt=0,ms=null;var V=R.sibling;if(V!==null)Dt=V;else{var ue=R.return;ue!==null?(Dt=ue,Rd(ue)):Dt=null}break t}}Vt=0,ms=null,rc(e,t,p,5);break;case 6:Vt=0,ms=null,rc(e,t,p,6);break;case 8:Om(),bn=6;break e;default:throw Error(l(462))}}hS();break}catch(xe){lv(e,xe)}while(!0);return Wa=rr=null,z.H=o,z.A=f,Pt=s,Dt!==null?0:(tn=null,_t=0,ar(),bn)}function hS(){for(;Dt!==null&&!U();)dv(Dt)}function dv(e){var t=Ig(e.alternate,e,ki);e.memoizedProps=e.pendingProps,t===null?Rd(e):Dt=t}function fv(e){var t=e,s=t.alternate;switch(t.tag){case 15:case 0:t=Tg(s,t,t.pendingProps,t.type,void 0,_t);break;case 11:t=Tg(s,t,t.pendingProps,t.type.render,t.ref,_t);break;case 5:eu(t);default:Og(s,t),t=Dt=_l(t,ki),t=Ig(s,t,ki)}e.memoizedProps=e.pendingProps,t===null?Rd(e):Dt=t}function rc(e,t,s,o){Wa=rr=null,eu(t),Is=null,$l=0;var f=t.return;try{if(nS(e,f,t,s,_t)){bn=1,vd(e,Un(s,e.current)),Dt=null;return}}catch(p){if(f!==null)throw Dt=f,p;bn=1,vd(e,Un(s,e.current)),Dt=null;return}t.flags&32768?(wt||o===1?e=!0:tc||(_t&536870912)!==0?e=!1:(nl=e=!0,(o===2||o===9||o===3||o===6)&&(o=wa.current,o!==null&&o.tag===13&&(o.flags|=16384))),mv(t,e)):Rd(t)}function Rd(e){var t=e;do{if((t.flags&32768)!==0){mv(t,nl);return}e=t.return;var s=rS(t.alternate,t,ki);if(s!==null){Dt=s;return}if(t=t.sibling,t!==null){Dt=t;return}Dt=t=e}while(t!==null);bn===0&&(bn=5)}function mv(e,t){do{var s=iS(e.alternate,e);if(s!==null){s.flags&=32767,Dt=s;return}if(s=e.return,s!==null&&(s.flags|=32768,s.subtreeFlags=0,s.deletions=null),!t&&(e=e.sibling,e!==null)){Dt=e;return}Dt=e=s}while(e!==null);bn=6,Dt=null}function hv(e,t,s,o,f,p,S,R,V){e.cancelPendingCommit=null;do Ed();while(qn!==0);if((Pt&6)!==0)throw Error(l(327));if(t!==null){if(t===e.current)throw Error(l(177));if(p=t.lanes|t.childLanes,p|=No,Yn(e,s,p,S,R,V),e===tn&&(Dt=tn=null,_t=0),ac=t,rl=e,ji=s,_m=p,Im=f,av=o,(t.subtreeFlags&10256)!==0||(t.flags&10256)!==0?(e.callbackNode=null,e.callbackPriority=0,yS(yt,function(){return bv(),null})):(e.callbackNode=null,e.callbackPriority=0),o=(t.flags&13878)!==0,(t.subtreeFlags&13878)!==0||o){o=z.T,z.T=null,f=se.p,se.p=2,S=Pt,Pt|=4;try{lS(e,t,s)}finally{Pt=S,se.p=f,z.T=o}}qn=1,pv(),gv(),vv()}}function pv(){if(qn===1){qn=0;var e=rl,t=ac,s=(t.flags&13878)!==0;if((t.subtreeFlags&13878)!==0||s){s=z.T,z.T=null;var o=se.p;se.p=2;var f=Pt;Pt|=4;try{Kg(t,e);var p=Qm,S=jo(e.containerInfo),R=p.focusedElem,V=p.selectionRange;if(S!==R&&R&&R.ownerDocument&&sd(R.ownerDocument.documentElement,R)){if(V!==null&&Kr(R)){var ue=V.start,xe=V.end;if(xe===void 0&&(xe=ue),"selectionStart"in R)R.selectionStart=ue,R.selectionEnd=Math.min(xe,R.value.length);else{var ke=R.ownerDocument||document,me=ke&&ke.defaultView||window;if(me.getSelection){var ge=me.getSelection(),Qe=R.textContent.length,ut=Math.min(V.start,Qe),Xt=V.end===void 0?ut:Math.min(V.end,Qe);!ge.extend&&ut>Xt&&(S=Xt,Xt=ut,ut=S);var ae=ad(R,ut),X=ad(R,Xt);if(ae&&X&&(ge.rangeCount!==1||ge.anchorNode!==ae.node||ge.anchorOffset!==ae.offset||ge.focusNode!==X.node||ge.focusOffset!==X.offset)){var oe=ke.createRange();oe.setStart(ae.node,ae.offset),ge.removeAllRanges(),ut>Xt?(ge.addRange(oe),ge.extend(X.node,X.offset)):(oe.setEnd(X.node,X.offset),ge.addRange(oe))}}}}for(ke=[],ge=R;ge=ge.parentNode;)ge.nodeType===1&&ke.push({element:ge,left:ge.scrollLeft,top:ge.scrollTop});for(typeof R.focus=="function"&&R.focus(),R=0;R<ke.length;R++){var Se=ke[R];Se.element.scrollLeft=Se.left,Se.element.scrollTop=Se.top}}Ud=!!Km,Qm=Km=null}finally{Pt=f,se.p=o,z.T=s}}e.current=t,qn=2}}function gv(){if(qn===2){qn=0;var e=rl,t=ac,s=(t.flags&8772)!==0;if((t.subtreeFlags&8772)!==0||s){s=z.T,z.T=null;var o=se.p;se.p=2;var f=Pt;Pt|=4;try{qg(e,t.alternate,t)}finally{Pt=f,se.p=o,z.T=s}}qn=3}}function vv(){if(qn===4||qn===3){qn=0,ve();var e=rl,t=ac,s=ji,o=av;(t.subtreeFlags&10256)!==0||(t.flags&10256)!==0?qn=5:(qn=0,ac=rl=null,yv(e,e.pendingLanes));var f=e.pendingLanes;if(f===0&&(sl=null),fn(s),t=t.stateNode,je&&typeof je.onCommitFiberRoot=="function")try{je.onCommitFiberRoot($e,t,void 0,(t.current.flags&128)===128)}catch{}if(o!==null){t=z.T,f=se.p,se.p=2,z.T=null;try{for(var p=e.onRecoverableError,S=0;S<o.length;S++){var R=o[S];p(R.value,{componentStack:R.stack})}}finally{z.T=t,se.p=f}}(ji&3)!==0&&Ed(),Er(e),f=e.pendingLanes,(s&261930)!==0&&(f&42)!==0?e===zm?fu++:(fu=0,zm=e):fu=0,mu(0)}}function yv(e,t){(e.pooledCacheLanes&=t)===0&&(t=e.pooledCache,t!=null&&(e.pooledCache=null,or(t)))}function Ed(){return pv(),gv(),vv(),bv()}function bv(){if(qn!==5)return!1;var e=rl,t=_m;_m=0;var s=fn(ji),o=z.T,f=se.p;try{se.p=32>s?32:s,z.T=null,s=Im,Im=null;var p=rl,S=ji;if(qn=0,ac=rl=null,ji=0,(Pt&6)!==0)throw Error(l(331));var R=Pt;if(Pt|=4,ev(p.current),Xg(p,p.current,S,s),Pt=R,mu(0,!1),je&&typeof je.onPostCommitFiberRoot=="function")try{je.onPostCommitFiberRoot($e,p)}catch{}return!0}finally{se.p=f,z.T=o,yv(e,t)}}function xv(e,t,s){t=Un(s,t),t=hm(e.stateNode,t,2),e=Os(e,t,2),e!==null&&(qs(e,2),Er(e))}function Wt(e,t,s){if(e.tag===3)xv(e,e,s);else for(;t!==null;){if(t.tag===3){xv(t,e,s);break}else if(t.tag===1){var o=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof o.componentDidCatch=="function"&&(sl===null||!sl.has(o))){e=Un(s,e),s=wg(2),o=Os(t,s,2),o!==null&&(Sg(s,o,t,e),qs(o,2),Er(o));break}}t=t.return}}function Fm(e,t,s){var o=e.pingCache;if(o===null){o=e.pingCache=new uS;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(s)||(Em=!0,f.add(s),e=pS.bind(null,e,t,s),t.then(e,e))}function pS(e,t,s){var o=e.pingCache;o!==null&&o.delete(t),e.pingedLanes|=e.suspendedLanes&s,e.warmLanes&=~s,tn===e&&(_t&s)===s&&(bn===4||bn===3&&(_t&62914560)===_t&&300>Ae()-jd?(Pt&2)===0&&sc(e,0):Dm|=s,nc===_t&&(nc=0)),Er(e)}function wv(e,t){t===0&&(t=ws()),e=_a(e,t),e!==null&&(qs(e,t),Er(e))}function gS(e){var t=e.memoizedState,s=0;t!==null&&(s=t.retryLane),wv(e,s)}function vS(e,t){var s=0;switch(e.tag){case 31:case 13:var o=e.stateNode,f=e.memoizedState;f!==null&&(s=f.retryLane);break;case 19:o=e.stateNode;break;case 22:o=e.stateNode._retryCache;break;default:throw Error(l(314))}o!==null&&o.delete(t),wv(e,s)}function yS(e,t){return Ze(e,t)}var Dd=null,ic=null,$m=!1,Ld=!1,Bm=!1,ll=0;function Er(e){e!==ic&&e.next===null&&(ic===null?Dd=ic=e:ic=ic.next=e),Ld=!0,$m||($m=!0,xS())}function mu(e,t){if(!Bm&&Ld){Bm=!0;do for(var s=!1,o=Dd;o!==null;){if(e!==0){var f=o.pendingLanes;if(f===0)var p=0;else{var S=o.suspendedLanes,R=o.pingedLanes;p=(1<<31-bt(42|e)+1)-1,p&=f&~(S&~R),p=p&201326741?p&201326741|1:p?p|2:0}p!==0&&(s=!0,jv(o,p))}else p=_t,p=Oe(o,o===tn?p:0,o.cancelPendingCommit!==null||o.timeoutHandle!==-1),(p&3)===0||wn(o,p)||(s=!0,jv(o,p));o=o.next}while(s);Bm=!1}}function bS(){Sv()}function Sv(){Ld=$m=!1;var e=0;ll!==0&&RS()&&(e=ll);for(var t=Ae(),s=null,o=Dd;o!==null;){var f=o.next,p=Cv(o,t);p===0?(o.next=null,s===null?Dd=f:s.next=f,f===null&&(ic=s)):(s=o,(e!==0||(p&3)!==0)&&(Ld=!0)),o=f}qn!==0&&qn!==5||mu(e),ll!==0&&(ll=0)}function Cv(e,t){for(var s=e.suspendedLanes,o=e.pingedLanes,f=e.expirationTimes,p=e.pendingLanes&-62914561;0<p;){var S=31-bt(p),R=1<<S,V=f[S];V===-1?((R&s)===0||(R&o)!==0)&&(f[S]=On(R,t)):V<=t&&(e.expiredLanes|=R),p&=~R}if(t=tn,s=_t,s=Oe(e,e===t?s:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),o=e.callbackNode,s===0||e===t&&(Vt===2||Vt===9)||e.cancelPendingCommit!==null)return o!==null&&o!==null&&dt(o),e.callbackNode=null,e.callbackPriority=0;if((s&3)===0||wn(e,s)){if(t=s&-s,t===e.callbackPriority)return t;switch(o!==null&&dt(o),fn(s)){case 2:case 8:s=it;break;case 32:s=yt;break;case 268435456:s=kt;break;default:s=yt}return o=kv.bind(null,e),s=Ze(s,o),e.callbackPriority=t,e.callbackNode=s,t}return o!==null&&o!==null&&dt(o),e.callbackPriority=2,e.callbackNode=null,2}function kv(e,t){if(qn!==0&&qn!==5)return e.callbackNode=null,e.callbackPriority=0,null;var s=e.callbackNode;if(Ed()&&e.callbackNode!==s)return null;var o=_t;return o=Oe(e,e===tn?o:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),o===0?null:(rv(e,o,t),Cv(e,Ae()),e.callbackNode!=null&&e.callbackNode===s?kv.bind(null,e):null)}function jv(e,t){if(Ed())return null;rv(e,t,!0)}function xS(){DS(function(){(Pt&6)!==0?Ze(ft,bS):Sv()})}function Pm(){if(ll===0){var e=oi;e===0&&(e=nt,nt<<=1,(nt&261888)===0&&(nt=256)),ll=e}return ll}function Av(e){return e==null||typeof e=="symbol"||typeof e=="boolean"?null:typeof e=="function"?e:Pr(""+e)}function Mv(e,t){var s=t.ownerDocument.createElement("input");return s.name=t.name,s.value=t.value,e.id&&s.setAttribute("form",e.id),t.parentNode.insertBefore(s,t),e=new FormData(e),s.parentNode.removeChild(s),e}function wS(e,t,s,o,f){if(t==="submit"&&s&&s.stateNode===f){var p=Av((f[Te]||null).action),S=o.submitter;S&&(t=(t=S[Te]||null)?Av(t.formAction):S.getAttribute("formAction"),t!==null&&(p=t,S=null));var R=new Qs("action","action",null,o,f);e.push({event:R,listeners:[{instance:null,listener:function(){if(o.defaultPrevented){if(ll!==0){var V=S?Mv(f,S):new FormData(f);om(s,{pending:!0,data:V,method:f.method,action:p},null,V)}}else typeof p=="function"&&(R.preventDefault(),V=S?Mv(f,S):new FormData(f),om(s,{pending:!0,data:V,method:f.method,action:p},p,V))},currentTarget:f}]})}}for(var Um=0;Um<Gi.length;Um++){var qm=Gi[Um],SS=qm.toLowerCase(),CS=qm[0].toUpperCase()+qm.slice(1);vn(SS,"on"+CS)}vn(Ns,"onAnimationEnd"),vn(Bc,"onAnimationIteration"),vn(qi,"onAnimationStart"),vn("dblclick","onDoubleClick"),vn("focusin","onFocus"),vn("focusout","onBlur"),vn(Pc,"onTransitionRun"),vn(Ao,"onTransitionStart"),vn(Mo,"onTransitionCancel"),vn(Ua,"onTransitionEnd"),Tn("onMouseEnter",["mouseout","mouseover"]),Tn("onMouseLeave",["mouseout","mouseover"]),Tn("onPointerEnter",["pointerout","pointerover"]),Tn("onPointerLeave",["pointerout","pointerover"]),Sn("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),Sn("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),Sn("onBeforeInput",["compositionend","keypress","textInput","paste"]),Sn("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),Sn("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),Sn("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var hu="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(" "),kS=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(hu));function Nv(e,t){t=(t&4)!==0;for(var s=0;s<e.length;s++){var o=e[s],f=o.event;o=o.listeners;e:{var p=void 0;if(t)for(var S=o.length-1;0<=S;S--){var R=o[S],V=R.instance,ue=R.currentTarget;if(R=R.listener,V!==p&&f.isPropagationStopped())break e;p=R,f.currentTarget=ue;try{p(f)}catch(xe){Pn(xe)}f.currentTarget=null,p=V}else for(S=0;S<o.length;S++){if(R=o[S],V=R.instance,ue=R.currentTarget,R=R.listener,V!==p&&f.isPropagationStopped())break e;p=R,f.currentTarget=ue;try{p(f)}catch(xe){Pn(xe)}f.currentTarget=null,p=V}}}}function Lt(e,t){var s=t[vt];s===void 0&&(s=t[vt]=new Set);var o=e+"__bubble";s.has(o)||(Tv(t,e,2,!1),s.add(o))}function Gm(e,t,s){var o=0;t&&(o|=4),Tv(s,e,o,t)}var _d="_reactListening"+Math.random().toString(36).slice(2);function Vm(e){if(!e[_d]){e[_d]=!0,Vs.forEach(function(s){s!=="selectionchange"&&(kS.has(s)||Gm(s,!1,e),Gm(s,!0,e))});var t=e.nodeType===9?e:e.ownerDocument;t===null||t[_d]||(t[_d]=!0,Gm("selectionchange",!1,t))}}function Tv(e,t,s,o){switch(sy(t)){case 2:var f=ZS;break;case 8:f=JS;break;default:f=lh}s=f.bind(null,t,s,e),f=void 0,!bo||t!=="touchstart"&&t!=="touchmove"&&t!=="wheel"||(f=!0),o?f!==void 0?e.addEventListener(t,s,{capture:!0,passive:f}):e.addEventListener(t,s,!0):f!==void 0?e.addEventListener(t,s,{passive:f}):e.addEventListener(t,s,!1)}function Wm(e,t,s,o,f){var p=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 R=o.stateNode.containerInfo;if(R===f)break;if(S===4)for(S=o.return;S!==null;){var V=S.tag;if((V===3||V===4)&&S.stateNode.containerInfo===f)return;S=S.return}for(;R!==null;){if(S=Hn(R),S===null)return;if(V=S.tag,V===5||V===6||V===26||V===27){o=p=S;continue e}R=R.parentNode}}o=o.return}Al(function(){var ue=p,xe=_i(s),ke=[];e:{var me=nr.get(e);if(me!==void 0){var ge=Qs,Qe=e;switch(e){case"keypress":if(Ml(s)===0)break e;case"keydown":case"keyup":ge=Hi;break;case"focusin":Qe="focus",ge=Oi;break;case"focusout":Qe="blur",ge=Oi;break;case"beforeblur":case"afterblur":ge=Oi;break;case"click":if(s.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":ge=xr;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":ge=xo;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":ge=Wp;break;case Ns:case Bc:case qi:ge=So;break;case Ua:ge=Kp;break;case"scroll":case"scrollend":ge=br;break;case"wheel":ge=td;break;case"copy":case"cut":case"paste":ge=Ju;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":ge=qr;break;case"toggle":case"beforetoggle":ge=nm}var ut=(t&4)!==0,Xt=!ut&&(e==="scroll"||e==="scrollend"),ae=ut?me!==null?me+"Capture":null:me;ut=[];for(var X=ue,oe;X!==null;){var Se=X;if(oe=Se.stateNode,Se=Se.tag,Se!==5&&Se!==26&&Se!==27||oe===null||ae===null||(Se=yr(X,ae),Se!=null&&ut.push(pu(X,Se,oe))),Xt)break;X=X.return}0<ut.length&&(me=new ge(me,Qe,null,s,xe),ke.push({event:me,listeners:ut}))}}if((t&7)===0){e:{if(me=e==="mouseover"||e==="pointerover",ge=e==="mouseout"||e==="pointerout",me&&s!==Cs&&(Qe=s.relatedTarget||s.fromElement)&&(Hn(Qe)||Qe[Pe]))break e;if((ge||me)&&(me=xe.window===xe?xe:(me=xe.ownerDocument)?me.defaultView||me.parentWindow:window,ge?(Qe=s.relatedTarget||s.toElement,ge=ue,Qe=Qe?Hn(Qe):null,Qe!==null&&(Xt=d(Qe),ut=Qe.tag,Qe!==Xt||ut!==5&&ut!==27&&ut!==6)&&(Qe=null)):(ge=null,Qe=ue),ge!==Qe)){if(ut=xr,Se="onMouseLeave",ae="onMouseEnter",X="mouse",(e==="pointerout"||e==="pointerover")&&(ut=qr,Se="onPointerLeave",ae="onPointerEnter",X="pointer"),Xt=ge==null?me:nn(ge),oe=Qe==null?me:nn(Qe),me=new ut(Se,X+"leave",ge,s,xe),me.target=Xt,me.relatedTarget=oe,Se=null,Hn(xe)===ue&&(ut=new ut(ae,X+"enter",Qe,s,xe),ut.target=oe,ut.relatedTarget=Xt,Se=ut),Xt=Se,ge&&Qe)t:{for(ut=jS,ae=ge,X=Qe,oe=0,Se=ae;Se;Se=ut(Se))oe++;Se=0;for(var rt=X;rt;rt=ut(rt))Se++;for(;0<oe-Se;)ae=ut(ae),oe--;for(;0<Se-oe;)X=ut(X),Se--;for(;oe--;){if(ae===X||X!==null&&ae===X.alternate){ut=ae;break t}ae=ut(ae),X=ut(X)}ut=null}else ut=null;ge!==null&&Rv(ke,me,ge,ut,!1),Qe!==null&&Xt!==null&&Rv(ke,Xt,Qe,ut,!0)}}e:{if(me=ue?nn(ue):window,ge=me.nodeName&&me.nodeName.toLowerCase(),ge==="select"||ge==="input"&&me.type==="file")var Ht=Wr;else if(pt(me))if(lt)Ht=$i;else{Ht=Yr;var Je=Fc}else ge=me.nodeName,!ge||ge.toLowerCase()!=="input"||me.type!=="checkbox"&&me.type!=="radio"?ue&&Br(ue.elementType)&&(Ht=Wr):Ht=Da;if(Ht&&(Ht=Ht(e,ue))){Rt(ke,Ht,s,xe);break e}Je&&Je(e,me,ue),e==="focusout"&&ue&&me.type==="number"&&ue.memoizedProps.value!=null&&$n(me,"number",me.value)}switch(Je=ue?nn(ue):window,e){case"focusin":(pt(Je)||Je.contentEditable==="true")&&(Qr=Je,un=ue,Bi=null);break;case"focusout":Bi=un=Qr=null;break;case"mousedown":Pi=!0;break;case"contextmenu":case"mouseup":case"dragend":Pi=!1,Xr(ke,s,xe);break;case"selectionchange":if(Qp)break;case"keydown":case"keyup":Xr(ke,s,xe)}var jt;if(Dc)e:{switch(e){case"compositionstart":var It="onCompositionStart";break e;case"compositionend":It="onCompositionEnd";break e;case"compositionupdate":It="onCompositionUpdate";break e}It=void 0}else Vr?_c(e,s)&&(It="onCompositionEnd"):e==="keydown"&&s.keyCode===229&&(It="onCompositionStart");It&&(Fi&&s.locale!=="ko"&&(Vr||It!=="onCompositionStart"?It==="onCompositionEnd"&&Vr&&(jt=la()):(js=xe,Pa="value"in js?js.value:js.textContent,Vr=!0)),Je=Id(ue,It),0<Je.length&&(It=new cs(It,e,null,s,xe),ke.push({event:It,listeners:Je}),jt?It.data=jt:(jt=Ic(s),jt!==null&&(It.data=jt)))),(jt=Lc?El(e,s):zc(e,s))&&(It=Id(ue,"onBeforeInput"),0<It.length&&(Je=new cs("onBeforeInput","beforeinput",null,s,xe),ke.push({event:Je,listeners:It}),Je.data=jt)),wS(ke,e,ue,s,xe)}Nv(ke,t)})}function pu(e,t,s){return{instance:e,listener:t,currentTarget:s}}function Id(e,t){for(var s=t+"Capture",o=[];e!==null;){var f=e,p=f.stateNode;if(f=f.tag,f!==5&&f!==26&&f!==27||p===null||(f=yr(e,s),f!=null&&o.unshift(pu(e,f,p)),f=yr(e,t),f!=null&&o.push(pu(e,f,p))),e.tag===3)return o;e=e.return}return[]}function jS(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5&&e.tag!==27);return e||null}function Rv(e,t,s,o,f){for(var p=t._reactName,S=[];s!==null&&s!==o;){var R=s,V=R.alternate,ue=R.stateNode;if(R=R.tag,V!==null&&V===o)break;R!==5&&R!==26&&R!==27||ue===null||(V=ue,f?(ue=yr(s,p),ue!=null&&S.unshift(pu(s,ue,V))):f||(ue=yr(s,p),ue!=null&&S.push(pu(s,ue,V)))),s=s.return}S.length!==0&&e.push({event:t,listeners:S})}var AS=/\r\n?/g,MS=/\u0000|\uFFFD/g;function Ev(e){return(typeof e=="string"?e:""+e).replace(AS,`
9
- `).replace(MS,"")}function Dv(e,t){return t=Ev(t),Ev(e)===t}function Qt(e,t,s,o,f,p){switch(s){case"children":typeof o=="string"?t==="body"||t==="textarea"&&o===""||Cn(e,o):(typeof o=="number"||typeof o=="bigint")&&t!=="body"&&Cn(e,""+o);break;case"className":Fn(e,"class",o);break;case"tabIndex":Fn(e,"tabindex",o);break;case"dir":case"role":case"viewBox":case"width":case"height":Fn(e,s,o);break;case"style":kl(e,o,p);break;case"data":if(t!=="object"){Fn(e,"data",o);break}case"src":case"href":if(o===""&&(t!=="a"||s!=="href")){e.removeAttribute(s);break}if(o==null||typeof o=="function"||typeof o=="symbol"||typeof o=="boolean"){e.removeAttribute(s);break}o=Pr(""+o),e.setAttribute(s,o);break;case"action":case"formAction":if(typeof o=="function"){e.setAttribute(s,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof p=="function"&&(s==="formAction"?(t!=="input"&&Qt(e,t,"name",f.name,f,null),Qt(e,t,"formEncType",f.formEncType,f,null),Qt(e,t,"formMethod",f.formMethod,f,null),Qt(e,t,"formTarget",f.formTarget,f,null)):(Qt(e,t,"encType",f.encType,f,null),Qt(e,t,"method",f.method,f,null),Qt(e,t,"target",f.target,f,null)));if(o==null||typeof o=="symbol"||typeof o=="boolean"){e.removeAttribute(s);break}o=Pr(""+o),e.setAttribute(s,o);break;case"onClick":o!=null&&(e.onclick=ra);break;case"onScroll":o!=null&&Lt("scroll",e);break;case"onScrollEnd":o!=null&&Lt("scrollend",e);break;case"dangerouslySetInnerHTML":if(o!=null){if(typeof o!="object"||!("__html"in o))throw Error(l(61));if(s=o.__html,s!=null){if(f.children!=null)throw Error(l(60));e.innerHTML=s}}break;case"multiple":e.multiple=o&&typeof o!="function"&&typeof o!="symbol";break;case"muted":e.muted=o&&typeof o!="function"&&typeof o!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(o==null||typeof o=="function"||typeof o=="boolean"||typeof o=="symbol"){e.removeAttribute("xlink:href");break}s=Pr(""+o),e.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",s);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":o!=null&&typeof o!="function"&&typeof o!="symbol"?e.setAttribute(s,""+o):e.removeAttribute(s);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":o&&typeof o!="function"&&typeof o!="symbol"?e.setAttribute(s,""):e.removeAttribute(s);break;case"capture":case"download":o===!0?e.setAttribute(s,""):o!==!1&&o!=null&&typeof o!="function"&&typeof o!="symbol"?e.setAttribute(s,o):e.removeAttribute(s);break;case"cols":case"rows":case"size":case"span":o!=null&&typeof o!="function"&&typeof o!="symbol"&&!isNaN(o)&&1<=o?e.setAttribute(s,o):e.removeAttribute(s);break;case"rowSpan":case"start":o==null||typeof o=="function"||typeof o=="symbol"||isNaN(o)?e.removeAttribute(s):e.setAttribute(s,o);break;case"popover":Lt("beforetoggle",e),Lt("toggle",e),Fr(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":Fr(e,"is",o);break;case"innerText":case"textContent":break;default:(!(2<s.length)||s[0]!=="o"&&s[0]!=="O"||s[1]!=="n"&&s[1]!=="N")&&(s=os.get(s)||s,Fr(e,s,o))}}function Ym(e,t,s,o,f,p){switch(s){case"style":kl(e,o,p);break;case"dangerouslySetInnerHTML":if(o!=null){if(typeof o!="object"||!("__html"in o))throw Error(l(61));if(s=o.__html,s!=null){if(f.children!=null)throw Error(l(60));e.innerHTML=s}}break;case"children":typeof o=="string"?Cn(e,o):(typeof o=="number"||typeof o=="bigint")&&Cn(e,""+o);break;case"onScroll":o!=null&&Lt("scroll",e);break;case"onScrollEnd":o!=null&&Lt("scrollend",e);break;case"onClick":o!=null&&(e.onclick=ra);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!zt.hasOwnProperty(s))e:{if(s[0]==="o"&&s[1]==="n"&&(f=s.endsWith("Capture"),t=s.slice(2,f?s.length-7:void 0),p=e[Te]||null,p=p!=null?p[s]:null,typeof p=="function"&&e.removeEventListener(t,p,f),typeof o=="function")){typeof p!="function"&&p!==null&&(s in e?e[s]=null:e.hasAttribute(s)&&e.removeAttribute(s)),e.addEventListener(t,o,f);break e}s in e?e[s]=o:o===!0?e.setAttribute(s,""):Fr(e,s,o)}}}function fa(e,t,s){switch(t){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":Lt("error",e),Lt("load",e);var o=!1,f=!1,p;for(p in s)if(s.hasOwnProperty(p)){var S=s[p];if(S!=null)switch(p){case"src":o=!0;break;case"srcSet":f=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(l(137,t));default:Qt(e,t,p,S,s,null)}}f&&Qt(e,t,"srcSet",s.srcSet,s,null),o&&Qt(e,t,"src",s.src,s,null);return;case"input":Lt("invalid",e);var R=p=S=f=null,V=null,ue=null;for(o in s)if(s.hasOwnProperty(o)){var xe=s[o];if(xe!=null)switch(o){case"name":f=xe;break;case"type":S=xe;break;case"checked":V=xe;break;case"defaultChecked":ue=xe;break;case"value":p=xe;break;case"defaultValue":R=xe;break;case"children":case"dangerouslySetInnerHTML":if(xe!=null)throw Error(l(137,t));break;default:Qt(e,t,o,xe,s,null)}}Li(e,p,R,V,ue,S,f,!1);return;case"select":Lt("invalid",e),o=S=p=null;for(f in s)if(s.hasOwnProperty(f)&&(R=s[f],R!=null))switch(f){case"value":p=R;break;case"defaultValue":S=R;break;case"multiple":o=R;default:Qt(e,t,f,R,s,null)}t=p,s=S,e.multiple=!!o,t!=null?Ra(e,!!o,t,!1):s!=null&&Ra(e,!!o,s,!0);return;case"textarea":Lt("invalid",e),p=f=o=null;for(S in s)if(s.hasOwnProperty(S)&&(R=s[S],R!=null))switch(S){case"value":o=R;break;case"defaultValue":f=R;break;case"children":p=R;break;case"dangerouslySetInnerHTML":if(R!=null)throw Error(l(91));break;default:Qt(e,t,S,R,s,null)}$r(e,o,f,p);return;case"option":for(V in s)s.hasOwnProperty(V)&&(o=s[V],o!=null)&&(V==="selected"?e.selected=o&&typeof o!="function"&&typeof o!="symbol":Qt(e,t,V,o,s,null));return;case"dialog":Lt("beforetoggle",e),Lt("toggle",e),Lt("cancel",e),Lt("close",e);break;case"iframe":case"object":Lt("load",e);break;case"video":case"audio":for(o=0;o<hu.length;o++)Lt(hu[o],e);break;case"image":Lt("error",e),Lt("load",e);break;case"details":Lt("toggle",e);break;case"embed":case"source":case"link":Lt("error",e),Lt("load",e);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(ue in s)if(s.hasOwnProperty(ue)&&(o=s[ue],o!=null))switch(ue){case"children":case"dangerouslySetInnerHTML":throw Error(l(137,t));default:Qt(e,t,ue,o,s,null)}return;default:if(Br(t)){for(xe in s)s.hasOwnProperty(xe)&&(o=s[xe],o!==void 0&&Ym(e,t,xe,o,s,void 0));return}}for(R in s)s.hasOwnProperty(R)&&(o=s[R],o!=null&&Qt(e,t,R,o,s,null))}function NS(e,t,s,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,p=null,S=null,R=null,V=null,ue=null,xe=null;for(ge in s){var ke=s[ge];if(s.hasOwnProperty(ge)&&ke!=null)switch(ge){case"checked":break;case"value":break;case"defaultValue":V=ke;default:o.hasOwnProperty(ge)||Qt(e,t,ge,null,o,ke)}}for(var me in o){var ge=o[me];if(ke=s[me],o.hasOwnProperty(me)&&(ge!=null||ke!=null))switch(me){case"type":p=ge;break;case"name":f=ge;break;case"checked":ue=ge;break;case"defaultChecked":xe=ge;break;case"value":S=ge;break;case"defaultValue":R=ge;break;case"children":case"dangerouslySetInnerHTML":if(ge!=null)throw Error(l(137,t));break;default:ge!==ke&&Qt(e,t,me,ge,o,ke)}}vo(e,S,R,V,ue,xe,p,f);return;case"select":ge=S=R=me=null;for(p in s)if(V=s[p],s.hasOwnProperty(p)&&V!=null)switch(p){case"value":break;case"multiple":ge=V;default:o.hasOwnProperty(p)||Qt(e,t,p,null,o,V)}for(f in o)if(p=o[f],V=s[f],o.hasOwnProperty(f)&&(p!=null||V!=null))switch(f){case"value":me=p;break;case"defaultValue":R=p;break;case"multiple":S=p;default:p!==V&&Qt(e,t,f,p,o,V)}t=R,s=S,o=ge,me!=null?Ra(e,!!s,me,!1):!!o!=!!s&&(t!=null?Ra(e,!!s,t,!0):Ra(e,!!s,s?[]:"",!1));return;case"textarea":ge=me=null;for(R in s)if(f=s[R],s.hasOwnProperty(R)&&f!=null&&!o.hasOwnProperty(R))switch(R){case"value":break;case"children":break;default:Qt(e,t,R,null,o,f)}for(S in o)if(f=o[S],p=s[S],o.hasOwnProperty(S)&&(f!=null||p!=null))switch(S){case"value":me=f;break;case"defaultValue":ge=f;break;case"children":break;case"dangerouslySetInnerHTML":if(f!=null)throw Error(l(91));break;default:f!==p&&Qt(e,t,S,f,o,p)}Ws(e,me,ge);return;case"option":for(var Qe in s)me=s[Qe],s.hasOwnProperty(Qe)&&me!=null&&!o.hasOwnProperty(Qe)&&(Qe==="selected"?e.selected=!1:Qt(e,t,Qe,null,o,me));for(V in o)me=o[V],ge=s[V],o.hasOwnProperty(V)&&me!==ge&&(me!=null||ge!=null)&&(V==="selected"?e.selected=me&&typeof me!="function"&&typeof me!="symbol":Qt(e,t,V,me,o,ge));return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var ut in s)me=s[ut],s.hasOwnProperty(ut)&&me!=null&&!o.hasOwnProperty(ut)&&Qt(e,t,ut,null,o,me);for(ue in o)if(me=o[ue],ge=s[ue],o.hasOwnProperty(ue)&&me!==ge&&(me!=null||ge!=null))switch(ue){case"children":case"dangerouslySetInnerHTML":if(me!=null)throw Error(l(137,t));break;default:Qt(e,t,ue,me,o,ge)}return;default:if(Br(t)){for(var Xt in s)me=s[Xt],s.hasOwnProperty(Xt)&&me!==void 0&&!o.hasOwnProperty(Xt)&&Ym(e,t,Xt,void 0,o,me);for(xe in o)me=o[xe],ge=s[xe],!o.hasOwnProperty(xe)||me===ge||me===void 0&&ge===void 0||Ym(e,t,xe,me,o,ge);return}}for(var ae in s)me=s[ae],s.hasOwnProperty(ae)&&me!=null&&!o.hasOwnProperty(ae)&&Qt(e,t,ae,null,o,me);for(ke in o)me=o[ke],ge=s[ke],!o.hasOwnProperty(ke)||me===ge||me==null&&ge==null||Qt(e,t,ke,me,o,ge)}function Lv(e){switch(e){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function TS(){if(typeof performance.getEntriesByType=="function"){for(var e=0,t=0,s=performance.getEntriesByType("resource"),o=0;o<s.length;o++){var f=s[o],p=f.transferSize,S=f.initiatorType,R=f.duration;if(p&&R&&Lv(S)){for(S=0,R=f.responseEnd,o+=1;o<s.length;o++){var V=s[o],ue=V.startTime;if(ue>R)break;var xe=V.transferSize,ke=V.initiatorType;xe&&Lv(ke)&&(V=V.responseEnd,S+=xe*(V<R?1:(R-ue)/(V-ue)))}if(--o,t+=8*(p+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,Qm=null;function zd(e){return e.nodeType===9?e:e.ownerDocument}function _v(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 Iv(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 Xm(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 Zm=null;function RS(){var e=window.event;return e&&e.type==="popstate"?e===Zm?!1:(Zm=e,!0):(Zm=null,!1)}var zv=typeof setTimeout=="function"?setTimeout:void 0,ES=typeof clearTimeout=="function"?clearTimeout:void 0,Ov=typeof Promise=="function"?Promise:void 0,DS=typeof queueMicrotask=="function"?queueMicrotask:typeof Ov<"u"?function(e){return Ov.resolve(null).then(e).catch(LS)}:zv;function LS(e){setTimeout(function(){throw e})}function ol(e){return e==="head"}function Hv(e,t){var s=t,o=0;do{var f=s.nextSibling;if(e.removeChild(s),f&&f.nodeType===8)if(s=f.data,s==="/$"||s==="/&"){if(o===0){e.removeChild(f),uc(t);return}o--}else if(s==="$"||s==="$?"||s==="$~"||s==="$!"||s==="&")o++;else if(s==="html")gu(e.ownerDocument.documentElement);else if(s==="head"){s=e.ownerDocument.head,gu(s);for(var p=s.firstChild;p;){var S=p.nextSibling,R=p.nodeName;p[Mt]||R==="SCRIPT"||R==="STYLE"||R==="LINK"&&p.rel.toLowerCase()==="stylesheet"||s.removeChild(p),p=S}}else s==="body"&&gu(e.ownerDocument.body);s=f}while(s);uc(t)}function Fv(e,t){var s=e;e=0;do{var o=s.nextSibling;if(s.nodeType===1?t?(s._stashedDisplay=s.style.display,s.style.display="none"):(s.style.display=s._stashedDisplay||"",s.getAttribute("style")===""&&s.removeAttribute("style")):s.nodeType===3&&(t?(s._stashedText=s.nodeValue,s.nodeValue=""):s.nodeValue=s._stashedText||""),o&&o.nodeType===8)if(s=o.data,s==="/$"){if(e===0)break;e--}else s!=="$"&&s!=="$?"&&s!=="$~"&&s!=="$!"||e++;s=o}while(s)}function Jm(e){var t=e.firstChild;for(t&&t.nodeType===10&&(t=t.nextSibling);t;){var s=t;switch(t=t.nextSibling,s.nodeName){case"HTML":case"HEAD":case"BODY":Jm(s),sa(s);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(s.rel.toLowerCase()==="stylesheet")continue}e.removeChild(s)}}function _S(e,t,s,o){for(;e.nodeType===1;){var f=s;if(e.nodeName.toLowerCase()!==t.toLowerCase()){if(!o&&(e.nodeName!=="INPUT"||e.type!=="hidden"))break}else if(o){if(!e[Mt])switch(t){case"meta":if(!e.hasAttribute("itemprop"))break;return e;case"link":if(p=e.getAttribute("rel"),p==="stylesheet"&&e.hasAttribute("data-precedence"))break;if(p!==f.rel||e.getAttribute("href")!==(f.href==null||f.href===""?null:f.href)||e.getAttribute("crossorigin")!==(f.crossOrigin==null?null:f.crossOrigin)||e.getAttribute("title")!==(f.title==null?null:f.title))break;return e;case"style":if(e.hasAttribute("data-precedence"))break;return e;case"script":if(p=e.getAttribute("src"),(p!==(f.src==null?null:f.src)||e.getAttribute("type")!==(f.type==null?null:f.type)||e.getAttribute("crossorigin")!==(f.crossOrigin==null?null:f.crossOrigin))&&p&&e.hasAttribute("async")&&!e.hasAttribute("itemprop"))break;return e;default:return e}}else if(t==="input"&&e.type==="hidden"){var p=f.name==null?null:""+f.name;if(f.type==="hidden"&&e.getAttribute("name")===p)return e}else return e;if(e=$s(e.nextSibling),e===null)break}return null}function IS(e,t,s){if(t==="")return null;for(;e.nodeType!==3;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!s||(e=$s(e.nextSibling),e===null))return null;return e}function $v(e,t){for(;e.nodeType!==8;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!t||(e=$s(e.nextSibling),e===null))return null;return e}function eh(e){return e.data==="$?"||e.data==="$~"}function th(e){return e.data==="$!"||e.data==="$?"&&e.ownerDocument.readyState!=="loading"}function zS(e,t){var s=e.ownerDocument;if(e.data==="$~")e._reactRetry=t;else if(e.data!=="$?"||s.readyState!=="loading")t();else{var o=function(){t(),s.removeEventListener("DOMContentLoaded",o)};s.addEventListener("DOMContentLoaded",o),e._reactRetry=o}}function $s(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 nh=null;function Bv(e){e=e.nextSibling;for(var t=0;e;){if(e.nodeType===8){var s=e.data;if(s==="/$"||s==="/&"){if(t===0)return $s(e.nextSibling);t--}else s!=="$"&&s!=="$!"&&s!=="$?"&&s!=="$~"&&s!=="&"||t++}e=e.nextSibling}return null}function Pv(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var s=e.data;if(s==="$"||s==="$!"||s==="$?"||s==="$~"||s==="&"){if(t===0)return e;t--}else s!=="/$"&&s!=="/&"||t++}e=e.previousSibling}return null}function Uv(e,t,s){switch(t=zd(s),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 gu(e){for(var t=e.attributes;t.length;)e.removeAttributeNode(t[0]);sa(e)}var Bs=new Map,qv=new Set;function Od(e){return typeof e.getRootNode=="function"?e.getRootNode():e.nodeType===9?e:e.ownerDocument}var Ai=se.d;se.d={f:OS,r:HS,D:FS,C:$S,L:BS,m:PS,X:qS,S:US,M:GS};function OS(){var e=Ai.f(),t=Nd();return e||t}function HS(e){var t=gn(e);t!==null&&t.tag===5&&t.type==="form"?lg(t):Ai.r(e)}var lc=typeof document>"u"?null:document;function Gv(e,t,s){var o=lc;if(o&&typeof t=="string"&&t){var f=Ba(t);f='link[rel="'+e+'"][href="'+f+'"]',typeof s=="string"&&(f+='[crossorigin="'+s+'"]'),qv.has(f)||(qv.add(f),e={rel:e,crossOrigin:s,href:t},o.querySelector(f)===null&&(t=o.createElement("link"),fa(t,"link",e),At(t),o.head.appendChild(t)))}}function FS(e){Ai.D(e),Gv("dns-prefetch",e,null)}function $S(e,t){Ai.C(e,t),Gv("preconnect",e,t)}function BS(e,t,s){Ai.L(e,t,s);var o=lc;if(o&&e&&t){var f='link[rel="preload"][as="'+Ba(t)+'"]';t==="image"&&s&&s.imageSrcSet?(f+='[imagesrcset="'+Ba(s.imageSrcSet)+'"]',typeof s.imageSizes=="string"&&(f+='[imagesizes="'+Ba(s.imageSizes)+'"]')):f+='[href="'+Ba(e)+'"]';var p=f;switch(t){case"style":p=oc(e);break;case"script":p=cc(e)}Bs.has(p)||(e=b({rel:"preload",href:t==="image"&&s&&s.imageSrcSet?void 0:e,as:t},s),Bs.set(p,e),o.querySelector(f)!==null||t==="style"&&o.querySelector(vu(p))||t==="script"&&o.querySelector(yu(p))||(t=o.createElement("link"),fa(t,"link",e),At(t),o.head.appendChild(t)))}}function PS(e,t){Ai.m(e,t);var s=lc;if(s&&e){var o=t&&typeof t.as=="string"?t.as:"script",f='link[rel="modulepreload"][as="'+Ba(o)+'"][href="'+Ba(e)+'"]',p=f;switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":p=cc(e)}if(!Bs.has(p)&&(e=b({rel:"modulepreload",href:e},t),Bs.set(p,e),s.querySelector(f)===null)){switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(s.querySelector(yu(p)))return}o=s.createElement("link"),fa(o,"link",e),At(o),s.head.appendChild(o)}}}function US(e,t,s){Ai.S(e,t,s);var o=lc;if(o&&e){var f=Ye(o).hoistableStyles,p=oc(e);t=t||"default";var S=f.get(p);if(!S){var R={loading:0,preload:null};if(S=o.querySelector(vu(p)))R.loading=5;else{e=b({rel:"stylesheet",href:e,"data-precedence":t},s),(s=Bs.get(p))&&ah(e,s);var V=S=o.createElement("link");At(V),fa(V,"link",e),V._p=new Promise(function(ue,xe){V.onload=ue,V.onerror=xe}),V.addEventListener("load",function(){R.loading|=1}),V.addEventListener("error",function(){R.loading|=2}),R.loading|=4,Hd(S,t,o)}S={type:"stylesheet",instance:S,count:1,state:R},f.set(p,S)}}}function qS(e,t){Ai.X(e,t);var s=lc;if(s&&e){var o=Ye(s).hoistableScripts,f=cc(e),p=o.get(f);p||(p=s.querySelector(yu(f)),p||(e=b({src:e,async:!0},t),(t=Bs.get(f))&&sh(e,t),p=s.createElement("script"),At(p),fa(p,"link",e),s.head.appendChild(p)),p={type:"script",instance:p,count:1,state:null},o.set(f,p))}}function GS(e,t){Ai.M(e,t);var s=lc;if(s&&e){var o=Ye(s).hoistableScripts,f=cc(e),p=o.get(f);p||(p=s.querySelector(yu(f)),p||(e=b({src:e,async:!0,type:"module"},t),(t=Bs.get(f))&&sh(e,t),p=s.createElement("script"),At(p),fa(p,"link",e),s.head.appendChild(p)),p={type:"script",instance:p,count:1,state:null},o.set(f,p))}}function Vv(e,t,s,o){var f=(f=ee.current)?Od(f):null;if(!f)throw Error(l(446));switch(e){case"meta":case"title":return null;case"style":return typeof s.precedence=="string"&&typeof s.href=="string"?(t=oc(s.href),s=Ye(f).hoistableStyles,o=s.get(t),o||(o={type:"style",instance:null,count:0,state:null},s.set(t,o)),o):{type:"void",instance:null,count:0,state:null};case"link":if(s.rel==="stylesheet"&&typeof s.href=="string"&&typeof s.precedence=="string"){e=oc(s.href);var p=Ye(f).hoistableStyles,S=p.get(e);if(S||(f=f.ownerDocument||f,S={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},p.set(e,S),(p=f.querySelector(vu(e)))&&!p._p&&(S.instance=p,S.state.loading=5),Bs.has(e)||(s={rel:"preload",as:"style",href:s.href,crossOrigin:s.crossOrigin,integrity:s.integrity,media:s.media,hrefLang:s.hrefLang,referrerPolicy:s.referrerPolicy},Bs.set(e,s),p||VS(f,e,s,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=s.async,s=s.src,typeof s=="string"&&t&&typeof t!="function"&&typeof t!="symbol"?(t=cc(s),s=Ye(f).hoistableScripts,o=s.get(t),o||(o={type:"script",instance:null,count:0,state:null},s.set(t,o)),o):{type:"void",instance:null,count:0,state:null};default:throw Error(l(444,e))}}function oc(e){return'href="'+Ba(e)+'"'}function vu(e){return'link[rel="stylesheet"]['+e+"]"}function Wv(e){return b({},e,{"data-precedence":e.precedence,precedence:null})}function VS(e,t,s,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}),fa(t,"link",s),At(t),e.head.appendChild(t))}function cc(e){return'[src="'+Ba(e)+'"]'}function yu(e){return"script[async]"+e}function Yv(e,t,s){if(t.count++,t.instance===null)switch(t.type){case"style":var o=e.querySelector('style[data-href~="'+Ba(s.href)+'"]');if(o)return t.instance=o,At(o),o;var f=b({},s,{"data-href":s.href,"data-precedence":s.precedence,href:null,precedence:null});return o=(e.ownerDocument||e).createElement("style"),At(o),fa(o,"style",f),Hd(o,s.precedence,e),t.instance=o;case"stylesheet":f=oc(s.href);var p=e.querySelector(vu(f));if(p)return t.state.loading|=4,t.instance=p,At(p),p;o=Wv(s),(f=Bs.get(f))&&ah(o,f),p=(e.ownerDocument||e).createElement("link"),At(p);var S=p;return S._p=new Promise(function(R,V){S.onload=R,S.onerror=V}),fa(p,"link",o),t.state.loading|=4,Hd(p,s.precedence,e),t.instance=p;case"script":return p=cc(s.src),(f=e.querySelector(yu(p)))?(t.instance=f,At(f),f):(o=s,(f=Bs.get(p))&&(o=b({},s),sh(o,f)),e=e.ownerDocument||e,f=e.createElement("script"),At(f),fa(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,Hd(o,s.precedence,e));return t.instance}function Hd(e,t,s){for(var o=s.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),f=o.length?o[o.length-1]:null,p=f,S=0;S<o.length;S++){var R=o[S];if(R.dataset.precedence===t)p=R;else if(p!==f)break}p?p.parentNode.insertBefore(e,p.nextSibling):(t=s.nodeType===9?s.head:s,t.insertBefore(e,t.firstChild))}function ah(e,t){e.crossOrigin==null&&(e.crossOrigin=t.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=t.referrerPolicy),e.title==null&&(e.title=t.title)}function sh(e,t){e.crossOrigin==null&&(e.crossOrigin=t.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=t.referrerPolicy),e.integrity==null&&(e.integrity=t.integrity)}var Fd=null;function Kv(e,t,s){if(Fd===null){var o=new Map,f=Fd=new Map;f.set(s,o)}else f=Fd,o=f.get(s),o||(o=new Map,f.set(s,o));if(o.has(e))return o;for(o.set(e,null),s=s.getElementsByTagName(e),f=0;f<s.length;f++){var p=s[f];if(!(p[Mt]||p[re]||e==="link"&&p.getAttribute("rel")==="stylesheet")&&p.namespaceURI!=="http://www.w3.org/2000/svg"){var S=p.getAttribute(t)||"";S=e+S;var R=o.get(S);R?R.push(p):o.set(S,[p])}}return o}function Qv(e,t,s){e=e.ownerDocument||e,e.head.insertBefore(s,t==="title"?e.querySelector("head > title"):null)}function WS(e,t,s){if(s===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 Xv(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function YS(e,t,s,o){if(s.type==="stylesheet"&&(typeof o.media!="string"||matchMedia(o.media).matches!==!1)&&(s.state.loading&4)===0){if(s.instance===null){var f=oc(o.href),p=t.querySelector(vu(f));if(p){t=p._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(e.count++,e=$d.bind(e),t.then(e,e)),s.state.loading|=4,s.instance=p,At(p);return}p=t.ownerDocument||t,o=Wv(o),(f=Bs.get(f))&&ah(o,f),p=p.createElement("link"),At(p);var S=p;S._p=new Promise(function(R,V){S.onload=R,S.onerror=V}),fa(p,"link",o),s.instance=p}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(s,t),(t=s.state.preload)&&(s.state.loading&3)===0&&(e.count++,s=$d.bind(e),t.addEventListener("load",s),t.addEventListener("error",s))}}var rh=0;function KS(e,t){return e.stylesheets&&e.count===0&&Pd(e,e.stylesheets),0<e.count||0<e.imgCount?function(s){var o=setTimeout(function(){if(e.stylesheets&&Pd(e,e.stylesheets),e.unsuspend){var p=e.unsuspend;e.unsuspend=null,p()}},6e4+t);0<e.imgBytes&&rh===0&&(rh=62500*TS());var f=setTimeout(function(){if(e.waitingForImages=!1,e.count===0&&(e.stylesheets&&Pd(e,e.stylesheets),e.unsuspend)){var p=e.unsuspend;e.unsuspend=null,p()}},(e.imgBytes>rh?50:800)+t);return e.unsuspend=s,function(){e.unsuspend=null,clearTimeout(o),clearTimeout(f)}}:null}function $d(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Pd(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Bd=null;function Pd(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Bd=new Map,t.forEach(QS,e),Bd=null,$d.call(e))}function QS(e,t){if(!(t.state.loading&4)){var s=Bd.get(e);if(s)var o=s.get(null);else{s=new Map,Bd.set(e,s);for(var f=e.querySelectorAll("link[data-precedence],style[data-precedence]"),p=0;p<f.length;p++){var S=f[p];(S.nodeName==="LINK"||S.getAttribute("media")!=="not all")&&(s.set(S.dataset.precedence,S),o=S)}o&&s.set(null,o)}f=t.instance,S=f.getAttribute("data-precedence"),p=s.get(S)||o,p===o&&s.set(null,f),s.set(S,f),this.count++,o=$d.bind(this),f.addEventListener("load",o),f.addEventListener("error",o),p?p.parentNode.insertBefore(f,p.nextSibling):(e=e.nodeType===9?e.head:e,e.insertBefore(f,e.firstChild)),t.state.loading|=4}}var bu={$$typeof:D,Provider:null,Consumer:null,_currentValue:W,_currentValue2:W,_threadCount:0};function XS(e,t,s,o,f,p,S,R,V){this.tag=1,this.containerInfo=e,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=pn(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=pn(0),this.hiddenUpdates=pn(null),this.identifierPrefix=o,this.onUncaughtError=f,this.onCaughtError=p,this.onRecoverableError=S,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=V,this.incompleteTransitions=new Map}function Zv(e,t,s,o,f,p,S,R,V,ue,xe,ke){return e=new XS(e,t,s,S,V,ue,xe,ke,R),t=1,p===!0&&(t|=24),p=En(3,null,null,t),e.current=p,p.stateNode=e,t=Oo(),t.refCount++,e.pooledCache=t,t.refCount++,p.memoizedState={element:o,isDehydrated:s,cache:t},Pl(p),e}function Jv(e){return e?(e=ca,e):ca}function ey(e,t,s,o,f,p){f=Jv(f),o.context===null?o.context=f:o.pendingContext=f,o=dr(t),o.payload={element:s},p=p===void 0?null:p,p!==null&&(o.callback=p),s=Os(e,o,t),s!==null&&(as(s,e,t),Ul(s,e,t))}function ty(e,t){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var s=e.retryLane;e.retryLane=s!==0&&s<t?s:t}}function ih(e,t){ty(e,t),(e=e.alternate)&&ty(e,t)}function ny(e){if(e.tag===13||e.tag===31){var t=_a(e,67108864);t!==null&&as(t,e,67108864),ih(e,67108864)}}function ay(e){if(e.tag===13||e.tag===31){var t=ps();t=ht(t);var s=_a(e,t);s!==null&&as(s,e,t),ih(e,t)}}var Ud=!0;function ZS(e,t,s,o){var f=z.T;z.T=null;var p=se.p;try{se.p=2,lh(e,t,s,o)}finally{se.p=p,z.T=f}}function JS(e,t,s,o){var f=z.T;z.T=null;var p=se.p;try{se.p=8,lh(e,t,s,o)}finally{se.p=p,z.T=f}}function lh(e,t,s,o){if(Ud){var f=oh(o);if(f===null)Wm(e,t,o,qd,s),ry(e,o);else if(t0(f,e,t,s,o))o.stopPropagation();else if(ry(e,o),t&4&&-1<e0.indexOf(e)){for(;f!==null;){var p=gn(f);if(p!==null)switch(p.tag){case 3:if(p=p.stateNode,p.current.memoizedState.isDehydrated){var S=pa(p.pendingLanes);if(S!==0){var R=p;for(R.pendingLanes|=2,R.entangledLanes|=2;S;){var V=1<<31-bt(S);R.entanglements[1]|=V,S&=~V}Er(p),(Pt&6)===0&&(Ad=Ae()+500,mu(0))}}break;case 31:case 13:R=_a(p,2),R!==null&&as(R,p,2),Nd(),ih(p,2)}if(p=oh(o),p===null&&Wm(e,t,o,qd,s),p===f)break;f=p}f!==null&&o.stopPropagation()}else Wm(e,t,o,null,s)}}function oh(e){return e=_i(e),ch(e)}var qd=null;function ch(e){if(qd=null,e=Hn(e),e!==null){var t=d(e);if(t===null)e=null;else{var s=t.tag;if(s===13){if(e=m(t),e!==null)return e;e=null}else if(s===31){if(e=h(t),e!==null)return e;e=null}else if(s===3){if(t.stateNode.current.memoizedState.isDehydrated)return t.tag===3?t.stateNode.containerInfo:null;e=null}else t!==e&&(e=null)}}return qd=e,null}function sy(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(Be()){case ft:return 2;case it:return 8;case yt:case ot:return 32;case kt:return 268435456;default:return 32}default:return 32}}var uh=!1,cl=null,ul=null,dl=null,xu=new Map,wu=new Map,fl=[],e0="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 ry(e,t){switch(e){case"focusin":case"focusout":cl=null;break;case"dragenter":case"dragleave":ul=null;break;case"mouseover":case"mouseout":dl=null;break;case"pointerover":case"pointerout":xu.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":wu.delete(t.pointerId)}}function Su(e,t,s,o,f,p){return e===null||e.nativeEvent!==p?(e={blockedOn:t,domEventName:s,eventSystemFlags:o,nativeEvent:p,targetContainers:[f]},t!==null&&(t=gn(t),t!==null&&ny(t)),e):(e.eventSystemFlags|=o,t=e.targetContainers,f!==null&&t.indexOf(f)===-1&&t.push(f),e)}function t0(e,t,s,o,f){switch(t){case"focusin":return cl=Su(cl,e,t,s,o,f),!0;case"dragenter":return ul=Su(ul,e,t,s,o,f),!0;case"mouseover":return dl=Su(dl,e,t,s,o,f),!0;case"pointerover":var p=f.pointerId;return xu.set(p,Su(xu.get(p)||null,e,t,s,o,f)),!0;case"gotpointercapture":return p=f.pointerId,wu.set(p,Su(wu.get(p)||null,e,t,s,o,f)),!0}return!1}function iy(e){var t=Hn(e.target);if(t!==null){var s=d(t);if(s!==null){if(t=s.tag,t===13){if(t=m(s),t!==null){e.blockedOn=t,Di(e.priority,function(){ay(s)});return}}else if(t===31){if(t=h(s),t!==null){e.blockedOn=t,Di(e.priority,function(){ay(s)});return}}else if(t===3&&s.stateNode.current.memoizedState.isDehydrated){e.blockedOn=s.tag===3?s.stateNode.containerInfo:null;return}}}e.blockedOn=null}function Gd(e){if(e.blockedOn!==null)return!1;for(var t=e.targetContainers;0<t.length;){var s=oh(e.nativeEvent);if(s===null){s=e.nativeEvent;var o=new s.constructor(s.type,s);Cs=o,s.target.dispatchEvent(o),Cs=null}else return t=gn(s),t!==null&&ny(t),e.blockedOn=s,!1;t.shift()}return!0}function ly(e,t,s){Gd(e)&&s.delete(t)}function n0(){uh=!1,cl!==null&&Gd(cl)&&(cl=null),ul!==null&&Gd(ul)&&(ul=null),dl!==null&&Gd(dl)&&(dl=null),xu.forEach(ly),wu.forEach(ly)}function Vd(e,t){e.blockedOn===t&&(e.blockedOn=null,uh||(uh=!0,n.unstable_scheduleCallback(n.unstable_NormalPriority,n0)))}var Wd=null;function oy(e){Wd!==e&&(Wd=e,n.unstable_scheduleCallback(n.unstable_NormalPriority,function(){Wd===e&&(Wd=null);for(var t=0;t<e.length;t+=3){var s=e[t],o=e[t+1],f=e[t+2];if(typeof o!="function"){if(ch(o||s)===null)continue;break}var p=gn(s);p!==null&&(e.splice(t,3),t-=3,om(p,{pending:!0,data:f,method:s.method,action:o},o,f))}}))}function uc(e){function t(V){return Vd(V,e)}cl!==null&&Vd(cl,e),ul!==null&&Vd(ul,e),dl!==null&&Vd(dl,e),xu.forEach(t),wu.forEach(t);for(var s=0;s<fl.length;s++){var o=fl[s];o.blockedOn===e&&(o.blockedOn=null)}for(;0<fl.length&&(s=fl[0],s.blockedOn===null);)iy(s),s.blockedOn===null&&fl.shift();if(s=(e.ownerDocument||e).$$reactFormReplay,s!=null)for(o=0;o<s.length;o+=3){var f=s[o],p=s[o+1],S=f[Te]||null;if(typeof p=="function")S||oy(s);else if(S){var R=null;if(p&&p.hasAttribute("formAction")){if(f=p,S=p[Te]||null)R=S.formAction;else if(ch(f)!==null)continue}else R=S.action;typeof R=="function"?s[o+1]=R:(s.splice(o,3),o-=3),oy(s)}}}function cy(){function e(p){p.canIntercept&&p.info==="react-transition"&&p.intercept({handler:function(){return new Promise(function(S){return f=S})},focusReset:"manual",scroll:"manual"})}function t(){f!==null&&(f(),f=null),o||setTimeout(s,20)}function s(){if(!o&&!navigation.transition){var p=navigation.currentEntry;p&&p.url!=null&&navigation.navigate(p.url,{state:p.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var o=!1,f=null;return navigation.addEventListener("navigate",e),navigation.addEventListener("navigatesuccess",t),navigation.addEventListener("navigateerror",t),setTimeout(s,100),function(){o=!0,navigation.removeEventListener("navigate",e),navigation.removeEventListener("navigatesuccess",t),navigation.removeEventListener("navigateerror",t),f!==null&&(f(),f=null)}}}function dh(e){this._internalRoot=e}Yd.prototype.render=dh.prototype.render=function(e){var t=this._internalRoot;if(t===null)throw Error(l(409));var s=t.current,o=ps();ey(s,o,e,t,null,null)},Yd.prototype.unmount=dh.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var t=e.containerInfo;ey(e.current,2,null,e,null,null),Nd(),t[Pe]=null}};function Yd(e){this._internalRoot=e}Yd.prototype.unstable_scheduleHydration=function(e){if(e){var t=Fa();e={blockedOn:null,target:e,priority:t};for(var s=0;s<fl.length&&t!==0&&t<fl[s].priority;s++);fl.splice(s,0,e),s===0&&iy(e)}};var uy=a.version;if(uy!=="19.2.7")throw Error(l(527,uy,"19.2.7"));se.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=y(t),e=e!==null?x(e):null,e=e===null?null:e.stateNode,e};var a0={bundleType:0,version:"19.2.7",rendererPackageName:"react-dom",currentDispatcherRef:z,reconcilerVersion:"19.2.7"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Kd=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Kd.isDisabled&&Kd.supportsFiber)try{$e=Kd.inject(a0),je=Kd}catch{}}return ku.createRoot=function(e,t){if(!c(e))throw Error(l(299));var s=!1,o="",f=vg,p=yg,S=bg;return t!=null&&(t.unstable_strictMode===!0&&(s=!0),t.identifierPrefix!==void 0&&(o=t.identifierPrefix),t.onUncaughtError!==void 0&&(f=t.onUncaughtError),t.onCaughtError!==void 0&&(p=t.onCaughtError),t.onRecoverableError!==void 0&&(S=t.onRecoverableError)),t=Zv(e,1,!1,null,null,s,o,null,f,p,S,cy),e[Pe]=t.current,Vm(e),new dh(t)},ku.hydrateRoot=function(e,t,s){if(!c(e))throw Error(l(299));var o=!1,f="",p=vg,S=yg,R=bg,V=null;return s!=null&&(s.unstable_strictMode===!0&&(o=!0),s.identifierPrefix!==void 0&&(f=s.identifierPrefix),s.onUncaughtError!==void 0&&(p=s.onUncaughtError),s.onCaughtError!==void 0&&(S=s.onCaughtError),s.onRecoverableError!==void 0&&(R=s.onRecoverableError),s.formState!==void 0&&(V=s.formState)),t=Zv(e,1,!0,t,s??null,o,f,V,p,S,R,cy),t.context=Jv(null),s=t.current,o=ps(),o=ht(o),f=dr(o),f.callback=null,Os(s,f,o),s=o,t.current.lanes=s,qs(t,s),Er(t),e[Pe]=t.current,Vm(e),new Yd(t)},ku.version="19.2.7",ku}var Cy;function K0(){if(Cy)return ph.exports;Cy=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(),ph.exports=Y0(),ph.exports}var Q0=K0();const X0="https://otbyfkjxrkngvjziawki.supabase.co",Z0="sb_publishable_NpUs0RDJH2YnllsqTKO6TQ_1jTdSsNQ",J0={getItem:()=>null,setItem:()=>{},removeItem:()=>{}},ky=typeof window<"u"&&!!window.liveDesk,Ct=U0(X0,Z0,{auth:{autoRefreshToken:!0,persistSession:!ky,storage:ky?J0:void 0,detectSessionInUrl:!0,flowType:"pkce",storageKey:"livedesk.mindexec.supabase.auth"}}),eC=new Set(["browserLanguage","platform","online","viewport","timezone","screen"]),tC={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,i])=>eC.has(a)&&i!==void 0))}};function nC(n,a="Support request failed."){if(n&&typeof n=="object"&&"message"in n){const i=String(n.message||"").trim();if(i)return i.replace(/^.*Support request failed:\s*/i,"")}return n instanceof Error?n.message:a}function aC(n=tC){return n.collect()}async function sC(n,a="livedesk"){const{data:i,error:l}=await Ct.from("app_admins").select("role").eq("user_id",n).limit(1);if(l)throw l;const c=i?.[0]?.role||"user";if(c!=="owner"){const{error:A}=await Ct.rpc("register_product_access",{p_product_key:a,p_access_type:"free"});if(A)throw A}const[d,m,h]=await Promise.all([Ct.from("products").select("id, product_key, name, description, sort_order").order("sort_order"),Ct.from("product_admins").select("product_id, role").eq("user_id",n),Ct.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(h.error)throw h.error;const g=d.data||[],y=(m.data||[]).map(A=>String(A.product_id)),x=(h.data||[]).map(A=>String(A.product_id)),b=c==="owner",w=b?g.map(A=>A.id):[...new Set([...y,...x])];return{products:g,access:{userId:n,globalRole:c,accessibleProductIds:w,managedProductIds:b?g.map(A=>A.id):y,canViewAllProducts:b,canViewAllPrivatePosts:b,canManageAllProducts:b,canCreateAnnouncements:b||y.length>0}}}async function rC(n=""){const{data:a,error:i}=await Ct.rpc("search_support_posts",{p_query:n.trim()||null,p_limit:250});if(i)throw i;return a||[]}async function iC(n){const{data:a,error:i}=await Ct.from("support_attachments").select("*").eq("post_id",n).order("created_at");if(i)throw i;const l=a||[];return Promise.all(l.map(async c=>{const d=await Ct.storage.from("support-attachments").createSignedUrl(c.storage_path,3600);return{...c,signed_url:d.data?.signedUrl||void 0}}))}async function lC(){const{data:n,error:a}=await Ct.from("support_notifications").select("*").order("created_at",{ascending:!1}).limit(30);if(a)throw a;return n||[]}async function oC(n){const{error:a}=await Ct.rpc("mark_support_notification_read",{p_notification_id:n});if(a)throw a}async function jy(n){const{data:a,error:i}=await Ct.from("support_comments").select("*").eq("post_id",n).order("created_at");if(i)throw i;return a||[]}async function cC(n){const{data:a,error:i}=await Ct.from("support_votes").select("post_id").eq("user_id",n);if(i)throw i;return new Set((a||[]).map(l=>String(l.post_id)))}async function uC(n){const{data:a,error:i}=await Ct.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?aC():{}});if(i)throw i;const l=Array.isArray(a)?a[0]?.post_id:a?.post_id;if(!l)throw new Error("Support post was not created.");return String(l)}const dC=new Set(["image/png","image/jpeg","image/webp","text/plain","text/markdown","application/json","application/pdf"]);async function fC(n,a){if(!dC.has(a.type))throw new Error("This file type is not allowed.");if(a.size<=0||a.size>10*1024*1024)throw new Error("Attachments must be smaller than 10 MB.");const i=a.name.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"attachment",l=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`,c=`${n}/${l}-${i}`,d=await Ct.storage.from("support-attachments").upload(c,a,{contentType:a.type,upsert:!1});if(d.error)throw d.error;const{data:m,error:h}=await Ct.rpc("add_support_attachment",{p_post_id:n,p_storage_path:c,p_file_name:i,p_mime_type:a.type,p_size_bytes:a.size});if(h)throw await Ct.storage.from("support-attachments").remove([c]),h;const g=Array.isArray(m)?m[0]?.attachment_id:m?.attachment_id;if(!g)throw new Error("Attachment metadata was not created.");return String(g)}async function mC(n,a,i,l){const{error:c}=await Ct.rpc("update_support_post",{p_post_id:n,p_title:a,p_body:i,p_visibility:l});if(c)throw c}async function hC(n,a){const{error:i}=await Ct.rpc("add_support_comment",{p_post_id:n,p_body:a});if(i)throw i}async function pC(n){const{data:a,error:i}=await Ct.rpc("toggle_support_vote",{p_post_id:n});if(i)throw i;const l=Array.isArray(a)?a[0]:a;return{voted:!!l?.voted,totalVotes:Number(l?.total_votes||0)}}async function gC(n,a){const{error:i}=await Ct.rpc("change_support_post_status",{p_post_id:n,p_target_status:a});if(i)throw i}async function vC(n){const{error:a}=await Ct.rpc("set_support_post_hidden",{p_post_id:n,p_hidden:!0});if(a)throw a}async function yC(n,a){const{error:i}=await Ct.rpc("set_support_post_locked",{p_post_id:n,p_locked:a});if(i)throw i}async function bC(n,a){const{error:i}=await Ct.rpc("set_support_post_pinned",{p_post_id:n,p_pinned:a});if(i)throw i}async function xC(n,a){const{error:i}=await Ct.rpc("mark_support_duplicate",{p_post_id:n,p_duplicate_of_post_id:a});if(i)throw i}async function wC(n,a){const{error:i}=await Ct.rpc("accept_support_answer",{p_post_id:n,p_comment_id:a});if(i)throw i}async function SC(n,a=!0){const{error:i}=await Ct.rpc("hide_support_comment",{p_comment_id:n,p_hidden:a});if(i)throw i}const Jh=[{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"}],CC=[{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"}],kC={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"]},jC={type:"all",product:"",status:"all",visibility:"all",sort:"recent",query:""};function yh(){if(typeof window>"u")return jC;const n=new URLSearchParams(window.location.search),a=window.location.pathname.match(/^\/support\/(questions|issues|features|announcements)$/)?.[1],i=n.get("type")||a||"",l=i==="questions"||i==="question"?"question":i==="issues"||i==="issue"?"issue":i==="features"||i==="feature"?"feature":i==="announcements"||i==="announcement"?"announcement":"all",c=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 AC(n){return n==="all"?"":n==="question"?"questions":n==="issue"?"issues":n==="feature"?"features":"announcements"}function MC(n,a){const i={...n,...a},l=new URLSearchParams;i.product&&l.set("product",i.product),i.status!=="all"&&l.set("status",i.status),i.visibility!=="all"&&l.set("visibility",i.visibility),i.sort!=="recent"&&l.set("sort",i.sort),i.query&&l.set("q",i.query);const c=AC(i.type),d=l.toString();return`/support${c?`/${c}`:""}${d?`?${d}`:""}`}function Qd(n){const a=new Date(n);return Number.isFinite(a.getTime())?a.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"}):n}function bh(n){return n.replaceAll("-"," ").replace(/\b\w/g,a=>a.toUpperCase())}function Ay(n){return n==="question"?c0:n==="issue"?ox:n==="feature"?u0:d0}function My(n){return Jh.find(a=>a.id===n)?.shortLabel||n}function xh(n,a){return n.find(i=>i.id===a)?.name||"Product"}function ss(n){const a=nC(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 xx({session:n,currentProductKey:a="livedesk",appVersion:i="",onSignIn:l}){const[c,d]=u.useState(()=>yh()),[m,h]=u.useState(null),[g,y]=u.useState([]),[x,b]=u.useState([]),[w,A]=u.useState(""),[j,k]=u.useState([]),[N,M]=u.useState([]),[T,D]=u.useState([]),[F,$]=u.useState(()=>new Set),[G,L]=u.useState(!0),[Q,q]=u.useState(""),[P,Y]=u.useState(""),[H,ye]=u.useState(!1),[de,Z]=u.useState(!1),[z,se]=u.useState(""),[W,O]=u.useState(()=>yh().query),[le,ce]=u.useState(!1),[K,be]=u.useState(!1),[he,fe]=u.useState(""),[ee,we]=u.useState(""),[Me,He]=u.useState("free"),[ne,qe]=u.useState(""),[mt,J]=u.useState(""),[Ce,Le]=u.useState("admin"),[Fe,_e]=u.useState(""),[Xe,We]=u.useState(""),[Ze,dt]=u.useState(""),[U,ve]=u.useState(""),[Ae,Be]=u.useState(""),[ft,it]=u.useState([]),[yt,ot]=u.useState({productId:"",postType:"question",title:"",body:"",visibility:"public",includeEnvironment:!0,files:[]}),kt=u.useCallback(B=>{const Ke={...c,...B};d(Ke),typeof window<"u"&&window.history.pushState({},"",MC(c,B))},[c]);u.useEffect(()=>{const B=()=>d(yh());return window.addEventListener("popstate",B),()=>window.removeEventListener("popstate",B)},[]);const pe=u.useCallback(async()=>{const B=await rC(c.query);return b(B),n?.user.id&&$(await cC(n.user.id)),B},[c.query,n?.user.id]),De=u.useCallback(async()=>{if(!n?.user.id){h(null),y([]),b([]),A(""),D([]),L(!1);return}L(!0),Y("");try{const B=await sC(n.user.id,a);h(B.access),y(B.products),await pe(),D(await lC())}catch(B){Y(ss(B))}finally{L(!1)}},[a,pe,n?.user.id]);u.useEffect(()=>{De()},[De]);const $e=u.useMemo(()=>m?m.canViewAllProducts?g:g.filter(B=>m.accessibleProductIds.includes(B.id)):[],[m,g]),je=u.useMemo(()=>{const B=$e.find(Ke=>Ke.product_key===c.product);return m?.canViewAllProducts&&!c.product||c.product==="all"&&m?.canViewAllProducts?"all":B?B.product_key:$e.some(Ke=>Ke.product_key===a)?a:$e[0]?.product_key||""},[m?.canViewAllProducts,$e,a,c.product]),ct=je==="all"?"":$e.find(B=>B.product_key===je)?.id||"",bt=u.useMemo(()=>{const B=new Map(g.map(ht=>[ht.id,ht.product_key]));return[...x.filter(ht=>c.type!=="all"&&ht.post_type!==c.type||je!=="all"&&ct&&ht.product_id!==ct||c.status==="needs-response"&&!["open","needs-info"].includes(ht.status)||c.status!=="all"&&c.status!=="needs-response"&&ht.status!==c.status||c.visibility!=="all"&&ht.visibility!==c.visibility?!1:B.has(ht.product_id))].sort((ht,fn)=>c.sort==="votes"?fn.vote_count-ht.vote_count||fn.updated_at.localeCompare(ht.updated_at):c.sort==="newest"?fn.created_at.localeCompare(ht.created_at):Number(fn.is_pinned)-Number(ht.is_pinned)||fn.updated_at.localeCompare(ht.updated_at))},[x,g,c.sort,c.status,c.type,c.visibility,ct,je]),ze=bt.find(B=>B.id===w)||bt[0]||null,aa=!!(ze&&m&&(m.canViewAllProducts||m.managedProductIds.includes(ze.product_id))),zn=!!(ze&&n?.user.id===ze.author_id)||aa;u.useEffect(()=>{if(!ze){A(""),k([]),Z(!1);return}ze.id!==w&&A(ze.id)},[ze,w]),u.useEffect(()=>{let B=!0;return w?(jy(w).then(Ke=>{B&&k(Ke)}).catch(Ke=>{B&&Y(ss(Ke))}),iC(w).then(Ke=>{B&&M(Ke)}).catch(Ke=>{B&&Y(ss(Ke))}),()=>{B=!1}):(k([]),M([]),()=>{B=!1})},[w]),u.useEffect(()=>{!yt.productId&&$e[0]&&ot(B=>({...B,productId:ct||$e[0].id}))},[$e,yt.productId,ct]),u.useEffect(()=>{O(c.query)},[c.query]),u.useEffect(()=>{!ee&&$e[0]&&we($e[0].id),!mt&&$e[0]&&J($e[0].id)},[$e,ee,mt]);const nt=B=>{ze&&b(Ke=>Ke.map(ht=>ht.id===ze.id?{...ht,...B}:ht))},Ot=async B=>{if(B.preventDefault(),!(!n||!yt.productId)){q("create"),Y("");try{const Ke=await uC({productId:yt.productId,postType:yt.postType,title:yt.title,body:yt.body,visibility:yt.postType==="announcement"?"public":yt.visibility,appVersion:i,includeEnvironment:yt.postType==="issue"&&yt.includeEnvironment});for(const fn of ft)await fC(Ke,fn);const ht=await pe();ye(!1),it([]),ot(fn=>({...fn,title:"",body:"",files:[]})),A(Ke),ht.some(fn=>fn.id===Ke)||await De()}catch(Ke){Y(ss(Ke))}finally{q("")}}},Nn=async B=>{if(B.preventDefault(),!!ze){q("edit"),Y("");try{await mC(ze.id,ze.title,ze.body,ze.visibility),Z(!1),await pe()}catch(Ke){Y(ss(Ke))}finally{q("")}}},pa=async B=>{if(B.preventDefault(),!(!ze||!z.trim())){q("comment"),Y("");try{await hC(ze.id,z),se(""),k(await jy(ze.id)),await pe()}catch(Ke){Y(ss(Ke))}finally{q("")}}},Oe=async()=>{if(!(!ze||ze.post_type!=="feature")){q("vote"),Y("");try{const B=await pC(ze.id);$(Ke=>{const ht=new Set(Ke);return B.voted?ht.add(ze.id):ht.delete(ze.id),ht}),nt({vote_count:B.totalVotes})}catch(B){Y(ss(B))}finally{q("")}}},wn=async B=>{if(ze){q("status"),Y("");try{await gC(ze.id,B),nt({status:B}),await pe()}catch(Ke){Y(ss(Ke))}finally{q("")}}},On=async()=>{if(!(!ze||!window.confirm("Hide this Support post from the board?"))){q("hide"),Y("");try{await vC(ze.id),A(""),await pe()}catch(B){Y(ss(B))}finally{q("")}}},ws=async()=>{if(ze){q("lock"),Y("");try{await yC(ze.id,!ze.is_locked),nt({is_locked:!ze.is_locked}),await pe()}catch(B){Y(ss(B))}finally{q("")}}},pn=async()=>{if(ze){q("pin"),Y("");try{await bC(ze.id,!ze.is_pinned),nt({is_pinned:!ze.is_pinned}),await pe()}catch(B){Y(ss(B))}finally{q("")}}},qs=async B=>{if(ze){q(`accept-${B}`),Y("");try{await wC(ze.id,B),nt({accepted_comment_id:B,status:ze.post_type==="question"?"answered":ze.status}),await pe()}catch(Ke){Y(ss(Ke))}finally{q("")}}},Yn=async()=>{if(!(!ze||!U||U===ze.id)){q("duplicate"),Y("");try{await xC(ze.id,U),A(""),ve(""),await pe()}catch(B){Y(ss(B))}finally{q("")}}},Gs=async B=>{if(!B.read_at)try{await oC(B.id),D(Ke=>Ke.map(ht=>ht.id===B.id?{...ht,read_at:new Date().toISOString()}:ht))}catch(Ke){Y(ss(Ke))}B.post_id&&A(B.post_id),ce(!1)};return n?G&&!m?r.jsxs("section",{className:"support-page support-loading",children:[r.jsx(Sc,{className:"support-spin",size:23})," Loading Support Board..."]}):r.jsxs("section",{className:"support-page",children:[r.jsx("header",{className:"support-page-header support-page-actions-only",children:r.jsxs("div",{className:"support-header-actions",children:[r.jsxs("div",{className:"support-notification-wrap",children:[r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>ce(B=>!B),title:"Notifications",children:[r.jsx(i0,{size:16})," ",T.filter(B=>!B.read_at).length>0&&r.jsx("b",{children:T.filter(B=>!B.read_at).length})]}),le&&r.jsxs("div",{className:"support-notification-popover",children:[r.jsx("strong",{children:"Notifications"}),T.length===0?r.jsx("span",{className:"support-muted",children:"No notifications yet."}):T.map(B=>r.jsxs("button",{type:"button",className:B.read_at?"":"unread",onClick:()=>{Gs(B)},children:[r.jsx("b",{children:B.title}),r.jsx("span",{children:B.body}),r.jsx("small",{children:Qd(B.created_at)})]},B.id))]})]}),m?.canViewAllProducts&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>be(B=>!B),children:[r.jsx(Wn,{size:16})," Admin"]}),r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{De()},disabled:G,children:[r.jsx(Sc,{size:16,className:G?"support-spin":""})," Refresh"]}),r.jsxs("button",{className:"support-primary-button",type:"button",onClick:()=>ye(!0),disabled:$e.length===0,children:[r.jsx(fh,{size:17})," New request"]})]})}),P&&r.jsxs("div",{className:"support-error",role:"alert",children:[r.jsx(Na,{size:17})," ",r.jsx("span",{children:P}),r.jsx("button",{type:"button",onClick:()=>Y(""),"aria-label":"Dismiss error",children:r.jsx(Na,{size:15})})]}),H&&r.jsxs("form",{className:"support-composer",onSubmit:B=>{Ot(B)},children:[r.jsxs("div",{className:"support-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"New Support request"}),r.jsx("strong",{children:"Describe one actionable problem or idea."})]}),r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>ye(!1),"aria-label":"Close composer",children:r.jsx(Na,{size:18})})]}),r.jsxs("div",{className:"support-form-grid",children:[r.jsxs("label",{children:[r.jsx("span",{children:"Product"}),r.jsx("select",{value:yt.productId,onChange:B=>ot(Ke=>({...Ke,productId:B.target.value})),children:$e.map(B=>r.jsx("option",{value:B.id,children:B.name},B.id))})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Type"}),r.jsx("select",{value:yt.postType,onChange:B=>ot(Ke=>({...Ke,postType:B.target.value})),children:Jh.filter(B=>B.id!=="announcement"||m?.canCreateAnnouncements).map(B=>r.jsx("option",{value:B.id,children:B.label},B.id))})]}),r.jsxs("label",{className:"support-form-wide",children:[r.jsx("span",{children:"Title"}),r.jsx("input",{required:!0,minLength:3,maxLength:180,value:yt.title,onChange:B=>ot(Ke=>({...Ke,title:B.target.value})),placeholder:"A short, searchable summary"})]}),r.jsxs("label",{className:"support-form-wide",children:[r.jsx("span",{children:yt.postType==="issue"?"What happened?":yt.postType==="feature"?"Describe the desired behavior":yt.postType==="announcement"?"Announcement":"Question"}),r.jsx("textarea",{required:!0,value:yt.body,onChange:B=>ot(Ke=>({...Ke,body:B.target.value})),placeholder:"Include the context another person needs to respond.",rows:6})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Visibility"}),r.jsxs("select",{value:yt.visibility,disabled:yt.postType==="announcement",onChange:B=>ot(Ke=>({...Ke,visibility:B.target.value})),children:[r.jsx("option",{value:"public",children:"Public"}),r.jsx("option",{value:"private",children:"Private"})]})]}),yt.postType==="issue"&&r.jsxs("label",{className:"support-checkbox",children:[r.jsx("input",{type:"checkbox",checked:yt.includeEnvironment,onChange:B=>ot(Ke=>({...Ke,includeEnvironment:B.target.checked}))}),r.jsx("span",{children:"Attach safe browser/runtime details"})]}),r.jsxs("label",{className:"support-form-wide",children:[r.jsx("span",{children:"Attachments"}),r.jsx("input",{type:"file",multiple:!0,accept:"image/png,image/jpeg,image/webp,text/plain,text/markdown,application/json,application/pdf",onChange:B=>it(Array.from(B.target.files||[]).slice(0,5))}),r.jsx("small",{className:"support-muted",children:"Up to 5 files, 10 MB each. Images, text, JSON, Markdown, and PDF."})]})]}),r.jsxs("div",{className:"support-composer-footer",children:[r.jsx("span",{children:ft.length>0?`${ft.length} attachment${ft.length===1?"":"s"} selected.`:"Private posts are visible only to you and the product support staff."}),r.jsxs("button",{className:"support-primary-button",type:"submit",disabled:Q==="create",children:[r.jsx(Bu,{size:16})," ",Q==="create"?"Submitting...":"Submit request"]})]})]}),r.jsxs("div",{className:"support-tabs",role:"tablist","aria-label":"Support post type",children:[r.jsx("button",{className:c.type==="all"?"active":"",type:"button",onClick:()=>kt({type:"all"}),children:"All"}),Jh.map(B=>{const Ke=Ay(B.id);return r.jsxs("button",{className:c.type===B.id?"active":"",type:"button",onClick:()=>kt({type:B.id}),children:[r.jsx(Ke,{size:15})," ",B.label]},B.id)})]}),K&&m?.canViewAllProducts&&r.jsxs("section",{className:"support-admin-panel",children:[r.jsxs("div",{className:"support-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Owner controls"}),r.jsx("strong",{children:"Products and access are managed by immutable user IDs behind these email lookup forms."})]}),r.jsx(Wn,{size:19})]}),r.jsxs("div",{className:"support-admin-grid",children:[r.jsxs("form",{onSubmit:B=>{},children:[r.jsx("strong",{children:"Grant product access"}),r.jsx("input",{type:"email",required:!0,placeholder:"User email",value:he,onChange:B=>fe(B.target.value)}),r.jsx("select",{value:ee,onChange:B=>we(B.target.value),children:$e.map(B=>r.jsx("option",{value:B.id,children:B.name},B.id))}),r.jsxs("select",{value:Me,onChange:B=>He(B.target.value),children:[r.jsx("option",{value:"free",children:"Free"}),r.jsx("option",{value:"user",children:"User"}),r.jsx("option",{value:"paid",children:"Paid"}),r.jsx("option",{value:"beta",children:"Beta"}),r.jsx("option",{value:"staff",children:"Staff"})]}),r.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:Ae==="access",children:[r.jsx(Ir,{size:15})," Grant access"]})]}),r.jsxs("form",{onSubmit:B=>{},children:[r.jsx("strong",{children:"Assign product admin"}),r.jsx("input",{type:"email",required:!0,placeholder:"Admin email",value:ne,onChange:B=>qe(B.target.value)}),r.jsx("select",{value:mt,onChange:B=>J(B.target.value),children:$e.map(B=>r.jsx("option",{value:B.id,children:B.name},B.id))}),r.jsxs("select",{value:Ce,onChange:B=>Le(B.target.value),children:[r.jsx("option",{value:"admin",children:"Admin"}),r.jsx("option",{value:"support",children:"Support"}),r.jsx("option",{value:"moderator",children:"Moderator"})]}),r.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:Ae==="product-admin",children:[r.jsx(Wn,{size:15})," Assign admin"]})]}),r.jsxs("form",{onSubmit:B=>{},children:[r.jsx("strong",{children:"Add a product"}),r.jsx("input",{required:!0,pattern:"[a-z0-9][a-z0-9_-]{1,48}",placeholder:"product-key",value:Fe,onChange:B=>_e(B.target.value)}),r.jsx("input",{required:!0,placeholder:"Product name",value:Xe,onChange:B=>We(B.target.value)}),r.jsx("input",{placeholder:"Description",value:Ze,onChange:B=>dt(B.target.value)}),r.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:Ae==="product",children:[r.jsx(fh,{size:15})," Add product"]})]})]})]}),r.jsxs("form",{className:"support-search-bar",onSubmit:B=>{B.preventDefault(),kt({query:W.trim()})},children:[r.jsxs("label",{children:[r.jsx("span",{children:"Search Support"}),r.jsx("input",{value:W,onChange:B=>O(B.target.value),placeholder:"Search titles and request details"})]}),r.jsxs("button",{className:"support-secondary-button",type:"submit",children:[r.jsx(dy,{size:15})," Search"]}),c.query&&r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{O(""),kt({query:""})},"aria-label":"Clear search",children:r.jsx(Na,{size:16})})]}),r.jsxs("div",{className:"support-filter-bar",children:[r.jsxs("div",{className:"support-filter-title",children:[r.jsx(dy,{size:16}),r.jsx("span",{children:"Filter"})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Product"}),r.jsxs("select",{value:je,onChange:B=>kt({product:B.target.value}),disabled:!m?.canViewAllProducts&&$e.length<=1,children:[r.jsx("option",{value:"all",children:"All products"}),$e.map(B=>r.jsx("option",{value:B.product_key,children:B.name},B.id))]})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Status"}),r.jsx("select",{value:c.status,onChange:B=>kt({status:B.target.value}),children:CC.map(B=>r.jsx("option",{value:B.id,children:B.label},B.id))})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Visibility"}),r.jsxs("select",{value:c.visibility,onChange:B=>kt({visibility:B.target.value}),children:[r.jsx("option",{value:"all",children:"All visibility"}),r.jsx("option",{value:"public",children:"Public"}),r.jsx("option",{value:"private",children:"Private"})]})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Sort"}),r.jsxs("select",{value:c.sort,onChange:B=>kt({sort:B.target.value}),children:[r.jsx("option",{value:"recent",children:"Recently updated"}),r.jsx("option",{value:"newest",children:"Newest"}),r.jsx("option",{value:"votes",children:"Most votes"})]})]})]}),m?.canViewAllProducts&&r.jsxs("div",{className:"support-admin-shortcuts",children:[r.jsxs("span",{children:[r.jsx(Wn,{size:15})," Owner view"]}),r.jsx("button",{type:"button",onClick:()=>kt({status:"needs-response"}),children:"Needs response"}),r.jsx("button",{type:"button",onClick:()=>kt({visibility:"private"}),children:"Private requests"}),r.jsx("button",{type:"button",onClick:()=>kt({type:"feature",status:"all",sort:"votes"}),children:"High-vote features"})]}),r.jsxs("div",{className:"support-board-layout",children:[r.jsxs("section",{className:"support-post-list","aria-label":"Support posts",children:[r.jsxs("div",{className:"support-list-heading",children:[r.jsxs("span",{children:[bt.length," request",bt.length===1?"":"s"]}),r.jsx("small",{children:je==="all"?"All products":xh($e,ct)})]}),bt.length===0?r.jsxs("div",{className:"support-list-empty",children:[r.jsx(_u,{size:25}),r.jsx("strong",{children:"No posts match these filters."}),r.jsx("span",{children:"Start with a focused question, issue report, or feature request."}),$e.length>0&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>ye(!0),children:[r.jsx(fh,{size:16})," Create the first request"]})]}):bt.map(B=>{const Ke=Ay(B.post_type);return r.jsxs("button",{type:"button",className:`support-post-row ${B.id===ze?.id?"active":""}`,onClick:()=>{A(B.id),Z(!1)},children:[r.jsx("span",{className:"support-post-row-icon",children:r.jsx(Ke,{size:17})}),r.jsxs("span",{className:"support-post-row-copy",children:[r.jsxs("span",{className:"support-post-row-meta",children:[r.jsx("b",{children:xh(g,B.product_id)}),r.jsx("em",{children:My(B.post_type)}),B.visibility==="private"&&r.jsx(Ti,{size:13})]}),r.jsx("strong",{children:B.title}),r.jsxs("small",{children:[bh(B.status)," · ",Qd(B.updated_at)," · ",B.comment_count," comments"]})]}),B.post_type==="feature"&&r.jsxs("span",{className:"support-vote-count",children:[r.jsx(lx,{size:14})," ",B.vote_count]})]},B.id)})]}),r.jsx("section",{className:"support-post-detail","aria-label":"Support post detail",children:ze?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"support-detail-head",children:[r.jsxs("div",{className:"support-detail-badges",children:[r.jsx("span",{className:"support-product-badge",children:xh(g,ze.product_id)}),r.jsx("span",{className:"support-type-badge",children:My(ze.post_type)}),r.jsx("span",{className:`support-status-badge status-${ze.status}`,children:bh(ze.status)}),ze.visibility==="private"&&r.jsxs("span",{className:"support-private-badge",children:[r.jsx(Ti,{size:13})," Private"]})]}),r.jsxs("div",{className:"support-detail-actions",children:[zn&&r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>Z(B=>!B),title:"Edit post",children:r.jsx(l0,{size:16})}),aa&&r.jsxs(r.Fragment,{children:[r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{pn()},disabled:Q==="pin",title:ze.is_pinned?"Unpin post":"Pin post",children:r.jsx(fy,{size:16})}),r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{ws()},disabled:Q==="lock",title:ze.is_locked?"Unlock post":"Lock post",children:r.jsx(Ti,{size:16})}),r.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{On()},disabled:Q==="hide",title:"Hide post",children:r.jsx(my,{size:16})})]})]})]}),de?r.jsxs("form",{className:"support-edit-form",onSubmit:B=>{Nn(B)},children:[r.jsx("input",{value:ze.title,onChange:B=>nt({title:B.target.value}),minLength:3,maxLength:180,required:!0}),r.jsx("textarea",{value:ze.body,onChange:B=>nt({body:B.target.value}),rows:9,required:!0}),r.jsxs("div",{className:"support-edit-actions",children:[r.jsxs("select",{value:ze.visibility,onChange:B=>nt({visibility:B.target.value}),children:[r.jsx("option",{value:"public",children:"Public"}),r.jsx("option",{value:"private",children:"Private"})]}),r.jsxs("button",{className:"support-primary-button",type:"submit",disabled:Q==="edit",children:[r.jsx(Ir,{size:16})," Save changes"]})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("h3",{children:ze.title}),r.jsx("div",{className:"support-detail-body",children:ze.body.split(`
10
- `).map((B,Ke)=>r.jsx("p",{children:B||" "},`${ze.id}-body-${Ke}`))})]}),r.jsxs("div",{className:"support-detail-meta",children:[r.jsxs("span",{children:["Opened ",Qd(ze.created_at)]}),ze.app_version&&r.jsxs("span",{children:["Version ",ze.app_version]}),ze.platform&&r.jsx("span",{children:ze.platform}),ze.is_locked&&r.jsxs("span",{children:[r.jsx(Ti,{size:13})," Locked"]}),ze.is_pinned&&r.jsxs("span",{children:[r.jsx(fy,{size:13})," Pinned"]})]}),r.jsxs("div",{className:"support-detail-controls",children:[ze.post_type==="feature"&&r.jsxs("button",{className:`support-vote-button ${F.has(ze.id)?"voted":""}`,type:"button",onClick:()=>{Oe()},disabled:Q==="vote",children:[r.jsx(o0,{size:16})," ",F.has(ze.id)?"Voted":"Vote"," ",r.jsx("b",{children:ze.vote_count})]}),aa&&r.jsxs("label",{className:"support-status-control",children:[r.jsx("span",{children:"Change status"}),r.jsx("select",{value:ze.status,onChange:B=>{wn(B.target.value)},disabled:Q==="status",children:(kC[ze.post_type]||[]).map(B=>r.jsx("option",{value:B,children:bh(B)},B))})]}),aa&&r.jsxs(r.Fragment,{children:[r.jsxs("select",{className:"support-status-control",value:U,onChange:B=>ve(B.target.value),children:[r.jsx("option",{value:"",children:"Duplicate of..."}),bt.filter(B=>B.id!==ze.id&&B.product_id===ze.product_id).map(B=>r.jsx("option",{value:B.id,children:B.title.slice(0,55)},B.id))]}),r.jsx("button",{className:"support-secondary-button",type:"button",onClick:()=>{Yn()},disabled:!U||Q==="duplicate",children:"Merge duplicate"})]})]}),N.length>0&&r.jsxs("div",{className:"support-attachments",children:[r.jsx("div",{className:"support-section-heading",children:r.jsxs("div",{children:[r.jsx("span",{children:"Attachments"}),r.jsxs("strong",{children:[N.length," file",N.length===1?"":"s"]})]})}),N.map(B=>r.jsxs("a",{href:B.signed_url,target:"_blank",rel:"noreferrer",children:[r.jsx(xp,{size:14})," ",B.file_name,r.jsxs("small",{children:[Math.ceil(B.size_bytes/1024)," KB"]})]},B.id))]}),r.jsxs("div",{className:"support-comments",children:[r.jsxs("div",{className:"support-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Discussion"}),r.jsxs("strong",{children:[j.length," comment",j.length===1?"":"s"]})]}),ze.is_locked&&r.jsxs("span",{className:"support-locked-label",children:[r.jsx(Ti,{size:14})," Locked"]})]}),j.length===0?r.jsx("p",{className:"support-muted",children:"No response yet. Keep the conversation focused on this request."}):r.jsx("div",{className:"support-comment-list",children:j.map(B=>r.jsxs("article",{className:`support-comment ${B.is_staff_answer?"staff":""} ${ze.accepted_comment_id===B.id?"accepted":""}`,children:[r.jsxs("div",{className:"support-comment-head",children:[r.jsx("strong",{children:B.is_staff_answer?"LiveDesk Support":B.author_id===n.user.id?"You":"Support user"}),B.is_staff_answer&&r.jsxs("span",{children:[r.jsx(Wn,{size:13})," Staff answer"]}),ze.accepted_comment_id===B.id&&r.jsxs("span",{children:[r.jsx(Zn,{size:13})," Accepted"]}),r.jsx("time",{children:Qd(B.created_at)})]}),r.jsx("p",{children:B.body}),r.jsxs("div",{className:"support-comment-actions",children:[(n.user.id===ze.author_id||aa)&&ze.post_type==="question"&&ze.accepted_comment_id!==B.id&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{qs(B.id)},disabled:Q===`accept-${B.id}`,children:[r.jsx(Ir,{size:14})," Accept answer"]}),aa&&r.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{SC(B.id)},title:"Hide comment",children:r.jsx(my,{size:14})})]})]},B.id))}),!ze.is_locked&&r.jsxs("form",{className:"support-comment-form",onSubmit:B=>{pa(B)},children:[r.jsx("textarea",{value:z,onChange:B=>se(B.target.value),placeholder:"Add a focused reply...",rows:3}),r.jsxs("button",{className:"support-primary-button",type:"submit",disabled:Q==="comment"||!z.trim(),children:[r.jsx(Bu,{size:15})," Reply"]})]})]})]}):r.jsxs("div",{className:"support-detail-empty",children:[r.jsx(_u,{size:28}),r.jsx("strong",{children:"Select a Support request"}),r.jsx("span",{children:"Its discussion and staff actions will appear here."})]})})]})]}):r.jsx("section",{className:"support-page support-auth-page",children:r.jsxs("div",{className:"support-empty-hero",children:[r.jsx("span",{className:"support-hero-icon",children:r.jsx(_u,{size:28})}),r.jsx("p",{className:"support-eyebrow",children:"LiveDesk Support"}),r.jsx("h2",{children:"Get help, report issues, and shape the product."}),r.jsx("p",{children:"Sign in to see the products attached to your account and submit a private or public request."}),r.jsxs("button",{className:"support-primary-button",type:"button",onClick:l,children:[r.jsx(Wn,{size:17})," Sign in with Google"]})]})})}function Xd(n){return!!n&&typeof n=="object"}function wx(n){let a=n;return Xd(a)&&"data"in a&&(a=a.data),Xd(a)&&"session"in a&&(a=a.session),!Xd(a)||typeof a.access_token!="string"||!a.access_token||!Xd(a.user)||typeof a.user.id!="string"||!a.user.id?null:a}function Ny(n){return n?.access_token?n.refresh_token?"":"refresh-token-required":"access-token-required"}const zu=5179,An=wl(`http://127.0.0.1:${zu}`);function NC(n){const a=n.split(".").map(i=>Number(i));return a.length===4&&a.every(i=>Number.isInteger(i)&&i>=0&&i<=255)?a:[]}function TC(n){const a=n.trim().toLowerCase();return a==="localhost"||a==="127.0.0.1"||a==="::1"||a==="[::1]"}function RC(n){const a=n.trim().toLowerCase();return!a||a==="0.0.0.0"||a==="::"||a==="[::]"}function EC(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 DC(n){return n.includes(":")&&!n.startsWith("[")?`[${n}]`:n}function LC(n){const a=String(n||"").trim();if(!a)return null;const i=/^[a-z][a-z\d+.-]*:\/\//i.test(a)?a:`tcp://${a}`;try{const l=new URL(i),c=l.hostname.replace(/^\[|\]$/g,""),d=Number(l.port);return!c||!Number.isInteger(d)||d<1||d>65535||RC(c)?null:{host:c,port:d}}catch{return null}}function wl(n){const a=String(n||"").trim()||`http://127.0.0.1:${zu}`,i=/^[a-z][a-z\d+.-]*:\/\//i.test(a)?a:`http://${a}`;try{const l=new URL(i);return l.port||(l.port=String(zu)),l.hash="",l.search="",l.toString().replace(/\/+$/,"")}catch{return`http://127.0.0.1:${zu}`}}function _C(n){const a=LC(n);return a?wl(`http://${DC(a.host)}:${zu}`):""}function Ty(n){const i=[n?.endpoint,...Array.isArray(n?.endpoint_candidates)?n.endpoint_candidates:[]].map(l=>_C(String(l||""))).filter(Boolean);return[...new Set(i)]}function Ou(n=An){if(!(typeof window>"u"||window.location.protocol!=="https:"))try{const a=new URL(n);if(a.protocol!=="http:")return;if(TC(a.hostname))return"loopback";if(EC(a.hostname))return"local"}catch{return}}function Pf(n,a=An){const i=new URL(n,wl(a));return i.protocol=i.protocol==="https:"?"wss:":"ws:",i.toString()}async function Ve(n,a,i=An){const l=wl(i),c={...a,headers:{"Content-Type":"application/json",...a?.headers||{}},cache:"no-store"},d=Ou(l);d&&(c.targetAddressSpace=d);let m;try{m=await fetch(`${l}${n}`,c)}catch(g){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."):g}let h=null;try{h=await m.json()}catch{h=null}if(!m.ok){const g=h&&typeof h=="object"&&"error"in h?String(h.error||""):"";throw new Error(`${m.status} ${g||m.statusText}`)}return h}async function Sx({baseUrl:n=An,targetRole:a,previousRuntimePid:i=0,allowedStates:l=["running","waiting-auth"],timeoutMs:c=3e4}){const d=Date.now()+c;let m=null;for(;Date.now()<d;){try{const g=await Ve("/api/runtime/status",void 0,n),y=String(g.role||"").toLowerCase(),x=String(g.state||"").toLowerCase(),b=Number(g.runtimePid||0),w=i>1?b>1&&b!==i:b>1;if(y===a&&l.map(A=>A.toLowerCase()).includes(x)&&w)return g}catch(g){m=g}await new Promise(g=>setTimeout(g,300))}const h=m instanceof Error?` ${m.message}`:"";throw new Error(`LiveDesk runtime did not become ${a} with a new process.${h}`)}function IC(n,a=120){if(typeof window>"u")return;const i=new URL(window.location.href);i.port=String(n),i.pathname="/",i.search="",i.hash="";const l=i.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 Cx(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 Cf(n){await navigator.clipboard.writeText(n)}function kx({size:n=22}){return r.jsxs("svg",{width:n,height:n,viewBox:"0 0 28 28",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[r.jsx("rect",{x:"2.5",y:"4",width:"14",height:"9",rx:"1.5",stroke:"currentColor",strokeWidth:"1.7",opacity:"0.42"}),r.jsx("path",{d:"M7 16v1.5h5",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",opacity:"0.42"}),r.jsx("rect",{x:"10.5",y:"2.5",width:"14",height:"9",rx:"1.5",stroke:"currentColor",strokeWidth:"1.7",opacity:"0.62"}),r.jsx("path",{d:"M15 14.5V16h5",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",opacity:"0.62"}),r.jsx("rect",{x:"6.5",y:"8.5",width:"15",height:"10",rx:"1.7",fill:"currentColor",fillOpacity:"0.12",stroke:"currentColor",strokeWidth:"1.9"}),r.jsx("path",{d:"M12 21v1.5H9.5M16 21v1.5h2.5M9.5 22.5h9",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round"})]})}const jx={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."},ep={en:jx,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 Uf(n){const a=n?[n]:typeof navigator>"u"?["en"]:navigator.languages?.length?navigator.languages:[navigator.language];for(const i of a){const l=String(i||"").trim(),c=l.toLowerCase();if(!c)continue;if(c.startsWith("zh-tw")||c.startsWith("zh-hk"))return"zh-TW";if(c.startsWith("zh"))return"zh";if(c.startsWith("pt"))return"pt-BR";const d=c.split("-")[0];if(ep[l])return l;if(ep[d])return d}return"en"}function Rf(n,a){const i=Uf(a);return ep[i]?.[n]||jx[n]}function tp(n,a,i){return`${n}
11
- ${Rf(a,i)}`}const Ax={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"},zC={en:Ax,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"}},Mx={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"},OC={en:Mx,ko:{eyebrow:"컴퓨터 역할",title:"이 컴퓨터를 Hub로 사용할까요?",description:"Hub는 Client 컴퓨터를 연결하고 관리합니다.",restartNotice:"다른 컴퓨터가 Hub라면 이 컴퓨터가 새 Hub가 됩니다.",cancel:"취소",confirm:"Hub로 설정",closeLabel:"Hub 설정 확인 닫기"}};function HC(n){const a=Uf(n);return zC[a]||Ax}function FC(n){const a=Uf(n);return OC[a]||Mx}const $C=[{id:"docs",label:"Doc",icon:Tf},{id:"support",label:"Support",icon:_u},{id:"pricing",label:"Pricing",icon:Iu},{id:"settings",label:"Settings",icon:wp}],Ry=[0,1e3,2e3,5e3,1e4,2e4,3e4];function BC(){return typeof window>"u"?"":window.location.port==="5179"?window.location.origin:"http://127.0.0.1:5179"}async function to(n,a=!1){const i=a?"":sessionStorage.getItem("livedesk.client.csrf");if(i)return i;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 np(n){return`${Math.max(0,Math.min(100,Number(n||0))).toFixed(0)}%`}function wh(n){return Number.isFinite(n)?`${Math.max(0,Math.min(100,Number(n))).toFixed(0)}%`:"—"}function Nx(n){return Number.isFinite(n)?np(Number(n)):"0%"}function uo(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 Ey(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 PC(n,a){const i=Number(n||0)/1073741824,l=Number(a||0)/1024**3;return l>0?`${i.toFixed(1)} / ${l.toFixed(1)} GB`:"Checking..."}function UC(n,a){return!Number.isFinite(a)||Number(a)<=0?"Dedicated memory unavailable":Number.isFinite(n)?`${uo(n)} / ${uo(a)}`:`${uo(a)} available`}function qC(n){const a=Math.max(0,Math.floor(Number(n||0)/60)),i=Math.floor(a/1440),l=Math.floor(a%1440/60),c=a%60;return i>0?`${i}d ${l}h`:l>0?`${l}h ${c}m`:`${c}m`}function Zd({icon:n,label:a,value:i,detail:l,percent:c}){return r.jsxs("article",{className:"client-resource-metric",children:[r.jsxs("div",{className:"client-resource-metric-head",children:[r.jsx(n,{size:17}),r.jsx("span",{children:a}),r.jsx("strong",{children:i})]}),r.jsx("small",{title:l,children:l}),r.jsx("i",{"aria-hidden":"true",children:r.jsx("b",{style:{width:Nx(c)}})})]})}function GC(n,a){const i=n?.user.user_metadata||{},l=i.full_name||i.name||i.preferred_username||n?.user.email||n?.user.id||a?.userName||a?.auth?.name||a?.userEmail||a?.userId||"Account";return String(l).trim()||"Account"}function VC(n,a){const i=n?.user.user_metadata||{},l=i.avatar_url||i.picture||a?.userAvatarUrl||a?.auth?.avatarUrl;return typeof l=="string"?l.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 r.jsxs("section",{className:"client-service-page",children:[r.jsx("span",{className:"client-unified-section-label",children:l.label}),r.jsx("h2",{children:l.title}),r.jsx("p",{children:l.body}),r.jsxs("div",{className:"client-service-page-card",children:[n==="docs"&&r.jsxs(r.Fragment,{children:[r.jsx("strong",{children:"Automatic connection"}),r.jsx("span",{children:"Start LiveDesk. This computer signs in, finds the Hub, and becomes available without another action."})]}),n==="pricing"&&r.jsxs(r.Fragment,{children:[r.jsx("strong",{children:"One plan, managed at the Hub"}),r.jsx("span",{children:"Computer access follows the account and plan used by the Hub."})]}),n==="settings"&&r.jsxs(r.Fragment,{children:[r.jsx("strong",{children:"Saved sign-in"}),r.jsx("span",{children:a?.auth?.persisted?"Enabled on this computer":"Sign in once to enable automatic reconnection"})]})]})]})}function YC({session:n,status:a,pin:i,error:l,roleChangeMessage:c,videoAccelerationBusy:d,slotInput:m,slotBusy:h,onSignIn:g,onPinChange:y,onSubmitPin:x,onSlotInputChange:b,onSaveSlot:w,onEnableVideoAcceleration:A}){const j=a?.connectionState==="connected",k=a?.videoAcceleration,N=d||k?.busy||k?.state==="installing",M=k?.ready?`${k.encoder||"H.264"} · ${k.driver||"VAAPI"}`:N?"Setting up…":k?.message||"Setup available",T=a?.system?.memoryTotalBytes?Number(a.system.memoryUsedBytes||0)/a.system.memoryTotalBytes*100:0,D=a?.system?.gpus||[],F=D.find(H=>Number.isFinite(H.usagePercent)||Number.isFinite(H.memoryTotalBytes))||D[0],$=Number.isFinite(F?.usagePercent)?Number(F?.usagePercent):null,G=Number.isFinite(F?.memoryTotalBytes)&&Number(F?.memoryTotalBytes)>0&&Number.isFinite(F?.memoryUsedBytes)?Number(F?.memoryUsedBytes)/Number(F?.memoryTotalBytes)*100:null,L=a?.system?.disks||[],Q=a?.system?.network,q=Q?.interfaces||[],P=[...new Set(q.map(H=>H.name).filter(Boolean))],Y=q.map(H=>H.address).filter(Boolean);return r.jsxs("section",{className:"client-home-page",children:[r.jsxs("header",{className:"client-home-heading",children:[r.jsxs("div",{children:[r.jsx("p",{className:"client-unified-eyebrow",children:"THIS COMPUTER"}),r.jsx("h2",{children:a?.deviceName||"This Computer"})]}),r.jsxs("span",{className:`client-unified-role-chip ${j?"connected":""}`,children:[r.jsx(Ta,{size:15})," ",j?"Online":"Connecting"]})]}),r.jsxs("div",{className:"client-home-layout",children:[r.jsxs("section",{className:"client-main-surface","aria-label":"Client computer",children:[r.jsxs("div",{className:"client-main-surface-head",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"SYSTEM STATUS"}),r.jsx("strong",{children:"Hardware at a glance"})]}),r.jsxs("small",{children:[r.jsx(dx,{size:14})," Uptime ",qC(a?.system?.uptimeSeconds)]})]}),r.jsxs("div",{className:"client-system-dashboard",children:[r.jsxs("section",{className:"client-performance-panel","aria-label":"Performance",children:[r.jsxs("div",{className:"client-system-subhead",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"PERFORMANCE"}),r.jsx("strong",{children:"Live resources"})]}),r.jsx("small",{children:"Live updates"})]}),r.jsxs("div",{className:"client-live-metrics",children:[r.jsx(Zd,{icon:Yh,label:"CPU",value:np(a?.system?.cpuUsagePercent),detail:a?.system?.cpuLogicalCores?`${a.system.cpuLogicalCores} logical cores · Current processor usage`:"Current processor usage",percent:a?.system?.cpuUsagePercent}),r.jsx(Zd,{icon:f0,label:"Memory",value:np(T),detail:PC(a?.system?.memoryUsedBytes,a?.system?.memoryTotalBytes),percent:T}),r.jsx(Zd,{icon:m0,label:"GPU",value:wh($),detail:F?.name||(a?.system?.hardwareCollecting?"Detecting graphics hardware…":"Graphics usage unavailable"),percent:$}),r.jsx(Zd,{icon:zr,label:"VRAM",value:wh(G),detail:UC(F?.memoryUsedBytes,F?.memoryTotalBytes),percent:G})]})]}),r.jsxs("section",{className:"client-storage-panel","aria-label":"Local storage",children:[r.jsxs("div",{className:"client-system-subhead",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"STORAGE"}),r.jsx("strong",{children:"Local drives"})]}),r.jsx("small",{children:L.length>0?`${L.length} ${L.length===1?"drive":"drives"}`:a?.system?.hardwareCollecting?"Detecting…":"Unavailable"})]}),r.jsxs("div",{className:"client-disk-list",children:[L.map(H=>r.jsxs("article",{className:"client-disk-row",children:[r.jsxs("div",{className:"client-disk-row-head",children:[r.jsxs("span",{children:[r.jsx(co,{size:16}),r.jsx("strong",{children:H.mount||"Disk"}),r.jsx("small",{children:H.name||"Local disk"})]}),r.jsx("strong",{children:wh(H.usedPercent)})]}),r.jsxs("small",{children:[uo(H.freeBytes)," free · ",uo(H.totalBytes)," total"]}),r.jsx("i",{"aria-hidden":"true",children:r.jsx("b",{style:{width:Nx(H.usedPercent)}})})]},`${H.mount}-${H.name||""}`)),L.length===0&&r.jsxs("div",{className:"client-disk-empty",children:[r.jsx(co,{size:18}),r.jsx("span",{children:a?.system?.hardwareCollecting?"Detecting local drives…":"Storage information is not available."})]})]})]}),r.jsxs("section",{className:"client-network-panel","aria-label":"Network activity",children:[r.jsxs("div",{className:"client-system-subhead",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"NETWORK"}),r.jsx("strong",{children:"Live traffic"})]}),r.jsx("small",{children:P.length>0?P.join(", "):"Detecting adapter"})]}),r.jsxs("div",{className:"client-network-live",children:[r.jsxs("div",{className:"client-network-adapter",children:[r.jsx($f,{size:18}),r.jsxs("span",{children:[r.jsx("strong",{children:P.join(", ")||"Network"}),r.jsx("small",{children:Y.join(" / ")||"Checking active connection"})]})]}),r.jsxs("div",{className:"client-network-rate download",children:[r.jsx(h0,{size:17}),r.jsxs("span",{children:[r.jsx("small",{children:"Receive"}),r.jsx("strong",{children:Ey(Q?.receiveBytesPerSecond)})]})]}),r.jsxs("div",{className:"client-network-rate upload",children:[r.jsx(p0,{size:17}),r.jsxs("span",{children:[r.jsx("small",{children:"Send"}),r.jsx("strong",{children:Ey(Q?.sendBytesPerSecond)})]})]}),r.jsxs("small",{className:"client-network-total",children:["Total ",uo(Q?.receivedBytes)," received / ",uo(Q?.sentBytes)," sent"]})]})]})]})]}),r.jsxs("aside",{className:"client-connection-panel",children:[r.jsx("span",{className:"client-unified-section-label",children:"LIVEDESK SERVICES"}),r.jsx("h3",{children:j?"Connected to the Hub":a?.authenticated?"Finding the Hub":"Connect this computer"}),j?r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"client-unified-copy",children:"This computer is available from the LiveDesk Hub."}),r.jsxs("div",{className:"client-service-status-list",children:[r.jsxs("div",{children:[r.jsx(Ta,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Screen sharing"}),r.jsx("small",{children:a?.permissions?.screenCapture?"Active":"Waiting"})]})]}),r.jsxs("div",{children:[r.jsx(Wn,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Remote control"}),r.jsx("small",{children:a?.permissions?.remoteInput?"Available":"Unavailable"})]})]}),r.jsxs("div",{children:[r.jsx(gc,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"File delivery"}),r.jsx("small",{children:a?.permissions?.files?"Ready to receive":"Unavailable"})]})]}),r.jsxs("div",{children:[r.jsx(ho,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Computer audio"}),r.jsx("small",{children:a?.permissions?.audio?"Available":"Unavailable"})]})]})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"client-unified-copy",children:a?.authenticated?"LiveDesk is checking the registered Hub endpoints. A temporary Hub PIN can be used as a fallback.":"Sign in once on this computer. LiveDesk saves the verified session, finds the Hub, and starts screen sharing automatically."}),!n&&!a?.authenticated?r.jsxs("button",{className:"client-unified-primary",type:"button",onClick:g,children:[r.jsx(mo,{size:16})," Sign in with Google"]}):r.jsxs("p",{className:"client-unified-success",children:[r.jsx(Zn,{size:16})," Signed in as ",n?.user.email||n?.user.id||a?.userEmail||a?.userId||"saved account"]}),r.jsxs("div",{className:"client-unified-pin-row",children:[r.jsx(fx,{size:16}),r.jsx("input",{value:i,onChange:H=>y(H.target.value),placeholder:"6-digit Hub PIN",inputMode:"numeric","aria-label":"6-digit Hub PIN"}),r.jsx("button",{className:"client-unified-secondary",type:"button",onClick:x,disabled:i.length!==6,children:"Connect"})]})]}),k?.supported&&r.jsxs("div",{className:`client-video-acceleration state-${k.ready?"ready":k.state||"setup-required"}`,children:[r.jsx(Yh,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Hardware video"}),r.jsx("small",{children:M})]}),!k.ready&&k.canInstall&&r.jsx("button",{type:"button",onClick:A,disabled:N,title:"Install and verify Linux FFmpeg hardware video support",children:N?"Setting up":"Enable"})]}),(l||a?.lastError)&&r.jsxs("p",{className:"client-unified-error",role:"alert",children:[r.jsx(ux,{size:15})," ",l||a?.lastError]}),c&&r.jsx("p",{className:"client-unified-success",children:c}),r.jsxs("div",{className:"client-slot-setting",children:[r.jsxs("label",{htmlFor:"client-slot-number",children:[r.jsx("span",{children:"Slot"}),r.jsx("input",{id:"client-slot-number",value:m,onChange:H=>b(H.target.value),inputMode:"numeric",pattern:"[0-9]*",placeholder:"1-999","aria-label":"Wall slot number",disabled:!j||h})]}),r.jsxs("button",{type:"button",onClick:w,disabled:!j||h||!m,"aria-label":"Save slot number",title:"Save slot number",children:[r.jsx(wp,{size:17}),r.jsx("span",{children:h?"Saving":"Set"})]})]})]})]})]})}function KC(){const[n,a]=u.useState(null),[i,l]=u.useState(null),[c,d]=u.useState(!1),[m,h]=u.useState(""),[g,y]=u.useState(""),[x,b]=u.useState(""),[w,A]=u.useState(!1),[j,k]=u.useState(!1),[N,M]=u.useState(""),[T,D]=u.useState(!1),[F,$]=u.useState(null),[G,L]=u.useState(!1),[Q,q]=u.useState("computer"),[P,Y]=u.useState(!1),H=u.useRef(null),ye=u.useRef(null),de=u.useRef(!1),Z=u.useRef(!1),z=u.useRef(!1),se=u.useRef(0),W=u.useRef(!1),O=u.useMemo(BC,[]),le=u.useMemo(()=>GC(i,n),[i,n]),ce=u.useMemo(()=>VC(i,n),[i,n]),[K,be]=u.useState(!1),he=le.slice(0,1).toUpperCase()||"L";u.useEffect(()=>{be(!1)},[ce]);const fe=u.useCallback(async()=>{if(y(""),window.liveDesk?.auth?.signInWithGoogle){const U=await window.liveDesk.auth.signInWithGoogle();return U?.ok===!1?(y(U.error||"LiveDesk could not open the system browser for Google sign-in."),!1):!0}return window.location.assign(`${O}/auth/google`),!0},[O]),ee=u.useCallback(async()=>{z.current||(z.current=!0,y("Your saved Google sign-in is incomplete. LiveDesk is reopening sign-in once to repair it."),await Ct.auth.signOut({scope:"local"}).catch(()=>{}),l(null),await fe()||(z.current=!1))},[fe]),we=u.useCallback(async U=>{const ve=Ny(U);if(ve)throw new Error(ve);if(de.current)return!1;de.current=!0;try{const Ae=await window.liveDesk?.auth?.persistSession?.(U);if(Ae?.ok===!1)throw new Error(Ae.error||"LiveDesk could not validate the desktop session.");for(let Be=0;Be<2;Be+=1){const ft=await to(O,Be>0),it=await fetch(`${O}/api/auth/session`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":ft},signal:AbortSignal.timeout(1e4),body:JSON.stringify({accessToken:U.access_token,refreshToken:U.refresh_token,expiresAt:U.expires_at,user:{id:U.user.id,email:U.user.email}})}),yt=await it.json().catch(()=>({}));if(it.status===403&&Be===0){sessionStorage.removeItem("livedesk.client.csrf");continue}if(!it.ok)throw new Error(yt.error||`Client runtime returned HTTP ${it.status}.`);return y(""),!0}throw new Error("Client runtime rejected the session transfer.")}finally{de.current=!1}},[O]),Me=u.useCallback(async()=>{try{const U=await fetch(`${O}/api/client/status`,{cache:"no-store"}),ve=await U.json().catch(()=>({}));if(!U.ok)throw new Error(ve.error||`Client runtime returned HTTP ${U.status}.`);if(ve.csrfToken&&sessionStorage.setItem("livedesk.client.csrf",ve.csrfToken),String(ve.role||"").toLowerCase()==="hub")throw new Error("This computer is assigned to the Hub role.");a(ve)}catch(U){y(U instanceof Error?U.message:String(U))}},[O]);u.useEffect(()=>{Me();const U=window.setInterval(()=>{Me()},2e3);return()=>window.clearInterval(U)},[Me]),u.useEffect(()=>{if(W.current)return;const U=Number(n?.slotNumber||0);M(U>0?String(U):"")},[n?.slotNumber]),u.useEffect(()=>{if(!F)return;const U=window.setTimeout(()=>$(null),5e3);return()=>window.clearTimeout(U)},[F]);const He=u.useCallback(async()=>{const U=Date.now();if(!(!n?.authenticated||n.connectionState==="connected"||!["waiting","reconnecting"].includes(String(n.agent?.state||""))||U-se.current<4e3)){se.current=U;try{const ve=await fetch(`${O}/api/client/reconnect`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await to(O)},body:JSON.stringify({onlyIfWaiting:!0,reason:"app-active"})});if(!ve.ok)throw new Error(`Client reconnect returned HTTP ${ve.status}.`);await Me()}catch(ve){y(ve instanceof Error?ve.message:String(ve))}}},[O,Me,n]);u.useEffect(()=>{const U=()=>{He()},ve=()=>{He()},Ae=()=>{document.visibilityState==="visible"&&He()};return window.addEventListener("online",U),window.addEventListener("focus",ve),document.addEventListener("visibilitychange",Ae),()=>{window.removeEventListener("online",U),window.removeEventListener("focus",ve),document.removeEventListener("visibilitychange",Ae)}},[He]),u.useEffect(()=>{if(!c||!n||!i?.access_token||n.authenticated)return;if(Ny(i)==="refresh-token-required"){ee().catch(ft=>{z.current=!1,y(ft instanceof Error?ft.message:String(ft))});return}let U=!1,ve,Ae=0;const Be=async()=>{if(U)return;try{const it=await we(i);if(await Me(),it)return}catch(it){y(it instanceof Error?it.message:String(it))}if(U)return;const ft=Ry[Math.min(Ae,Ry.length-1)];Ae+=1,ve=window.setTimeout(()=>{Be()},ft)};return Be(),()=>{U=!0,ve!==void 0&&window.clearTimeout(ve)}},[c,Me,ee,i,n,we]),u.useEffect(()=>{const U=new URLSearchParams(window.location.search),ve=U.get("auth_error");if(!ve)return;y(ve),U.delete("auth_error");const Ae=U.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${Ae?`?${Ae}`:""}${window.location.hash}`)},[]),u.useEffect(()=>{let U=!0;if(!window.liveDesk?.auth)return l(null),d(!0),Me(),()=>{U=!1};const ve=window.liveDesk?.auth?.onComplete?.(Be=>{Be.ok&&Be.session?Ct.auth.setSession(Be.session).catch(ft=>y(ft instanceof Error?ft.message:String(ft))):Be.error&&y(Be.error)});(async()=>{try{const Be=window.liveDesk?.auth?.getSession?await window.liveDesk.auth.getSession():await Ct.auth.getSession();if(!U)return;const ft=wx(Be);l(ft),Me()}catch(Be){U&&y(Be instanceof Error?Be.message:String(Be))}finally{U&&d(!0)}})();const{data:Ae}=Ct.auth.onAuthStateChange((Be,ft)=>{U&&(l(ft),d(!0),Me())});return()=>{U=!1,ve?.(),Ae.subscription.unsubscribe()}},[Me]),u.useEffect(()=>{if(!c||!n||Z.current||z.current||i||n.authenticated)return;const U=new URLSearchParams(window.location.search);if(!U.has("livedesk_launch"))return;Z.current=!0,U.delete("livedesk_launch");const ve=U.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${ve?`?${ve}`:""}${window.location.hash}`),fe().catch(Ae=>y(Ae instanceof Error?Ae.message:String(Ae)))},[c,i,fe,n]);const ne=async()=>{Y(!1),window.liveDesk?.auth?.persistSession?(await Ct.auth.signOut(),(await window.liveDesk.auth.persistSession(null))?.runtimeCleared===!1&&y("Signed out locally. The LiveDesk runtime could not be reached to clear its session.")):await fetch(`${O}/api/auth/session`,{method:"DELETE",headers:{"X-LiveDesk-CSRF":await to(O)}}).catch(()=>{}),l(null),await Me()};u.useEffect(()=>{if(!P)return;const U=Ae=>{Ae.target instanceof Element&&Ae.target.closest(".account-popover, .rail-account")||Y(!1)},ve=Ae=>{Ae.key==="Escape"&&Y(!1)};return window.addEventListener("pointerdown",U),window.addEventListener("keydown",ve),()=>{window.removeEventListener("pointerdown",U),window.removeEventListener("keydown",ve)}},[P]);const qe=u.useCallback((U=!0)=>{w||(L(!1),U&&window.requestAnimationFrame(()=>ye.current?.focus()))},[w]),mt=u.useCallback(()=>{w||!n?.authenticated||(ye.current=document.activeElement instanceof HTMLElement?document.activeElement:null,b(""),L(!0))},[w,n?.authenticated]);u.useEffect(()=>{if(!G)return;const U=window.requestAnimationFrame(()=>H.current?.focus()),ve=Be=>{Be.target instanceof Element&&Be.target.closest(".client-hub-switch-popover, .client-hub-switch-trigger")||qe(!1)},Ae=Be=>{Be.key==="Escape"&&qe()};return window.addEventListener("pointerdown",ve),window.addEventListener("keydown",Ae),()=>{window.cancelAnimationFrame(U),window.removeEventListener("pointerdown",ve),window.removeEventListener("keydown",Ae)}},[qe,G]);const J=async()=>{y("");try{const U=await fetch(`${O}/api/client/pin`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await to(O)},body:JSON.stringify({pin:m})}),ve=await U.json().catch(()=>({}));if(!U.ok||ve?.ok===!1)throw new Error(ve?.error||"PIN could not be accepted.");h(""),await Me()}catch(U){y(U instanceof Error?U.message:String(U))}},Ce=async()=>{L(!1),A(!0),b(""),y("");try{const U=await fetch(`${O}/api/runtime/switch-role`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await to(O)},body:JSON.stringify({role:"hub"})}),ve=await U.json().catch(()=>({}));if(!U.ok||ve?.ok===!1)throw new Error(ve?.error||`Role change failed with HTTP ${U.status}.`);b("Hub role accepted. LiveDesk is restarting this computer with the Hub Wall.");const Ae=Number(n?.runtimePid||0);await Sx({baseUrl:O,targetRole:"hub",previousRuntimePid:Ae,allowedStates:["running"]}),window.location.reload()}catch(U){y(U instanceof Error?U.message:String(U)),A(!1)}},Le=async()=>{if(T)return;const U=Number(N);if(!Number.isInteger(U)||U<1||U>999){$({kind:"error",message:"Enter a slot number from 1 to 999."});return}D(!0),$(null);try{const ve=await fetch(`${O}/api/client/slot`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await to(O)},body:JSON.stringify({slotNumber:U})}),Ae=await ve.json().catch(()=>({}));if(!ve.ok||Ae.ok===!1){if(Ae.error==="slot-taken"){const Be=Ae.conflict?.deviceName||Ae.conflict?.hostname||Ae.conflict?.deviceId||"another computer";throw new Error(`Slot ${String(U).padStart(3,"0")} is already used by ${Be}.`)}throw new Error(Ae.error||`Slot update failed with HTTP ${ve.status}.`)}W.current=!1,M(String(U)),a(Ae),$({kind:"success",message:`Slot ${String(U).padStart(3,"0")} saved. LiveDesk is reconnecting this Client.`})}catch(ve){$({kind:"error",message:ve instanceof Error?ve.message:String(ve)})}finally{D(!1),await Me()}},Fe=async()=>{if(!j){k(!0),y("");try{const U=await fetch(`${O}/api/client/video-acceleration/install`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await to(O)},body:JSON.stringify({confirm:!0})}),ve=await U.json().catch(()=>({}));if(a(ve),!U.ok||ve.videoAcceleration?.ready!==!0)throw new Error(ve.videoAcceleration?.error||ve.error||"Linux hardware video setup did not complete.")}catch(U){y(U instanceof Error?U.message:String(U))}finally{k(!1),await Me()}}},_e=!!(n?.authenticated||i),Xe=u.useMemo(()=>Uf(),[]),We=Rf("switch-to-hub",Xe),Ze=Rf("client",Xe),dt=HC(Xe);return r.jsxs("main",{className:"app-shell client-unified-shell",children:[r.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk Client tools",children:[r.jsx("div",{className:"rail-brand",title:"LiveDesk",children:r.jsx(kx,{size:25})}),r.jsx("nav",{className:"rail-tools","aria-label":"Client navigation",children:r.jsxs("div",{className:"client-main-tool-slot",children:[r.jsxs("button",{className:"rail-tool client-main-tool client-hub-tool client-hub-switch-trigger accent-blue",type:"button",onClick:mt,disabled:w||!n?.authenticated,"aria-busy":w,"aria-expanded":G,"aria-haspopup":"dialog","aria-controls":G?"client-hub-switch-popover":void 0,"aria-label":`Hub. ${We}`,"data-tooltip":G?void 0:tp("Hub","switch-to-hub",Xe),children:[r.jsx(zr,{size:19}),r.jsx("span",{children:w?"Switching…":"Hub"})]}),r.jsxs("button",{className:`rail-tool client-main-tool accent-blue ${Q==="computer"?"active":""}`,type:"button",onClick:()=>q("computer"),"aria-current":Q==="computer"?"page":void 0,"aria-label":`Client. ${Ze}`,"data-tooltip":tp("Client","client",Xe),children:[r.jsx(Ta,{size:19}),r.jsx("span",{children:"Client"})]})]})}),r.jsxs("div",{className:"rail-footer",children:[$C.map(U=>{const ve=U.icon;return r.jsxs("button",{className:`rail-tool compact ${Q===U.id?"active":""}`,type:"button",onClick:()=>q(U.id),title:U.label,children:[r.jsx(ve,{size:18}),r.jsx("span",{children:U.label})]},U.id)}),r.jsxs("button",{className:`rail-account ${_e?"signed-in":""}`,type:"button",onClick:()=>Y(U=>!U),"aria-expanded":P,"aria-haspopup":"dialog",title:_e?"Account":"Sign in",children:[_e&&ce&&!K?r.jsx("img",{src:ce,alt:le,referrerPolicy:"no-referrer",onError:()=>be(!0)},ce):_e?r.jsx("span",{className:"avatar-fallback",children:he}):r.jsx(mo,{size:18}),r.jsx("span",{children:_e?"Account":"Sign in"})]})]})]}),G&&r.jsxs("section",{id:"client-hub-switch-popover",className:"client-hub-switch-popover",role:"dialog","aria-modal":"false","aria-labelledby":"client-hub-switch-title","aria-describedby":"client-hub-switch-description client-hub-switch-restart",children:[r.jsxs("header",{className:"client-hub-switch-head",children:[r.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:r.jsx(zr,{size:19})}),r.jsx("span",{className:"client-hub-switch-eyebrow",children:dt.eyebrow}),r.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>qe(),"aria-label":dt.closeLabel,children:r.jsx(Na,{size:17})})]}),r.jsx("h2",{id:"client-hub-switch-title",children:dt.title}),r.jsx("p",{id:"client-hub-switch-description",children:dt.description}),r.jsxs("p",{id:"client-hub-switch-restart",className:"client-hub-switch-notice",children:[r.jsx(Wn,{size:16,"aria-hidden":"true"}),r.jsx("span",{children:dt.restartNotice})]}),r.jsxs("div",{className:"client-hub-switch-actions",children:[r.jsx("button",{type:"button",onClick:()=>qe(),children:dt.cancel}),r.jsxs("button",{ref:H,className:"primary",type:"button",onClick:()=>{Ce()},disabled:w||!n?.authenticated,children:[r.jsx(zr,{size:16}),dt.confirm]})]})]}),P&&r.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[r.jsxs("div",{className:"account-popover-head",children:[r.jsx("div",{className:"account-popover-avatar",children:_e&&ce&&!K?r.jsx("img",{src:ce,alt:le,referrerPolicy:"no-referrer",onError:()=>be(!0)},ce):_e?r.jsx("span",{children:he}):r.jsx(mo,{size:18})}),r.jsxs("div",{children:[r.jsx("strong",{children:_e?le:"Account"}),r.jsx("p",{children:i?.user.email||n?.userEmail||n?.userId||"Not signed in"})]})]}),r.jsxs("dl",{className:"account-popover-facts",children:[r.jsx("dt",{children:"User"}),r.jsx("dd",{children:i?.user.email||n?.userEmail||n?.userId||"Not signed in"}),r.jsx("dt",{children:"Runtime"}),r.jsx("dd",{children:n?"Local app ready":"Checking local app"}),r.jsx("dt",{children:"Session"}),r.jsx("dd",{children:n?.auth?.persisted?"Saved on this computer":_e?"Active for this run":"Not saved"}),r.jsx("dt",{children:"Role"}),r.jsx("dd",{children:"Client"})]}),_e?r.jsxs("button",{className:"account-popover-action",onClick:()=>{ne()},type:"button",children:[r.jsx(cx,{size:16}),"Logout"]}):r.jsxs("button",{className:"account-popover-action primary",onClick:()=>{Y(!1),fe()},type:"button",children:[r.jsx(mo,{size:16}),"Sign in with Google"]})]}),r.jsxs("section",{className:"desk-stage client-unified-stage",children:[r.jsx("header",{className:"topbar",children:r.jsxs("div",{className:"brand",children:[r.jsx("span",{className:"brand-mark",children:r.jsx(ho,{size:18})}),r.jsxs("div",{children:[r.jsx("h1",{children:"LiveDesk"}),r.jsx("p",{children:"Client workspace"})]})]})}),Q==="support"?r.jsx("section",{className:"client-unified-page",children:r.jsx(xx,{session:i,currentProductKey:"livedesk",appVersion:n?.appVersion||"",onSignIn:()=>{fe()}})}):Q!=="computer"?r.jsx("section",{className:"client-unified-page",children:r.jsx(WC,{page:Q,status:n})}):r.jsx(YC,{session:i,status:n,pin:m,error:g,roleChangeMessage:x,videoAccelerationBusy:j,slotInput:N,slotBusy:T,onSignIn:()=>{fe()},onPinChange:U=>h(U.replace(/\D/g,"").slice(0,6)),onSubmitPin:()=>{J()},onSlotInputChange:U=>{W.current=!0,M(U.replace(/\D/g,"").slice(0,3))},onSaveSlot:()=>{Le()},onEnableVideoAcceleration:()=>{Fe()}})]}),F&&r.jsxs("div",{className:`client-side-toast ${F.kind}`,role:F.kind==="error"?"alert":"status",children:[F.kind==="error"?r.jsx(ux,{size:18}):r.jsx(Zn,{size:18}),r.jsx("span",{children:F.message}),r.jsx("button",{type:"button",onClick:()=>$(null),"aria-label":"Dismiss notification",children:r.jsx(Na,{size:16})})]})]})}function pl(n,a,i){if(i<0||a<0||a+i>n.length)throw new Error("Invalid LZO1X block: input overrun.")}function Sh(n,a,i){let l=0;for(;pl(n,a.inputIndex,1),n[a.inputIndex]===0;)l+=1,a.inputIndex+=1;const c=l*255+i+n[a.inputIndex];return a.inputIndex+=1,c}function Jd(n,a,i,l){if(pl(n,a.inputIndex,l),a.outputIndex+l>i.length)throw new Error("Invalid LZO1X block: output overrun.");i.set(n.subarray(a.inputIndex,a.inputIndex+l),a.outputIndex),a.inputIndex+=l,a.outputIndex+=l}function QC(n,a,i,l){const c=a-i;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(i,i+d),a);d<l;){const m=Math.min(d,l-d);n.copyWithin(a+d,a,a+m),d+=m}return a+l}function Tx(n,a){if(!(n instanceof Uint8Array)||n.length<3||a<0)throw new Error("Invalid LZO1X block.");const i=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,Jd(n,l,i,m),c=4}else n[l.inputIndex]>=18&&(c=n[l.inputIndex]-17,l.inputIndex+=1,Jd(n,l,i,c));for(;;){pl(n,l.inputIndex,1);const m=n[l.inputIndex];l.inputIndex+=1;let h,g;if((m&192)!==0)pl(n,l.inputIndex,1),g=l.outputIndex-((n[l.inputIndex]<<3)+(m>>2&7)+1),l.inputIndex+=1,d=(m>>5)+1,h=m&3;else if((m&32)!==0){d=(m&31)+2,d===2&&(d+=Sh(n,l,31)),pl(n,l.inputIndex,2);const y=n[l.inputIndex]|n[l.inputIndex+1]<<8;l.inputIndex+=2,g=l.outputIndex-((y>>2)+1),h=y&3}else if((m&16)!==0){d=(m&7)+2,d===2&&(d+=Sh(n,l,7)),pl(n,l.inputIndex,2);const y=n[l.inputIndex]|n[l.inputIndex+1]<<8;if(l.inputIndex+=2,g=l.outputIndex-(((m&8)<<11)+(y>>2)),h=y&3,g===l.outputIndex)break;g-=16384}else if(c===0){let y=m+3;y===3&&(y+=Sh(n,l,15)),Jd(n,l,i,y),c=4;continue}else c!==4?(pl(n,l.inputIndex,1),h=m&3,g=l.outputIndex-((m>>2)+(n[l.inputIndex]<<2)+1),l.inputIndex+=1,d=2):(pl(n,l.inputIndex,1),h=m&3,g=l.outputIndex-((m>>2)+(n[l.inputIndex]<<2)+2049),l.inputIndex+=1,d=3);if(g<0||l.outputIndex+d+h>i.length)throw new Error("Invalid LZO1X block: lookbehind overrun.");l.outputIndex=QC(i,l.outputIndex,g,d),c=h,Jd(n,l,i,h)}if(d!==3||l.inputIndex!==n.length||l.outputIndex!==i.length)throw new Error("Invalid LZO1X block: incomplete output.");return i}const Dy=16,Ly=8,XC=24*1024*1024,Rx=new Uint8Array(new Uint32Array([16909060]).buffer)[0]===4,ap=new Uint32Array(65536);for(let n=0;n<ap.length;n+=1){const a=Math.round((n>>11&31)*255/31),i=Math.round((n>>5&63)*255/63),l=Math.round((n&31)*255/31);ap[n]=Rx?(a|i<<8|l<<16|4278190080)>>>0:(a<<24|i<<16|l<<8|255)>>>0}function hl(n,a){return n[a]|n[a+1]<<8}function ZC(n,a){const i=Number(a);if(!Number.isSafeInteger(i)||i<Dy||i>XC)throw new Error(`Invalid Mode 5 packet length: ${a}.`);const l=n instanceof Uint8Array?n:new Uint8Array(n),c=Tx(l,i);if(c[0]!==76||c[1]!==68||c[2]!==53||c[3]!==68)throw new Error("Invalid Mode 5 packet magic.");if(c[4]!==1)throw new Error(`Unsupported Mode 5 packet version: ${c[4]}.`);const d=(c[5]&1)!==0,m=hl(c,6),h=hl(c,8),g=hl(c,10),y=hl(c,12);if(m<=0||h<=0||m>3840||h>2160)throw new Error(`Invalid Mode 5 frame size: ${m}x${h}.`);if(g<=0||g>256||y>8192)throw new Error(`Invalid Mode 5 tile header: ${g}/${y}.`);const x=[];let b=Dy;for(let w=0;w<y;w+=1){if(b+Ly>c.length)throw new Error("Mode 5 tile header is truncated.");const A=hl(c,b),j=hl(c,b+2),k=hl(c,b+4),N=hl(c,b+6);b+=Ly;const M=k*N*2;if(k<=0||N<=0||k>g||N>g||A+k>m||j+N>h||b+M>c.length)throw new Error(`Invalid Mode 5 tile ${w}.`);x.push({x:A,y:j,width:k,height:N,pixels:c.subarray(b,b+M)}),b+=M}if(b!==c.length)throw new Error(`Mode 5 packet has ${c.length-b} trailing bytes.`);return{keyFrame:d,width:m,height:h,tileSize:g,tiles:x}}function JC(n,a,i,l){if(!(n instanceof Uint8ClampedArray)||n.length!==a*i*4||l.width!==a||l.height!==i)throw new Error("Mode 5 canvas state does not match the packet dimensions.");let c=a,d=i,m=0,h=0;const g=new Uint32Array(n.buffer,n.byteOffset,n.byteLength>>>2);for(const y of l.tiles){const x=Rx&&(y.pixels.byteOffset&1)===0?new Uint16Array(y.pixels.buffer,y.pixels.byteOffset,y.pixels.byteLength>>>1):null;let b=0;for(let w=0;w<y.height;w+=1){let A=(y.y+w)*a+y.x;for(let j=0;j<y.width;j+=1){const k=b<<1,N=x?x[b]:y.pixels[k]|y.pixels[k+1]<<8;g[A]=ap[N],b+=1,A+=1}}c=Math.min(c,y.x),d=Math.min(d,y.y),m=Math.max(m,y.x+y.width),h=Math.max(h,y.y+y.height)}return l.tiles.length>0?{x:c,y:d,width:m-c,height:h-d}:null}const Ha=new WeakMap,Uu=new WeakMap,sp=new WeakMap,qu=new Set,fo=new Set,Cc=new WeakMap,vc=new Set,Gu=new WeakMap,rp=new WeakMap,ip=new WeakMap,Ef=new WeakMap,Ex=4,e1=2,t1=2,n1=2,a1=18,s1=40,r1=0,i1=250,Dx=80,_y=5,l1=150,o1=1200,c1=18,u1=.65,d1=2e3,f1=500,Mp=250,m1=globalThis.LIVEDESK_ENABLE_CANVAS_VISUAL_SAMPLING===!0;let Lx=1,_x=0,Ix=0,zx=0,Ox,Hx,Ei={h264DecodeAcceleration:"prefer-hardware"};function h1(n){n.h264DecodeAcceleration&&(Ei={...Ei,h264DecodeAcceleration:n.h264DecodeAcceleration})}function lp(n,a=Ei.h264DecodeAcceleration){const i=Cc.get(n);return i?.requested===a?(i.actual!=="prefer-hardware"&&(fo.delete(n),vc.add(n)),i.actual):(i&&(Cc.delete(n),vc.delete(n)),a!=="prefer-hardware"?(fo.delete(n),vc.delete(n),a):(fo.has(n)||fo.add(n),"prefer-hardware"))}function Np(n,a,i){if(a!=="prefer-hardware")return!1;const l=Cc.get(n),c=Ha.get(n),d=Date.now();return Gu.has(n)||Gu.set(n,Lx++),Cc.set(n,{requested:a,actual:"prefer-software",reason:i,failedAt:d,failureCount:(l?.requested===a?l.failureCount:0)+1,codec:c?.codec||l?.codec||"",latencyMode:c?.latencyMode||l?.latencyMode||"smooth",inputCount:c?.inputSerial??l?.inputCount??0,outputCount:c?.outputSerial??l?.outputCount??0,lastInputAt:c?.lastInputAt??l?.lastInputAt??0,lastOutputAt:c?.lastOutputAt??l?.lastOutputAt??0,lastPaintAt:c?.lastPaintAt??l?.lastPaintAt??0}),fo.delete(n),vc.add(n),zx+=1,Ox=i,Hx=d,!0}function p1(n,a,i,l=64){try{let c=rp.get(n);c||(c={canvas:document.createElement("canvas"),lastHash:"",initialized:!1},rp.set(n,c));const d=Math.max(8,Math.min(64,Math.round(l))),m=Math.max(1,Math.round(d*Math.max(1,i)/Math.max(1,a)));(c.canvas.width!==d||c.canvas.height!==m)&&(c.canvas.width=d,c.canvas.height=m);const h=c.canvas.getContext("2d",{willReadFrequently:!0});if(!h)return{visualHash:"",visualChanged:!0};h.drawImage(n,0,0,Math.max(1,a),Math.max(1,i),0,0,d,m);const g=h.getImageData(0,0,d,m).data;let y=2166136261;for(let w=0;w<g.length;w+=4)y^=g[w],y=Math.imul(y,16777619),y^=g[w+1],y=Math.imul(y,16777619),y^=g[w+2],y=Math.imul(y,16777619);const x=(y>>>0).toString(16).padStart(8,"0"),b=!c.initialized||x!==c.lastHash;return c.initialized=!0,c.lastHash=x,{visualHash:x,visualChanged:b}}catch{return{visualHash:"",visualChanged:!0}}}function op(n,a,i,l=Mp,c=64,d){if(!m1&&d)return Fx(n,d);let m=ip.get(n);m||(m={lastHash:"",initialized:!1,lastCanvasSampleAt:0},ip.set(n,m));const h=performance.now();if(m.initialized&&l>0&&h-m.lastCanvasSampleAt<l)return{visualHash:m.lastHash,visualChanged:!1};const g=p1(n,a,i,c);return m.initialized=!0,m.lastHash=g.visualHash,m.lastCanvasSampleAt=h,g}function Fx(n,a){let i=Ef.get(n);i||(i={lastHash:"",initialized:!1},Ef.set(n,i));const l=String(a.contentHash||""),c=!i.initialized||!l||l!==i.lastHash;return i.initialized=!0,i.lastHash=l,{visualHash:l,visualChanged:c}}function $x(n,a){const i=sp.get(n);if(i)return i;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 sp.set(n,d),d}return null}function g1(n){const a=String(n.frameMode||n.mode||"").toLowerCase(),i=String(n.compression||"").toLowerCase(),l=String(n.mimeType||"").toLowerCase();return a==="mode2-lzo"||i==="lzo1x"||l==="application/vnd.livedesk.lzo-rgb565"||a==="mode2-lz4"||String(n.compression||"").toLowerCase()==="lz4"||l==="application/vnd.livedesk.lz4-raw"}function v1(n){return String(n.frameMode||n.mode||"").toLowerCase()==="mode3-h264-hw"||String(n.codec||"").toLowerCase()==="h264"||String(n.mimeType||"").toLowerCase()==="video/h264"}function y1(n){const a=String(n.frameMode||n.mode||"").toLowerCase(),i=String(n.mimeType||"").toLowerCase();return a==="mode5-lzo-delta"||i==="application/vnd.livedesk.lzo-rgb565-delta"}function Iy(n,a,i){let l=i,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 b1(n,a){const i=new Uint8Array(a);let l=0,c=0;for(;l<n.length;){const d=n[l];l+=1;const m=Iy(n,l,d>>4);l=m.cursor;const h=m.length;if(l+h>n.length||c+h>i.length)throw new Error("Invalid LZ4 block: literal overrun.");if(i.set(n.subarray(l,l+h),c),l+=h,c+=h,l>=n.length)break;if(l+2>n.length)throw new Error("Invalid LZ4 block: missing offset.");const g=n[l]|n[l+1]<<8;if(l+=2,g<=0||g>c)throw new Error("Invalid LZ4 block: bad match offset.");const y=Iy(n,l,d&15);l=y.cursor;const x=y.length+4;if(c+x>i.length)throw new Error("Invalid LZ4 block: match overrun.");let b=c-g;for(let w=0;w<x;w+=1)i[c]=i[b],c+=1,b+=1}if(c!==i.length)throw new Error("Invalid LZ4 block: incomplete output.");return i}function x1(n){const a=Math.max(1,Math.floor(n.width||0)),i=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 x=Math.max(1,Math.floor(n.bytesPerPixel||2)),b=a*i*2,w=Math.floor(n.uncompressedByteLength||b);if(x!==2||w!==b)throw new Error(`Invalid mode2 RGB565 frame size: ${w} for ${a}x${i}.`);if(c&&c!=="rgb565le"&&c!=="rgb565")throw new Error(`Unsupported mode2 pixel format: ${c}`);const A=Tx(n.payload,b),j=new Uint8ClampedArray(a*i*4);for(let k=0,N=0;k<A.length;k+=2,N+=4){const M=A[k]|A[k+1]<<8,T=M>>11&31,D=M>>5&63,F=M&31;j[N]=T<<3|T>>2,j[N+1]=D<<2|D>>4,j[N+2]=F<<3|F>>2,j[N+3]=255}return new ImageData(j,a,i)}const m=Math.max(1,Math.floor(n.bytesPerPixel||4)),h=Math.max(a*i*m,Math.floor(n.uncompressedByteLength||0)),g=b1(n.payload,h);if(m!==4)throw new Error(`Unsupported mode2 pixel size: ${m}`);const y=new Uint8ClampedArray(a*i*4);if(c==="rgba32"||c==="rgba")y.set(g.subarray(0,y.length));else for(let x=0,b=0;b<y.length;x+=4,b+=4)y[b]=g[x+2],y[b+1]=g[x+1],y[b+2]=g[x],y[b+3]=g[x+3];return new ImageData(y,a,i)}function zy(n,a="smooth",i=Ei.h264DecodeAcceleration){const l=window.VideoDecoder;if(!l||!window.EncodedVideoChunk)throw new Error("WebCodecs H.264 decode is not supported in this browser.");const c=Ha.get(n);if(c&&c.decoder.state!=="closed"&&c.latencyMode===a)return c;c&&Ps(n);let d;const m=new l({output:h=>{if(Ha.get(n)!==d){h.close();return}const g=Number(h.timestamp||0);d.outputSerial+=1;let y=d.pendingFrames.get(g);if(y)d.pendingFrames.delete(g);else if(d.pendingFrames.size>0){const k=d.pendingFrames.entries().next().value;k&&(d.pendingFrames.delete(k[0]),y=k[1],d.timestampFallbacks+=1)}const x=h.displayWidth||h.codedWidth||n.width||960,b=h.displayHeight||h.codedHeight||n.height||540,w=Number(y?.frame.durationUs||0),A=Number(h.duration||0),j=Math.max(16,Math.min(250,(w>0?w:A||83333)/1e3));for(d.targetPaintIntervalMs=j,d.decodedFrames.push({videoFrame:h,pending:y,decodedAt:performance.now(),width:x,height:b,durationMs:j}),d.lastOutputAt=performance.now();d.decodedFrames.length>Tp(d);)Df(d,d.decodedFrames.shift());Px(d),d.renderTimer!==null&&d.renderScheduledAt>0&&performance.now()-d.renderScheduledAt>f1&&(typeof document>"u"||document.visibilityState==="visible")&&(window.cancelAnimationFrame(d.renderTimer),d.renderTimer=null,d.renderScheduledAt=0),d.renderTimer!==null&&d.decodedFrames.length>=Ex&&(window.cancelAnimationFrame(d.renderTimer),d.renderTimer=null,d.renderScheduledAt=0),Lf(n,d)},error:()=>{Ha.get(n)===d&&(Np(n,d.requestedAcceleration,"decoder-error"),Ps(n))}});return _x+=1,Gu.has(n)||Gu.set(n,Lx++),d={decoder:m,configured:!1,configKey:"",codec:"",requestedAcceleration:i,hardwareAcceleration:lp(n,i),latencyMode:a,keyFrameSeen:!1,droppedForLatency:0,pendingFrames:new Map,decodedFrames:[],renderTimer:null,renderScheduledAt:0,flushTimer:null,flushInFlight:!1,flushCount:0,timestampFallbacks:0,inputSerial:0,outputSerial:0,lastFlushInputSerial:0,lastOutputAt:0,lastPaintAt:0,lastInputAt:0,interactiveBufferPrimed:!1,interactiveBufferStartedAt:0,interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,lastInputFrameSeq:void 0,targetPaintIntervalMs:1e3/12,nextChunkTimestampUs:0,healthSampleStartedAt:performance.now(),healthInputSerial:0,healthOutputSerial:0},Ha.set(n,d),qu.add(n),d}function Bx(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 Df(n,a){a&&(a.videoFrame.close(),n.droppedForLatency+=1)}function Tp(n){return n.latencyMode==="interactive"?t1:String(n.decodedFrames[0]?.pending?.frame.frameMode||n.decodedFrames[0]?.pending?.frame.mode||"").toLowerCase()==="mode4-h264-atlas"?e1:Ex}function Px(n,a=performance.now()){const i=Tp(n);for(;n.decodedFrames.length>i;)Df(n,n.decodedFrames.shift());const l=n.latencyMode==="interactive"?Dx:i1;let c=n.decodedFrames[0];for(;n.decodedFrames.length>1&&c?.pending&&a-c.pending.queuedAt>l;)Df(n,n.decodedFrames.shift()),c=n.decodedFrames[0]}function Ux(n,a){if(a.hardwareAcceleration!=="prefer-hardware"||a.latencyMode==="interactive"||a.flushTimer!==null||a.flushInFlight)return;const i=l1;a.flushTimer=window.setTimeout(async()=>{a.flushTimer=null;const l=performance.now();for(const[d,m]of a.pendingFrames.entries())l-m.queuedAt>d1&&a.pendingFrames.delete(d);if(Ha.get(n)!==a||a.decoder.state!=="configured"||a.pendingFrames.size===0||a.inputSerial<=a.lastFlushInputSerial||a.lastOutputAt>0&&l-a.lastOutputAt<i)return;const c=a.inputSerial;a.flushInFlight=!0,a.flushCount+=1,a.keyFrameSeen=!1;try{await a.decoder.flush(),a.lastFlushInputSerial=Math.max(a.lastFlushInputSerial,c)}catch{Ha.get(n)===a&&kf(a)}finally{a.flushInFlight=!1,Ha.get(n)===a&&a.inputSerial>c&&a.pendingFrames.size>0&&performance.now()-a.lastOutputAt>=i&&Ux(n,a)}},i)}function Oy(n,a,i){const l=performance.now();try{(n.width!==i.width||n.height!==i.height)&&(n.width=i.width,n.height=i.height);const c=$x(n,a.latencyMode);if(c?.context.drawImage(i.videoFrame,0,0,i.width,i.height),i.pending){const d=performance.now(),h=a.latencyMode==="interactive"?Fx(n,i.pending.frame):op(n,i.width,i.height,Mp,64,i.pending.frame);try{a.onPaint?.(i.pending.frame,{deviceId:i.pending.frame.deviceId,frameSeq:i.pending.frame.frameSeq,mode:i.pending.frame.frameMode||i.pending.frame.mode||i.pending.frame.codec||i.pending.frame.mimeType,width:i.width,height:i.height,byteLength:i.pending.frame.byteLength,queuedForMs:Math.max(0,l-i.pending.queuedAt),decodedForMs:Math.max(0,i.decodedAt-i.pending.queuedAt),scheduledForMs:Math.max(0,l-i.decodedAt),drawMs:Math.max(0,d-l),queueSize:i.pending.queueSize,renderQueueSize:a.decodedFrames.length,droppedForLatency:a.droppedForLatency,h264DecodeAcceleration:a.hardwareAcceleration,decoderLabel:a.hardwareAcceleration,decoderFlushCount:a.flushCount,decoderTimestampFallbacks:a.timestampFallbacks,decoderInputCount:a.inputSerial,decoderOutputCount:a.outputSerial,targetPaintIntervalMs:a.targetPaintIntervalMs,canvasPresentation:c?.presentation||"sync",interactiveBufferWaitCount:a.interactiveBufferWaitCount,interactiveBufferWaitMs:a.interactiveBufferWaitMs,interactiveQueueDrainCount:a.interactiveQueueDrainCount,visualHash:h.visualHash,visualChanged:h.visualChanged,paintedAt:d})}catch{}}a.lastPaintAt=performance.now()}finally{i.videoFrame.close()}}function Lf(n,a){if(a.renderTimer!==null||a.decodedFrames.length===0)return;const i=Math.max(16,Math.min(250,a.targetPaintIntervalMs||1e3/12)),l=()=>{if(a.renderTimer=null,a.renderScheduledAt=0,a.decodedFrames.length===0)return;const c=performance.now();if(Px(a,c),a.decodedFrames.length===0)return;if(a.latencyMode==="interactive"){const g=a.targetPaintIntervalMs<=s1,y=a.targetPaintIntervalMs<=20;if(y&&!a.interactiveBufferPrimed){a.interactiveBufferStartedAt<=0&&(a.interactiveBufferStartedAt=c,a.interactiveBufferWaitCount+=1);const k=a.decodedFrames.length>=n1,N=c-a.interactiveBufferStartedAt>=a1;if(!k&&!N){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}a.interactiveBufferWaitMs+=Math.max(0,c-a.interactiveBufferStartedAt),a.interactiveBufferPrimed=!0}else y||(a.interactiveBufferPrimed=!0);const x=a.decodedFrames[0],b=x?.pending?Math.max(0,c-x.pending.queuedAt):0,w=a.lastPaintAt>0?a.lastPaintAt+i:c;if(!(!g||c+_y>=w||b>=Dx)){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}const j=a.decodedFrames.shift();if(j)try{Oy(n,a,j)}catch{}a.decodedFrames.length===0&&(a.interactiveQueueDrainCount+=1,a.interactiveBufferPrimed=!1,a.interactiveBufferStartedAt=0),Lf(n,a);return}const d=a.lastPaintAt>0?a.lastPaintAt+i:c+r1;if(!(c+_y>=d||a.decodedFrames.length>=Math.max(1,Tp(a)-1))){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}const h=a.decodedFrames.shift();if(h)try{Oy(n,a,h)}catch{}Lf(n,a)};a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l)}function qx(n,a){if(Ha.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;)Df(a,a.decodedFrames.shift());return a.lastPaintAt=0,a.interactiveBufferPrimed=!1,a.interactiveBufferStartedAt=0,Lf(n,a),!0}function Ch(){if(!(typeof document>"u"||document.visibilityState!=="visible"))for(const n of qu){const a=Ha.get(n);if(!a||a.decoder.state==="closed"){qu.delete(n);continue}qx(n,a)}}typeof document<"u"&&typeof window<"u"&&(document.addEventListener("visibilitychange",Ch),window.addEventListener("focus",Ch),window.addEventListener("pageshow",Ch));function Ps(n){fo.delete(n),qu.delete(n),Ef.delete(n);const a=Ha.get(n);if(a){Ha.delete(n),Ix+=1;try{Bx(a),a.decoder.state!=="closed"&&a.decoder.close()}catch{}}}function dc(n){n&&(Cc.delete(n),vc.delete(n),sp.delete(n),ip.delete(n),rp.delete(n),Ef.delete(n),Uu.delete(n),Ps(n))}function w1(n,a){const i=Ha.get(n),l=Cc.get(n);if(!i&&!l)return null;const c=d=>d>0?Math.max(0,a-d):void 0;return{canvasId:Gu.get(n)||0,canvasWidth:Math.max(0,Number(n.width||0)),canvasHeight:Math.max(0,Number(n.height||0)),decoderState:i?.decoder.state||"fallback-pending",configured:i?.configured||!1,codec:i?.codec||l?.codec||"",requestedAcceleration:i?.requestedAcceleration||l?.requested||Ei.h264DecodeAcceleration,configuredAcceleration:i?.hardwareAcceleration||l?.actual||Ei.h264DecodeAcceleration,latencyMode:i?.latencyMode||l?.latencyMode||"smooth",decodeQueueSize:Math.max(0,Number(i?.decoder.decodeQueueSize||0)),pendingFrameCount:i?.pendingFrames.size||0,renderQueueSize:i?.decodedFrames.length||0,inputCount:i?.inputSerial??l?.inputCount??0,outputCount:i?.outputSerial??l?.outputCount??0,lastInputAgeMs:c(i?.lastInputAt??l?.lastInputAt??0),lastOutputAgeMs:c(i?.lastOutputAt??l?.lastOutputAt??0),lastPaintAgeMs:c(i?.lastPaintAt??l?.lastPaintAt??0),softwareFallbackReason:l?.reason,softwareFallbackAt:l?.failedAt,softwareFallbackCount:l?.failureCount||0}}function Hy(n){const a=performance.now(),l=(n?[n]:[...new Set([...qu,...vc])]).map(c=>w1(c,a)).filter(c=>c!==null);return{capturedAt:Date.now(),hardwareRequestPolicy:"all-active",activeDecoderCount:l.filter(c=>c.decoderState!=="fallback-pending").length,hardwareLeaseCount:fo.size,activeSoftwareFallbackCount:l.filter(c=>c.configuredAcceleration==="prefer-software"&&c.requestedAcceleration==="prefer-hardware").length,decoderCreateCount:_x,decoderCloseCount:Ix,softwareFallbackEventCount:zx,lastSoftwareFallbackReason:Ox,lastSoftwareFallbackAt:Hx,canvases:l}}function kf(n,a=1){try{n.decoder.state!=="closed"&&n.decoder.reset()}catch{}n.configured=!1,n.configKey="",n.keyFrameSeen=!1,n.pendingFrames.clear(),Bx(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 S1(n,a,i,l,c){n.decoder.configure(a),n.configured=!0,n.configKey=i,n.codec=a.codec,n.requestedAcceleration=c,n.hardwareAcceleration=l,n.keyFrameSeen=!1,n.nextChunkTimestampUs=0,n.lastInputFrameSeq=void 0}function C1(n,a){if(a.latencyMode!=="interactive"||a.hardwareAcceleration!=="prefer-hardware")return!1;const i=performance.now();if(i-a.healthSampleStartedAt<o1)return!1;const l=a.inputSerial-a.healthInputSerial,c=a.outputSerial-a.healthOutputSerial;return a.healthSampleStartedAt=i,a.healthInputSerial=a.inputSerial,a.healthOutputSerial=a.outputSerial,l<c1||c/Math.max(1,l)>=u1?!1:(Np(n,a.requestedAcceleration,"interactive-health"),Ps(n),!0)}function ju(n,a=1){if(!n)return!1;const i=Ha.get(n);return i?(i.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(a))),Ps(n),!0):!1}function k1(n){if(!n)return!1;const a=Ha.get(n);return a?qx(n,a):!1}function j1(n,a,i,l="interactive"){Ps(n);const c=performance.now(),d=ZC(a.payload,a.uncompressedByteLength||0),m=String(a.streamId||"mode5");let h=Uu.get(n);if(!h||h.streamId!==m||h.width!==d.width||h.height!==d.height){const k=new Uint8ClampedArray(d.width*d.height*4);for(let N=3;N<k.length;N+=4)k[N]=255;h={streamId:m,width:d.width,height:d.height,rgba:k,imageData:new ImageData(k,d.width,d.height),keyFrameSeen:!1,inputSerial:0,outputSerial:0},Uu.set(n,h)}if(!h)throw new Error("Mode 5 canvas state could not be initialized.");h.inputSerial+=1;const y=Number(a.streamFrameSeq||0);if(y>0&&(h.lastStreamFrameSeq=y),!d.keyFrame&&!h.keyFrameSeen)return;d.keyFrame&&(h.keyFrameSeen=!0);const x=JC(h.rgba,h.width,h.height,d),b=performance.now();(n.width!==h.width||n.height!==h.height)&&(n.width=h.width,n.height=h.height);const w=$x(n,l),A=performance.now();x&&w?.context.putImageData(h.imageData,0,0,x.x,x.y,x.width,x.height);const j=performance.now();h.outputSerial+=1,i?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.mimeType,width:h.width,height:h.height,byteLength:a.byteLength,queuedForMs:Math.max(0,j-c),decodedForMs:Math.max(0,b-c),scheduledForMs:0,drawMs:Math.max(0,j-A),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:"prefer-software",decoderLabel:"lzo-rgb565-delta",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:h.inputSerial,decoderOutputCount:h.outputSerial,targetPaintIntervalMs:Math.max(1,Number(a.durationUs||0)/1e3||1e3/30),canvasPresentation:w?.presentation||"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:String(a.contentHash||""),visualChanged:Number(a.deltaVisualTileCount||0)>0,paintedAt:j})}const kh=[{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 Fy(n,a){for(let i=Math.max(0,a);i+3<n.length;i+=1)if(!(n[i]!==0||n[i+1]!==0)){if(n[i+2]===1)return{index:i,length:3};if(n[i+2]===0&&n[i+3]===1)return{index:i,length:4}}return null}function A1(n){let a=0;for(;a<n.length;){const i=Fy(n,a);if(!i)break;const l=i.index+i.length,c=Fy(n,l),d=c?.index??n.length;if(l<d&&(n[l]&31)===7){const m=[];let h=0;for(let g=l+1;g<d;g+=1){const y=n[g];if(h>=2&&y===3){h=0;continue}m.push(y),h=y===0?h+1:0}if(m.length>=3)return`avc1.${m.slice(0,3).map(g=>g.toString(16).toUpperCase().padStart(2,"0")).join("")}`}a=c?c.index:n.length}return""}function M1(n,a,i,l,c=""){const d=Math.ceil(n/16)*Math.ceil(a/16),m=i>0?1e6/i:30,h=d*m,g=kh.find(y=>d<=y.maxFrameSize&&h<=y.maxMacroblocksPerSecond)||kh[kh.length-1];return A1(l)||c||`avc1.42E0${g.code.toString(16).toUpperCase().padStart(2,"0")}`}function Gx(n,a,i,l,c="smooth",d=!0){Uu.delete(n);const m=String(a.h264Format||"").toLowerCase()==="avc"?"avc":"annexb",h=Math.max(1,Math.floor(a.width||960)),g=Math.max(1,Math.floor(a.height||540)),y=Math.max(1,Math.floor(a.durationUs||1e6/12)),x=l||Ei.h264DecodeAcceleration;let b=zy(n,c,x);const w=M1(h,g,y,a.payload,b.codec),A=a.isKeyFrame===!0||String(a.chunkType||"").toLowerCase()==="key";let j=lp(n,x),k="";const N=()=>{k=[a.streamId||"",a.commandId||"",h,g,w,m,x,j,c].join("|")};N(),b.onPaint=i,b.configured&&b.decoder.state!=="configured"&&(b.configured=!1,b.configKey=""),b.configured&&b.configKey!==k&&(Ps(n),b=zy(n,c,x),b.onPaint=i,j=lp(n,x),N());const M=()=>({codec:w,codedWidth:h,codedHeight:g,hardwareAcceleration:j,optimizeForLatency:!0,avc:{format:m}}),T=Q=>b.hardwareAcceleration!=="prefer-hardware"||!Np(n,b.requestedAcceleration,Q)?!1:(Ps(n),d&&A&&Gx(n,a,i,x,c,!1),!0),D=()=>{try{return S1(b,M(),k,j,x),!0}catch(Q){if(T("configure-error"))return!1;throw Ps(n),Q}};if(!b.configured&&!D())return;const F=Number(a.streamFrameSeq||0);if(F>0&&b.lastInputFrameSeq!==void 0&&(F<=b.lastInputFrameSeq&&(!A||F===b.lastInputFrameSeq||(kf(b,b.lastInputFrameSeq-F+1),!D()))||F>b.lastInputFrameSeq+1&&(kf(b,F-b.lastInputFrameSeq-1),!A||!D()))||(F>0&&(b.lastInputFrameSeq=F),!A&&!b.keyFrameSeen))return;A&&(b.keyFrameSeen=!0);const $=Number(b.decoder.decodeQueueSize||0);if($>8){if(b.latencyMode==="interactive"&&b.hardwareAcceleration==="prefer-hardware"){T("decode-queue-overflow");return}if(kf(b),!A||!D())return;b.keyFrameSeen=!0}const G=b.nextChunkTimestampUs;b.nextChunkTimestampUs+=y,b.pendingFrames.set(G,{frame:a,queuedAt:performance.now(),queueSize:$}),b.inputSerial+=1,b.lastInputAt=performance.now();const L=new EncodedVideoChunk({type:A?"key":"delta",timestamp:G,duration:y,data:a.payload});try{b.decoder.decode(L)}catch(Q){if(T("decode-error"))return;throw Ps(n),Q}Ux(n,b),C1(n,b)}async function jh(n,a,i,l,c,d="smooth"){if(y1(a)){i()||j1(n,a,l,d);return}if(v1(a)){i()||Gx(n,a,l,c,d);return}if(Uu.delete(n),g1(a)){Ps(n);const b=x1(a);if(i())return;(n.width!==b.width||n.height!==b.height)&&(n.width=b.width,n.height=b.height);const w=n.getContext("2d"),A=performance.now();w?.putImageData(b,0,0);const j=performance.now(),k=op(n,b.width,b.height,Mp,64,a);l?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.codec||a.mimeType,width:b.width,height:b.height,byteLength:a.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,j-A),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:Ei.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:j});return}Ps(n);const m=new Blob([a.payload],{type:a.mimeType}),h=await createImageBitmap(m);if(i()){h.close();return}const g=a.width||h.width||960,y=a.height||h.height||540;(n.width!==g||n.height!==y)&&(n.width=g,n.height=y);const x=n.getContext("2d");if(x){const b=performance.now();x.clearRect(0,0,g,y),x.drawImage(h,0,0,g,y);const w=performance.now(),A=op(n,g,y);l?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.codec||a.mimeType,width:g,height:y,byteLength:a.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,w-b),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:Ei.h264DecodeAcceleration,decoderLabel:"image",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:A.visualHash,visualChanged:A.visualChanged,paintedAt:w})}h.close()}const $y="livedesk_remote_host_targets",N1="livedesk_entitlements",Rp=new TextDecoder;function T1(n){const i=(Array.isArray(n)?n:[n||An]).map(l=>wl(l||An));return[...new Set(i.filter(Boolean))]}function R1(){const[n,a]=u.useState(null),[i,l]=u.useState(!0);return u.useEffect(()=>{let c=!0;const d=window.liveDesk?.auth?.onComplete?.(h=>{h.ok&&h.session&&Ct.auth.setSession(h.session)});(window.liveDesk?.auth?.getSession?.()||Ct.auth.getSession()).then(h=>{c&&(a(wx(h)),l(!1))});const{data:{subscription:m}}=Ct.auth.onAuthStateChange((h,g)=>{a(g),l(!1),window.liveDesk?.auth?.persistSession?.(g)});return()=>{c=!1,d?.(),m.unsubscribe()}},[]),{session:n,loading:i}}function E1(n,a=!0){const[i,l]=u.useState(null),[c,d]=u.useState([]),[m,h]=u.useState(""),[g,y]=u.useState(""),[x,b]=u.useState(0),w=u.useRef(new Map),A=Array.isArray(n)?n.join(`
12
- `):String(n||""),j=u.useMemo(()=>T1(n),[A]),k=u.useMemo(()=>j.find(T=>Ou(T)==="loopback")||j[0]||An,[j]),N=u.useCallback(async()=>{if(!a){l(null),d([]),y(""),h("");return}let T=null;const D=Date.now(),F=j.filter($=>(w.current.get($)||0)<=D);if(F.length===0)throw new Error("No LiveDesk Hub endpoint is reachable. Retrying shortly.");for(const $ of F)try{const[G,L]=await Promise.all([Ve("/api/remote/status",void 0,$),Ve("/api/remote/devices",void 0,$)]);if(!Array.isArray(L.devices))throw new Error("Invalid Hub devices response.");w.current.delete($),l(G),d(L.devices),y($),h("");return}catch(G){T=G,w.current.set($,Date.now()+1e4)}throw y(""),T||new Error("No LiveDesk Hub endpoint is reachable.")},[a,j]),M=u.useCallback(()=>{w.current.clear(),N().catch(T=>{h(T instanceof Error?T.message:String(T))}),b(T=>T+1)},[N]);return u.useEffect(()=>{if(!a){l(null),d([]),y(""),h("");return}let T=!0;const D=async()=>{try{await N()}catch($){T&&h($ instanceof Error?$.message:String($))}};D();const F=window.setInterval(D,2500);return()=>{T=!1,window.clearInterval(F)}},[a,N,x]),{status:i,devices:c,error:m,refresh:M,hubBaseUrl:g||k,hubCandidates:j}}function D1(n){const[a,i]=u.useState(null),[l,c]=u.useState(""),d=n?.user?.id||"",m=u.useCallback(async()=>{if(!d){i(null);return}const{data:h,error:g}=await Ct.from($y).select("*").eq("user_id",d).maybeSingle();if(g){c(g.message);return}i(h),c("")},[d]);return u.useEffect(()=>{m()},[m]),u.useEffect(()=>{if(!d)return;const h=Ct.channel(`livedesk-remote-host-targets-${d.replace(/[^a-zA-Z0-9]/g,"")}`).on("postgres_changes",{event:"*",schema:"public",table:$y,filter:`user_id=eq.${d}`},g=>i(g.new)).subscribe();return()=>{Ct.removeChannel(h)}},[d]),{target:a,error:l,refresh:m}}function L1(n){const[a,i]=u.useState(null),[l,c]=u.useState(!1),[d,m]=u.useState(""),h=n?.user?.id||"",g=u.useCallback(async()=>{if(!h){i(null),m(""),c(!1);return}c(!0);const{data:x,error:b}=await Ct.from(N1).select("*").eq("user_id",h).eq("product_key","livedesk").maybeSingle();if(b){m(b.message),c(!1);return}i(x),m(""),c(!1)},[h]);u.useEffect(()=>{g()},[g]);const y=u.useMemo(()=>!a||a.status!=="active"?!1:a.expires_at?new Date(a.expires_at).getTime()>Date.now():!0,[a]);return{entitlement:a,licensed:y,loading:l,error:d,refresh:g}}const Hu={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},_1=2500,I1=3e4,z1=64*1024,O1=6,H1=O1,Vx=new Map;function F1(n){return Vx.get(n)}const By={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function $1(n,a,i){const l=Number(a);if(!Number.isFinite(l)||l<=0)return 0;const c=i-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>I1?(n.minimumHubClockOffsetMs=c,0):m}function Au(n){if(n==null||n==="")return;const a=Number(n);return Number.isFinite(a)?a:void 0}function Py(n,a,i=An,l={}){const[c,d]=u.useState(new Map),[m,h]=u.useState("idle"),[g,y]=u.useState(""),[x,b]=u.useState(Hu),w=u.useRef(new Map),A=u.useRef(new Map),j=u.useRef(0),k=u.useRef(new Map),N=u.useRef({enabled:!1,token:"",reason:""}),M=u.useRef(new Set),[T,D]=u.useState(0),F=u.useRef(l.onFrame),$=u.useRef(l.onStreamReady),G=u.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),L=u.useMemo(()=>[...n].sort().join(","),[n]),Q=Number.isFinite(l.fps)?Number(l.fps):2,q=Number.isFinite(l.maxWidth)?Number(l.maxWidth):640,P=Number.isFinite(l.maxHeight)?Number(l.maxHeight):360,Y=Number.isFinite(l.quality)?Number(l.quality):45,H=String(l.frameMode||l.mode||"mode3-h264-hw").trim()||"mode3-h264-hw",ye=l.streamPurpose==="control"?"control":"wall",de=l.forceRestart===!0,Z=String(l.forceRestartToken||"").trim(),z=String(l.restartReason||"").trim();N.current={enabled:de,token:Z,reason:z};const se=u.useMemo(()=>{const he=Object.entries(l.monitorSelections||{}).filter(([fe])=>!!fe).sort(([fe],[ee])=>fe.localeCompare(ee));return JSON.stringify(Object.fromEntries(he))},[l.monitorSelections]);u.useEffect(()=>{F.current=l.onFrame},[l.onFrame]),u.useEffect(()=>{$.current=l.onStreamReady},[l.onStreamReady]);const W=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{}},[]),O=u.useCallback(()=>{const he=[...A.current.values()].map(fe=>fe.socket);if(he.length===0){h("idle");return}if(he.some(fe=>fe.readyState===WebSocket.OPEN)){h("open");return}if(he.some(fe=>fe.readyState===WebSocket.CONNECTING)){h("connecting");return}h("closed")},[]),le=u.useCallback((he,fe,ee,we)=>{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:ee,restartToken:we})),!0}catch{return!1}},[]),ce=u.useCallback((he,fe)=>{if(!he||he.byteLength<5)return;const ee=Date.now(),Me=new DataView(he).getUint32(0,!1);if(Me<=0||Me+4>he.byteLength)return;const He=new Uint8Array(he,4,Me),ne=JSON.parse(Rp.decode(He)),qe=Au(ne.hubPacketEpochMs),mt=qe!==void 0&&qe>0?qe:void 0,J=$1(fe,mt,ee);if(J>_1)return;const Ce=new Uint8Array(he,4+Me),Le={deviceId:String(ne.deviceId||""),kind:ne.kind==="thumbnail"?"thumbnail":"live",frameSeq:Number(ne.frameSeq||0),streamFrameSeq:Number(ne.streamFrameSeq||0)||void 0,streamId:String(ne.streamId||""),commandId:ne.commandId?String(ne.commandId):void 0,sessionId:ne.sessionId?String(ne.sessionId):void 0,captureGeneration:Number(ne.captureGeneration||0)||void 0,streamPurpose:ne.streamPurpose?String(ne.streamPurpose):void 0,width:Number(ne.width||0),height:Number(ne.height||0),sourceWidth:Number(ne.sourceWidth||0)||void 0,sourceHeight:Number(ne.sourceHeight||0)||void 0,mimeType:String(ne.mimeType||"image/jpeg"),mode:ne.mode?String(ne.mode):void 0,frameMode:ne.frameMode?String(ne.frameMode):void 0,frameProfile:ne.frameProfile?String(ne.frameProfile):void 0,encoding:ne.encoding?String(ne.encoding):void 0,codec:ne.codec?String(ne.codec):void 0,compression:ne.compression?String(ne.compression):void 0,pixelFormat:ne.pixelFormat?String(ne.pixelFormat):void 0,bytesPerPixel:Number(ne.bytesPerPixel||0)||0,uncompressedByteLength:Number(ne.uncompressedByteLength||0)||0,h264Format:ne.h264Format?String(ne.h264Format):void 0,isKeyFrame:ne.isKeyFrame===!0,chunkType:ne.chunkType?String(ne.chunkType):void 0,timestampUs:Number(ne.timestampUs||0)||0,durationUs:Number(ne.durationUs||0)||0,sourceGapMs:Number(ne.sourceGapMs||0)||0,agentSendGapMs:Number(ne.agentSendGapMs||0)||0,agentSendDurationMs:Number(ne.agentSendDurationMs||0)||0,agentSendDurationFrameSeq:Number(ne.agentSendDurationFrameSeq||0)||0,agentPaceMs:Number(ne.agentPaceMs||0)||0,agentQueueBeforePaceMs:Number(ne.agentQueueBeforePaceMs||0)||0,agentFrameAgeMs:Number(ne.agentFrameAgeMs||0)||0,nativeCaptureTelemetryAvailable:ne.nativeCaptureTelemetryAvailable===!0,nativeEncoderHardwareAccelerationKnown:ne.nativeEncoderHardwareAccelerationKnown===!0,nativeEncoderHardwareAccelerated:typeof ne.nativeEncoderHardwareAccelerated=="boolean"?ne.nativeEncoderHardwareAccelerated:void 0,nativeEncoderHardwareQueryStatus:ne.nativeEncoderHardwareQueryStatus?String(ne.nativeEncoderHardwareQueryStatus):void 0,nativeCaptureFps:Number(ne.nativeCaptureFps||0)||0,nativeEncodedFps:Number(ne.nativeEncodedFps||0)||0,nativeCaptureSampleCount:Number(ne.nativeCaptureSampleCount||0)||0,nativeEncodableFrameCount:Number(ne.nativeEncodableFrameCount||0)||0,nativeSkippedFrameCount:Number(ne.nativeSkippedFrameCount||0)||0,nativeEncodedFrameCount:Number(ne.nativeEncodedFrameCount||0)||0,nativeCaptureTelemetryAt:ne.nativeCaptureTelemetryAt?String(ne.nativeCaptureTelemetryAt):void 0,droppedByAgent:Number(ne.droppedByAgent||0)||0,hubIngressDropped:Number(ne.hubIngressDropped||0)||0,hubClientDropped:Number(ne.hubClientDropped||0)||0,transport:ne.transport?String(ne.transport):void 0,videoTransport:ne.videoTransport?String(ne.videoTransport):void 0,frameTransportActive:ne.frameTransportActive?String(ne.frameTransportActive):void 0,frameTransportProtocol:ne.frameTransportProtocol?String(ne.frameTransportProtocol):void 0,frameTransportState:ne.frameTransportState?String(ne.frameTransportState):void 0,frameTransportReason:ne.frameTransportReason?String(ne.frameTransportReason):void 0,frameTransportChangedAt:ne.frameTransportChangedAt?String(ne.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(ne.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(ne.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:ne.frameTransportP2pReady===!0,hubClientQueueDepth:Number(ne.hubClientQueueDepth||0)||0,hubClientQueueLimit:Number(ne.hubClientQueueLimit||0)||0,hubClientBufferedBytes:Number(ne.hubClientBufferedBytes||0)||0,udpIncompleteFrames:Number(ne.udpIncompleteFrames||0)||0,hardwareEncoder:ne.hardwareEncoder?String(ne.hardwareEncoder):void 0,platformProfile:ne.platformProfile?String(ne.platformProfile):void 0,monitorIndex:Number.isFinite(Number(ne.monitorIndex))?Number(ne.monitorIndex):void 0,monitorCount:Number.isFinite(Number(ne.monitorCount))?Number(ne.monitorCount):void 0,requestedFps:Number(ne.requestedFps||0)||0,effectiveFps:Number(ne.effectiveFps||0)||0,captureTimingAvailable:ne.captureTimingAvailable===!0,captureAverageMs:Au(ne.captureAverageMs),captureP95Ms:Au(ne.captureP95Ms),slowFrameCount:Number(ne.slowFrameCount||0)||0,captureHelperRestarts:Number(ne.captureHelperRestarts||0)||0,capturedAt:String(ne.capturedAt||""),receivedAt:String(ne.receivedAt||""),hubPacketAt:ne.hubPacketAt?String(ne.hubPacketAt):void 0,hubPacketEpochMs:mt,browserReceivedEpochMs:ee,hubPacketTransitAgeMs:mt!==void 0?J:void 0,byteLength:Number(ne.byteLength||Ce.byteLength),contentHash:ne.contentHash?String(ne.contentHash):void 0,captureMs:Au(ne.captureMs),captureStageMs:Au(ne.captureStageMs),convertMs:Number(ne.convertMs||0)||0,compressMs:Number(ne.compressMs||0)||0,captureSourceSerial:Number(ne.captureSourceSerial||0)||0,captureSourceSkipped:Number(ne.captureSourceSkipped||0)||0,deltaTileSize:Number(ne.deltaTileSize||0)||0,deltaTileCount:Number(ne.deltaTileCount||0)||0,deltaVisualTileCount:Number(ne.deltaVisualTileCount||0)||0,deltaRefreshTileCount:Number(ne.deltaRefreshTileCount||0)||0,deltaTotalTiles:Number(ne.deltaTotalTiles||0)||0,payload:Ce};if(!Le.deviceId)return;const Fe=Number(fe.payload.monitorSelections?.[Le.deviceId]);if(Number.isFinite(Fe)&&Number.isFinite(Number(Le.monitorIndex))&&Number(Le.monitorIndex)!==Fe)return;const _e={streamId:fe.lastFrameStreamId,commandId:fe.lastFrameCommandId,order:fe.lastFrameOrder},Xe=Number(Le.streamFrameSeq||Le.frameSeq||0),We=!!_e.commandId&&!!Le.commandId,Ze=_e.streamId===Le.streamId&&(!We||_e.commandId===Le.commandId),dt=_e.order;if(Ze&&dt>=Xe&&(dt===Xe||We))return;fe.lastFrameStreamId=Le.streamId,fe.lastFrameCommandId=Le.commandId||"",fe.lastFrameOrder=Xe;const U=G.current;U.totalFrames+=1,U.totalBytes+=Ce.byteLength,U.sampleFrames+=1,U.sampleBytes+=Ce.byteLength;const ve=!w.current.has(Le.deviceId);w.current.set(Le.deviceId,Le),ve&&d(new Map(w.current)),F.current?.(Le)},[]);u.useEffect(()=>{const he=window.setInterval(()=>{const fe=performance.now(),ee=G.current,we=Math.max(1,fe-ee.sampleStartedAt);b({totalFrames:ee.totalFrames,totalBytes:ee.totalBytes,framesPerSecond:ee.sampleFrames*1e3/we,bytesPerSecond:ee.sampleBytes*1e3/we,sampleMs:we,lastUpdatedAt:Date.now()}),d(new Map(w.current)),ee.sampleFrames=0,ee.sampleBytes=0,ee.sampleStartedAt=fe},2e3);return()=>{window.clearInterval(he)}},[]),u.useEffect(()=>{const he=L?L.split(",").filter(Boolean):[],fe=new Set(he),ee=performance.now();for(const[we,Me]of A.current.entries())fe.has(we)||(W(Me,"livedesk-device-unsubscribed"),A.current.delete(we),k.current.delete(we),w.current.delete(we));if(he.length===0){for(const we of A.current.values())W(we,"livedesk-no-devices");A.current.clear(),k.current.clear(),w.current=new Map,d(new Map),y(""),G.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},b(Hu),O();return}G.current.sampleStartedAt<=0&&(G.current.sampleStartedAt=ee,b({...Hu,lastUpdatedAt:Date.now()}));for(const we of he){const Me=Number(l.monitorSelections?.[we]),He=Number.isInteger(Me)&&Me>=0?Me:0,ne={[we]:He},qe={type:"subscribe",deviceIds:[we],autoStartLive:a,fps:Q,maxWidth:q,maxHeight:P,quality:Y,mode:H,frameMode:H,streamPurpose:ye,monitorSelections:ne},mt=JSON.stringify(qe),J=A.current.get(we),Ce=Number(J?.payload.monitorSelections?.[we]),Le=Number(ne[we]),Fe=!!J&&Number.isFinite(Ce)&&Number.isFinite(Le)&&Ce!==Le;if(J){const Ze=J.socket.readyState===WebSocket.CONNECTING||J.socket.readyState===WebSocket.OPEN;if(J.payloadKey===mt&&Ze&&!J.disposed)continue}const _e=J&&(J.socket.readyState===WebSocket.CONNECTING||J.socket.readyState===WebSocket.OPEN)&&!J.disposed?J.handoffFrom&&!J.handoffCompleted?J.handoffFrom:J:void 0;J&&J!==_e&&W(J,"livedesk-subscription-superseded");const Xe=new WebSocket(Pf(`/api/remote/frames/ws?devices=${encodeURIComponent(we)}`,i));Xe.binaryType="arraybuffer";const We={socket:Xe,payload:qe,payloadKey:mt,generation:j.current+1,monitorRestartToken:Fe?`monitor-${we}-${Le}-${j.current+1}`:"",disposed:!1,handoffFrom:_e,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1};j.current=We.generation,Fe&&(w.current.delete(we),d(new Map(w.current))),A.current.set(we,We),Xe.addEventListener("open",()=>{if(We.disposed||A.current.get(we)!==We){W(We,"livedesk-stale-frame-socket");return}y("");const Ze=N.current,dt=Ze.enabled&&(!Ze.token||k.current.get(we)!==Ze.token),U=dt||We.monitorRestartToken!=="",ve=dt?Ze.token:We.monitorRestartToken,Ae=dt?Ze.reason:We.monitorRestartToken?"monitor-selection-change":"";Xe.send(JSON.stringify({...We.payload,forceRestart:U,restartReason:U?Ae:"",restartToken:U?ve:""})),dt&&Ze.token&&k.current.set(we,Ze.token);const Be=We.handoffFrom;We.handoffFrom=void 0,We.handoffCompleted=!0,Be&&!Be.disposed&&W(Be,"livedesk-subscription-replaced"),O()}),Xe.addEventListener("message",Ze=>{if(We.disposed||A.current.get(we)!==We)return;if(typeof Ze.data=="string"){try{const U=JSON.parse(Ze.data);if(U?.type==="RemoteFrameSubscriptionError")y(String(U.error||"control-stream-start-failed"));else if(U?.type==="RemoteFrameLiveAutoStart"){const Ae=(Array.isArray(U.skipped)?U.skipped:[]).find(Be=>Be?.deviceId===we);if(Ae)y(String(Ae.reason||"control-stream-start-failed"));else if(Array.isArray(U.started)){const Be=U.started.find(ft=>ft?.deviceId===we);Be&&(y(""),Be.ready===!0&&Be.streamPurpose==="control"&&Be.sessionId&&Be.commandId&&Number(Be.captureGeneration||0)>0&&$.current?.({deviceId:we,sessionId:String(Be.sessionId),streamId:String(Be.streamId||""),streamPurpose:"control",commandId:String(Be.commandId),captureGeneration:Number(Be.captureGeneration),monitorIndex:Number(Be.monitorIndex||0)}))}}else U?.type==="RemoteFrameStreamReady"&&U.deviceId===we&&U.streamPurpose==="control"&&U.sessionId&&U.commandId&&Number(U.captureGeneration||0)>0&&(y(""),$.current?.({deviceId:we,sessionId:String(U.sessionId),streamId:String(U.streamId||""),streamPurpose:"control",commandId:String(U.commandId),captureGeneration:Number(U.captureGeneration),monitorIndex:Number(U.monitorIndex||0)}))}catch{}return}const dt=Ze.data instanceof ArrayBuffer?Ze.data:null;dt&&(y(""),ce(dt,We))}),Xe.addEventListener("error",()=>{We.disposed||A.current.get(we)!==We||h("connecting")}),Xe.addEventListener("close",()=>{const Ze=!We.disposed;We.disposed=!0;const dt=A.current.get(we);let U=!1;if(dt===We){const ve=We.handoffFrom;We.handoffFrom=void 0,ve&&!ve.disposed&&(ve.socket.readyState===WebSocket.CONNECTING||ve.socket.readyState===WebSocket.OPEN)?(A.current.set(we,ve),U=!0):A.current.delete(we)}if(O(),Ze&&dt===We&&!U){const ve=window.setTimeout(()=>{M.current.delete(ve),D(Ae=>Ae+1)},750);M.current.add(ve)}})}O()},[a,W,L,Q,H,ce,i,P,q,se,l.monitorSelections,Y,T,ye,O]),u.useEffect(()=>{if(!de||!Z)return;const he=L?L.split(",").filter(Boolean):[];for(const fe of he){if(k.current.get(fe)===Z)continue;const ee=A.current.get(fe);!ee||!le(fe,ee,z,Z)||k.current.set(fe,Z)}},[L,de,Z,z,le]),u.useEffect(()=>()=>{for(const he of A.current.values())W(he,"livedesk-hook-unmount");A.current.clear();for(const he of M.current)window.clearTimeout(he);M.current.clear()},[W]);const K=u.useCallback((he,fe="browser-stale")=>{const ee=Array.isArray(he)&&he.length>0?he:L.split(",").filter(Boolean);if(ee.length===0)return!1;let we=!1;for(const Me of ee){const He=A.current.get(Me);!He||He.socket.readyState!==WebSocket.OPEN||(we=le(Me,He,fe,`${Date.now()}-${Math.random().toString(36).slice(2)}`)||we)}return we},[L,le]),be=u.useCallback((he,fe="browser-reconnect")=>{const ee=Array.isArray(he)&&he.length>0?he:L.split(",").filter(Boolean);if(ee.length===0)return!1;let we=!1;for(const Me of ee){const He=A.current.get(Me);He&&(W(He,`livedesk-${fe}`),A.current.delete(Me),k.current.delete(Me),w.current.delete(Me),we=!0)}return we&&d(new Map(w.current)),D(Me=>Me+1),O(),!0},[W,L,O]);return{frames:c,state:m,error:g,stats:x,restartLive:K,reconnectLive:be}}function B1(n,a,i=An,l={}){const[c,d]=u.useState(null),[m,h]=u.useState(null),[g,y]=u.useState("idle"),[x,b]=u.useState(Hu),w=u.useRef(null),A=u.useRef(l.onFrame),j=u.useRef(null),k=u.useRef(0),N=u.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),M=u.useMemo(()=>[...new Set(n.filter(Boolean))].join(","),[n]),T=u.useMemo(()=>[...new Set((l.captureDeviceIds||n).filter(Boolean))].join(","),[n,l.captureDeviceIds]),D=u.useMemo(()=>JSON.stringify(l.monitorSelections||{}),[l.monitorSelections]),F=u.useMemo(()=>({deviceIds:M.split(",").filter(Boolean),captureDeviceIds:T.split(",").filter(Boolean),fps:Number(l.fps||20),inputFps:Number(l.inputFps||8),width:Number(l.width||1920),height:Number(l.height||1080),tileWidth:Number(l.tileWidth||320),tileHeight:Number(l.tileHeight||180),monitorSelections:l.monitorSelections||{}}),[T,M,D,l.fps,l.height,l.inputFps,l.monitorSelections,l.tileHeight,l.tileWidth,l.width]),$=u.useMemo(()=>JSON.stringify(F),[F]),G=u.useRef(F);G.current=F;const L=a&&F.deviceIds.length>0,Q=u.useCallback(P=>P.readyState!==WebSocket.OPEN?!1:(P.send(JSON.stringify({type:"configure",...G.current})),!0),[]);u.useEffect(()=>{A.current=l.onFrame},[l.onFrame]),u.useEffect(()=>{const P=window.setInterval(()=>{const Y=N.current,H=performance.now(),ye=Math.max(1,H-Y.sampleStartedAt);b({totalFrames:Y.totalFrames,totalBytes:Y.totalBytes,framesPerSecond:Y.sampleFrames*1e3/ye,bytesPerSecond:Y.sampleBytes*1e3/ye,sampleMs:ye,lastUpdatedAt:Date.now()});const de=j.current;de&&de.frameSeq!==k.current&&(k.current=de.frameSeq,d(de)),Y.sampleFrames=0,Y.sampleBytes=0,Y.sampleStartedAt=H},1e3);return()=>window.clearInterval(P)},[]),u.useEffect(()=>{if(!L){w.current?.close(),w.current=null,d(null),j.current=null,k.current=0,h(null),y("idle"),b(Hu);return}let P=!1,Y=0;const H=()=>{if(P)return;const ye=new WebSocket(Pf("/api/remote/atlas/ws",i));ye.binaryType="arraybuffer",w.current=ye,y("connecting"),ye.addEventListener("open",()=>{N.current.sampleStartedAt=performance.now(),y("open"),Q(ye)}),ye.addEventListener("message",de=>{if(typeof de.data=="string"){try{const z=JSON.parse(de.data);z?.type==="Mode4AtlasLayout"&&h({layoutVersion:Number(z.layoutVersion||0),width:Number(z.width||1920),height:Number(z.height||1080),columns:Number(z.columns||1),rows:Number(z.rows||1),tiles:Array.isArray(z.tiles)?z.tiles:[]})}catch{}return}const Z=de.data instanceof ArrayBuffer?de.data:null;if(!(!Z||Z.byteLength<5))try{const z=Date.now(),W=new DataView(Z).getUint32(0,!1);if(W<=0||W+4>Z.byteLength)return;const O=JSON.parse(Rp.decode(new Uint8Array(Z,4,W))),le=new Uint8Array(Z,4+W),ce={deviceId:String(O.deviceId||"__livedesk_mode4_atlas__"),kind:"live",frameSeq:Number(O.frameSeq||0),streamFrameSeq:Number(O.streamFrameSeq||0)||void 0,streamId:String(O.streamId||"mode4-atlas"),commandId:O.commandId?String(O.commandId):void 0,width:Number(O.width||1920),height:Number(O.height||1080),sourceWidth:Number(O.sourceWidth||O.width||1920),sourceHeight:Number(O.sourceHeight||O.height||1080),mimeType:String(O.mimeType||"video/h264"),mode:String(O.mode||"mode4-h264-atlas"),frameMode:String(O.frameMode||"mode4-h264-atlas"),frameProfile:String(O.frameProfile||"mode4-h264-atlas-v1"),encoding:String(O.encoding||"video-atlas"),codec:String(O.codec||"h264"),compression:String(O.compression||"video/h264"),h264Format:String(O.h264Format||"annexb"),isKeyFrame:O.isKeyFrame===!0,chunkType:String(O.chunkType||""),timestampUs:Number(O.timestampUs||0),durationUs:Number(O.durationUs||0),transport:O.transport?String(O.transport):void 0,videoTransport:O.videoTransport?String(O.videoTransport):void 0,frameTransportActive:O.frameTransportActive?String(O.frameTransportActive):void 0,frameTransportProtocol:O.frameTransportProtocol?String(O.frameTransportProtocol):void 0,frameTransportState:O.frameTransportState?String(O.frameTransportState):void 0,frameTransportReason:O.frameTransportReason?String(O.frameTransportReason):void 0,frameTransportChangedAt:O.frameTransportChangedAt?String(O.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(O.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(O.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:O.frameTransportP2pReady===!0,hubClientQueueDepth:Number(O.hubClientQueueDepth||0)||0,hubClientQueueLimit:Number(O.hubClientQueueLimit||0)||0,hubClientBufferedBytes:Number(O.hubClientBufferedBytes||0)||0,udpIncompleteFrames:Number(O.udpIncompleteFrames||0)||0,hardwareEncoder:O.hardwareEncoder?String(O.hardwareEncoder):void 0,platformProfile:O.platformProfile?String(O.platformProfile):void 0,capturedAt:String(O.capturedAt||""),receivedAt:String(O.receivedAt||""),hubPacketAt:O.hubPacketAt?String(O.hubPacketAt):void 0,hubPacketEpochMs:Number(O.hubPacketEpochMs||0)||void 0,browserReceivedEpochMs:z,byteLength:le.byteLength,layoutVersion:Number(O.layoutVersion||0),atlasComposeMs:Number(O.atlasComposeMs||0),atlasPoolStarved:Number(O.atlasPoolStarved||0),atlasReadyTiles:Number(O.atlasReadyTiles||0),atlasTileCount:Number(O.atlasTileCount||0),atlasInputRevision:Number(O.atlasInputRevision||0),atlasSourceNewestAtEpochMs:Number(O.atlasSourceNewestAtEpochMs||0),atlasSourceOldestAtEpochMs:Number(O.atlasSourceOldestAtEpochMs||0),atlasSourceMaxAgeMs:Number(O.atlasSourceMaxAgeMs||0),payload:le},K=N.current;K.totalFrames+=1,K.totalBytes+=le.byteLength,K.sampleFrames+=1,K.sampleBytes+=le.byteLength,j.current=ce,k.current===0&&(k.current=ce.frameSeq,d(ce)),A.current?.(ce)}catch{}}),ye.addEventListener("error",()=>y("error")),ye.addEventListener("close",()=>{w.current===ye&&(w.current=null),!P&&(y("closed"),Y=window.setTimeout(H,1200))})};return H(),()=>{P=!0,window.clearTimeout(Y),w.current?.close(),w.current=null}},[L,i,Q]),u.useEffect(()=>{if(!L)return;const P=w.current;P&&Q(P)},[$,L,Q]);const q=u.useCallback(()=>{const P=w.current;return P?Q(P):!1},[Q]);return{frame:c,layout:m,state:g,stats:x,refreshInputs:q}}function P1(n,a=An){const i=u.useRef(null),l=u.useRef(0),c=u.useRef(0),d=u.useRef(new Map),m=u.useRef(""),[h,g]=u.useState("idle"),[y,x]=u.useState(""),[b,w]=u.useState(By),A=u.useRef({totalSent:0,totalDropped:0,sampleSent:0,sampleDropped:0,sampleStartedAt:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0});u.useEffect(()=>{if(!n){i.current?.close(),i.current=null,c.current=0,m.current="",d.current.clear(),g("idle"),x(""),w(By);return}let k=!1,N=0;const M=()=>{if(k)return;const T=new WebSocket(Pf("/api/remote/input/ws",a));i.current=T,A.current.sampleStartedAt=performance.now(),g("connecting"),x(""),T.addEventListener("open",()=>{k||i.current!==T||(x(""),g("open"))}),T.addEventListener("message",D=>{if(!(k||i.current!==T||typeof D.data!="string"))try{const F=JSON.parse(D.data),$=Number(F.inputSeq||F.result?.inputSeq||0),G=String(F.deviceId||F.result?.deviceId||""),L=String(F.inputEventId||F.result?.inputEventId||""),Q=d.current.get($);if(G&&(Q&&Q.deviceId!==G||!Q&&m.current&&m.current!==G)||Q?.inputEventId&&L&&Q.inputEventId!==L)return;if(F?.type==="RemoteInputError"){$>0&&d.current.delete($),x(String(F.error||F.result?.error||"Remote input failed.")),T.readyState===WebSocket.OPEN&&g("open");return}if(F?.type!=="RemoteInputApplied")return;Q&&(A.current.lastRoundTripMs=Math.max(0,performance.now()-Q.sentAt),d.current.delete($)),A.current.lastInputSeq=$,A.current.lastAgentApplyMs=Math.max(0,Number(F.agentApplyMs||0)),x(""),g("open")}catch{}}),T.addEventListener("close",()=>{k||i.current!==T||(i.current=null,g("closed"),N=window.setTimeout(M,1200))}),T.addEventListener("error",()=>{!k&&i.current===T&&g("error")})};return M(),()=>{k=!0,window.clearTimeout(N);const T=i.current;i.current=null,T?.close(),d.current.clear()}},[n,a]),u.useEffect(()=>{if(!n)return;const k=window.setInterval(()=>{const N=performance.now(),M=A.current,T=Math.max(1,N-M.sampleStartedAt);w({totalSent:M.totalSent,totalDropped:M.totalDropped,sentPerSecond:M.sampleSent*1e3/T,droppedPerSecond:M.sampleDropped*1e3/T,bufferedAmount:i.current?.bufferedAmount||0,lastInputType:M.lastInputType,lastInputSeq:M.lastInputSeq,lastRoundTripMs:M.lastRoundTripMs,lastAgentApplyMs:M.lastAgentApplyMs,lastUpdatedAt:Date.now()}),M.sampleSent=0,M.sampleDropped=0,M.sampleStartedAt=N},1e3);return()=>window.clearInterval(k)},[n]);const j=u.useCallback((k,N)=>{const M=i.current;if(!M||M.readyState!==WebSocket.OPEN||!k)return!1;const T=String(N.type||"").toLowerCase(),D=T==="pointermove",$=D||T==="wheel",G=A.current;if(D&&M.bufferedAmount>z1)return G.totalDropped+=1,G.sampleDropped+=1,G.lastInputType="pointermove-drop",!1;const L=l.current+1;l.current=L;const Q=`${L}-${crypto.randomUUID()}`,q=Date.now(),P=!$||L-c.current>=H1;for(P&&(d.current.set(L,{sentAt:performance.now(),deviceId:k,inputEventId:Q}),$&&(c.current=L)),m.current=k,D||Vx.set(k,{inputSeq:L,inputType:T||"input",sentAt:performance.now()});d.current.size>256;){const Y=d.current.keys().next().value;if(Y===void 0)break;d.current.delete(Y)}return M.send(JSON.stringify({type:"input",requestId:$?"":crypto.randomUUID(),fireAndForget:$,deviceId:k,input:{...N,inputEventId:Q,inputSeq:L,requestAck:P,issuedAtEpochMs:q,issuedAt:new Date(q).toISOString()}})),G.totalSent+=1,G.sampleSent+=1,G.lastInputType=T||"input",!0},[]);return{state:h,sendInput:j,stats:b,error:y}}function U1(n){const a=String(n||"").toLowerCase();return a.includes("audio/pcm")||a.includes("audio/l16")||a.includes("f32le")||a.includes("s16le")}const ef={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},q1=.08,G1=.25,V1=.02,Uy=300,W1=4,tf=1500,Ah=5e3,Y1=2e3,K1=1e4,nf=[0,1e3,3e3];function qy(n){const a=Date.parse(String(n||""));return Number.isFinite(a)?Math.max(0,Date.now()-a):0}function Q1(n,a,i){const l=Math.max(1,Math.min(8,Math.floor(a.channels||2))),c=Math.max(8e3,Math.min(192e3,Math.floor(a.sampleRate||48e3))),d=String(a.mimeType||"").toLowerCase(),m=d.includes("s16le")||d.includes("audio/l16"),h=m?2:4,g=Math.floor(i.byteLength/h),y=Math.floor(g/l),x=n.createBuffer(l,y,c),b=new DataView(i);for(let w=0;w<l;w+=1){const A=x.getChannelData(w);for(let j=0;j<y;j+=1){const N=(j*l+w)*h;A[j]=m?Math.max(-1,Math.min(1,b.getInt16(N,!0)/32768)):Math.max(-1,Math.min(1,b.getFloat32(N,!0)))}}return x}function X1(n,a,i=An){const l=u.useRef(null),c=u.useRef(0),[d,m]=u.useState("idle"),[h,g]=u.useState(null),[y,x]=u.useState(ef),[b,w]=u.useState("");return u.useEffect(()=>{if(!a||!n){m("idle"),g(null),x(ef),w("");return}m("connecting"),g(null),x(ef),w("");const A=window.AudioContext||window.webkitAudioContext;if(!A){m("unsupported"),x(ef),w("Audio playback is not supported in this browser.");return}const j=new A;l.current=j,c.current=j.currentTime;const k=new WebSocket(Pf("/api/remote/audio/ws?devices="+encodeURIComponent(n),i));k.binaryType="arraybuffer";const N=new Set,M={browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:!1,helperAlive:!1,captureRestartCount:0,localProcessingAgeMs:0,lastPacketAt:0,lastAcceptedAt:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:String(j.state),stalledCount:0,automaticRestarts:0,activeStreamId:"",lastCaptureStatusAt:0,lastPcmAtEpochMs:0};let T=!1,D=0,F=!1,$=0,G=0;const L=(z=!0)=>{for(const se of N)try{se.stop()}catch{}N.clear(),z&&(c.current=j.currentTime+q1)},Q=()=>{M.audioContextState=String(j.state),!T&&(M.audioContextState==="suspended"||M.audioContextState==="interrupted"?m("suspended"):M.audioContextState==="closed"&&(m("error"),w("The browser audio context is closed. Toggle Remote Audio off and on to recover.")))},q=async()=>{if(T||String(j.state)==="closed")return!1;try{if(String(j.state)!=="running"&&await j.resume(),M.audioContextState=String(j.state),!T&&!F&&M.audioContextState==="running"){const z=M.lastAcceptedAt>0&&performance.now()-M.lastAcceptedAt<=tf,se=M.lastCaptureStatusAt>0&&performance.now()-M.lastCaptureStatusAt<=Ah&&M.captureAlive&&M.helperAlive;m(z?"playing":se?"silent":"open")}return M.audioContextState==="running"}catch(z){return T||(m("suspended"),w(z instanceof Error?"Audio playback is suspended: "+z.message:"Audio playback is suspended.")),!1}},P=async()=>{if(T||F||k.readyState!==WebSocket.OPEN)return;if($>=nf.length){m("error"),w("Remote audio stopped sending frames. Toggle Audio off and on to retry.");return}const z=$;$+=1,F=!0,M.stalledCount+=1,M.automaticRestarts+=1,m("reconnecting");try{const se=await Ve("/api/remote/devices/"+encodeURIComponent(n)+"/audio/stop",{method:"POST",body:JSON.stringify({})},i);if(se.ok===!1)throw new Error(se.error||"Remote audio stop failed.");if(T)return;const W=await Ve("/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})},i);if(W.ok===!1)throw new Error(W.error||"Remote audio start failed.");const O=performance.now();D=O,M.lastPacketAt=O,M.lastAcceptedAt=0,M.lastCaptureStatusAt=0,M.lastPcmAtEpochMs=0,M.captureAlive=!1,M.helperAlive=!1,M.silentForMs=0,G=O+(nf[z+1]??3e3),w(""),T||m("open")}catch(se){T||(G=performance.now()+(nf[z+1]??3e3),m("error"),w(se instanceof Error?"Remote audio restart failed: "+se.message:"Remote audio restart failed."))}finally{F=!1}},Y=()=>{M.drops+=1},H=window.setInterval(()=>{if(T)return;const z=performance.now(),se=M.lastPacketAt>0?Math.max(0,z-M.lastPacketAt):D>0?Math.max(0,z-D):0,W=M.lastAcceptedAt>0?Math.max(0,z-M.lastAcceptedAt):0,O=M.lastCaptureStatusAt>0?Math.max(0,z-M.lastCaptureStatusAt):0,le=k.readyState===WebSocket.OPEN,ce=M.lastCaptureStatusAt>0,K=ce&&O<=Ah,be=ce&&(!M.captureAlive||!M.helperAlive)&&O>Y1,he=ce&&O>Ah,fe=!ce&&D>0&&z-D>K1,ee=D>0&&(M.lastAcceptedAt<=0?z-D>tf:W>tf);le&&D>0&&(be||he||fe)?$>=nf.length&&!F?(m("error"),w("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!F&&z>=G?P():F||m("stalled"):le&&ee&&!F&&M.audioContextState!=="suspended"&&M.audioContextState!=="interrupted"&&m(K?"silent":"open"),x({queuedMs:Math.max(0,(c.current-j.currentTime)*1e3),browserAgeMs:M.browserAgeMs,captureAgeMs:M.captureAgeMs,captureStatusAgeMs:O,silentForMs:M.silentForMs,captureAlive:M.captureAlive,helperAlive:M.helperAlive,captureRestartCount:M.captureRestartCount,localProcessingAgeMs:M.localProcessingAgeMs,lastPacketAgeMs:se,lastAcceptedAgeMs:W,framesReceived:M.framesReceived,drops:M.drops,resyncs:M.resyncs,pendingDecodes:M.pendingDecodes,lastFrameSeq:M.lastFrameSeq,audioContextState:M.audioContextState,stalledCount:M.stalledCount,automaticRestarts:M.automaticRestarts,lastUpdatedAt:Date.now()})},250),ye=()=>{Q(),(String(j.state)==="suspended"||String(j.state)==="interrupted")&&q()},de=()=>{document.visibilityState==="visible"&&q()},Z=()=>{q()};return j.addEventListener("statechange",ye),document.addEventListener("visibilitychange",de),window.addEventListener("pageshow",Z),window.addEventListener("pointerdown",Z),window.addEventListener("keydown",Z),m("connecting"),w(""),Q(),k.addEventListener("open",()=>{T||(D=performance.now(),M.lastPacketAt=D,M.lastAcceptedAt=0,M.lastCaptureStatusAt=0,M.lastPcmAtEpochMs=0,M.captureAlive=!1,M.helperAlive=!1,M.silentForMs=0,m("open"),k.send(JSON.stringify({type:"subscribe",deviceIds:[n]})),q())}),k.addEventListener("message",z=>{if(typeof z.data=="string")return;const se=z.data instanceof ArrayBuffer?z.data:null;if(!se||se.byteLength<5)return;const W=performance.now();M.lastPacketAt=W,(async()=>{try{const le=new DataView(se).getUint32(0,!1);if(le<=0||le+4>se.byteLength){Y();return}const ce=new Uint8Array(se,4,le),K=JSON.parse(Rp.decode(ce)),be=se.slice(4+le),he=String(K.frameKind||K.kind||"").toLowerCase();if(K.type==="remote.audio.status"||he==="audio-status"){if(M.lastCaptureStatusAt=W,M.captureAlive=K.captureAlive===!0,M.helperAlive=K.helperAlive===!0,M.captureRestartCount=Math.max(0,Number(K.restartCount||0)||0),M.lastPcmAtEpochMs=Math.max(0,Number(K.lastPcmAtEpochMs||0)||0),M.silentForMs=Math.max(0,Number(K.silentForMs||0)||0),M.captureAgeMs=M.lastPcmAtEpochMs>0?Math.max(0,Date.now()-M.lastPcmAtEpochMs):M.silentForMs,M.captureAlive&&M.helperAlive){if($=0,G=0,!F){w("");const ee=String(j.state)==="running",we=M.lastAcceptedAt>0&&performance.now()-M.lastAcceptedAt<=tf;m(ee?we?"playing":"silent":"suspended")}}else F||m("stalled");return}const fe={deviceId:String(K.deviceId||""),frameSeq:Number(K.frameSeq||0),streamId:String(K.streamId||""),mimeType:String(K.mimeType||"audio/webm;codecs=opus"),sampleRate:Number(K.sampleRate||48e3),channels:Number(K.channels||2),capturedAt:String(K.capturedAt||""),receivedAt:String(K.receivedAt||""),byteLength:Number(K.byteLength||be.byteLength),payload:be};if(!fe.deviceId||T)return;if(performance.now()-W>Uy){Y();return}if(M.pendingDecodes>=W1){Y();return}M.pendingDecodes+=1;try{const ee=U1(fe.mimeType)?Q1(j,fe,be):await j.decodeAudioData(be.slice(0));if(M.localProcessingAgeMs=Math.max(0,performance.now()-W),T)return;if(M.localProcessingAgeMs>Uy){Y();return}if(fe.frameSeq>0&&fe.frameSeq<=M.lastFrameSeq){Y();return}if(M.activeStreamId&&fe.streamId!==M.activeStreamId&&fe.frameSeq<=M.lastFrameSeq){Y();return}fe.streamId&&fe.streamId!==M.activeStreamId&&(M.activeStreamId=fe.streamId,M.lastFrameSeq=0,L());const we=j.currentTime;Math.max(0,c.current-we)>G1&&(L(),M.resyncs+=1);const He=j.createBufferSource();He.buffer=ee,He.connect(j.destination),N.add(He),He.onended=()=>{N.delete(He),He.onended=null};const ne=Math.max(j.currentTime+V1,c.current);He.start(ne),c.current=ne+ee.duration,M.browserAgeMs=qy(fe.receivedAt),M.captureAgeMs=qy(fe.capturedAt),M.lastAcceptedAt=performance.now(),M.framesReceived+=1,M.lastFrameSeq=fe.frameSeq,$=0,G=0,g(fe),q();const qe=String(j.state)==="running";qe&&w(""),m(qe?"playing":"suspended")}finally{M.pendingDecodes=Math.max(0,M.pendingDecodes-1)}}catch(O){T||(m("error"),w(O instanceof Error?O.message:String(O)))}})()}),k.addEventListener("error",()=>{T||(m("error"),w("Remote audio WebSocket error."))}),k.addEventListener("close",()=>{T||m("closed")}),()=>{T=!0,window.clearInterval(H),j.removeEventListener("statechange",ye),document.removeEventListener("visibilitychange",de),window.removeEventListener("pageshow",Z),window.removeEventListener("pointerdown",Z),window.removeEventListener("keydown",Z),L(!1),k.close(),j.close().catch(()=>{}),l.current===j&&(l.current=null)}},[n,a,i]),{state:d,lastFrame:h,stats:y,error:b}}const Z1=3;function Gy(n,a,i){const l=Math.max(1,Number(i)||1),c=Math.max(0,Math.min(l,Number(n)-Number(a))),d=Math.min(l/2,Z1);return c<=d?0:c>=l-d?1:c/l}function J1(n,a,i){return{normalizedX:Gy(n,i.left,i.width),normalizedY:Gy(a,i.top,i.height)}}const _f=Object.freeze({shiftKey:Object.freeze(["ShiftLeft","ShiftRight"]),ctrlKey:Object.freeze(["ControlLeft","ControlRight"]),altKey:Object.freeze(["AltLeft","AltRight"]),metaKey:Object.freeze(["MetaLeft","MetaRight"])}),ek=Object.freeze({shiftKey:"ShiftLeft",ctrlKey:"ControlLeft",altKey:"AltLeft",metaKey:"MetaLeft"}),cp=64;function yc(n,a=80){return String(n||"").replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,a)}function Wx(n={}){const a=yc(n.key),i=Number.isFinite(Number(n.location))?Math.max(0,Math.min(3,Math.trunc(Number(n.location)))):0;return a?`Key:${i}:${a}`.slice(0,80):""}function Vy(n){for(const[a,i]of Object.entries(_f))if(i.includes(n))return a;return""}function Ru(n,a){return _f[a].some(i=>n.has(i))}function Wy(n,a,i={}){for(const l of Object.keys(_f)){const c=i[l]===!0,d=_f[l];if(c){!Ru(n,l)&&n.size<cp&&n.add(ek[l]);continue}for(const m of d)a.has(m)||n.delete(m)}}function up(n){return{shiftKey:Ru(n,"shiftKey"),ctrlKey:Ru(n,"ctrlKey"),altKey:Ru(n,"altKey"),metaKey:Ru(n,"metaKey")}}function tk(n={},a={}){return{shiftKey:n.shiftKey===!0||a.shiftKey===!0,ctrlKey:n.ctrlKey===!0||a.ctrlKey===!0,altKey:n.altKey===!0||a.altKey===!0,metaKey:n.metaKey===!0||a.metaKey===!0}}function nk(n,a,i){const l=yc(n.code)||Wx(n),c=yc(n.key),d=Number(n.keyCode??n.which),m=Number(n.location);return{type:a,key:c,code:l,keyCode:Number.isFinite(d)?Math.max(0,Math.min(65535,Math.trunc(d))):0,location:Number.isFinite(m)?Math.max(0,Math.min(255,Math.trunc(m))):0,text:c.length===1?c:"",repeat:a==="keydown"&&n.repeat===!0,pressedCodes:[...i],...up(i)}}function ak(){const n=new Set,a=new Set;return{event(i={},l=""){if(l!=="keydown"&&l!=="keyup")return null;const c=yc(i.code)||Wx(i);if(!c)return null;const d=Vy(c),m=n.has(c);return d?(l==="keydown"?n.size<cp&&n.add(c):a.has(c)||n.delete(c),Wy(n,a,i)):(Wy(n,a,i),l==="keydown"?n.size<cp&&n.add(c):n.delete(c)),l==="keydown"&&m&&i.repeat!==!0?null:nk(i,l,n)},modifier(i,l){const c=yc(i),d=Vy(c);if(!d)return null;const m=a.has(c);return l===m?null:(l?(a.add(c),n.add(c)):(a.delete(c),n.delete(c)),{type:l?"keydown":"keyup",key:d==="metaKey"?"Meta":d==="ctrlKey"?"Control":d==="altKey"?"Alt":"Shift",code:c,keyCode:0,location:c.endsWith("Right")?2:1,text:"",repeat:!1,pressedCodes:[...n],...up(n)})},reset(i="keyboard-owner-reset",l=!1){const c=n.size>0;return n.clear(),a.clear(),!c&&!l?null:{type:"keyboard.reset",reason:yc(i,120)||"keyboard-owner-reset",pressedCodes:[],shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1,repeat:!1}},snapshot(){return{pressedCodes:[...n],latchedCodes:[...a],...up(n)}}}}function kc(n){const a=Number(n);return Number.isSafeInteger(a)&&a>0?a:0}function Jn(n){return String(n||"").trim()}function af(n,a,i={}){return{deviceId:Jn(n),transitionGeneration:kc(a),sessionId:Jn(i.sessionId),streamId:Jn(i.streamId),commandId:Jn(i.commandId),captureGeneration:kc(i.captureGeneration),monitorIndex:Math.max(0,Math.floor(Number(i.monitorIndex)||0))}}function gs(n,a){return!!n&&!!a&&Jn(n.deviceId)===Jn(a.deviceId)&&kc(n.transitionGeneration)===kc(a.transitionGeneration)}function Yy(n,a){const i=Promise.resolve(n).catch(()=>{}).then(a);return{result:i,tail:i.then(()=>{},()=>{})}}function sf(n,a,i){const l=Jn(n);return!l||!a||Jn(a.deviceId)!==l?!1:!i||Jn(i.deviceId)!==l}function Ky(n,a){if(!n||!a)return!1;const i=kc(a.captureGeneration),l=Jn(a.commandId),c=Jn(a.sessionId),d=Jn(a.streamId),m=Number(n.monitorIndex);return!i||!l||!c||!d||!Number.isInteger(m)||m<0?!1:Jn(n.deviceId)===Jn(a.deviceId)&&Jn(n.sessionId)===c&&Jn(n.streamId)===d&&Jn(n.commandId)===l&&kc(n.captureGeneration)===i&&Jn(n.streamPurpose).toLowerCase()==="control"&&m===a.monitorIndex}const bs=Object.freeze({automaticDirectH264:!0,interactiveDirectFps:30,directFullFpsDeviceLimit:6,directMinAdaptiveFps:8,controlWallReuseMaxFps:30,scalableAtlasMinInputFps:8,scalableAtlasMaxInputFps:20,scalableAtlasAggregateInputFps:120,atlasOutputFps:20,maxDirectFramesPerSecond:180,directDecodeAcceleration:"prefer-hardware",directLatencyMode:"interactive"});function sk(n,a){const i=Math.max(0,Math.floor(Number(a)||0));return n===!0&&i>0}function Mu({mode4Enabled:n,directMode4WallEnabled:a,isMac:i}){return"direct"}function rk({mode4Enabled:n,directMode4WallEnabled:a,adaptiveFps:i,directDeviceCount:l,adaptive:c=!0}){const d=Math.max(1,Math.floor(Number(i)||1));if(!c)return d;const m=Math.max(1,Math.floor(Number(l)||1));return m<=bs.directFullFpsDeviceLimit?d:Math.max(bs.directMinAdaptiveFps,Math.min(d,Math.floor(bs.maxDirectFramesPerSecond/m)))}function ik({deviceCount:n,targetFps:a,adaptive:i=!0}){const l=Math.max(1,Math.floor(Number(n)||1)),c=Math.max(1,Math.min(bs.scalableAtlasMaxInputFps,Math.floor(Number(a)||bs.scalableAtlasMaxInputFps)));if(!i)return c;const d=Math.max(bs.scalableAtlasMinInputFps,Math.min(bs.scalableAtlasMaxInputFps,Math.floor(bs.scalableAtlasAggregateInputFps/l)));return Math.min(c,d)}function lk(n,a){return{acceleration:bs.directDecodeAcceleration,latencyMode:bs.directLatencyMode}}const lo={revision:0,settings:{security:{accessMode:"trusted-only"},control:{allowKeyboardMouse:!0},filesAudio:{allowFileTransfer:!0,allowRemoteAudio:!0,rollingBufferEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0}}},ok=[{id:"connection",label:"Connection",icon:$f},{id:"remote-access",label:"Remote Access",icon:Wn},{id:"capture-audio",label:"Capture & Audio",icon:Kh},{id:"agent",label:"Agent",icon:yl}];function jf(n,a){return n?.settings?.[a]||lo.settings[a]||{}}function Qy(n,a){return{...n,settings:{...n.settings,[a.section]:{...jf(n,a.section),[a.key]:a.value}}}}function Mh(n){return{revision:Number(n.revision||0),updatedAt:n.updatedAt,settings:n.settings}}function fc({icon:n,title:a,description:i,children:l,recommended:c=!1}){return r.jsxs("div",{className:"product-setting-row",children:[r.jsx("div",{className:"product-setting-control",children:l}),n&&r.jsx("span",{className:"product-setting-icon",children:r.jsx(n,{size:17})}),r.jsxs("div",{className:"product-setting-copy",children:[r.jsx("strong",{children:a}),c&&r.jsx("em",{children:"Recommended"}),r.jsx("small",{children:i})]})]})}function rf({checked:n,onChange:a,label:i}){return r.jsxs("label",{className:"product-switch",children:[r.jsx("input",{"aria-label":i,type:"checkbox",checked:n,onChange:l=>a(l.target.checked)}),r.jsx("span",{})]})}function Xy({value:n,onChange:a,options:i,label:l}){return r.jsx("select",{"aria-label":l,value:String(n),onChange:c=>a(c.target.value),children:i.map(([c,d])=>r.jsx("option",{value:c,children:d},c))})}function ck({hubUrl:n="",runtimeRole:a="hub",runtimeDeviceId:i="",sessionAccessToken:l="",initialTab:c="connection",pin:d,agent:m,captureGallery:h}){const[g,y]=u.useState(c),[x,b]=u.useState(null),[w,A]=u.useState("loading"),[j,k]=u.useState(""),[N,M]=u.useState("idle"),[T,D]=u.useState(""),F=u.useRef(null),$=u.useRef(null),G=u.useRef([]),L=u.useRef(Promise.resolve()),Q=u.useRef(0),q=u.useRef(0);u.useEffect(()=>{const ce=++q.current;let K=!0;return G.current=[],$.current=null,F.current=null,L.current=Promise.resolve(),A("loading"),Ve("/api/settings",void 0,n).then(be=>{if(!K||ce!==q.current)return;const he=Mh(be);$.current=he,F.current=he,b(he),A("saved")}).catch(be=>{!K||ce!==q.current||(k(be instanceof Error?be.message:String(be)),$.current=lo,F.current=lo,b(lo),A("failed"))}),()=>{K=!1}},[n]);const P=async(ce,K,be)=>{const he={id:++Q.current,section:ce,key:K,value:be},fe=q.current;G.current.push(he);const ee=Qy(F.current||$.current||lo,he);F.current=ee,b(ee),A("saving"),k(""),L.current=L.current.then(async()=>{if(fe!==q.current)return;let we=null,Me=null;for(let qe=0;qe<2&&!we;qe+=1){const mt=$.current||lo;try{const J=await Ve("/api/settings",{method:"PATCH",body:JSON.stringify({revision:mt.revision,[he.section]:{[he.key]:he.value}})},n);we=Mh(J)}catch(J){if(Me=J,qe!==0||!String(J instanceof Error?J.message:J).startsWith("409 "))break;try{const Ce=await Ve("/api/settings",void 0,n);if(fe!==q.current)return;$.current=Mh(Ce)}catch(Ce){Me=Ce;break}}}if(fe!==q.current)return;G.current=G.current.filter(qe=>qe.id!==he.id),we&&($.current=we);const He=$.current||lo,ne=G.current.reduce(Qy,He);F.current=ne,b(ne),we?(k(""),A(G.current.length>0?"saving":"saved")):(A(G.current.length>0?"saving":"failed"),k(Me instanceof Error?Me.message:String(Me||"Settings could not be saved.")))}),await L.current},Y=(ce,K)=>be=>{P(ce,K,be)},H=async()=>{if(a!=="hub"||!i||!l){M("failed"),D("Sign in to this Hub before changing its runtime role.");return}M("changing"),D("");try{const ce=await Ve("/api/runtime/status",void 0,n);await Ve("/api/runtime/role",{method:"POST",headers:{Authorization:`Bearer ${l}`},body:JSON.stringify({role:"client"})},n),M("accepted"),await Sx({baseUrl:n,targetRole:"client",previousRuntimePid:Number(ce.runtimePid||0),allowedStates:["running","waiting-auth"]}),IC(5179)}catch(ce){M("failed"),D(ce instanceof Error?ce.message:String(ce))}},ye=jf(x,"security"),de=jf(x,"control"),Z=jf(x,"filesAudio"),z=`settings-panel-${g}`,se=r.jsxs("div",{className:"settings-tab-content product-settings-content",children:[d,r.jsxs("section",{className:"settings-section-card runtime-role-settings",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Runtime role"}),r.jsx("h3",{children:"Use this computer as a Client"})]}),r.jsx(mx,{size:20})]}),r.jsx("p",{className:"settings-help",children:"Stop hosting from this computer and reconnect it to the selected Hub."}),N==="accepted"?r.jsx("p",{className:"settings-help runtime-role-success",children:"LiveDesk is restarting as Client."}):T?r.jsx("p",{className:"settings-help runtime-role-error",role:"alert",children:T}):null,r.jsx("button",{className:"settings-reset",onClick:()=>{H()},disabled:N==="changing"||a!=="hub",type:"button",children:N==="changing"?"Switching role...":"Switch this computer to Client"})]})]}),W=r.jsxs("div",{className:"settings-tab-content product-settings-content",children:[r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Remote access"}),r.jsx("h3",{children:"Who may connect?"})]}),r.jsx(Ti,{size:20})]}),r.jsx(fc,{icon:Wn,title:"Access mode",description:"Choose the default permission boundary for remote sessions.",recommended:!0,children:r.jsx(Xy,{value:String(ye.accessMode),onChange:Y("security","accessMode"),label:"Access mode",options:[["trusted-only","Trusted devices only"],["block-remote-access","Block remote access"]]})})]}),r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Session permissions"}),r.jsx("h3",{children:"What may remote users do?"})]}),r.jsx(Ta,{size:20})]}),r.jsx(fc,{icon:Ta,title:"Keyboard and mouse control",description:"Allow Control to send keyboard and pointer input.",recommended:!0,children:r.jsx(rf,{checked:!!de.allowKeyboardMouse,onChange:Y("control","allowKeyboardMouse"),label:"Keyboard and mouse control"})}),r.jsx(fc,{icon:Kh,title:"File transfer",description:"Allow files to be delivered to connected computers.",children:r.jsx(rf,{checked:!!Z.allowFileTransfer,onChange:Y("filesAudio","allowFileTransfer"),label:"File transfer"})}),r.jsx(fc,{icon:ho,title:"Remote audio",description:"Allow sound capture from connected computers.",children:r.jsx(rf,{checked:!!Z.allowRemoteAudio,onChange:Y("filesAudio","allowRemoteAudio"),label:"Remote audio"})})]})]}),O=r.jsxs("div",{className:"settings-tab-content product-settings-content",children:[r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Capture"}),r.jsx("h3",{children:"Recording defaults"})]}),r.jsx(Kh,{size:20})]}),r.jsx(fc,{icon:ho,title:"Keep a Last 30s buffer",description:"Keep recent video in memory until you explicitly save it.",children:r.jsx(rf,{checked:!!Z.rollingBufferEnabled,onChange:Y("filesAudio","rollingBufferEnabled"),label:"Keep a Last 30s buffer"})}),r.jsx(fc,{icon:ho,title:"Timelapse interval",description:"Choose how often a timelapse frame is captured.",children:r.jsx(Xy,{value:Number(Z.timelapseIntervalSeconds),onChange:ce=>Y("filesAudio","timelapseIntervalSeconds")(Number(ce)),label:"Timelapse interval",options:[["5","5 seconds"],["10","10 seconds"],["30","30 seconds"],["60","60 seconds"]]})})]}),h]}),le=g==="connection"?se:g==="remote-access"?W:g==="capture-audio"?O:m;return r.jsxs("section",{className:"settings-page",children:[r.jsx("div",{className:"settings-page-tabs",role:"tablist","aria-label":"LiveDesk settings",children:ok.map(({id:ce,label:K,icon:be})=>r.jsxs("button",{className:g===ce?"active":"",id:`settings-tab-${ce}`,role:"tab","aria-selected":g===ce,"aria-controls":`settings-panel-${ce}`,tabIndex:g===ce?0:-1,onClick:()=>y(ce),type:"button",children:[r.jsx(be,{size:16}),K]},ce))}),w==="saving"&&r.jsx("div",{className:"product-save-state",role:"status",children:"Saving settings..."}),j&&r.jsx("div",{className:"agent-settings-alert error",role:"alert",children:j}),r.jsx("section",{className:"settings-page-panel",id:z,role:"tabpanel","aria-labelledby":`settings-tab-${g}`,tabIndex:0,children:le})]})}function uk({children:n}){return r.jsx("div",{className:"settings-tab-content",children:n})}const dp={enabled:!1,provider:"codex",codexModelId:"",codexReasoningEffort:"medium",codexTaskTimeoutMs:6e5,codexMaxToolCalls:20,codexWorkingDirectory:"",codexResumeSessions:!0,codexShowDetailedEvents:!0,deterministicParserFirst:!0,generateSummary:!0,fallbackSummary:!0,includeRawDeviceDetails:!1,baseUrl:"https://opencode.ai/zen/go/v1",defaultModelId:"deepseek-v4-flash"};function Zy(n){return{...dp,...n||{}}}async function dk(n,a,i){let l=null;for(let c=0;c<2;c+=1){const d=await Ve("/api/settings",{signal:i},a);if(d.settings.agent?.enabled===n)return;try{await Ve("/api/settings",{method:"PATCH",signal:i,body:JSON.stringify({revision:d.revision,agent:{enabled:n}})},a);return}catch(m){if(l=m,c!==0||!String(m instanceof Error?m.message:m).startsWith("409 "))throw m}}throw l}function fk({hubUrl:n}){const[a,i]=u.useState(dp),[l,c]=u.useState(null),[d,m]=u.useState(""),[h,g]=u.useState(""),[y,x]=u.useState(""),[b,w]=u.useState(""),A=u.useRef(0),j=u.useRef(null);u.useEffect(()=>{let q=!0;j.current?.abort();const P=new AbortController;j.current=P;const Y=++A.current;return c(null),i(dp),m(""),g(""),w(""),x(""),Ve("/api/settings/agent",{signal:P.signal},n).then(H=>{!q||P.signal.aborted||Y!==A.current||(c(H.settings),i(Zy(H.settings)))}).catch(H=>{q&&!P.signal.aborted&&Y===A.current&&w(H instanceof Error?H.message:String(H))}),()=>{q=!1,P.abort(),j.current===P&&(j.current=null)}},[n]);const k=(q,P)=>i(Y=>({...Y,[q]:P})),N=q=>{c(q),i(Zy(q))},M=()=>({generation:A.current,controller:j.current}),T=q=>q.generation===A.current&&q.controller!==null&&q.controller===j.current&&!q.controller.signal.aborted,D=async()=>{if(!l){w("Agent settings are not available yet.");return}const q=M();if(T(q)){g("save"),w(""),x("");try{if(await dk(a.enabled,n,q.controller.signal),!T(q))return;const{enabled:P,...Y}=a,H={...Y};d.trim()&&(H.apiKey=d.trim());const ye=await Ve("/api/settings/agent",{method:"PUT",signal:q.controller.signal,body:JSON.stringify(H)},n);if(!T(q))return;N(ye.settings),m(""),x("Agent settings saved.")}catch(P){T(q)&&w(P instanceof Error?P.message:String(P))}finally{T(q)&&g("")}}},F=async()=>{const q=M();if(T(q)){g("reset"),w("");try{const P=await Ve("/api/settings/agent/reset",{method:"POST",signal:q.controller.signal,body:JSON.stringify({})},n);if(!T(q))return;N(P.settings),x("Codex defaults restored.")}catch(P){T(q)&&w(P instanceof Error?P.message:String(P))}finally{T(q)&&g("")}}},$=async()=>{const q=M();if(T(q)){g("test"),w(""),x("");try{const P=await Ve("/api/settings/agent/test",{method:"POST",signal:q.controller.signal,body:JSON.stringify({})},n);if(!T(q))return;const Y=await Ve("/api/settings/agent",{signal:q.controller.signal},n);if(!T(q))return;N(Y.settings),x(`Codex connection verified with ${P.connection?.modelName||"the configured model"}${P.connection?.latencyMs?` in ${P.connection.latencyMs} ms.`:"."}`)}catch(P){T(q)&&w(P instanceof Error?P.message:String(P))}finally{T(q)&&g("")}}},G=async()=>{const q=M();if(T(q)){g("clear-key"),w("");try{const P=await Ve("/api/settings/agent/api-key",{method:"DELETE",signal:q.controller.signal},n);if(!T(q))return;N(P.settings),m(""),x("The optional OpenCode Go key was removed.")}catch(P){T(q)&&w(P instanceof Error?P.message:String(P))}finally{T(q)&&g("")}}},L=l?.codexInstallation==="installed"&&l.codexAuth==="signed-in",Q=l!==null;return r.jsxs("div",{className:"settings-tab-content agent-settings-content",children:[r.jsx("section",{className:"settings-section-card agent-enable-card",children:r.jsxs("label",{className:"settings-toggle agent-enable-toggle",children:[r.jsx("input",{type:"checkbox",checked:a.enabled,onChange:q=>k("enabled",q.target.checked),disabled:!Q||h!==""}),r.jsx("span",{children:"Enable Agent AI"})]})}),b&&r.jsx("div",{className:"agent-settings-alert error",role:"alert",children:b}),y&&r.jsx("div",{className:"agent-settings-alert success",role:"status",children:y}),r.jsxs("div",{className:"settings-section-grid",children:[r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Provider"}),r.jsx("h3",{children:"Choose the AI service"})]}),r.jsx(Wn,{size:20})]}),r.jsxs("label",{className:"settings-field",children:[r.jsx("span",{children:"Agent provider"}),r.jsxs("select",{value:a.provider,onChange:q=>k("provider",q.target.value),children:[r.jsx("option",{value:"codex",children:"Codex SDK"}),r.jsx("option",{value:"opencode-go",children:"OpenCode Go"})]})]}),a.provider==="codex"&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"agent-connection-row",children:[r.jsx("span",{className:`agent-connection-dot ${L?"connected":l?.codexAuth==="not-signed-in"?"unavailable":""}`}),r.jsx("span",{children:l?.codexInstallation==="not-installed"?"Codex SDK not installed":l?.codexAuth==="signed-in"?"Codex CLI signed in":l?.codexAuth==="not-signed-in"?"Codex CLI sign-in required":"Codex status not tested"}),r.jsxs("button",{className:"settings-reset",onClick:()=>{$()},disabled:h!=="",type:"button",children:[r.jsx(g0,{size:15})," ",h==="test"?"Testing":"Test connection"]})]}),r.jsxs("p",{className:"settings-help",children:[r.jsx(v0,{size:12})," Authentication uses the installed Codex CLI."]})]})]}),a.provider==="codex"?r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Codex"}),r.jsx("h3",{children:"Model and reasoning"})]}),r.jsx(y0,{size:20})]}),r.jsxs("label",{className:"settings-field",children:[r.jsx("span",{children:"Model"}),r.jsx("input",{value:a.codexModelId,onChange:q=>k("codexModelId",q.target.value),placeholder:"Codex default"})]}),r.jsxs("label",{className:"settings-field",children:[r.jsx("span",{children:"Reasoning effort"}),r.jsxs("select",{value:a.codexReasoningEffort,onChange:q=>k("codexReasoningEffort",q.target.value),children:[r.jsx("option",{value:"minimal",children:"Minimal"}),r.jsx("option",{value:"low",children:"Low"}),r.jsx("option",{value:"medium",children:"Medium"}),r.jsx("option",{value:"high",children:"High"}),r.jsx("option",{value:"xhigh",children:"Extra high"})]})]})]}):r.jsxs("section",{className:"settings-section-card agent-legacy-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"OpenCode Go"}),r.jsx("h3",{children:"Connection"})]}),r.jsx(fx,{size:20})]}),r.jsxs("label",{className:"settings-field",children:[r.jsx("span",{children:"Base URL"}),r.jsx("input",{value:a.baseUrl,onChange:q=>k("baseUrl",q.target.value)})]}),r.jsxs("label",{className:"settings-field",children:[r.jsx("span",{children:"API key"}),r.jsx("input",{type:"password",value:d,onChange:q=>m(q.target.value),placeholder:l?.hasApiKey?l.apiKeyPreview:"Stored only in the Hub",autoComplete:"new-password"})]}),r.jsxs("button",{className:"settings-reset",onClick:()=>{G()},disabled:h!==""||!l?.hasApiKey,type:"button",children:[r.jsx(Sp,{size:15})," Clear key"]})]})]}),r.jsxs("div",{className:"settings-action-row agent-settings-actions",children:[r.jsxs("button",{className:"settings-reset",onClick:()=>{F()},disabled:h!=="",type:"button",children:[r.jsx(Cp,{size:15})," Reset defaults"]}),r.jsxs("button",{className:"text-button primary",onClick:()=>{D()},disabled:!Q||h!=="",type:"button",children:[r.jsx(b0,{size:15})," ",h==="save"?"Saving":"Save Agent settings"]})]})]})}new Date().valueOf();function Or(n){const[a,i]=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,i(n)}},[n]),[a,i]}function Ep(n,a){return typeof n=="function"?typeof a=="object"?n(a):n():n}function jc(n,a="data-id"){let i=n;for(!i.tagName&&n.target&&(i=n.target);i;){if(i.getAttribute&&i.getAttribute(a))return i;i=i.parentNode}return null}function mk(n,a="data-id"){const i=jc(n,a);return i?i.getAttribute(a):null}function Vu(n,a="data-id"){const i=jc(n,a);return i?qf(i,a):null}function qf(n,a="data-id"){const i=n.getAttribute(a);return i?hk(i):null}function ea(n){return typeof n=="string"?":"+n:n}function hk(n){if(n.startsWith(":"))return n.substring(1);const a=n*1;return isNaN(a)?n:a}function pk(){return{detect:()=>!0,addEvent:function(n,a,i){return n.addEventListener(a,i),()=>n.removeEventListener(a,i)},addGlobalEvent:function(n,a){return document.addEventListener(n,a),()=>document.removeEventListener(n,a)},getTopNode:function(){return window.document.body}}}var ls=pk();function Dp(n){Object.assign(ls,n)}function Jy(n,a,i){function l(c){const d=jc(c);if(!d)return;const m=qf(d);if(typeof a=="function")return a(m,c);let h,g=c.target;for(;g!=d;){if(h=g.dataset?g.dataset.action:null,h&&a[h]){a[h](m,c);return}g=g.parentNode}a[i]&&a[i](m,c)}ls.addEvent(n,i,l)}function Ac(n,a){Jy(n,a,"click"),a.dblclick&&Jy(n,a.dblclick,"dblclick")}function gk(n,a){for(let i=n.length-1;i>=0;i--)if(n[i]===a){n.splice(i,1);break}}function vk(n,a,i){for(let l=0;l<Ri.length;l++){if(l===i)continue;const c=Ri[l],d=c.props.parent?.();if(d&&n.contains(d)&&c.node.contains(a))return!0}return!1}var Yx=new Date,If=!1,lf=[],Ri=[],eb=n=>{const a=n.target;if(If||!a.isConnected){If=!1;return}for(let i=Ri.length-1;i>=0;i--){const{node:l,date:c,props:d}=Ri[i];if(!(c>Yx)&&!l.contains(a)&&l!==a&&(vk(l,a,i)||(d.callback&&d.callback(n),d.modal||n.defaultPrevented)))break}},yk=n=>{Yx=new Date,If=!0;for(let a=Ri.length-1;a>=0;a--){const{node:i}=Ri[a];if(!i.contains(n.target)&&i!==n.target){If=!1;break}}};function Hr(n,a){lf.length||(lf=[ls.addGlobalEvent("click",eb,n),ls.addGlobalEvent("contextmenu",eb,n),ls.addGlobalEvent("mousedown",yk,n)]),typeof a!="object"&&(a={callback:a});const i={node:n,date:new Date,props:a};return Ri.push(i),{destroy(){gk(Ri,i),Ri.length||(lf.forEach(l=>l()),lf=[])}}}var of=n=>n.indexOf("bottom")!==-1,cf=n=>n.indexOf("left")!==-1,uf=n=>n.indexOf("right")!==-1,Nh=n=>n.indexOf("top")!==-1,tb=n=>n.indexOf("fit")!==-1,Nu=n=>n.indexOf("overlap")!==-1,bk=n=>n.split("-").every(a=>["center","fit"].indexOf(a)>-1),xk=n=>{const a=n.match(/(start|center|end)/);return a?a[0]:null};function wk(n,a){let i=0;const l=ls.getTopNode(n);for(;n&&n!==l;){const c=getComputedStyle(n).position;if((c==="absolute"||c==="relative"||c==="fixed")&&(i=parseInt(getComputedStyle(n).zIndex)||0),n=n.parentNode,n===a)break}return i}var In,ka,Tu,ma;function Kx(n,a,i="bottom",l=0,c=0){if(!n)return null;In=l,ka=c,Tu="auto";let d=0,m=0,h=i;const g=Qx(n),y=Nu(i)?ls.getTopNode(n):g;if(!g)return null;const x=g.getBoundingClientRect(),b=n.getBoundingClientRect(),w=y.getBoundingClientRect(),A=window.getComputedStyle(y),j={left:0,top:0,bottom:0,right:0};for(const F in j){const $=`border-${F}-width`;j[F]=parseFloat(A.getPropertyValue($))}if(a){const F=wk(a,g);d=Math.max(F+1,20)}if(a){if(ma=a.getBoundingClientRect(),tb(i)&&(Tu=ma.width+"px"),i!=="point")if(bk(i))tb(i)?In=0:(In=w.width/2,m=1),ka=(w.height-b.height)/2;else{const F=Nu(i)?0:1;In=uf(i)?ma.right+F:ma.left-F,ka=of(i)?ma.bottom+1:ma.top;const $=xk(i);$&&(uf(i)||cf(i)?$==="center"?ka-=(b.height-ma.height)/2:$==="end"&&(ka-=b.height-ma.height):(of(i)||Nh(i))&&($==="center"?In-=(b.width-ma.width)/2:$==="end"&&(In-=b.width-ma.width),Nu(i)||(In+=1)))}}else ma={left:l,right:l,top:c,bottom:c};const k=(cf(i)||uf(i))&&(of(i)||Nh(i));cf(i)&&(m=2);const N=In-b.width-w.left;a&&cf(i)&&!k&&N<0&&(In=ma.right,m=0,h=h.replace("left","right"));const M=In+b.width*(1-m/2)-w.right;if(M>0)if(!uf(i))In=w.right-j.right-b.width;else{const F=ma.left-w.x-b.width;a&&!k&&F>=0?(In=ma.left-b.width,h=h.replace("right","left")):In-=M+j.right}m&&(In=Math.round(In-b.width*m/2));const T=N<0||M>0||!k;Nh(i)&&(ka=ma.top-b.height,a&&ka<w.y&&T&&(ka=ma.bottom,h=h.replace("top","bottom")));const D=ka+b.height-w.bottom;return D>0&&(a&&of(i)&&T?(ka-=b.height+ma.height+1,h=h.replace("bottom","top")):ka-=D+j.bottom),In-=x.left+j.left,ka-=x.top+j.top,In=(Nu(i)?In:Math.max(In,0))+y.scrollLeft,ka=(Nu(i)?ka:Math.max(ka,0))+y.scrollTop,Tu=Tu||"auto",{at:h,x:In,y:ka,z:d,width:Tu}}function Qx(n){const a=ls.getTopNode(n);for(n&&(n=n.parentElement);n;){const i=getComputedStyle(n).position;if(n===a||i==="relative"||i==="absolute"||i==="fixed")return n;n=n.parentNode}return null}function Sk(n){const a=[];let i=n;const l=ls.getTopNode(n);for(;i&&i!==l&&!i.getAttribute("data-wx-portal-root");)getComputedStyle(i).position==="absolute"&&a.push(i),i=i.parentNode;return a}var nb=new Date().valueOf();function Lp(){return nb+=1,nb}function Aa(n){return n<10?"0"+n:n.toString()}function Ck(n){const a=Aa(n);return a.length==2?"0"+a:a}function Xx(n){const a=Math.floor(n/11)*11;return{start:a,end:a+11}}function Th(n){const a=(n.getDay()+6)%7,i=new Date(n.valueOf());i.setDate(n.getDate()+(3-a)),i.setHours(0,0,0,0);const l=new Date(i.getFullYear(),0,1),c=Math.round((i.getTime()-l.getTime())/864e5);return 1+Math.floor(c/7)}var ab=["",""];function kk(n,a,i){switch(n){case"%d":return Aa(a.getDate());case"%m":return Aa(a.getMonth()+1);case"%j":return a.getDate();case"%n":return a.getMonth()+1;case"%y":return Aa(a.getFullYear()%100);case"%Y":return a.getFullYear();case"%D":return i.dayShort[a.getDay()];case"%l":return i.dayFull[a.getDay()];case"%M":return i.monthShort[a.getMonth()];case"%F":return i.monthFull[a.getMonth()];case"%h":return Aa((a.getHours()+11)%12+1);case"%g":return(a.getHours()+11)%12+1;case"%G":return a.getHours();case"%H":return Aa(a.getHours());case"%i":return Aa(a.getMinutes());case"%a":return((a.getHours()>11?i.pm:i.am)||ab)[0];case"%A":return((a.getHours()>11?i.pm:i.am)||ab)[1];case"%s":return Aa(a.getSeconds());case"%S":return Ck(a.getMilliseconds());case"%W":return Aa(Th(a));case"%w":{const l=i.weekStart??1;if(l===1)return Aa(Th(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)),Aa(Th(m))}case"%c":{let l=a.getFullYear()+"";return l+="-"+Aa(a.getMonth()+1),l+="-"+Aa(a.getDate()),l+="T",l+=Aa(a.getHours()),l+=":"+Aa(a.getMinutes()),l+=":"+Aa(a.getSeconds()),l}case"%Q":return Math.floor(a.getMonth()/3)+1;default:return n}}var jk=/%[a-zA-Z]/g;function bc(n,a){return typeof n=="function"?n:function(i){return i?(i.getMonth||(i=new Date(i)),n.replace(jk,l=>kk(l,i,a))):""}}function sb(n){return n&&typeof n=="object"&&!Array.isArray(n)}function fp(n,a){for(const i in a){const l=a[i];sb(n[i])&&sb(l)?n[i]=fp({...n[i]},a[i]):n[i]=a[i]}return n}function Yu(n){return{getGroup(a){const i=n[a];return l=>i&&i[l]||l},getRaw(){return n},extend(a,i){if(!a)return this;let l;return i?l=fp({...a},n):l=fp({...n},a),Yu(l)}}}var Ak=bx();const Mk="en-US",Nk={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},Tk={ok:"OK",cancel:"Cancel",select:"Select","No data":"No data","Rows per page":"Rows per page","Total pages":"Total pages"},Rk={timeFormat:"%H:%i",dateFormat:"%m/%d/%Y",monthYearFormat:"%F %Y",yearFormat:"%Y"},Zx={core:Tk,calendar:Nk,formats:Rk,lang:Mk},_p=u.createContext(""),Jx=u.createContext({}),gr=u.createContext(null),ew=u.createContext(null),na=Object.freeze(Object.defineProperty({__proto__:null,fieldId:ew,helpers:Jx,i18n:gr,theme:_p},Symbol.toStringTag,{value:"Module"}));function tw(n){const a=u.useContext(ew),[i]=u.useState(()=>n||a||Lp());return i}function Fu({type:n="",css:a="",icon:i="",disabled:l=!1,title:c="",tooltip:d,text:m="",children:h,onClick:g}){const y=u.useMemo(()=>{let b=n?n.split(" ").filter(w=>w!=="").map(w=>"wx-"+w).join(" "):"";return a+(a?" ":"")+b},[n,a]),x=b=>{g&&g(b)};return r.jsxs("button",{title:c,className:`wx-2ZWgb4 wx-button ${y} ${i&&!h?"wx-icon":""}`,disabled:l,onClick:x,"data-tooltip-text":d,children:[i&&r.jsx("i",{className:"wx-2ZWgb4 "+i}),h||m||" "]})}function Ek({id:n,label:a="",inputValue:i="",value:l=!1,onChange:c,disabled:d=!1,css:m=""}){const h=tw(n),[g,y]=Or(l),x=({target:b})=>{const w=b.checked;y(w),c&&c({value:w,inputValue:i})};return r.jsxs("div",{className:`wx-2IvefP wx-checkbox ${m}`,children:[r.jsx("input",{type:"checkbox",id:h,disabled:d,className:"wx-2IvefP wx-check",checked:g,value:i,onChange:x}),r.jsxs("label",{htmlFor:h,className:"wx-2IvefP wx-label",children:[r.jsx("span",{className:"wx-2IvefP wx-before"}),a&&r.jsx("span",{className:"wx-2IvefP wx-after",children:a})]})]})}function Ip({theme:n="",target:a,children:i}){const l=u.useRef(null),c=u.useRef(null),[d,m]=u.useState(null);l.current||(l.current=document.createElement("div"));const h=u.useContext(_p);return u.useEffect(()=>{m(a||Dk(c.current)||ls.getTopNode(c.current))},[c.current]),r.jsxs(r.Fragment,{children:[r.jsx("span",{ref:c,style:{display:"none"}}),c.current&&d?Ak.createPortal(r.jsx("div",{className:`wx-3ZWsT0 wx-${n||h}-theme`,children:i}),d):null]})}function Dk(n){const a=ls.getTopNode(n);for(;n&&n!==a&&!n.getAttribute("data-wx-portal-root");)n=n.parentNode;return n}function Lk({left:n=0,top:a=0,at:i="bottom",parent:l=null,width:c="auto",css:d="",onCancel:m,children:h,trackScroll:g=!1}){const[y,x]=u.useState(0),[b,w]=u.useState(0),[A,j]=u.useState("auto"),[k,N]=u.useState(!1),M=u.useRef(null),T=u.useRef(null),D=u.useRef(m);u.useEffect(()=>{D.current=m},[m]);function F(G){return l&&(c+"").indexOf("%")>-1?c.replace(/(\d+)%/,(L,Q)=>(Q=Q*l.offsetWidth/100+"px",c.replace(L,Q))):c&&c!=="auto"?c:G}const $=u.useCallback(()=>{if(!M.current)return;const G=Kx(M.current,l,i,n,a);G&&(x(G.x),w(G.y),j(F(G.width)))},[M,l,i,n,a,c]);return u.useLayoutEffect(()=>{const G=Q=>{D.current&&Q.target!==T.current&&M.current&&!M.current.contains(Q.target)&&D.current(Q)};let L;return requestAnimationFrame(()=>{$(),N(!0),g&&M.current&&(T.current=Qx(M.current),T.current&&T.current.addEventListener("scroll",G,!0)),l&&(L=new ResizeObserver($),L.observe(l))}),()=>{g&&T.current&&T.current.removeEventListener("scroll",G,!0),L?.disconnect()}},[]),u.useLayoutEffect(()=>{$()},[l,i,n,a]),u.useEffect(()=>{const G=L=>{D.current&&D.current(L)};if(M.current)return Hr(M.current,{callback:G,parent:()=>l}).destroy},[l]),r.jsx("div",{ref:M,className:["wx-37M6Fj","wx-popup",d].filter(Boolean).join(" "),style:{position:"absolute",visibility:k?"visible":"hidden",top:b+"px",left:y+"px",width:A},children:h})}function _k({position:n="bottom",align:a="start",autoFit:i=!0,onCancel:l=null,width:c="100%",css:d="",children:m}){const h=u.useRef(null),[g,y]=u.useState(n),[x,b]=u.useState(a),w=u.useRef(l);return u.useEffect(()=>{w.current=l},[l]),u.useEffect(()=>{if(i){const A=h.current;if(A){const j=A.getBoundingClientRect(),k=document.body.getBoundingClientRect();j.right>=k.right&&b("end"),j.bottom>=k.bottom&&y("top")}}},[]),u.useEffect(()=>{if(h.current){const A=j=>{w.current&&w.current(j)};return Hr(h.current,A).destroy}},[]),r.jsx("div",{ref:h,className:["wx-dropdown",`wx-${g}-${x}`,d||"","wx-aaaVytZW"].filter(Boolean).join(" "),style:{width:c},children:m})}function zp({position:n="bottom",align:a="start",autoFit:i=!0,inline:l=!1,onCancel:c,width:d="100%",children:m,...h}){const[g,y]=u.useState(void 0),x=u.useRef(null),b=u.useMemo(()=>`${n}-${a}`,[n,a]);return u.useLayoutEffect(()=>{x.current&&y(x.current.parentNode)},[]),r.jsxs(r.Fragment,{children:[g&&(l?r.jsx(_k,{onCancel:c,position:n,align:a,autoFit:i,width:d,...h,children:m}):r.jsx(Ip,{children:r.jsx(Lk,{parent:g,at:b,onCancel:c,width:d,...h,children:m})})),r.jsx("span",{ref:x,className:"wx-portal-node wx-32GZ52"})]})}function Gf(){return Yu(Zx)}function Ik(){let n=null,a=!1,i=!1,l,c,d,m;const h=(b,w,A,j,k)=>{l=b,c=w,d=A,m=j,i=k},g=b=>{n=b,a=n!==null,d(n)},y=(b,w)=>{if(!i&&b!==null&&l){const A=l.querySelectorAll(".wx-list > .wx-item")[b];A&&(A.scrollIntoView({block:"nearest"}),w&&w.preventDefault())}},x=(b,w)=>{const A=b===null?null:Math.max(0,Math.min(n+b,c.length-1));A!==n&&(g(A),l?y(A,w):requestAnimationFrame(()=>y(A,w)))};return{move:b=>{const w=Vu(b),A=c.findIndex(j=>j.id===w);A!==n&&g(A)},keydown:(b,w)=>{switch(b.code){case"Enter":a?m():g(0);break;case"Space":a||g(0);break;case"Escape":d(n=null);break;case"Tab":d(n=null);break;case"ArrowDown":x(a?1:w||0,b);break;case"ArrowUp":x(a?-1:w||0,b);break}},init:h,navigate:x}}const rb=10,zk=u.memo(function({data:n,checkboxes:a,itemTemplate:i,value:l}){return r.jsxs(r.Fragment,{children:[a&&r.jsx(Ek,{id:n.id,css:"wx-list-checkbox",value:l&&l.includes(n.id)}),i?Ep(i,{option:n}):n.label]})});function ib({visibleItems:n,visibleRange:a,navIndex:i,checkboxes:l,itemTemplate:c,value:d,measureRefCallback:m}){return n.map((h,g)=>{const y=a.start+g;return r.jsx("div",{ref:g===0?m:void 0,className:`wx-233fr7 wx-item ${y===i?"wx-focus":""}`,"data-id":h.id,children:r.jsx(zk,{data:h,checkboxes:l,itemTemplate:c,value:d})},h.id)})}function Vf({items:n=[],children:a,onSelect:i,onReady:l,virtualized:c=!1,checkboxes:d,multiselect:m,value:h,...g}){const y=u.useRef(),x=u.useRef(!1),b=u.useRef(Ik()),[w,A]=u.useState(null),j=u.useRef(w),[k,N]=u.useState(0),[M,T]=u.useState(24),D=u.useRef(!1),F=(u.useContext(gr)||Gf()).getGroup("core"),$=u.useRef(n);u.useEffect(()=>{$.current=n},[n]);const G=u.useRef(h);u.useEffect(()=>{G.current=h},[h]);const L=u.useRef(0);u.useEffect(()=>{L.current=M},[M]);const Q=u.useCallback(K=>{K&&K.stopPropagation();const be=$.current,he=G.current,fe=j.current;let ee;const we=be[fe]?.id;m?he&&he.includes(we)?ee=he.filter(Me=>Me!==we):ee=[...he||[],we]:ee=we,i&&i({id:ee})},[m,i]),q=u.useRef(Q);u.useEffect(()=>{q.current=Q},[Q]);const P=u.useCallback(K=>{if(y.current){let be=K*L.current-y.current.clientHeight+L.current;N(be),y.current.scrollTop=be}},[L.current]),Y=u.useCallback(K=>{y.current=K,c&&(K&&!x.current&&j.current!==null&&requestAnimationFrame(()=>{y.current&&(P(j.current),x.current=!0)}),K||(x.current=!1))},[P]),H=u.useCallback(K=>{if(!K||D.current)return;const be=K.getBoundingClientRect().height;be&&(T(be),L.current=be,D.current=!0)},[]);u.useEffect(()=>{b.current.init(y.current,n,K=>{A(K),j.current=K},K=>q.current(K),c)},[n,y.current,c]),u.useEffect(()=>{const K=(he,fe)=>{b.current.navigate(he,fe),P(j.current)},be=(he,fe)=>{const ee=j.current,we=$.current;if(ee!==0&&ee!==we.length-1&&(he.key==="ArrowDown"||he.key==="ArrowUp")&&he.preventDefault(),b.current.keydown(he,fe),y.current){const Me=y.current.scrollTop<=j.current*L.current,He=y.current.scrollTop+y.current.clientHeight>=j.current*L.current+L.current;Me?He||P(j.current):(y.current.scrollTop=j.current*L.current,N(y.current.scrollTop))}};l&&l({navigate:c?K:b.current.navigate,keydown:c?be:b.current.keydown,move:b.current.move})},[]);const ye=u.useRef(0),de=u.useRef(n);de.current!==n&&(de.current=n,ye.current+=1);const Z=u.useCallback(()=>{b.current.navigate(null)},[b]),z=u.useCallback(K=>{c&&N(K.target.scrollTop)},[c]),se=u.useMemo(()=>Math.ceil((y.current?.clientHeight||0)/M),[M,k]),W=u.useMemo(()=>{if(!c)return{start:0,end:n.length};if(!n.length)return{start:0,end:0};const K=Math.floor(k/M),be=K+se;return{start:Math.max(0,K-rb),end:Math.min(n.length,be+rb)}},[c,n,k,M,se]),O=u.useMemo(()=>{if(!c)return n;const{start:K,end:be}=W;return n.slice(K,be).map(he=>({...he}))},[c,n,W]),le=W.start*M,ce=n.length*M;return u.useEffect(()=>{c&&N(0)},[n,c]),u.useEffect(()=>{w===null&&(x.current=!1)},[w]),w===null?null:r.jsx(zp,{onCancel:Z,...g,children:r.jsx("div",{className:"wx-233fr7 wx-list",ref:Y,onClick:Q,onMouseMove:b.current.move,onScroll:z,children:n.length?c?r.jsx("div",{className:"wx-233fr7 wx-list-wrapper",style:{height:`${ce}px`},children:r.jsx("div",{className:"wx-233fr7 wx-list-content",style:{transform:`translateY(${le}px)`},children:r.jsx(ib,{visibleRange:W,visibleItems:O,navIndex:w,measureRefCallback:H,checkboxes:d,itemTemplate:a,value:h})})}):r.jsx(ib,{visibleRange:W,visibleItems:O,navIndex:w,measureRefCallback:H,checkboxes:d,itemTemplate:a,value:h}):r.jsx("div",{className:"wx-233fr7 wx-no-data",children:F("No data")})})},ye.current)}function Op({value:n="",id:a,readonly:i=!1,focus:l=!1,select:c=!1,type:d="text",placeholder:m="",disabled:h=!1,error:g=!1,title:y="",tooltip:x,css:b="",icon:w="",clear:A=!1,onChange:j}){const k=tw(a),[N,M]=Or(n),T=u.useRef(null),D=u.useMemo(()=>w&&b.indexOf("wx-icon-left")===-1?"wx-icon-right "+b:b,[w,b]),F=u.useMemo(()=>w&&b.indexOf("wx-icon-left")!==-1,[w,b]);u.useEffect(()=>{const q=setTimeout(()=>{l&&T.current&&T.current.focus(),c&&T.current&&T.current.select()},1);return()=>clearTimeout(q)},[l,c]);const $=u.useCallback(q=>{const P=q.target.value;M(P),j&&j({value:P,input:!0})},[j]),G=u.useCallback(q=>j&&j({value:q.target.value}),[j]);function L(q){q.stopPropagation(),M(""),j&&j({value:""})}let Q=d;return d!=="password"&&d!=="number"&&(Q="text"),u.useEffect(()=>{const q=G,P=T.current;return P.addEventListener("change",q),()=>{P&&P.removeEventListener("change",q)}},[G]),r.jsxs("div",{className:`wx-hQ64J4 wx-text ${D} ${g?"wx-error":""} ${h?"wx-disabled":""} ${A?"wx-clear":""}`,"data-tooltip-text":x,children:[r.jsx("input",{className:"wx-hQ64J4 wx-input",ref:T,id:k,readOnly:i,disabled:h,placeholder:m,type:Q,title:y,value:N,onInput:$}),A&&!h&&N?r.jsxs(r.Fragment,{children:[r.jsx("i",{className:"wx-hQ64J4 wx-icon wxi-close",onClick:L}),F&&r.jsx("i",{className:`wx-hQ64J4 wx-icon ${w}`})]}):w?r.jsx("i",{className:`wx-hQ64J4 wx-icon ${w}`}):null]})}function Ok({date:n,type:a,part:i,onShift:l}){const{calendar:c,formats:d}=u.useContext(gr).getRaw(),m=n.getFullYear(),h=u.useMemo(()=>{switch(a){case"month":return bc(d.monthYearFormat,c)(n);case"year":return bc(d.yearFormat,c)(n);case"duodecade":{const{start:y,end:x}=Xx(m),b=bc(d.yearFormat,c);return`${b(new Date(y,0,1))} - ${b(new Date(x,11,31))}`}default:return""}},[n,a,m,c,d]);function g(){l&&l({diff:0,type:a})}return r.jsxs("div",{className:"wx-8HQVQV wx-header",children:[i!=="right"?r.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-left",onClick:()=>l&&l({diff:-1,type:a})}):r.jsx("span",{className:"wx-8HQVQV wx-spacer"}),r.jsx("span",{className:"wx-8HQVQV wx-label",onClick:g,children:h}),i!=="left"?r.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-right",onClick:()=>l&&l({diff:1,type:a})}):r.jsx("span",{className:"wx-8HQVQV wx-spacer"})]})}function Hp({onClick:n,children:a}){return r.jsx("button",{className:"wx-3s8W4d wx-button",onClick:n,children:a})}function Hk({value:n,current:a,part:i="",markers:l=null,css:c="",onCancel:d,onChange:m}){const h=(u.useContext(gr)||Gf()).getRaw().calendar,g=(h.weekStart||7)%7,y=h.dayShort.slice(g).concat(h.dayShort.slice(0,g)),x=($,G,L)=>new Date($.getFullYear(),$.getMonth()+(G||0),$.getDate()+(L||0));let b=i!=="normal";function w($){const G=$.getDay();return G===0||G===6}function A(){const $=x(a,0,1-a.getDate());return $.setDate($.getDate()-($.getDay()-(g-7))%7),$}function j(){const $=x(a,1,-a.getDate());return $.setDate($.getDate()+(6-$.getDay()+g)%7),$}const k=u.useRef(0);function N($,G){G.timeStamp!==k.current&&(k.current=G.timeStamp,G.stopPropagation(),m&&m(new Date($)),d&&d())}const M=u.useMemo(()=>i=="normal"?[n?x(n).valueOf():0]:n?[n.start?x(n.start).valueOf():0,n.end?x(n.end).valueOf():0]:[0,0],[i,n]),T=u.useMemo(()=>{const $=A(),G=j(),L=a.getMonth();let Q=[];for(let q=$;q<=G;q.setDate(q.getDate()+1)){const P={day:q.getDate(),in:q.getMonth()===L,date:q.valueOf()};let Y="";if(Y+=P.in?"":" wx-inactive",Y+=M.indexOf(P.date)>-1?" wx-selected":"",b){const H=P.date==M[0],ye=P.date==M[1];H&&!ye?Y+=" wx-left":ye&&!H&&(Y+=" wx-right"),P.date>M[0]&&P.date<M[1]&&(Y+=" wx-inrange")}if(Y+=w(q)?" wx-weekend":"",l){const H=l(q);H&&(Y+=" "+H)}Q.push({...P,css:Y})}return Q},[a,M,b,l]),D=u.useRef(null);let F=u.useRef({});return F.current.click=N,u.useEffect(()=>{Ac(D.current,F.current)},[]),r.jsxs("div",{className:`wx-398RBS wx-month ${c}`,children:[r.jsx("div",{className:"wx-398RBS wx-weekdays",children:y.map($=>r.jsx("div",{className:"wx-398RBS wx-weekday",children:$},$))}),r.jsx("div",{className:"wx-398RBS wx-days",ref:D,children:T.map($=>r.jsx("div",{className:`wx-398RBS wx-day ${$.css} ${$.in?"":"wx-out"}`,"data-id":$.date,children:$.day},$.date))})]})}function Fk({value:n,current:a,part:i,onCancel:l,onChange:c,onShift:d}){const m=u.useRef(new Date),[h,g]=Or(n||m.current),[y,x]=Or(a||m.current),b=u.useContext(gr).getRaw().calendar,w=b.monthShort||[],A=u.useMemo(()=>y.getMonth(),[y]),j=u.useCallback((M,T)=>{if(M!=null){T.stopPropagation();const D=new Date(y);D.setMonth(M),x(D),d&&d({current:D})}i==="normal"&&g(new Date(y)),l&&l()},[y,i,d,l]),k=u.useCallback(()=>{const M=new Date(nw(h,i)||y);M.setMonth(y.getMonth()),M.setFullYear(y.getFullYear()),c&&c(M)},[h,y,i,c]),N=u.useCallback(M=>{const T=M.target.closest("[data-id]");if(T){const D=parseInt(T.getAttribute("data-id"),10);j(D,M)}},[j]);return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-34U8T8 wx-months",onClick:N,children:w.map((M,T)=>r.jsx("div",{className:"wx-34U8T8 wx-month"+(A===T?" wx-current":""),"data-id":T,children:M},T))}),r.jsx("div",{className:"wx-34U8T8 wx-buttons",children:r.jsx(Hp,{onClick:k,children:b.done})})]})}const Rh="wx-1XEF33",$k=({value:n,current:a,onCancel:i,onChange:l,onShift:c,part:d})=>{const m=u.useContext(gr).getRaw().calendar,[h,g]=Or(a),[y,x]=Or(n),b=u.useMemo(()=>h.getFullYear(),[h]),w=u.useMemo(()=>{const{start:M,end:T}=Xx(b),D=[];for(let F=M;F<=T;++F)D.push(F);return D},[b]),A={click:j};function j(M,T){if(M){T.stopPropagation();const D=new Date(h);D.setFullYear(M),g(D),c&&c({current:D})}d==="normal"&&x(new Date(h)),i&&i()}function k(){const M=new Date(nw(y,d)||h);M.setFullYear(h.getFullYear()),l&&l(M)}const N=u.useRef(null);return u.useEffect(()=>{N.current&&Ac(N.current,A)},[]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:Rh+" wx-years",ref:N,children:w.map((M,T)=>r.jsx("div",{className:Rh+` wx-year ${b==M?"wx-current":""} ${T===0?"wx-prev-decade":""} ${T===11?"wx-next-decade":""}`,"data-id":M,children:M},T))}),r.jsx("div",{className:Rh+" wx-buttons",children:r.jsx(Hp,{onClick:k,children:m.done})})]})},lb={month:{component:Hk,next:Pk,prev:Bk},year:{component:Fk,next:qk,prev:Uk},duodecade:{component:$k,next:Vk,prev:Gk}};function Bk(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 Uk(n){return n=new Date(n),n.setFullYear(n.getFullYear()-1),n}function qk(n){return n=new Date(n),n.setFullYear(n.getFullYear()+1),n}function Gk(n){return n=new Date(n),n.setFullYear(n.getFullYear()-10),n}function Vk(n){return n=new Date(n),n.setFullYear(n.getFullYear()+10),n}function nw(n,a){let i;if(a==="normal")i=n;else{const{start:l,end:c}=n;a==="left"?i=l:a=="right"?i=c:i=l&&c}return i}const Wk=["clear","today"];function Yk(n){if(n==="done")return-1;if(n==="clear")return null;if(n==="today")return new Date}function Kk({value:n,current:a,onCurrentChange:i,part:l="normal",markers:c=null,buttons:d,css:m="",onShift:h,onChange:g}){const y=u.useContext(gr).getGroup("calendar"),[x,b]=u.useState("month"),w=Array.isArray(d)?d:d?Wk:[],A=(T,D)=>{T.preventDefault(),g&&g({value:D})},j=()=>{x==="duodecade"?b("year"):x==="year"&&b("month")},k=T=>{const{diff:D,current:F}=T;if(D===0){x==="month"?b("year"):x==="year"&&b("duodecade");return}if(D){const $=lb[x];i(D>0?$.next(a):$.prev(a))}else F&&i(F);h&&h()},N=T=>{b("month"),g&&g({select:!0,value:T})},M=u.useMemo(()=>lb[x].component,[x]);return r.jsx("div",{className:`wx-2Gr4AS wx-calendar ${l!=="normal"&&l!=="both"?"wx-part":""} ${m}`,children:r.jsxs("div",{className:"wx-2Gr4AS wx-wrap",children:[r.jsx(Ok,{date:a,part:l,type:x,onShift:k}),r.jsxs("div",{children:[r.jsx(M,{value:n,current:a,onCurrentChange:i,part:l,markers:c,onCancel:j,onChange:N,onShift:k}),x==="month"&&w.length>0&&r.jsx("div",{className:"wx-2Gr4AS wx-buttons",children:w.map(T=>r.jsx("div",{className:"wx-2Gr4AS wx-button-item",children:r.jsx(Hp,{onClick:D=>A(D,Yk(T)),children:y(T)})},T))})]})]})})}function Fp(n){let{words:a=null,optional:i=!1,children:l}=n,c=u.useContext(gr);const d=u.useMemo(()=>{let m=c;return(!m||!m.extend)&&(m=Yu(Zx)),a!==null&&(m=m.extend(a,i)),m},[a,i,c]);return r.jsx(gr.Provider,{value:d,children:l})}function ob(n,a,i,l){if(!n||l){const c=a?new Date(a):new Date;c.setDate(1),i(c)}else if(n.getDate()!==1){const c=new Date(n);c.setDate(1),i(c)}}const Qk=["clear","today"];function aw({value:n,current:a,markers:i=null,buttons:l=Qk,css:c="",onChange:d}){const[m,h]=Or(n),[g,y]=Or(a);u.useEffect(()=>{ob(g,m,y,!1)},[m,g]);const x=u.useCallback(w=>{const A=w.value;A?(h(new Date(A)),ob(g,new Date(A),y,!0)):h(null),d&&d({value:A?new Date(A):null})},[d,g]),b=u.useCallback(w=>{y(w)},[y]);return g?r.jsx(Fp,{children:r.jsx(Kk,{value:m,current:g,markers:i,buttons:l,css:c,onChange:x,onCurrentChange:b})}):null}function Xk(n){return n||(n={}),n.width||(n.width="unset"),n}const Zk=["clear","today"];function Jk({value:n,id:a,disabled:i=!1,error:l=!1,placeholder:c="",format:d="",buttons:m=Zk,css:h="",title:g="",tooltip:y,editable:x=!1,clear:b=!1,onChange:w,dropdown:A={}}){const{calendar:j,formats:k}=(u.useContext(gr)||Gf()).getRaw(),N=d||k?.dateFormat;let M=typeof N=="function"?N:bc(N,j);const[T,D]=u.useState(n),[F,$]=u.useState(!1);u.useEffect(()=>{D(n)},[n]);function G(){$(!1)}function L(P){const Y=P===T||P&&T&&P.valueOf()===T.valueOf()||!P&&!T;D(P),Y||w&&w({value:P}),setTimeout(G,1)}const Q=u.useMemo(()=>T?M(T):"",[T,M]);function q({value:P,input:Y}){if(!x&&!b||Y)return;let H=typeof x=="function"?x(P):P?new Date(P):null;H=isNaN(H)?T||null:H||null,L(H)}return u.useEffect(()=>{const P=G;return window.addEventListener("scroll",P),()=>window.removeEventListener("scroll",P)},[]),r.jsxs("div",{className:"wx-1lKOFG wx-datepicker",onClick:()=>$(!0),children:[r.jsx(Op,{css:`wx-date-input ${h}`,title:g,tooltip:y,value:Q,id:a,readonly:!x,disabled:i,error:l,placeholder:c,onInput:G,onChange:q,icon:"wxi-calendar",clear:b}),F&&!i&&r.jsx(zp,{onCancel:G,...Xk(A),children:r.jsx(aw,{buttons:m,value:T,onChange:P=>L(P.value)})})]})}function ej({value:n="",options:a=[],textOptions:i=null,placeholder:l="",disabled:c=!1,error:d=!1,title:m="",tooltip:h,textField:g="label",clear:y=!1,css:x="",children:b,onChange:w,dropdown:A={}}){const j=u.useRef(null),k=u.useRef(null);let[N,M]=Or(n);function T(L){j.current=L.navigate,k.current=L.keydown}const D=u.useMemo(()=>N||N===0?(i||a).find(L=>L.id===N):null,[N,i,a]),F=u.useCallback(({id:L})=>{(L||L===0)&&(M(L),j.current(null),w&&w({value:L}))},[M,w]),$=u.useCallback(L=>{L.stopPropagation(),M(""),w&&w({value:""})},[M,w]),G=u.useCallback(()=>a.findIndex(L=>L.id===N),[a,N]);return r.jsxs("div",{className:`wx-2YgblL wx-richselect ${x} ${d?"wx-2YgblL wx-error":""} ${c?"wx-2YgblL wx-disabled":""} ${b?"":"wx-2YgblL wx-nowrap"}`,title:m,onClick:()=>j.current(G()),onKeyDown:L=>k.current(L,G()),tabIndex:0,"data-tooltip-text":h,children:[r.jsx("div",{className:"wx-2YgblL wx-label",children:D?b?b(D):D[g]:l?r.jsx("span",{className:"wx-2YgblL wx-placeholder",children:l}):" "}),y&&!c&&N?r.jsx("i",{className:"wx-2YgblL wx-icon wxi-close",onClick:$}):r.jsx("i",{className:"wx-2YgblL wx-icon wxi-angle-down"}),!c&&r.jsx(Vf,{items:a,onReady:T,onSelect:F,...A,children:({option:L})=>b?b(L):L[g]})]})}const tj=({options:n=[],value:a="",css:i="",children:l,onChange:c})=>{const[d,m]=u.useState(a),h=g=>{m(g),c&&c({value:g})};return u.useEffect(()=>{m(a)},[a]),r.jsx("div",{className:`wx-0hMO7P wx-segmented ${i}`,children:n.map(g=>r.jsx("button",{className:`wx-0hMO7P wx-segment ${g.css} ${g.id===d?"wx-selected":""}`,title:g.title,onClick:()=>h(g.id),"data-tooltip-text":g.tooltip,children:l?Ep(l,{option:g}):r.jsxs(r.Fragment,{children:[g.icon&&r.jsx("i",{className:`wx-0hMO7P wx-icon ${g.icon} ${g.label?"":"wx-only"}`}),g.label&&r.jsx("span",{className:"wx-0hMO7P wx-label",children:g.label})]})},g.id))})};function nj({notice:n={}}){function a(){n.remove&&n.remove()}return r.jsxs("div",{className:`wx-11sNg5 wx-notice wx-${n.type?n.type:""}`,role:"status","aria-live":"polite",children:[r.jsx("div",{className:"wx-11sNg5 wx-text",children:n.text}),r.jsx("div",{className:"wx-11sNg5 wx-button",children:r.jsx("i",{className:"wx-11sNg5 wxi-close",onClick:a})})]})}function aj({data:n=[]}){return r.jsx("div",{className:"wx-3nwoO9 wx-notices",children:n.map(a=>r.jsx(nj,{notice:a},a.id))})}function mp({title:n="",buttons:a=["cancel","ok"],header:i,children:l,footer:c,css:d="",onConfirm:m,onCancel:h}){const g=(u.useContext(gr)||Gf()).getGroup("core"),y=u.useRef(null);u.useEffect(()=>{y.current?.focus()},[]);function x(w){switch(w.code){case"Enter":{const A=w.target.tagName;if(A==="TEXTAREA"||A==="BUTTON")return;m&&m({event:w});break}case"Escape":h&&h({event:w});break}}function b(w,A){const j={event:w,button:A};A==="cancel"?h&&h(j):m&&m(j)}return r.jsx("div",{className:`wx-1FxkZa wx-modal ${d}`,ref:y,tabIndex:0,onKeyDown:x,children:r.jsxs("div",{className:"wx-1FxkZa wx-window",children:[i||(n?r.jsx("div",{className:"wx-1FxkZa wx-header",children:n}):null),r.jsx("div",{children:l}),c||a&&r.jsx("div",{className:"wx-1FxkZa wx-buttons",children:a.map(w=>r.jsx("div",{className:"wx-1FxkZa wx-button",children:r.jsx(Fu,{type:`block ${w==="ok"?"primary":"secondary"}`,onClick:A=>b(A,w),children:g(w)})},w))})]})})}function sj({children:n},a){const[i,l]=u.useState(null),[c,d]=u.useState([]);return u.useImperativeHandle(a,()=>({showModal:m=>{const h={...m};return l(h),new Promise((g,y)=>{h.resolve=x=>{l(null),g(x)},h.reject=x=>{l(null),y(x)}})},showNotice:m=>{m={...m},m.id=m.id||Lp(),m.remove=()=>d(h=>h.filter(g=>g.id!==m.id)),m.expire!=-1&&setTimeout(m.remove,m.expire||5100),d(h=>[...h,m])}}),[]),r.jsxs(r.Fragment,{children:[n,i&&r.jsx(mp,{title:i.title,buttons:i.buttons,onConfirm:i.resolve,onCancel:i.reject,children:i.message}),r.jsx(aj,{data:c})]})}const rj=u.forwardRef(sj);function ij(n){let{children:a}=n,i=u.useRef();const l=u.useMemo(()=>({showNotice:c=>i.current.showNotice(c),showModal:c=>i.current.showModal(c)}),[]);return r.jsx(Jx.Provider,{value:l,children:r.jsx(rj,{ref:i,children:a})})}const lj=({value:n=!1,type:a="",icon:i="",disabled:l=!1,iconActive:c="",onClick:d,title:m="",tooltip:h,css:g="",text:y="",textActive:x="",children:b,active:w,onChange:A})=>{const[j,k]=Or(n),N=u.useMemo(()=>(j?"pressed":"")+(a?" "+a:""),[j,a]),M=u.useCallback(T=>{let D=!j;d&&d(T),T.defaultPrevented||(k(D),A&&A({value:D}))},[j,d,A]);return j&&w?r.jsx(Fu,{title:m,tooltip:h,text:j&&x||y,css:g,type:N,icon:j&&c||i,onClick:M,disabled:l,children:Ep(w,{value:j})}):b?r.jsx(Fu,{title:m,tooltip:h,text:j&&x||y,css:g,type:N,icon:j&&c||i,onClick:M,disabled:l,children:b}):r.jsx(Fu,{title:m,tooltip:h,text:j&&x||y,css:g,type:N,icon:j&&c||i,onClick:M,disabled:l})};function oj(){return r.jsx(r.Fragment,{})}function cb(n){const{fonts:a=!0,children:i}=n;return r.jsx(_p.Provider,{value:"willow",children:r.jsxs(r.Fragment,{children:[i&&i&&r.jsx("div",{className:"wx-theme wx-willow-theme",children:i}),a&&r.jsxs(r.Fragment,{children:[r.jsx("link",{rel:"preconnect",href:"https://cdn.svar.dev",crossOrigin:"true"}),r.jsx(oj,{}),r.jsx("link",{rel:"stylesheet",href:"https://cdn.svar.dev/fonts/wxi/wx-icons.css"})]})]})})}Dp(ls);const $p={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 sw=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 cj=class{constructor(n){const a={id:0,$level:0,data:[],parent:null},i=new Map;i.set(0,a),this._pool=i,n&&n.length&&this.parse(n,0)}parse(n,a){const i=this._pool;for(let c=0;c<n.length;c++){const d=n[c];d.parent=d.parent||a,d.data=null,i.set(d.id,d)}for(let c=0;c<n.length;c++){const d=n[c],m=i.get(d.parent);m&&(m.data||(m.data=[]),m.data.push(d))}const l=i.get(a);this.setLevel(l,l.$level+1,!1)}add(n,a){const i=this._pool.get(n.parent||0);n.$level=i.$level+1,this._pool.set(n.id,n),i.data?a===-1?i.data=[...i.data,n]:ub(i,a,n):i.data=[n]}addAfter(n,a){if(!a)return this.add(n,-1);const i=this.byId(a),l=this.byId(i.parent),c=df(l,i.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 i=this._pool.get(a.parent);i.data=i.data.filter(l=>l.id!=n),this._clearBranch(i)}_remove(n){n.data&&n.data.forEach(a=>this._remove(a)),this._pool.delete(n.id)}update(n,a){let i=this._pool.get(n);const l=this._pool.get(i.parent),c=df(l,i.id);i={...i,...a},l&&c>=0&&(l.data[c]=i,l.data=[...l.data]),this._pool.set(i.id,i)}move(n,a,i){const l=this._pool.get(n),c=a==="child",d=this._pool.get(i),m=d.$level+(c?1:0);if(!l||!d)return;const h=this._pool.get(l.parent),g=c?d:this._pool.get(d.parent);g.data||(g.data=[]);const y=df(h,l.id);uj(h,y);const x=c?g.data.length:df(g,d.id)+(a==="after"?1:0);if(ub(g,x,l),h.id===g.id&&y===x)return null;l.parent=g.id,l.$level!==m&&(l.$level=m,this.setLevel(l,m+1,!0)),this.update(l.id,l),this._clearBranch(h)}_clearBranch(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&&rw(a,n),n}byId(n){return this._pool.get(n)}getBranch(n){return this._pool.get(n).data}forEach(n){this._pool.forEach((a,i)=>{i!==0&&n(a)})}eachChild(n,a){const i=this.byId(a);!i||!i.data||i.data.forEach((l,c)=>{n(this.byId(l.id),c),this.eachChild(n,l.id)})}setLevel(n,a,i){n.data&&(n.data=n.data.map(l=>(i&&(l={...l},this._pool.set(l.id,l)),l.$level=a,l.data&&this.setLevel(l,a+1,i),l)))}};function rw(n,a){n.forEach(i=>{a.push(i),i.open===!0&&rw(i.data,a)})}function uj(n,a){const i=[...n.data];i.splice(a,1),n.data=i}function ub(n,a,i){const l=[...n.data];l.splice(a,0,i),n.data=l}function df(n,a){return n?.data.findIndex(i=>i.id===a)}var iw=2,dj=class{constructor(a){a&&(this._writable=a.writable,this._async=a.async),this._values={},this._state={}}setState(a,i=0){const l={};return this._wrapProperties(a,this._state,this._values,"",l,i),l}getState(){return this._values}getReactive(){return this._state}_wrapProperties(a,i,l,c,d,m){for(const h in a){const g=i[h],y=l[h],x=a[h];if(g&&(y===x&&typeof x!="object"||x instanceof Date&&y instanceof Date&&y.getTime()===x.getTime()))continue;const b=c+(c?".":"")+h;g?(g.__parse(x,b,d,m)&&(l[h]=x),m&iw?d[b]=g.__trigger:g.__trigger()):(x&&x.__reactive?i[h]=this._wrapNested(x,x,b,d):i[h]=this._wrapWritable(x),l[h]=x),d[b]=d[b]||null}}_wrapNested(a,i,l,c){const d=this._wrapWritable(a);return this._wrapProperties(a,d,i,l,c,0),d.__parse=(m,h,g,y)=>(this._wrapProperties(m,d,i,h,g,y),!1),d}_wrapWritable(a){const i=[],l=function(){for(let c=0;c<i.length;c++)i[c](a)};return{subscribe:c=>(i.push(c),this._async?setTimeout(c,1,a):c(a),()=>{const d=i.indexOf(c);d>=0&&i.splice(d,1)}),__trigger:()=>{i.length&&(this._async?setTimeout(l,1):l())},__parse:function(c){return a=c,!0}}}};function db(n,a){return Object.defineProperty(n,"__reactive",{value:!0,enumerable:!1,writable:!1}),n}var fj=class{constructor(a,i,l,c){typeof a=="function"?this._setter=a:this._setter=a.setState.bind(a),this._routes=i,this._parsers=l,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(d=>{d.in.forEach(m=>{const h=this._triggers.get(m)||[];h.push(d),this._triggers.set(m,h)}),d.out.forEach(m=>{const h=this._sources.get(m)||{};d.in.forEach(g=>h[g]=!0),this._sources.set(m,h)})}),this._routes.forEach(d=>{d.length=Math.max(...d.in.map(m=>lw(m,this._sources,1)))}),this._bus=c}init(a){const i={};for(const l in a)if(this._prev[l]!==a[l]){const c=this._parsers[l];i[l]=c?c(a[l]):a[l]}this._prev=this._prev?{...this._prev,...a}:{...a},this.setState(i),this._bus&&this._bus.exec("init-state",i)}setStateAsync(a){const i=this._setter(a,iw);return this._async?Object.assign(this._async.signals,i):this._async={signals:i,timer:setTimeout(this._applyState.bind(this),1)},i}_applyState(){const a=this._async;if(a){this._async=null,this._triggerUpdates(a.signals,[]);for(const i in a.signals){const l=a.signals[i];l&&l()}}}setState(a,i=[]){const l=this._setter(a);return this._triggerUpdates(l,i),l}_triggerUpdates(a,i){const l=Object.keys(a),c=!i.length;i=i||[];for(let d=0;d<l.length;d++){const m=l[d],h=this._triggers.get(m);h&&h.forEach(g=>{i.indexOf(g)==-1&&i.push(g)})}c&&this._execNext(i)}_execNext(a){for(;a.length;){a.sort((l,c)=>l.length<c.length?1:-1);const i=a[a.length-1];a.splice(a.length-1),i.exec(a)}}};function lw(n,a,i){const l=a.get(n);if(!l)return i;const c=Object.keys(l).map(d=>lw(d,a,i+1));return Math.max(...c)}var mj=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(a,i,l){let c=this._handlers[a];c?l&&l.intercept?c.unshift(i):c.push(i):c=this._handlers[a]=[i],l&&l.tag&&this._tag.set(i,l.tag)}intercept(a,i,l){this.on(a,i,{...l,intercept:!0})}detach(a){for(const i in this._handlers){const l=this._handlers[i];for(let c=l.length-1;c>=0;c--)this._tag.get(l[c])===a&&l.splice(c,1)}}async exec(a,i){const l=this._handlers[a];if(l)for(let c=0;c<l.length;c++){const d=l[c](i);if(d===!1||d&&d.then&&await d===!1)return}return this._nextHandler&&await this._nextHandler.exec(a,i),i}setNext(a){return this._nextHandler=a}};const mc=1024;function Wu(n){return n<mc?`${n} B`:n<mc**2?`${(n/mc).toFixed(1)} KB`:n<mc**3?`${(n/mc**2).toFixed(1)} MB`:`${(n/mc**3).toFixed(1)} GB`}function fb(n,a){a||(a={key:"name",order:"asc"});const i=n.filter(m=>m.type==="folder"),l=n.filter(m=>m.type!=="folder"),c=i.sort(mb(a)),d=l.sort(mb(a));return[...c,...d]}function hj(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 pj(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 mb({key:n,order:a}){const i=a==="asc"?hj:pj;return(l,c)=>i(l[n],c[n])}function Bp(n,a){const i=n==="/"?1:n.split("/").length;return i>=a.length?null:a[i].id}function gj(n){return n.length>1?n[n.length-2].id:null}let vj=class extends cj{constructor(a){const i={id:"/",name:"My files",open:!0,$level:1,parent:0,ext:"",type:"folder"};super([i]),this.parse(a,"/")}parse(a,i,l){!a||!a.length||(a.forEach(c=>this.parseId(c,l?i:void 0)),super.parse(a,i))}parseId(a,i){if(a.parent===0)return;const l=a.id,c=l.lastIndexOf("/");if(a.parent=i??(c===0?"/":l.slice(0,c)),a.name=l.slice(c+1),a.type=a.type||"file",a.type!=="folder"){const d=a.name.lastIndexOf("."),m=d!==-1?a.name.slice(d+1):"";a.ext=m!=="new"?m?.toLocaleLowerCase():""}}getParents(a){const i=[];let l=this.byId(a);if(!l)return i;for(;l.id!==0;)i.push(l),l=this.byId(l.parent);return i.reverse()}findFiles(a,i="/"){const l=[],c=a.toLocaleLowerCase();return this.eachChild(d=>{d.name.toLowerCase().indexOf(c)!==-1&&l.push(d)},i),l}add(a,i){const l=this.byId(a.parent||"/"),c=a.data?[...a.data]:null;a.data=null,super.add(a,i??l.data?l.data.length:0),c&&c.forEach(d=>this.add(d))}renameFiles(a,i,l){const c=this.byId(a),d=this.normalizeFile(c,i),m=[];return d.data?.forEach(h=>m.push(this.renameFiles(h.id,d.id,l))),m.length&&(d.data=m),l[a]=d.id,d}copyFiles(a,i,l){const c={};return a.forEach(d=>{const m=this.renameFiles(d,i,c);this.add(m),l&&this.remove(d),c[d]=m.id}),c}moveFiles(a,i){if(this.byId(a[0]).parent!==i)return this.copyFiles(a,i,!0)}serialize(a="/"){const i=[],l=this.byId(a);return l?(l.data?.forEach(c=>{const{id:d,date:m,type:h,size:g,lazy:y}=c,x={id:d,date:m,type:h??"file"};y&&(x.lazy=y),g&&(x.size=g),i.push(x);const b=this.serialize(d);b.length&&i.push(...b)}),i):null}normalizeFile(a,i){const l=a.name,c=l.lastIndexOf("."),d=c!==-1?l.slice(c+1):"",m=d?`.${d}`:"";let h=c!==-1?l.slice(0,c):l,g=i+(i==="/"?"":"/")+h;for(;this.byId(g+m);){const y=".new";g+=y,h+=y}return{...a,id:g+m,name:h+m,parent:i,ext:d.toLocaleLowerCase()}}},yj=class extends dj{in;_router;constructor(a){super({writable:a,async:!1});const i=[];for(let d=0;d<2;d++)i.push({in:["data",`panels.${d}.path`],out:[`panels.${d}._crumbs`],exec:m=>{const{data:h,panels:g}=this.getState(),y=[];y[d]={_crumbs:h.getParents(g[d].path)},this.setState({panels:y},m)}}),i.push({in:["data",`panels.${d}.path`,`panels.${d}._sorts`,"search"],out:[`panels.${d}._files`],exec:m=>{const{data:h,panels:g,search:y}=this.getState();let x;y?x=h.findFiles(y,g[d].path):x=h.byId(g[d].path)?.data||[];const{path:b,_sorts:w}=g[d];x=fb(x,w[b]);const A=[];A[d]={_files:x},this.setState({panels:A},m)}}),i.push({in:["data",`panels.${d}.selected`,`panels.${d}._sorts`],out:[`panels.${d}._selected`],exec:m=>{const{data:h,panels:g}=this.getState(),y=[];g[d].selected.forEach(j=>{const k=h.byId(j);k&&y.push(k)});const{path:x,_sorts:b}=g[d],w=fb(y,b[x]),A=[];A[d]={_selected:w},this.setState({panels:A},m)}});this._router=new fj(super.setState.bind(this),i,{data:d=>new vj(d)});const l=this.in=new mj;l.on("select-file",({id:d,toggle:m,range:h,panel:g,type:y})=>{const{panels:x,activePanel:b}=this.getState();typeof g>"u"&&(g=b),d||(m=h=!1);let w=[...x[g].selected];if(m){const j=w.indexOf(d);j===-1?w.push(d):w.splice(j,1)}else if(h&&x[g]._lastSelected){const j=x[g]._files;let k=j.findIndex(T=>T.id==x[g]._lastSelected),N=j.findIndex(T=>T.id==d);N<k&&([k,N]=[N,k]);const M=j.slice(k,N+1).map(T=>T.id);w=[...new Set([...w,...M])]}else w=d?[d]:[];const A=[];A[g]={selected:w,_lastSelected:d,_selectNavigation:y==="navigation"},this.setState({panels:A})}),l.on("set-path",({id:d,panel:m,selected:h})=>{const{data:g,activePanel:y}=this.getState(),x=g.byId(d);if(x){const b=[];typeof m>"u"&&(m=y),b[m]={path:d},this.setState({panels:b}),l.exec("select-file",{panel:m}),h&&h.forEach(w=>l.exec("select-file",{id:w,panel:m,toggle:!0})),x.lazy&&l.exec("request-data",{id:d})}}),l.on("provide-data",({id:d,data:m})=>{const{mode:h,data:g}=this.getState(),y=g.byId(d);y&&(y.lazy||(y.data=[]),y.lazy=!1,g.parse(m,d,h==="search"),this.setState({data:g}))}),l.on("open-tree-folder",({id:d,mode:m})=>{const{data:h}=this.getState();h.update(d,{open:m}),this.setState({data:h})}),l.on("show-preview",({mode:d})=>{this.setState({preview:d})}),l.on("rename-file",d=>{const{id:m,name:h}=d,{data:g,panels:y}=this.getState(),x=g.byId(m);if(x.name!==h){x.name=h;const b=g.normalizeFile(x,x.parent);d.newId=b.id,b.data=null,g.add(b);let w={[m]:b.id};x.data?.forEach(j=>w={...g.moveFiles([j.id],b.id),...w});const A=y.map(j=>({selected:j.selected,_crumbs:j._crumbs,_lastSelected:j._lastSelected,_sorts:j._sorts}));g.remove(m),this._updatePanels(A,w),this.setState({data:g,panels:A})}}),l.on("create-file",d=>{const{file:m,parent:h}=d,{data:g}=this.getState(),y=g.normalizeFile(m,h);y.type=m.type||"file",d.newId=y.id,g.add(y),this.setState({data:g}),l.exec("select-file",{id:y.id})}),l.on("delete-files",({ids:d})=>{const{data:m,panels:h}=this.getState(),g=h.map(y=>({selected:y.selected,_crumbs:y._crumbs,_lastSelected:y._lastSelected,_sorts:y._sorts}));d.forEach(y=>m.remove(y)),this._updatePanels(g,{}),this.setState({data:m,panels:g})}),l.on("copy-files",d=>{const{ids:m,target:h}=d;if(this._isPlacedIntoSelf(m,h)){console.error("You cannot copy a folder into itself"),d.skipProvider=!0;return}const{data:g,panels:y,activePanel:x}=this.getState(),b=g.copyFiles(m,h);d.newIds=m.map(w=>b[w]),this.setState({data:g}),y[x].path==h&&(l.exec("select-file",{}),m.forEach(w=>{l.exec("select-file",{id:b[w],toggle:!0})}))}),l.on("move-files",d=>{const{ids:m,target:h}=d;if(this._isPlacedIntoSelf(m,h)){console.error("You cannot move a folder into itself"),d.skipProvider=!0;return}const{data:g,panels:y,activePanel:x}=this.getState(),b=g.moveFiles(m,h);if(b){d.newIds=m.map(A=>b[A]);const w=y.map(A=>({selected:A.selected,_crumbs:A._crumbs,_lastSelected:A._lastSelected,_sorts:A._sorts}));this._updatePanels(w,b,!0),this.setState({data:g,panels:w}),y[x].path==h&&(l.exec("select-file",{}),m.forEach(A=>{l.exec("select-file",{id:b[A],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:h}=this.getState();c||(c={panels:m,mode:h,search:""}),this.setState({mode:"search",search:d})}),l.on("set-mode",({mode:d})=>{const{activePanel:m}=this.getState(),h=[];h[m]={_selectNavigation:!1};const g={mode:d,search:"",panels:h};c=null,this.setState(g)}),l.on("set-active-panel",({panel:d})=>{this.setState({activePanel:d})}),l.on("sort-files",({key:d,order:m,panel:h,path:g})=>{const{activePanel:y,panels:x}=this.getState();h=h??y,g=g??x[h].path;const b=[];b[h]={_sorts:{...x[h]._sorts,[g]:{key:d,order:m}}},this.setState({panels:b})}),this.initOnce()}initOnce(){const a=[];for(let l=0;l<2;l++)a[l]=db({_crumbs:[],_files:[],_selected:[],_sorts:{},path:"/",selected:[],...a[l]});const i={panels:db(a),data:[],search:""};this._router.init(i)}init(a){const i={...a};this._router.init(i)}setState(a,i){return this._router.setState(a,i)}getFile(a){const{data:i}=this.getState();return i.byId(a)||null}serialize(a){const{data:i}=this.getState();return i.serialize(a)}_updatePanels(a,i,l){const{data:c}=this.getState();a.forEach(d=>{const m=[];d.selected.forEach(y=>{c.byId(y)?m.push(y):!l&&i[y]&&m.push(i[y])}),d.selected=m,c.byId(d._lastSelected)||(d._lastSelected=l?null:i[d._lastSelected]||null);const h={};Object.keys(d._sorts).forEach(y=>{c.byId(y)?h[y]=d._sorts[y]:i[y]&&!l&&(h[i[y]]=d._sorts[y])}),d._sorts=h;const g=d._crumbs[d._crumbs.length-1];g?.id!=="/"&&(i[g.id]?d.path=i[g.id]:c.byId(g.id)||(d.path="/"))})}_isPlacedIntoSelf(a,i){return a.some(l=>l===i||this.getState().data.getParents(i).some(c=>c.id===l))}};function bj(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 xj(n,a="data-id"){let i=n;for(!i.tagName&&n.target&&(i=n.target);i;){if(i.getAttribute&&i.getAttribute(a))return i;i=i.parentNode}return null}function wj(n,a="data-id"){const i=xj(n,a);return i?i.getAttribute(a):null}new Date().valueOf();function Sj(n,a){const{api:i}=a;function l(d,m){const h=a.getPanel(),g=h.selected,y=m.ctrlKey||m.metaKey,x=m.shiftKey;let b;const w=g?.[0]?i.getFile(g[0]):null;g?.length?g.length>1?b=a.menuOptions("multiselect"):b=a.menuOptions(w.type,w):b=a.menuOptions("body");const A=`${y?"ctrl+":""}${x?"shift+":""}${d}`,j=b?b.find(N=>N.hotkey?.toLowerCase()===A):!1,k=a.performAction;if(j)switch(A){case"ctrl+c":k("copy");break;case"ctrl+x":k("move");break;case"ctrl+v":k("paste",w);break;case"delete":k("delete");break;case"ctrl+r":m.preventDefault(),k("rename",w);break;case"ctrl+d":m.preventDefault(),k("download",w);break;default:j.handler?.({context:w})}switch(d){case"enter":{if(y||x)break;const{_crumbs:N,_selectNavigation:M}=h;if(M){const T=gj(N);if(T){const D=Bp(T,N);i.exec("set-path",{id:T,selected:[D]})}}else if(g.length===1){const T=i.getFile(g[0]);T&&i.exec(T.type==="folder"?"set-path":"open-file",{id:T.id})}break}case"arrowup":case"arrowleft":{const{_files:N,_selected:M,path:T,_selectNavigation:D}=h;let F;if(M.length){const $=M.at(0).id,G=N.findIndex(L=>L.id===$);if(G!==-1){const L=G-1;N[L]?F=N[L].id:T!=="/"&&!(y||x)&&i.exec("select-file",{type:"navigation"})}}else{if(D)break;if(T!=="/"){i.exec("select-file",{type:"navigation"});break}F=N.at(0)?.id}F&&i.exec("select-file",{id:F,toggle:y,range:x});break}case"arrowdown":case"arrowright":{const{_files:N,_selected:M,path:T,_selectNavigation:D}=h;let F;if(M.length){const $=M.at(-1).id,G=N.findIndex(L=>L.id===$);if(G!==-1){const L=G+1;N[L]&&(F=N[L].id)}}else{if(T!=="/"&&!D){i.exec("select-file",{type:"navigation"});break}F=N.at(0)?.id}F&&i.exec("select-file",{id:F,toggle:y,range:x});break}}}function c(d){const m=d.code.replace("Key","").toLowerCase();l(m,d),m=="tab"&&setTimeout(()=>{const h=document.activeElement;h.className.indexOf("table")!=-1&&i.exec("set-active-panel",{panel:+wj(h,"data-panel")})})}return n.addEventListener("keydown",c),{destroy:()=>{n.removeEventListener("keydown",c)}}}function Cj(n,a="data-id"){let i=n;for(!i.tagName&&n.target&&(i=n.target);i;){if(i.getAttribute&&i.getAttribute(a))return i;i=i.parentNode}return null}function kj(n,a="data-id"){const i=n.getAttribute(a);return i?jj(i):null}function jj(n){if(n.startsWith(":"))return n.substring(1);const a=n*1;return isNaN(a)?n:a}function Aj(){return{detect:()=>!0,addEvent:function(n,a,i){return n.addEventListener(a,i),()=>n.removeEventListener(a,i)},addGlobalEvent:function(n,a){return document.addEventListener(n,a),()=>document.removeEventListener(n,a)},getTopNode:function(){return window.document.body}}}var Mj=Aj();new Date().valueOf();function ow(n){const[a,i]=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,i(n)}},[n]),[a,i]}function Nj(n,a,i){const[l,c]=u.useState(()=>a);return n||console.warn(`Writable ${i} is not defined`),u.useEffect(()=>n?n.subscribe(m=>{c(()=>m)}):void 0,[n]),l}function gt(n,a){const i=n.getState(),l=n.getReactiveState();return Nj(l[a],i[a],a)}function Tj(n,a){const i=u.useRef(a);i.current=a;const[l,c]=u.useState(1);return u.useEffect(()=>n.subscribe(m=>{i.current=m,c(h=>h+1)}),[n]),[i.current,l]}function Us(n,a){const i=n.getState(),l=n.getReactiveState();return Tj(l[a],i[a])}function cw(n){const a={};return n.split(";").forEach(i=>{const[l,c]=i.split(":");if(c){let d=l.trim();d.indexOf("-")&&(d=d.replace(/-([a-z])/g,(m,h)=>h.toUpperCase())),a[d]=c.trim()}}),a}function uw(n){let a=n,i=[];return{subscribe:h=>{i.push(h),h(a)},unsubscribe:h=>{i=i.filter(g=>g!==h)},set:h=>{a=h,i.forEach(g=>g(a))},update:h=>{a=h(a),i.forEach(g=>g(a))}}}function hb(n,a,i){function l(c){const d=Cj(c);if(!d)return;const m=kj(d);if(typeof a=="function")return a(m,c);let h,g=c.target;for(;g!=d;){if(h=g.dataset?g.dataset.action:null,h&&a[h]){a[h](m,c);return}g=g.parentNode}a[i]&&a[i](m,c)}return Mj.addEvent(n,i,l)}function Rj(n,a){const i=[hb(n,a,"click")];return a.dblclick&&i.push(hb(n,a.dblclick,"dblclick")),()=>{i.forEach(l=>l())}}function dw(n,a){return n.map((i,l)=>{const c=a(i,l);return i.data&&i.data.length&&(c.data=dw(i.data,a)),c}).filter(Boolean)}function fw(n,a){const i=[];return n.forEach(l=>{if(l.data){const c=fw(l.data,a);c.length&&i.push({...l,data:c})}else a(l)&&i.push(l)}),i}function Ej(n){return dw(n,(a,i)=>{const l={...a,id:a.id||Lp()};return l.type&&(l.comp=l.type),l.comp==="separator"&&n[i-1]?.comp==="separator"?null:l})}const mw={};function Dj(n){return mw[n]||n}function Lj(n,a){mw[n]=a}function _j({onClick:n,onShow:a,option:i}){const l=u.useRef(null),c=u.useCallback(()=>{a(i.data?i.id:!1,l.current)},[a,i]),d=u.useCallback(h=>{if(i.data){h.stopPropagation(),a(i.id,l.current);return}n(h)},[n,a,i]),m=u.useMemo(()=>i&&i.comp?Dj(i.comp):null,[i]);return r.jsxs("div",{ref:l,className:`wx-cDCz9rZQ wx-option ${i.css||""} ${i.disabled?"wx-disabled":""}`,"data-id":ea(i.id),onMouseEnter:c,onClick:d,children:[i.icon?r.jsx("i",{className:`wx-cDCz9rZQ wx-icon ${i.icon}`}):null,i.comp?m?r.jsx(m,{item:i,option:i}):null:r.jsxs("span",{className:"wx-cDCz9rZQ wx-value",children:[" ",i.text," "]}),i.subtext?r.jsx("span",{className:"wx-cDCz9rZQ wx-subtext",children:i.subtext}):null,i.data?r.jsx("i",{className:"wx-cDCz9rZQ wx-sub-icon wxi-angle-right"}):null]})}function Pp({options:n,left:a=0,top:i=0,at:l="bottom",parent:c=null,mount:d=null,context:m=null,css:h="",onClick:g,onCancel:y}){const[x,b]=u.useState(-1e4),[w,A]=u.useState(-1e4),[j,k]=u.useState(20),[N,M]=u.useState(),T=u.useRef(null),[D,F]=u.useState(!1),[$,G]=u.useState(null),L=u.useCallback(()=>{const de=Kx(T.current,c,l,a,i);de&&(b(de.x),A(de.y),M(de.width));let Z=de?.z??20;const z=c?Sk(c):[];let se=0;for(const W of z){const O=parseInt(getComputedStyle(W).zIndex,10);O>se&&(se=O)}se>=Z&&(Z=se+1),k(Z)},[c,l,a,i]);u.useEffect(()=>{d&&d(L)},[]);const Q=u.useCallback(()=>{F(!1)},[]),q=u.useCallback((de,Z)=>{F(de),G(Z)},[]),P=u.useMemo(()=>Ej(n),[n]);u.useEffect(()=>{L()},[c,L]);const Y=u.useRef(g),H=u.useRef(y),ye=u.useRef(c);return u.useEffect(()=>{Y.current=g},[g]),u.useEffect(()=>{H.current=y},[y]),u.useEffect(()=>{ye.current=c},[c]),u.useEffect(()=>{if(!T.current)return;function de(Z){H.current?H.current(Z):Y.current&&Y.current({action:null,option:null})}return Hr(T.current,{callback:de,modal:!0,parent:()=>ye.current}).destroy},[]),r.jsx("div",{ref:T,"data-wx-menu":"true",className:`wx-XMmAGqVx wx-menu ${h}`,style:{position:"absolute",top:w+"px",left:x+"px",width:N,zIndex:j},onMouseLeave:Q,children:P.map(de=>r.jsxs(u.Fragment,{children:[de.comp==="separator"?r.jsx("div",{className:"wx-XMmAGqVx wx-separator"}):r.jsx(_j,{option:de,onShow:q,onClick:Z=>{if(!de.data&&!Z.defaultPrevented){const z={context:m,action:de,option:de,event:Z};de.handler&&de.handler(z),g&&g(z),Z.stopPropagation()}}}),de.data&&D===de.id?r.jsx(Pp,{css:h,options:de.data,at:"right-overlap",parent:$,context:m,onClick:g,onCancel:y}):null]},de.id))})}const hw=u.forwardRef(function(n,a){const{options:i,at:l="bottom",resolver:c=null,dataKey:d="contextId",filter:m=null,css:h="",children:g,onClick:y}=n,[x,b]=u.useState(null),[w,A]=u.useState(null),[j,k]=u.useState(0),[N,M]=u.useState(0),T=u.useRef(null),D=u.useMemo(()=>`data-${d.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,[d]),F=u.useMemo(()=>x!==null&&m?fw(i,Q=>m(Q,x)):i,[x,m,i]);function $(Q){A(null),y&&y(Q)}function G(Q){if(T.current===Q){T.current=null;return}A(null),y&&y({action:null,option:null})}const L=u.useCallback((Q,q)=>{if(!Q){A(null);return}if(Q.defaultPrevented)return;const P=Q.target;if(P&&P.dataset&&P.dataset.menuIgnore)return;if(w&&w===P){A(null),Q.preventDefault();return}k(Q.clientX+1),M(Q.clientY+1);let Y=typeof q<"u"?q:Vu(P,D);c&&(Y=c(Y,Q),!Y)||(b(Y),A(P),T.current=Q.nativeEvent||Q,Q.preventDefault())},[w,D,c]);return u.useImperativeHandle(a,()=>({show:L}),[L]),r.jsxs(r.Fragment,{children:[g?r.jsx("span",{onClick:L,"data-menu-ignore":"true",children:typeof g=="function"?g():g}):null,w?r.jsx(Ip,{children:r.jsx(Pp,{css:h,at:l,top:N,left:j,parent:w,context:x,onClick:$,onCancel:G,options:F},w)}):null]})}),Ij=u.forwardRef(function(n,a){const{options:i,at:l="bottom",css:c="",children:d,onClick:m}=n,[h,g]=u.useState(null),y=u.useRef(null);function x(j){g(null),m&&m(j)}function b(j){if(y.current===j){y.current=null;return}g(null),m&&m({action:null,option:null})}const w=u.useCallback(j=>{g(j.target),y.current=j.nativeEvent||j,j.preventDefault()},[]);u.useImperativeHandle(a,()=>({show:w}),[w]);function A(j){let k=j.target;for(;!k.dataset.menuIgnore;)g(k),k=k.parentNode}return r.jsxs(r.Fragment,{children:[r.jsx("span",{onClick:A,"data-menu-ignore":"true",children:d}),h?r.jsx(Ip,{children:r.jsx(Pp,{css:c,at:l,parent:h,options:i,onClick:x,onCancel:b})}):null]})}),zj=u.forwardRef(function(n,a){const{options:i,at:l="bottom",resolver:c=null,dataKey:d="contextId",filter:m=null,css:h="",children:g,onClick:y}=n,x=u.useRef(null),b=u.useCallback((w,A)=>{x.current.show(w,A)},[]);return u.useImperativeHandle(a,()=>({show:b}),[b]),r.jsxs(r.Fragment,{children:[g?r.jsx("span",{onContextMenu:b,"data-menu-ignore":"true",children:g}):null,r.jsx(hw,{css:h,at:l,options:i,resolver:c,dataKey:d,filter:m,ref:x,onClick:y})]})}),Oj={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 Hj=class{constructor(a,i,l,c,d){this.setFiles=a,this.setReady=i,this.setSignal=l,this.setDrag=c,d&&d.length&&this.setFiles(d)}open(a){this.setSignal(["click",a||{}])}getState(){let a="server";const i=this.files;for(let l=0;l<i.length;l++){if(i[l].status==="client")return"client";i[l].status==="error"&&(a="error")}return a}droparea(a,i){i=i||{};const l=()=>{i.dragEnter&&i.dragEnter(),this.setDrag(!0)},c=()=>{i.dragLeave&&i.dragLeave(),this.setDrag(!1)},d=h=>{h.preventDefault()},m=h=>{h.preventDefault(),this.setDrag(!1),this.setSignal(["drop",i,h]),i.dragLeave&&i.dragLeave(),i.drop&&i.drop()};return a.addEventListener("dragenter",l),a.addEventListener("dragleave",c),a.addEventListener("dragover",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,i){const l=this.files.findIndex(d=>d.id===a);if(l===-1)return;const c=[...this.files];return c[l]={...c[l],...i},this.files=c,this.setFiles(this.files),this.files[l]}deleteFile(a){this.files=this.files.filter(i=>i.id!==a),this.setFiles(this.files)}addFile(a,i){i?this.files=[...this.files,a]:this.files=[a],this.setFiles(this.files)}deleteAll(){this.files=[],this.setFiles(this.files)}};function pw(n){const[a,i]=u.useState([]),[l,c]=u.useState(Promise.resolve(null)),[d,m]=u.useState(null),[h,g]=u.useState(!1),y=u.useRef();return y.current||(y.current=new Hj(i,c,m,g,n)),y.current.files=a,y.current.ready=l,y.current.signal=d,y.current.drag=h,y.current}function Fj(n,a){{if(n){const i=n.getGroup(a);if(i)return i}return Yu(Oj).getGroup(a)}}const $j=()=>Math.random().toString(36).substr(2,9),Bj=({data:n,accept:a="",multiple:i=!0,folder:l=!1,uploadURL:c="",apiOnly:d=!1,disabled:m=!1,children:h,onChange:g,onUpload:y})=>{const x=u.useRef(null),b=u.useRef(null),[w,A]=u.useState({}),j=pw(),k=n||j,N=u.useContext(na.i18n),M=Fj(N,"uploader");u.useEffect(()=>{x.current&&l&&(x.current.webkitdirectory=!0)},[l]),u.useEffect(()=>{if(!d&&b.current&&!m)return k.droparea(b.current)},[d,m,b]);const T=P=>{const Y=new FormData;return Y.append("upload",P.file),fetch(c,{method:"POST",body:Y}).then(H=>H.json()).then(H=>({id:P.id,...H}),()=>({id:P.id,status:"error"})).catch(H=>(console.log(H),{id:P.id,status:"error"}))},D=(P,Y)=>{const H=k.updateFile(P,Y),ye={...H,status:k.getState()};H&&H.uploaded&&H.uploaded(ye),y&&y(ye),H.temp&&k.deleteFile(H.id)},F=P=>{if(!P)return;const Y=typeof c=="function"?c(P):T(P);k.setReady(Y.then(H=>{H.status=H.status||"server",D(P.id,H)}).catch(H=>{D(P.id,{status:"error",error:H})}))},$=(P,Y)=>{const H={...Y||w,id:$j(),status:"client",name:P.name,file:P};H.selected&&H.selected(H),g&&g(H),k.addFile(H,i),F(H),x.current&&(x.current.value="")},G=(P,Y,H)=>{P.isFile?P.file(ye=>{$(ye,H)}):P.isDirectory&&P.createReader().readEntries(ye=>{ye.forEach(de=>{G(de,Y+de.name+"/",H)})})},L=P=>{Array.from(P.target.files).forEach(Y=>$(Y))},Q=(P,Y)=>{Array.from(P.dataTransfer.items).forEach(H=>{const ye=H.webkitGetAsEntry();ye&&G(ye,"",Y)})},q=()=>{x.current&&x.current.click()};return u.useEffect(()=>{if(k.signal){const[P,Y,H]=k.signal;A(Y),P==="click"?q():P==="drop"&&Q(H,Y),k.setSignal(null)}},[k.signal]),d?r.jsxs(r.Fragment,{children:[r.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:x,onChange:L,accept:a,multiple:i,disabled:m}),h]}):r.jsxs("div",{className:`wx-at1A8tb8 wx-label ${k.drag?"wx-active":""} ${m?"wx-disabled":""}`,ref:b,children:[r.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:x,onChange:L,accept:a,multiple:i,disabled:m}),h||r.jsx("div",{className:"wx-at1A8tb8 wx-dropzone",children:r.jsxs("span",{children:[M("Drop files here or")," ",r.jsx("span",{className:"wx-at1A8tb8 wx-action",onClick:q,children:M("select files")})]})})]})};new Date().valueOf();function Pj(n,a){if(Object.keys(n).length!==Object.keys(a).length)return!1;for(const i in a){const l=n[i],c=a[i];if(!Wf(l,c))return!1}return!0}function Wf(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 i=n.length-1;i>=0;i--)if(!Wf(n[i],a[i]))return!1;return!0}else return Pj(n,a);return n===a}function hp(n){if(typeof n!="object"||n===null)return n;if(n instanceof Date)return new Date(n);if(n instanceof Array)return n.map(hp);const a={};for(const i in n)a[i]=hp(n[i]);return a}var gw=2,Uj=class{constructor(n){n&&(this._writable=n.writable,this._async=n.async),this._values={},this._state={}}setState(n,a=0){const i={};return this._wrapProperties(n,this._state,this._values,"",i,a),i}getState(){return this._values}getReactive(){return this._state}_wrapProperties(n,a,i,l,c,d){for(const m in n){const h=a[m],g=i[m],y=n[m];if(h&&(g===y&&typeof y!="object"||y instanceof Date&&g instanceof Date&&g.getTime()===y.getTime()))continue;const x=l+(l?".":"")+m;h?(h.__parse(y,x,c,d)&&(i[m]=y),d&gw?c[x]=h.__trigger:h.__trigger()):(y&&y.__reactive?a[m]=this._wrapNested(y,y,x,c):a[m]=this._wrapWritable(y),i[m]=y),c[x]=c[x]||null}}_wrapNested(n,a,i,l){const c=this._wrapWritable(n);return this._wrapProperties(n,c,a,i,l,0),c.__parse=(d,m,h,g)=>(this._wrapProperties(d,c,a,m,h,g),!1),c}_wrapWritable(n){const a=[],i=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(i,1):i())},__parse:function(l){return n=l,!0}}}},qj=class{constructor(n,a,i,l){typeof n=="function"?this._setter=n:this._setter=n.setState.bind(n),this._routes=a,this._parsers=i,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(h=>m[h]=!0),this._sources.set(d,m)})}),this._routes.forEach(c=>{c.length=Math.max(...c.in.map(d=>vw(d,this._sources,1)))}),this._bus=l}init(n){const a={};for(const i in n)if(this._prev[i]!==n[i]){const l=this._parsers[i];a[i]=l?l(n[i]):n[i]}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,gw);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 i=n.signals[a];i&&i()}}}setState(n,a=[]){const i=this._setter(n);return this._triggerUpdates(i,a),i}_triggerUpdates(n,a){const i=Object.keys(n),l=!a.length;a=a||[];for(let c=0;c<i.length;c++){const d=i[c],m=this._triggers.get(d);m&&m.forEach(h=>{a.indexOf(h)==-1&&a.push(h)})}l&&this._execNext(a)}_execNext(n){for(;n.length;){n.sort((i,l)=>i.length<l.length?1:-1);const a=n[n.length-1];n.splice(n.length-1),a.exec(n)}}};function vw(n,a,i){const l=a.get(n);if(!l)return i;const c=Object.keys(l).map(d=>vw(d,a,i+1));return Math.max(...c)}var Gj=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(n,a,i){let l=this._handlers[n];l?i&&i.intercept?l.unshift(a):l.push(a):l=this._handlers[n]=[a],i&&i.tag&&this._tag.set(a,i.tag)}intercept(n,a,i){this.on(n,a,{...i,intercept:!0})}detach(n){for(const a in this._handlers){const i=this._handlers[a];for(let l=i.length-1;l>=0;l--)this._tag.get(i[l])===n&&i.splice(l,1)}}async exec(n,a){const i=this._handlers[n];if(i)for(let l=0;l<i.length;l++){const c=i[l](a);if(c===!1||c&&c.then&&await c===!1)return}return this._nextHandler&&await this._nextHandler.exec(n,a),a}setNext(n){return this._nextHandler=n}};function Vj(n){return a=>a[n]}function Wj(n){return(a,i)=>a[n]=i}function xl(n,a){return(a.getter||Vj(a.id))(n)}function Eh(n,a,i){return(a.setter||Wj(a.id))(n,i)}function Yj(n,a){const i=document.createElement("a");i.href=URL.createObjectURL(n),i.download=a,document.body.appendChild(i),i.click(),document.body.removeChild(i)}function bl(n,a){let i=xl(n,a)??"";return a.template?i=a.template(i,n,a):a.optionsMap&&(Array.isArray(i)?i=i.map(l=>a.optionsMap.get(l)).join(", "):i=a.optionsMap.get(i)),typeof i>"u"?"":i+""}function Kj(n,a){const i=/\n|"|;|,/;let l="";const c=a.rows||`
13
- `,d=a.cols||" ",m=n._columns,h=n.flatData;a.header!==!1&&m[0].header&&(l=pb("header",m,l,d,c));for(let g=0;g<h.length;g++){const y=[];for(let x=0;x<m.length;x++){let b=bl(h[g],m[x]);i.test(b)&&(b='"'+b.replace(/"/g,'""')+'"'),y.push(b)}l+=(l?c:"")+y.join(d)}return a.footer!==!1&&m[0].footer&&(l=pb("footer",m,l,d,c)),l}function pb(n,a,i,l,c){const d=/\n|"|;|,/;for(let m=0;m<a[0][n].length;m++){const h=[];for(let g=0;g<a.length;g++){let y=(a[g][n][m].text||"")+"";d.test(y)&&(y='"'+y.replace(/"/g,'""')+'"'),h.push(y)}i+=(i?c:"")+h.join(l)}return i}const Qj="portrait",Xj=100,Zj="a4",Jj={a3:{width:11.7,height:16.5},a4:{width:8.27,height:11.7},letter:{width:8.5,height:11}};function eA(n,a){const i=[];let l=[],c=0;const d=n.filter(h=>!h.hidden),m=tA(a);return d.forEach((h,g)=>{c+h.width<=m?(c+=h.width,l.push(h)):(l.length&&i.push(l),l=[h],c=h.width),g===d.length-1&&l.length&&i.push(l)}),i}function gb(n,a,i){const l=[];return n.forEach((c,d)=>{const m=c[a];for(let h=0;h<i.length;h++){l[h]||(l[h]=[]);const g={...m[h]};if(l[h][d]!==null){if(!d&&!g.rowspan&&!g.colspan){let y=1,x=n[d+y][a][h],b=g.width;for(;!x.rowspan&&!x.colspan;)y++,x=n[d+y][a][h],b+=x.width;g.colspan=y,g.width=b,g.height=i[h]}if(l[h].push(g),!g.collapsed&&g.colspan>1){let y=g.colspan-1;if(g.colspan+d>n.length){const x=g.colspan-(g.colspan+d-n.length);g.colspan=x,g.width=n.slice(d,d+y+1).reduce((b,w)=>b+w.width,0),x>1&&(y=x-1)}for(let x=0;x<y;x++)l[h].push(null)}if(g.rowspan>1){const y=g.rowspan;for(let x=1;x<y;x++)l[h+x]||(l[h+x]=[]),l[h+x].push(null)}}}if(c.collapsed)for(let h=0;h<l.length;h++){const g=l[h],y=g[d];if(y&&y.collapsed){if(g[d]=null,!h)break}else{const x=y||g.findLast(b=>b?.colspan>=1);x&&(x.colspan=x.colspan-1,x.width=x.width-c.width)}}}),l.map(c=>c.filter(d=>d&&d.colspan!==0))}function tA(n){const{mode:a,ppi:i,paper:l}=n,{width:c,height:d}=Jj[l];return nA(a==="portrait"?c:d,i)}function nA(n,a){return n*a}function aA(n={}){const{mode:a,ppi:i,paper:l}=n;return{mode:a||Qj,ppi:i||Xj,paper:l||Zj}}function yw(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 sA(n,a,i){let l=n[i.id];if(i.filter.type==="richselect"&&l){const c=i.filter.config?.options||a.find(({id:d})=>d==i.id).options;c&&(l=c.find(({id:d})=>d==l).label)}return l??""}const vb=["resize-column","hide-column","update-cell"],rA=["delete-row","update-row","update-cell"],iA=["move-item"],lA=["resize-column","move-item"];class oA{undo=[];redo=[];progress={};in;getState;setState;_previousValues={};constructor(a,i,l){this.in=a,this.getState=i,this.setState=l,this.setHandlers(),this.resetStateHistory()}getHandlers(){return{"add-row":{handler:a=>({action:"delete-row",data:{id:a.id},source:{action:"add-row",data:a}})},"delete-row":{handler:a=>{const{id:i}=a,{data:l}=this.getPrev(),c=l.findIndex(d=>d.id===i);return{action:"add-row",data:{id:i,row:l[c],before:c<l.length-1?l[c+1].id:void 0},source:{action:"delete-row",data:a}}}},"update-cell":{handler:a=>{const{id:i,column:l}=a,c=this.getRow(i),d=this.getColumn(l),m=xl(c,d);return Wf(m,a.value)?null:{action:"update-cell",data:{id:i,column:l,value:m},source:{action:"update-cell",data:a}}}},"update-row":{handler:a=>{const{id:i,row:l}=a,c=this.getRow(i);for(const d in l)Object.keys(c).includes(d)||(c[d]=void 0);return{action:"update-row",data:{id:i,row:c},source:{action:"update-row",data:a}}}},"copy-row":{handler:a=>{const{id:i}=a,{data:l}=this.getState(),c=l.findIndex(m=>m.id===i),d=l[c];return{action:"delete-row",data:{id:i},source:{action:"add-row",data:{id:i,row:d,before:c<l.length-1?l[c+1].id:void 0}}}}},"resize-column":{handler:a=>{const{id:i,width:l}=a,c=this.getColumn(i),{_sizes:d}=this.getState();return{action:"resize-column",data:{id:i,width:c.width??d.columnWidth},source:{action:"resize-column",data:{id:i,width:l}}}}},"hide-column":{handler:a=>{const{id:i}=a,l=this.getColumn(i);return{action:"hide-column",data:{id:i,mode:l.hidden},source:{action:"hide-column",data:a}}}},"collapse-column":{handler:a=>{const{id:i,row:l,mode:c}=a;return{action:"collapse-column",data:{id:i,row:l,mode:typeof c=="boolean"?!c:c},source:{action:"collapse-column",data:a}}}},"move-item":{handler:a=>{const{id:i,target:l,mode:c}=a,{flatData:d}=this.getPrev(),m=d.findIndex(h=>h.id===i);return{action:"move-item",data:{id:i,target:d[m+(m?-1:1)].id,mode:m?"after":"before"},source:{action:"move-item",data:{id:i,target:l,mode:c}}}}},"open-row":{handler:a=>{const{id:i,nested:l}=a;return{action:"close-row",data:{id:i,nested:l},source:{action:"open-row",data:a}}}},"close-row":{handler:a=>{const{id:i,nested:l}=a;return{action:"open-row",data:{id:i,nested:l},source:{action:"close-row",data:a}}}}}}resetHistory(){this.undo=[],this.redo=[],this.progress={},this.resetStateHistory()}getPrev(){return this._previousValues}setHandlers(){const a=this.getHandlers();for(const i in a)this.in.intercept(i,l=>{if(!(l.eventSource==="undo"||l.eventSource==="redo"||l.skipUndo)){if(lA.includes(i)){(l.inProgress&&!this.progress[i]||typeof l.inProgress!="boolean")&&(iA.includes(i)&&this.setPrev("flatData"),vb.includes(i)&&this.setPrev("columns")),this.progress[i]=l.inProgress;return}rA.includes(i)&&this.setPrev("data"),vb.includes(i)&&this.setPrev("columns")}}),this.in.on(i,l=>{if(l.eventSource==="undo"||l.eventSource==="redo"||l.skipUndo||l.inProgress)return;const c=a[i].handler(l);c&&this.addToHistory(c)})}setPrev(a){this._previousValues[a]=hp(this.getState()[a])}addToHistory(a){this.undo.push(a),this.redo=[],this.setStateHistory()}handleUndo(){if(!this.undo.length)return;const a=this.undo.pop();this.redo.push({...a.source,source:a}),this.in.exec(a.action,{...a.data,eventSource:"undo"}),this.setStateHistory()}handleRedo(){if(!this.redo.length)return;const a=this.redo.pop();this.undo.push({...a.source,source:a}),this.in.exec(a.action,{...a.data,eventSource:"redo"}),this.setStateHistory()}resetStateHistory(){this.setState({history:{undo:0,redo:0}})}setStateHistory(){this.setState({history:{undo:this.undo.length,redo:this.redo.length}})}getRow(a){const{data:i}=this.getPrev();return this.getState().tree?this.getTreeRow(i,a):i.find(l=>l.id===a)}getTreeRow(a,i){for(let l=0;l<a.length;l++){if(a[l].id===i)return a[l];if(a[l].data){const c=this.getTreeRow(a[l].data,i);if(c)return c}}return null}getColumn(a){const{columns:i}=this.getPrev();return i.find(l=>l.id===a)}}function bw(n,a){return typeof n>"u"||n===null?-1:typeof a>"u"||a===null?1:n===a?0:n>a?1:-1}function cA(n,a){return-bw(n,a)}function uA(n,a){if(typeof a.sort=="function")return function(l,c){const d=a.sort(l,c);return n==="asc"?d:-d};const i=n==="asc"?bw:cA;return function(l,c){return i(xl(l,a),xl(c,a))}}function dA(n,a){if(!n||!n.length)return;const i=n.map(l=>{const c=a.find(d=>d.id==l.key);return uA(l.order,c)});return n.length===1?i[0]:function(l,c){for(let d=0;d<i.length;d++){const m=i[d](l,c);if(m!==0)return m}return 0}}const ff=28,fA=20;function mA(){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 zf(n,a,i,l,c){const d=document.createElement("div"),m=document.createElement("div"),h=document.body;c=c?`${c}px`:"auto";let g,y;m.className=a,d.classList.add(`wx-${i}-theme`),d.style.cssText=`height:auto;position:absolute;top:0px;left:100px;overflow:hidden;width=${c};white-space:nowrap;`,d.appendChild(m),h.appendChild(d),typeof n!="object"&&(n=[n]);for(let x=0;x<n.length;x++){m.innerText=n[x]+"";const b=d.getBoundingClientRect(),w=Math.ceil(b.width)+(l&&l.length?l[x]:0),A=Math.ceil(b.height);g=Math.max(g||0,w),y=Math.max(y||0,A)}return d.remove(),{width:g,height:y}}function yb(n,a,i,l,c){const d=[];for(let m=0;m<n.length;m++){const h=n[m][a],g=h.length;for(let y=0;y<g;y++){const{text:x,vertical:b,collapsed:w,rowspan:A,css:j}=h[y];if(!x){d[y]=Math.max(d[y]||0,l);continue}let k=0;if(b&&!w){let N=`wx-measure-cell-${a}`;if(N+=j?` ${j}`:"",k=zf(x,N,c).width,(A>1||!h[y+1])&&i>y+1){const M=A||i-y,T=d.slice(y,y+M).reduce((D,F)=>D+F,0);if(T<k){const D=Math.ceil((k-T)/M);for(let F=y;F<y+M;F++)d[F]=(d[F]||l)+D}continue}}d[y]=Math.max(d[y]||l,k)}}return d}function hA(n,a,i){const l=[],c=[];let d="wx-measure-cell-body";d+=n.css?` ${n.css}`:"";for(let m=0;m<a.length;m++){const h=a[m],g=bl(h,n);g&&(l.push(g),n.treetoggle?c.push(a[m].$level*ff+(a[m].$count?ff:0)+(n.draggable?ff:0)):n.draggable&&c.push(ff))}return zf(l,d,i,c).width}function pA(n,a){const i="wx-measure-cell-header",l=n.sort?fA:0;let c=n.header;if(typeof c=="string")return zf(c,i,a).width+l;let d;Array.isArray(c)||(c=[c]);for(let m=0;m<c.length;m++){const h=c[m],g=typeof h=="string"?h:h.text,y=i+(typeof h=="string"?"":` ${h.css}`);let x=zf(g,y,a).width;m===c.length-1&&(x+=l),d=Math.max(d||0,x)}return d}const gA={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&&yA(n,a):!0,multiselect:(n,a)=>!a||a?.length===0?!0:Array.isArray(n)?n?.some(i=>a.includes(i)):n&&a.includes(n)};function xw(n){return gA[n]}function vA(n,a){const i=[];for(const l in n){const c=a.find(g=>g.id==l),{config:d,type:m}=c.header.find(g=>g.filter).filter,h=n[l];i.push(g=>{const y=xl(g,c);return d?.handler?d.handler(y,h):xw(m)(y,h)})}return l=>{for(let c=0;c<i.length;c++)if(!i[c](l))return!1;return!0}}function yA(n,a){return n.getFullYear()===a.getFullYear()&&n.getMonth()===a.getMonth()&&n.getDate()===a.getDate()}let bA=class extends Uj{in;_router;_branches;_xlsxWorker;_historyManager;constructor(a){super({writable:a,async:!1});const i={rowHeight:37,columnWidth:160,headerHeight:36,footerHeight:36};this._router=new qj(super.setState.bind(this),[{in:["columns","sizes","_skin"],out:["_columns","_sizes"],exec:c=>{const{columns:d,sizes:m,_skin:h}=this.getState(),g=this.copyColumns(d),y=g.reduce((w,A)=>Math.max(A.header.length,w),0),x=g.reduce((w,A)=>Math.max(A.footer.length,w),0);g.forEach(this.setCollapsibleColumns);const b=this.normalizeSizes(g,m,y,x,h);for(let w=0;w<g.length;w++)this.normalizeColumns(g,w,"header",y,b),this.normalizeColumns(g,w,"footer",x,b);this.setState({_columns:g,_sizes:b},c)}},{in:["data","tree","_filterIds"],out:["flatData","_rowHeightFromData"],exec:c=>{const{data:d,tree:m,dynamic:h,_filterIds:g}=this.getState(),y=g&&new Set(g),x=m?this.flattenRows(d,[],g):y?d.filter(w=>y.has(w.id)):d,b=!h&&x.some(w=>w.rowHeight);this.setState({flatData:x,_rowHeightFromData:b},c)}}],{sizes:c=>({...i,...c})});const l=this.in=new Gj;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 h=this.getRow(c),g=d?this.getColumn(d):this.getNextEditor(h);if(g?.editor){let y=g.editor;if(typeof y=="function"&&(y=y(h,g)),!y)return;m={column:g.id,id:c,value:xl(h,g)??"",renderedValue:bl(h,g),type:y.type||y},typeof y=="object"&&y.config&&(m.config=y.config,y.config.options&&(m.options=y.config.options)),g.options&&!m.options&&(m.options=g.options),this.setState({editor:m})}}),l.on("editor",({value:c})=>{let d=this.getState().editor;if(d){d={...d},d.value=c;const m=this.getColumn(d.column),h={...this.getRow(d.id)};Eh(h,m,c),d.renderedValue=bl(h,m),this.setState({editor:d})}}),l.on("add-row",c=>{const d=this.getState();let{data:m}=d;const{select:h,_filterIds:g}=d,{row:y,before:x,after:b,select:w}=c;if(c.id=y.id=c.id||y.id||mf(),x||b){const j=x||b,k=m.findIndex(N=>N.id===j);m=[...m],m.splice(k+(b?1:0),0,c.row)}else m=[...m,c.row];const A={data:m};g&&(A._filterIds=[...g,c.id]),this.setState(A),!(typeof w=="boolean"&&!w)&&(w||h)&&l.exec("select-row",{id:y.id,show:!0})}),l.on("delete-row",c=>{const{data:d,selectedRows:m,focusCell:h,editor:g}=this.getState(),{id:y}=c,x={data:d.filter(b=>b.id!==y)};this.isSelected(y)&&(x.selectedRows=m.filter(b=>b!==y)),g?.id===y&&(x.editor=null),this.setState(x),h?.row===y&&this.in.exec("focus-cell",{eventSource:"delete-row"})}),l.on("update-cell",c=>{const d=this.getState();let{data:m}=d;m=[...m];const{tree:h}=d,{id:g,column:y,value:x}=c,b=this.getColumn(y);if(h){const w={...this._branches[g]};Eh(w,b,x);const A=this.updateTreeRow(w);w.$parent===0&&(m=A)}else{const w=m.findIndex(j=>j.id===g),A={...m[w]};Eh(A,b,x),m[w]=A}this.setState({data:m})}),l.on("update-row",c=>{let{data:d}=this.getState();const{id:m,row:h}=c,g=d.findIndex(y=>y.id===m);d=[...d],d[g]={...d[g],...h},this.setState({data:d})}),l.on("select-row",({id:c,toggle:d,range:m,mode:h,show:g,column:y})=>{const x=this.getState(),{focusCell:b}=x;let{selectedRows:w}=x;if(w.length||(m=d=!1),m){const{data:A}=this.getState();let j=A.findIndex(N=>N.id===w[w.length-1]),k=A.findIndex(N=>N.id===c);j>k&&([j,k]=[k,j]),A.slice(j,k+1).forEach(N=>{this.isSelected(N.id)||w.push(N.id)})}else if(d&&this.isSelected(c)){if(h===!0)return;w=w.filter(A=>A!==c)}else if(d){if(h===!1)return;w.push(c)}else w=[c];this.setState({selectedRows:[...w]}),b?.row!==c&&this.in.exec("focus-cell",{eventSource:"select-row"}),g&&this.in.exec("scroll",{row:c,column:y})}),this.in.on("focus-cell",c=>{const{row:d,column:m,eventSource:h}=c,{_columns:g,split:y}=this.getState();d&&m?(this.setState({focusCell:{row:d,column:m}}),h!=="click"&&((!y.left||g.findIndex(x=>x.id===c.column)>=y.left)&&(!y.right||g.findIndex(x=>x.id===c.column)<g.length-y.right)?this.in.exec("scroll",{row:d,column:m}):this.in.exec("scroll",{row:d}))):this.setState({focusCell:null})}),l.on("resize-column",c=>{const{id:d,auto:m,maxRows:h,inProgress:g}=c;if(g===!1)return;let y=c.width||0;const x=[...this.getState().columns],b=this.getColumn(d);if(m){if(m==="data"||m===!0){const{flatData:w,_skin:A}=this.getState();let j=w.length;h&&(j=Math.min(h,j));const k=w.slice(0,j);y=hA(b,k,A)}if(m==="header"||m===!0){const{_skin:w}=this.getState();y=Math.max(pA(b,w),y)}}b.width=Math.max(17,y),delete b.flexgrow,this.setState({columns:x})}),l.on("hide-column",c=>{const{id:d,mode:m}=c,h=[...this.getState().columns],g=this.getColumn(d),y=h.reduce((x,b)=>x+(b.hidden?0:1),0);!m||y>1?(g.hidden=!g.hidden,this.setState({columns:h})):c.skipUndo=!0}),l.on("sort-rows",c=>{const{key:d,add:m,sort:h}=c,g=this.getState(),{columns:y,data:x,tree:b}=g;if(h){const T=[...x];T.sort(h),this.setState({data:T});return}const{order:w="asc"}=c;let A=g.sortMarks;const j=Object.keys(A),k=j.length;!m||!k||k===1&&A[d]?A={[d]:{order:w}}:(k===1&&(A[j[0]]={...A[j[0]],index:0}),A={...A,[d]:{order:w,index:typeof m=="number"?m:A[d]?.index??k}});const N=Object.keys(A).sort((T,D)=>A[T].index-A[D].index).map(T=>({key:T,order:A[T].order}));this.setState({sortMarks:A});const M=dA(N,y);if(M){const T=[...x];b?this.sortTree(T,M):T.sort(M),this.setState({data:T})}}),l.on("filter-rows",c=>{const{value:d,key:m,filter:h}=c;if(!Object.keys(c).length){this.setState({filterValues:{},_filterIds:null});return}const g=this.getState(),{data:y,tree:x,_columns:b}=g;let w=g.filterValues;const A={};m&&(w={...w,[m]:d},A.filterValues=w);const j=h??vA(w,b);let k=[];x?k=this.filterTree(y,j,k):y.forEach(N=>{j(N)&&k.push(N.id)}),A._filterIds=k,this.setState(A)}),l.on("collapse-column",c=>{const{id:d,row:m,mode:h}=c,g=[...this.getState().columns],y=this.getColumn(d).header,x=Array.isArray(y)?y[m]:y;typeof x=="object"&&(x.collapsed=h??!x.collapsed,this.setState({columns:g}))}),l.on("move-item",c=>{const{id:d,inProgress:m}=c;let{target:h,mode:g="after"}=c;const{data:y,flatData:x,tree:b}=this.getState(),w=x.findIndex(k=>k.id===d);let A;if(g==="up"||g==="down"){if(g==="up"){if(w===0)return;A=w-1,g="before"}else if(g==="down"){if(w===x.length-1)return;A=w+1,g="after"}h=x[A]&&x[A].id}else A=x.findIndex(k=>k.id===h);if(w===-1||A===-1||m===!1)return;let j;b||(j=this.moveItem(d,h,y,g)),this.setState({data:b?this.normalizeTreeRows(j):j})}),l.on("copy-row",c=>{const{id:d,target:m,mode:h="after"}=c,g=this.getState(),{flatData:y,_filterIds:x}=g;let{data:b}=g;const w=this.getRow(d);if(!w)return;const A={...w,id:mf()};c.id=A.id;const j=y.findIndex(N=>N.id===m);if(j===-1)return;b.splice(j+(h==="after"?1:0),0,A),b=[...b];const k={data:b};x&&(k._filterIds=[...x,A.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 h=c.format||"csv",g=`${c.fileName||"data"}.${h}`;if(h==="csv"){const y=Kj(this.getState(),c.csv||{});c.download!==!1?Yj(new Blob(["\uFEFF"+y],{type:"text/csv"}),g):c.result=y,d(!0)}else m()})),l.on("hotkey",({key:c,event:d,isInput:m})=>{switch(c){case"arrowup":{const{flatData:h,focusCell:g,select:y}=this.getState();if(d.preventDefault(),m)return;const x=g?g.column:this._getFirstVisibleColumn()?.id,b=g?this.getPrevRow(g.row)?.id:h[h.length-1]?.id;x&&b&&(this.in.exec("focus-cell",{row:b,column:x,eventSource:"key"}),y&&this.in.exec("select-row",{id:b}));break}case"arrowdown":{const{flatData:h,focusCell:g,select:y}=this.getState();if(d.preventDefault(),m)return;const x=g?g.column:this._getFirstVisibleColumn()?.id,b=g?this.getNextRow(g.row)?.id:h[0]?.id;x&&b&&(this.in.exec("focus-cell",{row:b,column:x,eventSource:"key"}),y&&this.in.exec("select-row",{id:b}));break}case"arrowright":{const{focusCell:h}=this.getState();if(m)return;if(d.preventDefault(),h){const g=this.getNextColumn(h.column,!0)?.id;g&&this.in.exec("focus-cell",{row:h.row,column:g,eventSource:"key"})}break}case"arrowleft":{const{focusCell:h}=this.getState();if(m)return;if(d.preventDefault(),h){const g=this.getPrevColumn(h.column,!0)?.id;g&&this.in.exec("focus-cell",{row:h.row,column:g,eventSource:"key"})}break}case"tab":{const{editor:h,focusCell:g,select:y}=this.getState();if(h){d.preventDefault();const x=h.column;let b=h.id,w=this.getNextEditor(this.getRow(b),this.getColumn(x));if(!w){const A=this.getNextRow(b);A&&(b=A.id,w=this.getNextEditor(A))}w&&(this.in.exec("open-editor",{id:b,column:w.id}),this.in.exec("focus-cell",{row:b,column:w.id,eventSource:"key"}),y&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}else g&&this.in.exec("focus-cell",{eventSource:"key"});break}case"shift+tab":{const{editor:h,focusCell:g,select:y}=this.getState();if(h){d.preventDefault();const x=h.column;let b=h.id,w=this.getPrevEditor(this.getRow(b),this.getColumn(x));if(!w){const A=this.getPrevRow(b);A&&(b=A.id,w=this.getPrevEditor(A))}w&&(this.in.exec("open-editor",{id:b,column:w.id}),this.in.exec("focus-cell",{row:b,column:w.id,eventSource:"key"}),y&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}else g&&this.in.exec("focus-cell",{eventSource:"key"});break}case"escape":{const{editor:h}=this.getState();h&&(this.in.exec("close-editor",{ignore:h.type!="multiselect"}),this.in.exec("focus-cell",{row:h.id,column:h.column,eventSource:"key"}));break}case"f2":{const{editor:h,focusCell:g}=this.getState();!h&&g&&this.in.exec("open-editor",{id:g.row,column:g.column});break}case"enter":{const{focusCell:h,tree:g}=this.getState();if(!m&&g&&h&&this.getColumn(h.column).treetoggle){const y=this.getRow(h.row);if(!y.data)return;this.in.exec(y.open?"close-row":"open-row",{id:h.row,nested:!0})}break}case"home":{const{editor:h,focusCell:g}=this.getState();if(!h&&g){d.preventDefault();const y=this._getFirstVisibleColumn()?.id;this.in.exec("focus-cell",{row:g.row,column:y,eventSource:"key"})}break}case"ctrl+home":{const{editor:h,focusCell:g,flatData:y,select:x}=this.getState();if(!h&&g){d.preventDefault();const b=y[0]?.id,w=this._getFirstVisibleColumn()?.id;b&&w&&(this.in.exec("focus-cell",{row:b,column:w,eventSource:"key"}),x&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}break}case"end":{const{editor:h,focusCell:g}=this.getState();if(!h&&g){d.preventDefault();const y=this._getLastVisibleColumn()?.id,x=g.row;this.in.exec("focus-cell",{row:x,column:y,eventSource:"key"})}break}case"ctrl+end":{const{editor:h,focusCell:g,flatData:y,select:x}=this.getState();if(!h&&g){d.preventDefault();const b=y.at(-1).id,w=this._getLastVisibleColumn()?.id;b&&w&&(this.in.exec("focus-cell",{row:b,column:w,eventSource:"key"}),x&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}break}case"ctrl+z":{this.in.exec("undo",{});break}case"ctrl+y":{this.in.exec("redo",{});break}}}),l.on("scroll",c=>{const{_columns:d,split:m,_sizes:h,flatData:g,dynamic:y,_rowHeightFromData:x}=this.getState();let b=-1,w=-1,A=0,j=0;if(c.column){b=0;const k=d.findIndex(N=>N.id===c.column);A=d[k].width;for(let N=m.left??0;N<k;N++){const M=d[N];M.hidden||(b+=M.width)}}if(c.row&&!y){const k=g.findIndex(N=>N.id===c.row);k>=0&&(x?(w=g.slice(0,k).reduce((N,M)=>N+(M.rowHeight||h.rowHeight),0),j=g[k].rowHeight):w=h.rowHeight*k)}this.setState({scroll:{top:w,left:b,width:A,height:j||h.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=aA(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 i=window.URL.createObjectURL(new Blob([`importScripts('${a}');`],{type:"text/javascript"}));this._xlsxWorker=new Promise(l=>{const c=new Worker(i);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=mA()),a.columns&&a.columns.forEach(i=>{i.options&&(i.optionsMap=new Map(i.options.map(l=>[l.id,l.label])))}),Wf(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 oA(this.in,this.getState.bind(this),this.setState.bind(this))),this._router.init({...a})}setState(a,i){return this._router.setState(a,i)}setStateAsync(a){this._router.setStateAsync(a)}getRow(a){const{tree:i}=this.getState();return i?this._branches[a]:this.getState().data.find(l=>l.id===a)}getRowIndex(a,i){return i||(i=this.getState().flatData),i.findIndex(l=>l.id===a)}getNextRow(a){const i=this.getState().flatData,l=this.getRowIndex(a,i);return i[l+1]}getPrevRow(a){const i=this.getState().flatData,l=this.getRowIndex(a,i);return i[l-1]}getColumn(a){return this.getState().columns.find(i=>i.id===a)}getNextColumn(a,i){const l=this.getState()._columns,c=l.findIndex(d=>d.id===a);return i?this._getFirstVisibleColumn(c+1):l[c+1]}getPrevColumn(a,i){const l=this.getState()._columns,c=l.findIndex(d=>d.id===a);return i?this._getLastVisibleColumn(c-1):l[c-1]}_getFirstVisibleColumn(a){const i=this.getState()._columns;let l=a??0;for(;l<i.length&&(i[l]?.hidden||i[l]?.collapsed);)l++;return i[l]}_getLastVisibleColumn(a){const i=this.getState()._columns;let l=a??i.length-1;for(;l<i.length&&(i[l]?.hidden||i[l]?.collapsed);)l--;return i[l]}isCellEditable(a,i){const{editor:l,hidden:c}=i;return!l||c?!1:typeof l=="function"?l(a,i):!0}getNextEditor(a,i){let l=this.getState().columns;if(i){const c=l.findIndex(d=>d.id===i.id);l=l.slice(c+1)}return l.find(c=>this.isCellEditable(a,c))}getPrevEditor(a,i){let l=this.getState().columns;if(i){const c=l.findLastIndex(d=>d.id===i.id);l=l.slice(0,c)}return l.findLast(c=>this.isCellEditable(a,c))}toggleBranch(a,i,l){let c=this._branches[a],{data:d}=this.getState();if(d=[...d],a!==0){c={...c,open:i};const m=this.updateTreeRow(c);c.$parent===0&&(d=m)}l&&c.data?.length&&c.data.forEach(m=>{const h=this.toggleKids(m,i,l);a===0&&(d=h)}),this.setState({data:d})}toggleKids(a,i,l){a={...a,open:i};const c=this.updateTreeRow(a);return l&&a.data?.length&&a.data.forEach(d=>{this.toggleKids(d,i,l)}),c}updateTreeRow(a){const i=a.id;this._branches[i]=a;const l=this._branches[a.$parent],c=l.data.findIndex(d=>d.id===i);return l.data=[...l.data],l.data[c]=a,l.data}isSelected(a){return this.getState().selectedRows.indexOf(a)!==-1}findAndRemove(a,i){for(let l=0;l<a.length;l++){if(a[l].id===i)return a.splice(l,1)[0];if(a[l].data){const c=[...a[l].data],d=this.findAndRemove(c,i);if(d)return a[l]={...a[l],data:c},d}}return null}insertItem(a,i,l,c){for(let d=0;d<a.length;d++){if(a[d].id===i){const m=a[d],h=c==="before"?d:d+1;if(m.data){if(c==="before"){const g=d>0?a[d-1]:null;return g?.data&&g.open?a[d-1]={...g,data:[...g.data,l]}:a.splice(h,0,l),!0}else if(m.open)return a[d]={...m,data:[l,...m.data]},!0}return a.splice(h,0,l),!0}if(a[d].data&&(a[d]={...a[d],data:[...a[d].data]},this.insertItem(a[d].data,i,l,c)))return!0}return!1}moveItem(a,i,l,c){const d=[...l],m=this.findAndRemove(d,a);return this.insertItem(d,i,m,c),d}copyColumns(a){const i=[];for(let l=0;l<a.length;l++){const c={...a[l]};this.copyHeaderFooter(c,"header"),this.copyHeaderFooter(c,"footer"),i[l]=c}return i}copyHeaderFooter(a,i){let l=a[i];l=Array.isArray(l)?[...l]:[l],l.forEach((c,d)=>{l[d]=typeof c=="string"?{text:c}:{...c}}),a[i]=l}setCollapsibleColumns(a,i,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 g=c.length-d;c=c.slice(0,d+1),c[d].rowspan=g}const h=m.colspan;if(h){const g=c[d+1];let y=1;g&&g.colspan&&!g.collapsed&&(y=g.colspan);for(let x=y;x<h;x++){const b=l[i+x];b&&(b.hidden=!0)}}}}}normalizeColumns(a,i,l,c,d){const m=a[i];m.width||(m.width=m.flexgrow?17:d.columnWidth),m._colindex=i+1;const h=m[l],g=d[`${l}RowHeights`];for(let y=0;y<c;y++){const x=h[y];x.id=m.id,y===h.length-1&&(x.rowspan=x.rowspan?Math.min(x.rowspan,c-y):c-y);for(let b=1;b<x.rowspan;b++){h.splice(y+b,0,{_hidden:!0});for(let w=1;w<x.colspan;w++)a[i+w][l].splice(y+b,0,{})}if(x.rowspan){const b=(x.rowspan===c?g:g.slice(y,x.rowspan+y)).reduce((w,A)=>w+A,0);x.height=b,y+x.rowspan!=c&&x.height--}if(x.colspan){let b=m.width,w=m.flexgrow||0;const A=x.colspan;for(let j=1;j<A;j++){const k=a[i+j];k&&(k.hidden?x.colspan-=1:k.flexgrow?w+=k.flexgrow:b+=k.width||d.columnWidth),w?x.flexgrow=w:x.width=b}}else x.width=m.width,x.flexgrow=m.flexgrow;l==="header"&&x.filter&&typeof x.filter=="string"&&(x.filter={type:x.filter})}h.length>c&&(h.length=c),m[l]=h}normalizeRows(a){for(let i=0;i<a.length;i++)a[i].id||(a[i].id=mf());return a}normalizeTreeRows(a,i,l){return!i&&!l&&(this._branches={0:{data:a}}),a.forEach(c=>{c.id||(c.id=mf()),c.$level=i||0,c.$parent=l||0,this._branches[c.id]=c,c.data&&(c.data.length?(c.$count=c.data.length,this.normalizeTreeRows(c.data,c.$level+1,c.id)):(delete c.data,delete c.$count,delete c.open))}),a}sortTree(a,i){a.sort(i),a.forEach(l=>{l.data&&this.sortTree(l.data,i)})}filterTree(a,i,l){return a.forEach(c=>{i(c)&&l.push(c.id),c.data&&this.filterTree(c.data,i,l)}),l}flattenRows(a,i,l){const c=i;return a.forEach(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:i}=this.getState(),l=[];for(const c in a){const d=i.find(y=>y.id==c),{config:m,type:h}=d.header.find(y=>y.filter).filter,g=a[c];l.push(y=>{const x=xl(y,d);return m?.handler?m.handler(x,g):xw(h)(x,g)})}return c=>{for(let d=0;d<l.length;d++)if(!l[d](c))return!1;return!0}}searchRows(a,i){a=a.trim().toLowerCase();const l={};if(!a)return l;const{flatData:c,columns:d}=this.getState(),m=i?d.filter(h=>i[h.id]):d;return c.forEach(h=>{const g={};m.forEach(y=>{const x=bl(h,y);String(x).toLowerCase().includes(a)&&(g[y.id]=!0)}),Object.keys(g).length&&(l[h.id]=g)}),l}normalizeSizes(a,i,l,c,d){const m=yb(a,"header",l,i.headerHeight,d),h=yb(a,"footer",c,i.footerHeight,d),g=m.reduce((x,b)=>x+b,0),y=h.reduce((x,b)=>x+b,0);return{...i,headerRowHeights:m,footerRowHeights:h,headerHeight:g,footerHeight:y}}},xA=new Date().valueOf();function mf(){return"temp://"+xA++}function wA(n,a="data-id"){let i=n;for(!i.tagName&&n.target&&(i=n.target);i;){if(i.getAttribute&&i.getAttribute(a))return i;i=i.parentNode}return null}new Date().valueOf();var SA=class{constructor(){this.store=new Map}configure(n,a){this.node=a;for(const i in n)if(n[i]){const l=i.toLowerCase().replace(/[ ]/g,""),c=n[i];this.store.set(l,c)}}},xc=[],CA={subscribe:n=>{kA();const a=new SA;return xc.push(a),n(a),()=>{const i=xc.findIndex(l=>l===a);i>=0&&xc.splice(i,1)}}},bb=!1;function kA(){bb||(bb=!0,document.addEventListener("keydown",n=>{if(xc.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 i=n.code.replace("Key","").toLocaleLowerCase();n.key===" "&&(i="space"),a.push(i);const l=a.join("+");for(let c=xc.length-1;c>=0;c--){const d=xc[c],m=d.store.get(l)||d.store.get(i);m&&d.node.contains(n.target)&&m(n,{key:l,evKey:i})}}}))}const jA={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 AA(n,{keys:a,exec:i}){if(!a)return;function l(m){const h=m.target;return h.tagName==="INPUT"||h.tagName==="TEXTAREA"||wA(h,"data-header-id")?.classList.contains("wx-filter")||!!h.closest(".wx-cell.wx-editor")}const c={};for(const m in a){const h=a[m];typeof h<"u"&&(typeof h=="function"?c[m]=h:h&&(c[m]=g=>{const y=l(g);i({key:m,event:g,isInput:y})}))}const d=CA.subscribe(m=>{m.configure(c,n)});return{destroy:()=>{d()}}}function MA(n,a){let i=null;a.scroll.subscribe(l=>{if(!l||l===i)return;i=l;const{left:c,top:d,height:m,width:h}=l,g=a.getHeight(),y=a.getWidth(),x=a.getScrollMargin();if(d>=0){const b=n.scrollTop;d<b?n.scrollTop=d:d+m>b+g&&(n.scrollTop=d-g+m)}if(c>=0){const b=n.scrollLeft;c<b?n.scrollLeft=c:c+h>b+y-x&&(n.scrollLeft=c-y+h+x)}}),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 xs=u.createContext(null);function NA(n,a){const i=new ResizeObserver(l=>{requestAnimationFrame(()=>a(l[0].contentRect))});return i.observe(n.parentNode),{destroy(){i.disconnect()}}}const xb=5,TA=700;function Af(n){const a=n.getBoundingClientRect(),i=document.body,l=a.top+i.scrollTop-i.clientTop||0,c=a.left+i.scrollLeft-i.clientLeft||0;return{y:Math.round(l),x:Math.round(c),width:n.offsetWidth,height:n.offsetHeight}}function pp(n,a){const i=Af(a);return{x:n.clientX-i.x,y:n.clientY-i.y}}function RA(n,a){const i=a.current;let l=null,c,d,m=!1,h=!1;const g=document.createElement("DIV");g.className="wx-drag-zone",g.setAttribute("tabindex",-1);function y(){clearTimeout(c),c=null}function x(L){const Q=jc(L);Q&&(l={container:g,sourceNode:L.target,from:qf(Q),pos:pp(L,n)},d=l.pos,b(L))}function b(L){if(!l)return;const Q=l.pos=pp(L,n);if(!m){if(!h&&!L?.target?.getAttribute("draggable-data")&&Math.abs(d.x-Q.x)<xb&&Math.abs(d.y-Q.y)<xb)return;if($(L)===!1)return G()}if(h){const q=window.scrollX||document.documentElement.scrollLeft||document.body.scrollLeft,P=window.scrollY||document.documentElement.scrollTop||document.body.scrollTop;l.targetNode=document.elementFromPoint(L.pageX-q,L.pageY-P)}else l.targetNode=L.target;i.move&&i.move(L,l),g.style.left=-(l.offset?l.offset.x:0)+"px",g.style.top=l.pos.y+(l.offset?l.offset.y:0)+"px"}function w(L){g.parentNode&&g.parentNode.removeChild(g),g.innerHTML="",m&&i.end&&i.end(L,l),l=d=null,G()}function A(L){i.getReorder&&!i.getReorder()||L.button===0&&(F(L),window.addEventListener("mousemove",j),window.addEventListener("mouseup",k),x(L))}function j(L){b(L)}function k(L){w(L)}function N(L){if(i.getReorder&&!i.getReorder())return;c=setTimeout(()=>{h=!0,x(L.touches[0])},TA),F(L);function Q(){c&&y(),L.target.removeEventListener("touchmove",M),L.target.removeEventListener("touchend",Q),w(L)}L.target.addEventListener("touchmove",M),L.target.addEventListener("touchend",Q),n.addEventListener("contextmenu",T)}function M(L){m?(L.preventDefault(),b(L.touches[0])):c&&y()}function T(L){if(m||c)return L.preventDefault(),!1}function D(L){L.preventDefault()}function F(L){if(!i.getDraggableInfo)return;const{hasDraggable:Q}=i.getDraggableInfo();(!Q||L.target.getAttribute("draggable-data"))&&(document.body.style.userSelect="none",document.body.style.webkitUserSelect="none")}function $(L){if(m=!0,i.start){if(i.start(L,l)===!1)return!1;n.appendChild(g),document.body.style.cursor="move"}}function G(L){m=h=!1,document.body.style.cursor="",document.body.style.userSelect="",document.body.style.webkitUserSelect="",window.removeEventListener("mousemove",j),window.removeEventListener("mouseup",k),L&&(n.removeEventListener("mousedown",A),n.removeEventListener("touchstart",N),n.removeEventListener("dragstart",D))}return n.addEventListener("mousedown",A),n.addEventListener("touchstart",N),n.addEventListener("dragstart",D),{destroy(){G(!0)}}}const EA=.004;function DA(){return{dirX:0,dirY:0,scrollSpeedFactor:1}}function LA(n,a,i,l){const{node:c,left:d,top:m,bottom:h,sense:g,xScroll:y,yScroll:x}=l,b=pp(n,c);i.scrollState||(i.scrollState=DA());let w=0,A=0;b.x<d+g?w=-1:b.x>a.width-g&&(w=1),b.y<m+Math.round(g/2)?A=-1:b.y>a.height-h-Math.round(g/2)&&(A=1),(i.scrollState.dirX!==w||i.scrollState.dirY!==A)&&(ww(i),i.scrollState.dirX=w,i.scrollState.dirY=A),(y&&i.scrollState.dirX!==0||x&&i.scrollState.dirY!==0)&&_A(i,l,{x:i.scrollState.dirX,y:i.scrollState.dirY})}function _A(n,a,i){n.autoScrollTimer||(n.autoScrollTimer=setTimeout(()=>{n.activeAutoScroll=setInterval(IA,15,n,a,i)},250))}function ww(n){n.scrollSpeedFactor=1,n.autoScrollTimer&&(n.autoScrollTimer=clearTimeout(n.autoScrollTimer),n.activeAutoScroll=clearInterval(n.activeAutoScroll))}function IA(n,a,i){const{x:l,y:c}=i;n.scrollSpeedFactor+=EA,l!==0&&OA(n,a,l),c!==0&&zA(n,a,c)}function zA(n,a,i){const l=a.node.scrollTop;Sw(l+Math.round(a.sense/3)*n.scrollSpeedFactor*i,"scrollTop",a)}function OA(n,a,i){const l=a.node.scrollLeft;Sw(l+Math.round(a.sense/3)*n.scrollSpeedFactor*i,"scrollLeft",a)}function Sw(n,a,i){i.node[a]=n}function Yf(n,a,i,l,c,d){const m={};return n&&(m.width=`${n}px`,m.minWidth=`${n}px`),a&&(m.flexGrow=a),d&&(m.height=`${d}px`),i&&(m.position="sticky",i.left&&(m.left=`${l}px`),i.right&&(m.right=`${c}px`)),m}function Cw(n,a,i){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+=i?i(n)+" ":"",l}function HA(n){const{row:a,column:i,cellStyle:l=null,columnStyle:c=null,children:d,focusable:m}=n,h=u.useContext(xs),g=gt(h,"focusCell"),y=gt(h,"search"),x=gt(h,"reorder"),b=u.useMemo(()=>y?.rows[a.id]&&y.rows[a.id][i.id],[y,a.id,i.id]),w=u.useMemo(()=>Yf(i.width,i.flexgrow,i.fixed,i.left,i.right),[i.width,i.flexgrow,i.fixed,i.left,i.right]);function A($,G){let L="wx-cell";return L+=i.fixed?" "+(i.fixed===-1?"wx-shadow":"wx-fixed"):"",L+=$?" "+$(i):"",L+=G?" "+G(a,i):"",L+=i.treetoggle?" wx-tree-cell":"",L}const j=u.useMemo(()=>A(c,l),[c,l,i,a]),k=u.useMemo(()=>typeof i.draggable=="function"?i.draggable(a,i)!==!1:i.draggable,[i,a]),N=u.useRef(null);u.useEffect(()=>{N.current&&m&&g?.row===a.id&&g?.column===i.id&&N.current.focus()},[g,m,a.id,i.id]);const M=u.useCallback(()=>{m&&!g&&h.exec("focus-cell",{row:a.id,column:i.id,eventSource:"focus"})},[h,m,g,a.id,i.id]);function T($){const G=new RegExp(`(${y.value.trim()})`,"gi");return String($).split(G).map(L=>({text:L,highlight:G.test(L)}))}const D=u.useMemo(()=>{const $=i.fixed&&i.fixed.left===-1||i.fixed.right===-1,G=i.fixed&&i.fixed.right;return[j,$?"wx-shadow":"",G?"wx-fixed-right":""].filter(Boolean).join(" ")},[j,i]),F=i.cell;return r.jsxs("div",{className:"wx-TSCaXsGV "+D,ref:N,onFocus:M,style:w,"data-row-id":ea(a.id),"data-col-id":ea(i.id),tabIndex:m?"0":"-1",role:"gridcell","aria-colindex":i._colindex,"aria-readonly":i.editor?void 0:!0,children:[x&&i.draggable?k?r.jsx("i",{"draggable-data":"true",className:"wx-TSCaXsGV wx-draggable wxi-drag"}):r.jsx("i",{className:"wx-TSCaXsGV wx-draggable-stub"}):null,i.treetoggle?r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{marginLeft:`${a.$level*28}px`}}),a.$count?r.jsx("i",{"data-action":"toggle-row",className:`wx-TSCaXsGV wx-table-tree-toggle wxi-menu-${a.open!==!1?"down":"right"}`}):null]}):null,F?r.jsx(F,{api:h,row:a,column:i,onAction:({action:$,data:G})=>h.exec($,G)}):d?d():b?r.jsx("span",{children:T(bl(a,i)).map(({highlight:$,text:G},L)=>$?r.jsx("mark",{className:"wx-TSCaXsGV wx-search",children:G},L):r.jsx("span",{children:G},L))}):bl(a,i)]})}function wb(n,a){let i,l;function c(h){i=h.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(h){l=h.clientX-i,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:i,filterValue:l}){function c({value:d}){i({value:d,key:a.id})}return r.jsx(Op,{...n.config??{},value:l,onChange:c})}function $A({filter:n,column:a,action:i,filterValue:l}){const c=u.useContext(xs),d=gt(c,"flatData"),m=u.useMemo(()=>n?.config?.options||a?.options||g(),[n,a,d]),h=u.useMemo(()=>n?.config?.template,[n]);function g(){const b=[];return d.forEach(w=>{const A=xl(w,a);b.includes(A)||b.push(A)}),b.map(w=>({id:w,label:w}))}function y({value:b}){i({value:b,key:a.id})}function x(b){b.key!=="Tab"&&b.preventDefault()}return r.jsx("div",{style:{width:"100%"},onKeyDown:x,children:r.jsx(ej,{placeholder:"",clear:!0,...n?.config??{},options:m,value:l,onChange:y,children:b=>h?h(b):b.label})})}function BA({filter:n,column:a,action:i,filterValue:l}){function c({value:d}){i({value:d,key:a.id})}return r.jsx("div",{className:"wx-aaaK5VYO",style:{width:"100%"},children:r.jsx(Jk,{placeholder:"",clear:!0,...n?.config??{},value:l,onChange:c})})}function kw(n){const{value:a,options:i=[],placeholder:l="",clear:c=!1,text:d=null,template:m=null,cell:h=null,dropdown:g={},autoOpen:y=!1,onChange:x,onAction:b}=n,[w,A]=ow(a||[]),j=u.useMemo(()=>(w||[]).map(P=>i.find(Y=>Y.id===P)).filter(Boolean),[w,i]),k=u.useRef(null),N=u.useRef(null),[M,T]=u.useState(null),D=()=>{const P=w||[];if(!P.length)return 0;const Y=i.find(H=>P.includes(H.id));return Y?i.indexOf(Y):0};function F(P){N.current=P.navigate,T(()=>P.keydown),y&&P.navigate(D())}u.useEffect(()=>{y&&(k.current?.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges())},[]);function $({id:P}){A(P),x&&x({value:P})}function G(P){P.stopPropagation(),A([]),x&&x({value:[]})}function L(){N.current?.(D())}function Q(){N.current?.(null)}function q(P){M?.(P,D())}return r.jsxs("div",{ref:k,className:"wx-multiselect wx-aadNNOwy",onClick:L,onKeyDown:q,tabIndex:0,children:[r.jsx("div",{className:"wx-label wx-aadNNOwy",children:m?m(j):h?r.jsx(h,{data:j,onAction:b}):d?r.jsx("span",{className:"wx-text wx-aadNNOwy",children:d}):j.length?r.jsx("span",{className:"wx-text wx-aadNNOwy",children:j.map(P=>P.label).join(", ")}):l?r.jsx("span",{className:"wx-placeholder wx-aadNNOwy",children:l}):" "}),c&&w?.length?r.jsx("i",{className:"wx-icon wxi-close wx-aadNNOwy",onClick:G}):r.jsx("i",{className:"wx-icon wxi-angle-down wx-aadNNOwy"}),r.jsx(Vf,{items:i,onReady:F,onSelect:$,multiselect:!0,checkboxes:!0,value:w||[],onCancel:Q,...g,children:({option:P})=>r.jsx("div",{className:"wx-option wx-aadNNOwy",children:m?m(P):h?r.jsx(h,{data:P,onAction:b}):P.label})})]})}function PA({filter:n,column:a,action:i,filterValue:l}){const c=u.useContext(na.i18n)?.getGroup("grid")||Yu($p).getGroup("grid"),d=u.useMemo(()=>({clear:!0,...n?.config||{}}),[n]),m=u.useMemo(()=>d.options||a.options,[d,a]),h=u.useMemo(()=>{const x=l?.length;return x?x<3?l.map(b=>a.optionsMap.get(b)).join(", "):x+" "+c("selected"):""},[l,a,c]);function g({value:x}){i({value:x,key:a.id})}function y(x){x.key!=="Tab"&&x.preventDefault()}return r.jsx("div",{style:{width:"100%"},onKeyDown:y,children:r.jsx(kw,{placeholder:"",...d,options:m,value:l||[],text:h,onChange:g})})}const UA={text:FA,richselect:$A,datepicker:BA,multiselect:PA};function qA({filter:n,column:a}){const i=u.useContext(xs),l=gt(i,"filterValues");function c(m){i.exec("filter-rows",m)}const d=u.useMemo(()=>UA[n.type],[n.type]);return r.jsx(d,{filter:n,column:a,action:c,filterValue:l[a.id]})}function GA(n){const{cell:a,column:i,row:l,lastRow:c,sortRow:d,columnStyle:m,bodyHeight:h,hasSplit:g}=n,y=u.useContext(xs),x=gt(y,"sortMarks"),b=u.useMemo(()=>x?x[i.id]:void 0,[x,i.id]),w=u.useRef(),A=u.useCallback(de=>{w.current=a.flexgrow?de.parentNode.clientWidth:a.width},[a.flexgrow,a.width]),j=u.useCallback((de,Z)=>{y.exec("resize-column",{id:a.id,width:Math.max(1,(w.current||0)+de),inProgress:Z})},[y,a.id]),k=u.useCallback(de=>j(de,!0),[j]),N=u.useCallback(de=>j(de,!1),[j]),M=u.useCallback(de=>{if(!i.sort||a.filter)return;let Z=b?.order;Z&&(Z=Z==="asc"?"desc":"asc"),y.exec("sort-rows",{key:a.id,add:de.ctrlKey||de.metaKey,order:Z})},[y,a.id,a.filter,i.sort,b?.order]),T=u.useCallback(de=>{de&&de.stopPropagation(),y.exec("collapse-column",{id:a.id,row:l})},[y,a.id,l]),D=u.useCallback(de=>{de.key==="Enter"&&T()},[T]),F=u.useCallback(de=>{de.key==="Enter"&&!a.filter&&M(de)},[M,a.filter]),$=u.useMemo(()=>a.collapsed&&i.collapsed,[a.collapsed,i.collapsed]),G=u.useMemo(()=>$&&!g&&a.collapsible!=="header",[$,g,a.collapsible]),L=u.useMemo(()=>G?{top:-h/2,position:"absolute"}:{},[G,h]),Q=u.useMemo(()=>Yf(a.width,a.flexgrow,i.fixed,i.left,a.right??i.right,a.height+($&&G?h:0)),[a.width,a.flexgrow,i.fixed,i.left,a.right,i.right,a.height,$,G,h]),q=u.useMemo(()=>Cw(i,a,m),[i,a,m]),P=u.useCallback(()=>Object.fromEntries(Object.entries(a).filter(([de])=>de!=="cell")),[a]),Y=`wx-cell ${q} ${a.css||""} wx-collapsed`,H=["wx-cell",q,a.css||"",a.filter?"wx-filter":"",i.fixed&&i.fixed.right?"wx-fixed-right":""].filter(Boolean).join(" "),ye=u.useRef(null);return u.useEffect(()=>{const de=ye.current;if(!de)return;const Z=wb(de,{down:A,move:k,up:N});return()=>{typeof Z=="function"&&Z()}},[A,k,N,wb]),$?r.jsx("div",{className:"wx-RsQD74qC "+Y,style:Q,role:"button","aria-label":`Expand column ${a.text||""}`,"aria-expanded":!a.collapsed,tabIndex:0,onKeyDown:D,onClick:T,"data-header-id":ea(i.id),children:r.jsx("div",{className:"wx-RsQD74qC wx-text",style:L,children:a.text||""})}):r.jsxs("div",{className:"wx-RsQD74qC "+H,style:Q,onClick:M,"data-header-id":ea(i.id),tabIndex:!a._hidden&&i.sort&&!a.filter?0:void 0,role:"columnheader","aria-colindex":i._colindex,"aria-colspan":a.colspan>1?a.colspan:void 0,"aria-rowspan":a.rowspan>1?a.rowspan:void 0,"aria-sort":!b?.order||a.filter?"none":b?.order==="asc"?"ascending":"descending",onKeyDown:F,children:[a.collapsible?r.jsx("div",{className:"wx-RsQD74qC wx-collapse",role:"button","aria-label":a.collapsed?"Expand column":"Collapse column","aria-expanded":!a.collapsed,tabIndex:0,onKeyDown:D,onClick:T,children:r.jsx("i",{className:`wx-RsQD74qC wxi-angle-${a.collapsed?"down":"right"}`})}):null,a.cell?(()=>{const de=a.cell;return r.jsx(de,{api:y,cell:P(),column:i,row:l,onAction:({action:Z,data:z})=>y.exec(Z,z)})})():a.filter?r.jsx(qA,{filter:a.filter,column:i}):r.jsx("div",{className:"wx-RsQD74qC wx-text",children:a.text||""}),i.resize&&c&&!a._hidden?r.jsx("div",{className:"wx-RsQD74qC wx-grip",role:"presentation","aria-label":"Resize column",ref:ye,onClick:de=>de.stopPropagation(),children:r.jsx("div",{})}):null,d?r.jsx("div",{className:"wx-RsQD74qC wx-sort",children:b?r.jsxs(r.Fragment,{children:[typeof b.index<"u"?r.jsx("div",{className:"wx-RsQD74qC wx-order",children:b.index+1}):null,r.jsx("i",{className:`wx-RsQD74qC wxi-arrow-${b.order==="asc"?"up":"down"}`})]}):null}):null]})}function VA({cell:n,column:a,row:i,columnStyle:l}){const c=u.useContext(xs),d=u.useMemo(()=>Yf(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(()=>Cw(a,n,l),[a,n,l]),h=u.useCallback(()=>Object.fromEntries(Object.entries(n||{}).filter(([y])=>y!=="cell")),[n]),g=`wx-6Sdi3Dfd wx-cell ${m||""} ${n?.css||""}`+(a?.fixed&&a?.fixed.right?" wx-fixed-right":"");return r.jsx("div",{className:g,style:d,children:!a?.collapsed&&!n?.collapsed?n?.cell?kp.createElement(n.cell,{api:c,cell:h(),column:a,row:i,onAction:({action:y,data:x})=>c.exec(y,x)}):r.jsx("div",{className:"wx-6Sdi3Dfd wx-text",children:n?.text||""}):null})}function Sb({deltaLeft:n,contentWidth:a,columns:i,type:l="header",columnStyle:c,bodyHeight:d}){const m=u.useContext(xs),h=gt(m,"_sizes"),g=gt(m,"split"),y=u.useMemo(()=>h?.[`${l}RowHeights`],[h,l]),x=u.useMemo(()=>{let k=[];if(i&&i.length){const N=i[0][l].length;for(let M=0;M<N;M++){let T=0;k.push([]),i.forEach((D,F)=>{const $={...D[l][M]};T||k[M].push($),$.colspan>1?T=$.colspan-1:T&&T--})}}return k},[i,l]),b=u.useMemo(()=>g?.left||g?.right,[g]);function w(k){return i.find(N=>N.id===k)}function A(k,N){let M=N;return k.rowspan&&(M+=k.rowspan-1),M===x.length-1}function j(k,N,M){if(!M.sort)return!1;for(let T=x.length-1;T>=0;T--){const D=M.header[T];if(!D.filter&&!D._hidden)return N===T}return A(k,N)}return r.jsx("div",{className:`wx-sAsPVaUK wx-${l}`,style:{paddingLeft:`${n}px`,width:`${a}px`},role:"rowgroup",children:x.map((k,N)=>r.jsx("div",{className:l==="header"?"wx-sAsPVaUK wx-h-row":"wx-sAsPVaUK wx-f-row",style:{height:`${y?.[N]}px`,display:"flex"},role:"row",children:k.map(M=>{const T=w(M.id);return l==="header"?r.jsx(GA,{cell:M,columnStyle:c,column:T,row:N,lastRow:A(M,N),bodyHeight:d,sortRow:j(M,N,T),hasSplit:b},M.id):r.jsx(VA,{cell:M,columnStyle:c,column:w(M.id),row:N},M.id)})},N))})}function WA({overlay:n}){const a=u.useContext(xs);function i(c){return typeof c=="function"}const l=n;return r.jsx("div",{className:"wx-1ty666CQ wx-overlay",children:i(n)?r.jsx(l,{onAction:({action:c,data:d})=>a.exec(c,d)}):n})}function YA(n){const{editor:a,onSave:i,onApply:l}=n,[c,d]=u.useState(a?.value||""),{type:m="text"}=u.useMemo(()=>a?.config||{},[a]),h=u.useRef(null);u.useEffect(()=>{h.current&&h.current.focus()},[]),u.useEffect(()=>{if(!h.current)return;const x=Hr(h.current,()=>i(!0));return()=>x.destroy()},[i]);function g(){h.current&&(d(h.current.value),l(h.current.value))}function y({key:x}){x==="Enter"&&i()}return r.jsx("input",{className:"wx-e7Ao5ejY wx-text",onInput:g,onKeyDown:y,ref:h,type:m,value:c})}function KA({editor:n,onAction:a,onSave:i,onApply:l,onCancel:c}){const[d,m]=u.useState(n?.value),[h,g]=u.useState(n?.renderedValue),[y,x]=u.useState(n?.options||[]),b=u.useMemo(()=>n?.config?.template,[n]),w=u.useMemo(()=>n?.config?.cell,[n]),A=u.useMemo(()=>n?.config?.dropdown||{},[n]),j=u.useMemo(()=>({trackScroll:!0,...A}),[A]),k=u.useMemo(()=>(y||[]).findIndex(L=>L.id===d),[y,d]),N=u.useRef(null),M=u.useRef(null),T=u.useCallback(L=>{N.current=L.navigate,M.current=L.keydown,N.current(k)},[k,N]),D=u.useCallback(L=>{const Q=L?.target?.value??"";g(Q);const q=Q?(n?.options||[]).filter(P=>(P.label||"").toLowerCase().includes(Q.toLowerCase())):n?.options||[];x(q),q.length?N.current(-1/0):N.current(null)},[n]),F=u.useRef(null);u.useEffect(()=>{F.current&&F.current.focus()},[]);const $=u.useRef(i);u.useEffect(()=>{$.current=i},[i]),u.useEffect(()=>{if(!F.current)return;const L=Hr(F.current,()=>$.current(!0));return()=>L.destroy()},[]),u.useEffect(()=>{m(n?.value),g(n?.renderedValue),x(n?.options||[])},[n]);const G=u.useCallback(({id:L})=>{l(L),i()},[l,i]);return r.jsxs(r.Fragment,{children:[r.jsx("input",{className:"wx-0UYfSd1x wx-input",ref:F,value:h??"",onChange:D,onKeyDown:L=>M.current?M.current(L,k):void 0}),r.jsx(Vf,{items:y,onReady:T,onSelect:G,...j,onCancel:c,children:({option:L})=>b?b(L):w?r.jsx(w,{data:L,onAction:a}):L.label})]})}function QA({editor:n,onAction:a,onSave:i,onApply:l,onCancel:c}){const[d]=u.useState(()=>n.value||new Date),{template:m,cell:h,dropdown:g={}}=n?.config||{},y=u.useMemo(()=>({trackScroll:!0,width:"auto",...g}),[g]);function x({value:j}){l(j),i()}const b=u.useRef(null),[w,A]=u.useState(null);return u.useEffect(()=>{b.current&&b.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),u.useEffect(()=>{if(!w)return;const j=Hr(w,()=>i(!0));return()=>j.destroy()},[w,i]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-lNWNYUb6 wx-value",ref:b,tabIndex:0,onClick:c,onKeyDown:j=>j.preventDefault(),children:m?m(d):h?r.jsx(h,{data:n.value,onAction:a}):r.jsx("span",{className:"wx-lNWNYUb6 wx-text",children:n.renderedValue})}),r.jsx(zp,{...y,onCancel:c,children:r.jsx("div",{ref:A,className:"wx-lNWNYUb6",children:r.jsx(aw,{value:d,onChange:x,buttons:n.config?.buttons})})})]})}function XA(n){const{editor:a}=n,i=n.onAction??n.onaction,l=n.onSave??n.onsave,c=n.onApply??n.onapply,d=n.onCancel??n.oncancel,m=a.config||{},{dropdown:h={}}=m,g=u.useMemo(()=>({trackScroll:!0,...h}),[h]),[y]=u.useState(a.options.find(D=>D.id===a.value)),[x]=u.useState(a.value),[b]=u.useState(a.options),w=u.useMemo(()=>b.findIndex(D=>D.id===x),[b,x]);function A({id:D}){c(D),l()}let j;const[k,N]=u.useState();function M(D){j=D.navigate,N(()=>D.keydown),j(w)}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 D=Hr(T.current,()=>l(!0));return()=>D.destroy()},[l]),r.jsxs(r.Fragment,{children:[r.jsx("div",{ref:T,className:"wx-ywGRk611 wx-value",tabIndex:0,onClick:d,onKeyDown:D=>{k(D,w),D.preventDefault()},children:m.template?m.template(y):m.cell?(()=>{const D=m.cell;return r.jsx(D,{data:y,onAction:i})})():r.jsx("span",{className:"wx-ywGRk611 wx-text",children:a.renderedValue})}),r.jsx(Vf,{items:b,onReady:M,onSelect:A,...g,onCancel:d,children:({option:D})=>m.template?m.template(D):m.cell?(()=>{const F=m.cell;return r.jsx(F,{data:D,onAction:i})})():D.label})]})}function ZA(n){const{editor:a,onAction:i,onSave:l,onApply:c}=n,d=a?.config||{},m=a?.options??[],h=a?.value||[],g=a?.renderedValue,y=u.useMemo(()=>({trackScroll:!0,...d.dropdown||{}}),[d]);function x({value:w}){c(w)}const b=u.useRef(null);return u.useEffect(()=>{if(!b.current)return;const w=Hr(b.current,()=>l(!0));return()=>w.destroy()},[l]),r.jsx("div",{ref:b,className:"wx-value wx-aacZ4gNU",onClick:()=>l(!0),children:r.jsx(kw,{value:h,options:m,text:g,template:d.template,cell:d.cell,clear:d.clear,dropdown:y,autoOpen:!0,onChange:x,onAction:i})})}const JA={text:YA,combo:KA,datepicker:QA,richselect:XA,multiselect:ZA};function eM({column:n,row:a}){const i=u.useContext(xs),l=gt(i,"editor"),c=u.useCallback((j,k)=>{i.exec("close-editor",{ignore:j}),k&&i.exec("focus-cell",{...k,eventSource:"click"})},[i]),d=u.useCallback(j=>{const k=j?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]),h=u.useCallback(j=>{i.exec("editor",{value:j})},[i]),g=u.useCallback(j=>{j.key==="Enter"&&l&&(n.editor.type==="multiselect"?h(l.value):m())},[l,n.editor,m,h]),y=u.useMemo(()=>Yf(n.width,n.flexgrow,n.fixed,n.left,n.right),[n.width,n.flexgrow,n.fixed,n.left,n.right]),x=u.useMemo(()=>{let j=n.editor;if(typeof j=="function"&&(j=j(a,n)),!j)return null;let k=typeof j=="string"?j:j.type;return JA[k]},[n,a]),b=u.useRef(null);u.useEffect(()=>{b.current&&typeof y=="string"&&b.current.setAttribute("style",y)},[y]);const w=typeof a.$parent<"u"?"gridcell":"cell",A=typeof a.$parent<"u"?!n.editor:void 0;return r.jsx("div",{className:"wx-8l724t2g wx-cell wx-editor",ref:b,style:typeof y=="object"&&y!==null?y:void 0,role:w,"aria-readonly":A,tabIndex:-1,onClick:j=>j.stopPropagation(),onDoubleClick:j=>j.stopPropagation(),onKeyDown:g,children:x?r.jsx(x,{editor:l,onSave:d,onApply:h,onCancel:m,onAction:({action:j,data:k})=>i.exec(j,k)}):null})}function Cb(n){const{columns:a,type:i,columnStyle:l}=n,c=u.useContext(xs),{filterValues:d,_columns:m,_sizes:h}=c.getState();function g(y){return l?" "+l(y):""}return r.jsx(r.Fragment,{children:a.map((y,x)=>r.jsx("tr",{children:y.map(b=>{const w=m.find(k=>k.id===b.id),A=`wx-print-cell-${i}${g(w)}${b.filter?" wx-print-cell-filter":""}${b.vertical?" wx-vertical":""}`,j=b.cell;return r.jsx("th",{style:cw(yw(b,h.columnWidth)),className:"wx-Gy81xq2u "+A,rowSpan:b.rowspan,colSpan:b.colspan,children:j?r.jsx(j,{api:c,cell:Object.fromEntries(Object.entries(b).filter(([k])=>k!=="cell")),column:w,row:x}):b.filter?r.jsx("div",{className:"wx-Gy81xq2u wx-print-filter",children:sA(d,m,b)}):r.jsx("div",{className:"wx-Gy81xq2u wx-text",children:b.text??""})},b.id)})},x))})}function tM(n){const{columns:a,rowStyle:i,columnStyle:l,cellStyle:c,header:d,footer:m,reorder:h}=n,g=u.useContext(xs),{flatData:y,_sizes:x}=g.getState(),b=d&&gb(a,"header",x.headerRowHeights),w=m&&gb(a,"footer",x.footerRowHeights);function A(k,N){let M="";return M+=l?" "+l(N):"",M+=c?" "+c(k,N):"",M}function j(k,N){return typeof N.draggable=="function"?N.draggable(k,N)!==!1:N.draggable}return r.jsxs("table",{className:`wx-8NTMLH0z wx-print-grid ${a.some(k=>k.flexgrow)?"wx-flex-columns":""}`,children:[d?r.jsx("thead",{children:r.jsx(Cb,{columns:b,type:"header",columnStyle:l})}):null,r.jsx("tbody",{children:y.map((k,N)=>r.jsx("tr",{className:"wx-8NTMLH0z wx-row"+(i?" "+i(k):""),style:{height:`${k.rowHeight||x.rowHeight}px`},children:a.map(M=>M.collapsed?null:r.jsxs("td",{className:`wx-8NTMLH0z wx-print-cell wx-cell ${A(k,M)}`,style:cw(yw(M,x.columnWidth)),children:[h&&M.draggable?r.jsx("span",{className:"wx-8NTMLH0z wx-print-draggable",children:j(k,M)?r.jsx("i",{className:"wx-8NTMLH0z wxi-drag"}):null}):null,M.treetoggle?r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{marginLeft:k.$level*28+"px"}}),k.$count?r.jsx("i",{className:`wx-8NTMLH0z wx-print-grid-tree-toggle wxi-menu-${k.open!==!1?"down":"right"}`}):null]}):null,M.cell?(()=>{const T=M.cell;return r.jsx(T,{api:g,row:k,column:M})})():r.jsx("span",{children:bl(k,M)})]},M.id))},N))}),m?r.jsx("tfoot",{children:r.jsx(Cb,{columns:w,type:"footer",columnStyle:l})}):null]})}function nM(n){const{config:a,...i}=n,l=u.useContext(xs),{_skin:c,_columns:d}=l.getState(),m=u.useMemo(()=>eA(d,a),[]),h=u.useRef(null);return u.useEffect(()=>{const g=document.body;g.classList.add("wx-print");const y=h.current;if(!y)return;const x=y.cloneNode(!0);g.appendChild(x);const b=`@media print { @page { size: ${a.paper} ${a.mode}; }`,w=document.createElement("style");w.setAttribute("type","text/css"),w.setAttribute("media","print"),document.getElementsByTagName("head")[0].appendChild(w),w.appendChild(document.createTextNode(b)),window.print(),w.remove(),g.classList.remove("wx-print"),x.remove()},[]),r.jsx("div",{className:`wx-4zwCKA7C wx-${c}-theme wx-print-container`,ref:h,children:m.map((g,y)=>r.jsx("div",{className:"wx-4zwCKA7C wx-print-grid-wrapper",children:r.jsx(tM,{columns:g,...i})},y))})}function aM(n){const{header:a,footer:i,overlay:l,multiselect:c,onreorder:d,rowStyle:m,columnStyle:h,cellStyle:g,autoRowHeight:y,resize:x,clientWidth:b,clientHeight:w,responsiveLevel:A,hotkeys:j}=n,k=u.useContext(xs),N=gt(k,"dynamic"),M=gt(k,"_columns"),T=gt(k,"flatData"),D=gt(k,"split"),F=gt(k,"_sizes"),[$,G]=Us(k,"selectedRows"),L=gt(k,"select"),Q=gt(k,"editor"),q=gt(k,"scrollLeft"),P=gt(k,"scrollTop"),Y=gt(k,"tree"),H=gt(k,"focusCell"),ye=gt(k,"_print"),de=gt(k,"undo"),Z=gt(k,"reorder"),z=gt(k,"_rowHeightFromData"),[se,W]=u.useState(0);u.useEffect(()=>{W(pn())},[]);const[O,le]=u.useState(0),ce=u.useMemo(()=>(M||[]).some(re=>!re.hidden&&re.flexgrow),[M]),K=u.useMemo(()=>F?.rowHeight||0,[F]),be=u.useRef(null),[he,fe]=u.useState(null),[ee,we]=u.useState(null),Me=u.useMemo(()=>{let re=[],Te=0;return D&&D.left&&(re=(M||[]).slice(0,D.left).filter(Pe=>!Pe.hidden).map(Pe=>({...Pe})),re.forEach(Pe=>{Pe.fixed={left:1,leftSize:D.left},Pe.left=Te,Te+=Pe.width}),re.length&&(re[re.length-1].fixed.left=-1)),{columns:re,width:Te}},[D,M]),He=u.useMemo(()=>{let re=[],Te=0;if(D&&D.right){re=(M||[]).slice(D.right*-1).filter(Pe=>!Pe.hidden).map(Pe=>({...Pe}));for(let Pe=re.length-1;Pe>=0;Pe--){const vt=re[Pe];vt.fixed={right:1},vt.right=Te,Te+=vt.width}re.length&&(re[0].fixed={right:-1})}return{columns:re,width:Te}},[D,M]),ne=u.useMemo(()=>{const re=(M||[]).slice(D?.left||0,(M||[]).length-(D?.right??0)).filter(Te=>!Te.hidden);return re.forEach(Te=>{Te.fixed=0}),re},[M,D]),qe=u.useMemo(()=>(M||[]).reduce((re,Te)=>(Te.hidden||(re+=Te.width),re),0),[M]),mt=1;function J(re,Te,Pe){let vt=Te,qt=re;if(ne.length){let Yt=ne.length;for(let st=re;st>=0;st--)ne[st][Pe].forEach(Mt=>{Mt.colspan>1&&st>re-Mt.colspan&&st<Yt&&(Yt=st)});if(Yt!==ne.length&&Yt<re){for(let st=Yt;st<re;st++)vt-=ne[st].width;qt=Yt}}return{index:qt,delta:vt}}const Ce=u.useMemo(()=>{let re,Te,Pe;const vt=q||0,qt=(q||0)+(b||0);let Yt=0,st=0,Mt=0,sa=0;ne.forEach((Sn,Tn)=>{vt>Mt&&(Yt=Tn,sa=Mt),Mt=Mt+Sn.width,qt>Mt&&(st=Tn+mt)});const Hn={header:0,footer:0};for(let Sn=st;Sn>=Yt;Sn--)["header","footer"].forEach(Tn=>{ne[Sn]&&ne[Sn][Tn].forEach(go=>{const Nt=go.colspan;if(Nt&&Nt>1){const ga=Nt-(st-Sn+1);ga>0&&(Hn[Tn]=Math.max(Hn[Tn],ga))}})});const gn=J(Yt,sa,"header"),nn=J(Yt,sa,"footer"),Ye=gn.delta,At=gn.index,Vs=nn.delta,zt=nn.index;return ce&&qe>(b||0)?re=Te=Pe=[...Me.columns,...ne,...He.columns]:(re=[...Me.columns,...ne.slice(Yt,st+1),...He.columns],Te=[...Me.columns,...ne.slice(At,st+Hn.header+1),...He.columns],Pe=[...Me.columns,...ne.slice(zt,st+Hn.footer+1),...He.columns]),{data:re||[],header:Te||[],footer:Pe||[],d:sa,df:Vs,dh:Ye}},[ne,Me,He,q,b,ce,qe]),Le=u.useMemo(()=>a&&F?.headerHeight||0,[a,F]),Fe=u.useMemo(()=>i&&F?.footerHeight||0,[i,F]),_e=u.useMemo(()=>b&&w?qe>=b:!1,[b,w,qe]),[Xe,We]=u.useState(!1),Ze=u.useMemo(()=>(w||0)-Le-Fe-(_e?se:0),[w,Le,Fe,_e,se]),dt=u.useMemo(()=>Math.ceil((Ze||0)/(K||1))+1,[Ze,K]),U=u.useRef([]),[ve,Ae]=u.useState(0),[Be,ft]=u.useState(void 0),it=u.useMemo(()=>{let re=0,Te=0;const Pe=2,vt=P||0;if(y){let st=vt;for(;st>0;)st-=U.current[re]||K,re++;Te=vt-st;for(let Mt=Math.max(0,re-Pe-1);Mt<re;Mt++)Te-=U.current[re-Mt]||K;re=Math.max(0,re-Pe)}else{if(z){let st=0,Mt=0;for(let nn=0;nn<(T||[]).length;nn++){const Ye=T[nn].rowHeight||K;if(Mt+Ye>vt){st=nn;break}Mt+=Ye}re=Math.max(0,st-Pe);for(let nn=0;nn<re;nn++)Te+=T[nn].rowHeight||K;let sa=0,Hn=0;for(let nn=st+1;nn<(T||[]).length;nn++){const Ye=T[nn].rowHeight||K;if(sa++,Hn+Ye>Ze)break;Hn+=Ye}const gn=Math.min(N?N.rowCount:(T||[]).length,st+sa+Pe);return{d:Te,start:re,end:gn}}re=Math.floor(vt/(K||1)),re=Math.max(0,re-Pe),Te=re*(K||0)}const qt=N?N.rowCount:(T||[]).length,Yt=Math.min(qt,re+(dt||0)+Pe);return{d:Te,start:re,end:Yt}},[y,z,P,K,N,T,dt,Ze]),yt=u.useMemo(()=>{const re=N?N.rowCount:(T||[]).length;if(y)return ve+it.d+(re-(Be||0))*(K||0);if(!z)return re*(K||0);let Te=0;for(let Pe=0;Pe<re;Pe++)Te+=T[Pe]?.rowHeight||K;return Te},[N,T,K,y,z,ve,it.d,Be]),ot=u.useRef({});ot.current={clientWidth:b,clientHeight:w,fullHeight:yt,headerHeight:Le,footerHeight:Fe,fullWidth:qe,SCROLLSIZE:se};const kt=u.useCallback(()=>{const re=ot.current;We(re.clientWidth&&re.clientHeight?re.fullHeight+re.headerHeight+re.footerHeight>=re.clientHeight-(re.fullWidth>=re.clientWidth?re.SCROLLSIZE:0):!1)},[]);u.useEffect(()=>{const re=requestAnimationFrame(kt);return()=>window.cancelAnimationFrame(re)},[O,kt]),u.useEffect(()=>{kt()},[w,kt]);const pe=u.useMemo(()=>ce&&qe<=(b||0)?(b||0)-0-(Xe?se:0):qe,[ce,qe,b,Xe,se,_e]),De=u.useMemo(()=>ce&&qe<=(b||0)?b||0:pe<(b||0)?qe+(Xe?se:0):-1,[ce,qe,b,pe,Xe,se]),$e=u.useRef({});u.useEffect(()=>{if(N&&($e.current.start!==it.start||$e.current.end!==it.end)){const{start:re,end:Te}=it;$e.current={start:re,end:Te},k&&k.exec&&k.exec("request-data",{row:{start:re,end:Te}})}},[N,it,k]);const je=u.useMemo(()=>N?T||[]:(T||[]).slice(it.start,it.end),[N,T,it]),ct=u.useMemo(()=>($||[]).filter(re=>(je||[]).some(Te=>Te.id===re)),[G,je]),bt=u.useMemo(()=>it.start,[it.start]),ze=u.useRef({top:P,left:q});ze.current={top:P,left:q};const aa=u.useCallback(re=>{const Te=re.target.scrollTop,Pe=re.target.scrollLeft,vt=ze.current;(Te!==vt.top||Pe!==vt.left)&&k.exec("scroll-to",{top:Te,left:Pe})},[k]),zn=u.useCallback(re=>{re.shiftKey&&re.preventDefault(),be.current&&be.current.focus&&be.current.focus()},[]),nt=u.useCallback(()=>!!(M||[]).find(re=>!!re.draggable),[M]),Ot=u.useRef(null),Nn=u.useRef(null),pa=u.useRef({dblclick:(re,Te)=>{const Pe={id:re,column:Vu(Te,"data-col-id")};k.exec("open-editor",Pe)},click:(re,Te)=>{if(Te.target.closest("input")||Ot.current)return;const Pe=Vu(Te,"data-col-id");if(H?.id!==re&&k.exec("focus-cell",{row:re,column:Pe,eventSource:"click"}),L===!1)return;const vt=c&&(Te.ctrlKey||Te.metaKey),qt=c&&Te.shiftKey;(vt||$.length>1||!$.includes(re))&&k.exec("select-row",{id:re,toggle:vt,range:qt})},"toggle-row":re=>{const Te=k.getRow(re);k.exec(Te.open!==!1?"close-row":"open-row",{id:re})},"ignore-click":()=>!1}),Oe=u.useMemo(()=>({top:Le,bottom:Fe,left:Me.width,xScroll:_e,yScroll:Xe,sense:y&&ee?ee.offsetHeight:Math.max(F?.rowHeight||0,40),node:be.current&&be.current.firstElementChild}),[Le,Fe,Me.width,_e,Xe,y,ee,F]);function wn(re,Te){const{container:Pe,sourceNode:vt,from:qt}=Te;if(nt()&&!vt.getAttribute("draggable-data"))return!1;fe(qt),Y&&k.getRow(qt).open&&k.exec("close-row",{id:qt,nested:!0});const Yt=jc(vt),st=Yt.cloneNode(!0);st.classList.remove("wx-selected"),st.querySelectorAll("[tabindex]").forEach(gn=>gn.setAttribute("tabindex","-1")),Pe.appendChild(st),we(st);const Mt=(q||0)-Ce.d,sa=Xe?se:0;Pe.style.width=Math.min((b||0)-sa,ce&&qe<=(b||0)?pe:pe-sa)+Mt+"px";const Hn=Af(Yt);Te.offset={x:Mt,y:-Math.round(Hn.height/2)},Nn.current||(Nn.current=re.clientY)}function On(re,Te){const{from:Pe}=Te,vt=Te.pos,qt=Af(be.current);vt.x=qt.x;const Yt=Oe.top;if(vt.y<Yt)vt.y=Yt;else{const st=qt.height-(_e&&se>0?se:Math.round(Oe.sense/2))-Oe.bottom;vt.y>st&&(vt.y=st)}if(be.current.contains(Te.targetNode)){const st=jc(Te.targetNode),Mt=st&&qf(st);if(Mt&&Mt!==Pe){Te.to=Mt;const sa=y?ee?.offsetHeight:F?.rowHeight;if(ee&&((P||0)===0||vt.y>Yt+sa-1)){const Hn=st.getBoundingClientRect(),gn=Af(ee).y,nn=Hn.y,Ye=gn>nn?-1:1,At=Ye===1?"after":"before",Vs=k.getState().flatData,zt=Math.abs(Vs.findIndex(Tn=>Tn.id===Pe)-Vs.findIndex(Tn=>Tn.id===Mt)),Sn=zt!==1?At==="before"?"after":"before":At;if(zt===1&&(Ye===-1&&re.clientY>Nn.current||Ye===1&&re.clientY<Nn.current))return;Nn.current=re.clientY,k.exec("move-item",{id:Pe,target:Mt,mode:Sn,inProgress:!0})}}d&&d({event:re,context:Te})}LA(re,qt,Te,Oe)}function ws(re,Te){const{from:Pe,to:vt}=Te;k.exec("move-item",{id:Pe,target:vt,inProgress:!1}),Ot.current=setTimeout(()=>{Ot.current=0},1),fe(null),we(null),Nn.current=null,ww(Te)}function pn(){const re=document.createElement("div");re.style.cssText="position:absolute;left:-1000px;width:100px;padding:0px;margin:0px;min-height:100px;overflow-y:scroll;",document.body.appendChild(re);const Te=re.offsetWidth-re.clientWidth;return document.body.removeChild(re),Te}const qs=u.useMemo(()=>De>0?{width:`${De}px`}:void 0,[De]),Yn=u.useRef(null);function Gs(){Promise.resolve().then(()=>{let re=0,Te=bt;const Pe=Yn.current;Pe&&(Array.from(Pe.children).forEach((vt,qt)=>{U.current[bt+qt]=vt.offsetHeight,re+=vt.offsetHeight,Te++}),Ae(re),ft(Te))})}u.useEffect(()=>{je&&y&&Gs()},[je,y,bt]);let[B,Ke]=u.useState();u.useEffect(()=>{if(H&&(!L||!ct.length||ct.includes(H.row)))Ke({...H});else if(je.length&&Ce.data.length){if(!B||ct.length&&!ct.includes(B.row)||je.findIndex(re=>re.id===B.row)===-1||Ce.data.findIndex(re=>re.id===B.column&&!re.collapsed)===-1){const re=ct[0]||je[0].id,Te=Ce.data.findIndex(Pe=>!Pe.collapsed);Ke(Te!==-1?{row:re,column:Ce.data[Te].id}:null)}}else Ke(null)},[H]);const ht=u.useRef(null);u.useEffect(()=>{const re=be.current;if(!re)return;const Te=NA(re,x);return()=>{typeof Te=="function"&&Te()}},[x]);const fn=u.useRef({});Object.assign(fn.current,{start:wn,move:On,end:ws,getReorder:()=>Z,getDraggableInfo:()=>({hasDraggable:nt()})}),u.useEffect(()=>{const re=be.current;return re?RA(re,fn).destroy:void 0},[Z,be.current]),u.useEffect(()=>{const re=be.current;return re?AA(re,{keys:j!==!1&&{...jA,"ctrl+z":de,"ctrl+y":de,...j},exec:Te=>k.exec("hotkey",Te)}).destroy:void 0},[k,de,j]);const Fa=u.useRef({scroll:k.getReactiveState().scroll,scrollLeft:k.getReactiveState().scrollLeft,scrollTop:k.getReactiveState().scrollTop});Fa.current.getWidth=()=>(b||0)-(Xe?se:0),Fa.current.getHeight=()=>Ze,Fa.current.getScrollMargin=()=>Me.width+He.width,u.useEffect(()=>{MA(ht.current,Fa.current)},[]);const Di=u.useRef(null);u.useEffect(()=>{const re=Di.current;if(!re)return;const Te=[];Te.push(Hr(re,()=>H&&k.exec("focus-cell",{eventSource:"click"})).destroy),Te.push(Rj(re,pa.current)),le(re.clientHeight);const Pe=new ResizeObserver(()=>{le(re.clientHeight)});return Pe.observe(re),Te.push(()=>Pe.disconnect()),()=>Te.forEach(vt=>vt())},[]);const Ss=`wx-grid ${A?`wx-responsive-${A}`:""}`;return u.useEffect(()=>{H&&(je.some(re=>re.id===H.row)&&Ce.data.some(re=>re.id===H.column&&!re.collapsed)||k.exec("focus-cell",{eventSource:"destroy"}))},[H,je,Ce.data,k]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-4VuBwK2D "+Ss,style:{"--header-height":`${Le}px`,"--footer-height":`${Fe}px`,"--split-left-width":`${Me.width}px`,"--split-right-width":`${He.width}px`},children:r.jsx("div",{ref:be,className:"wx-4VuBwK2D wx-table-box",style:qs,role:Y?"treegrid":"grid","aria-colcount":Ce.data.length,"aria-rowcount":je.length,"aria-multiselectable":Y&&c?!0:void 0,tabIndex:-1,children:r.jsxs("div",{ref:ht,className:"wx-4VuBwK2D wx-scroll",style:{overflowX:_e?"scroll":"hidden",overflowY:Xe?"scroll":"hidden"},onScroll:aa,children:[a?r.jsx("div",{className:"wx-4VuBwK2D wx-header-wrapper",children:r.jsx(Sb,{contentWidth:pe,deltaLeft:Ce.dh,columns:Ce.header,columnStyle:h,bodyHeight:Ze-+i})}):null,r.jsxs("div",{ref:Di,className:"wx-4VuBwK2D wx-body",style:{width:`${pe}px`,height:`${yt}px`},onMouseDown:re=>zn(re),children:[l?r.jsx(WA,{overlay:l}):null,r.jsx("div",{ref:Yn,className:"wx-4VuBwK2D wx-data",style:{paddingTop:`${it.d}px`,paddingLeft:`${Ce.d}px`},children:je.map((re,Te)=>{const Pe=$.indexOf(re.id)!==-1,vt=he===re.id,qt="wx-row"+(y?" wx-autoheight":"")+(m?" "+m(re):"")+(Pe?" wx-selected":"")+(vt?" wx-inactive":""),Yt=y?{minHeight:`${re.rowHeight||K}px`}:{height:`${re.rowHeight||K}px`};return r.jsx("div",{className:"wx-4VuBwK2D "+qt,"data-id":ea(re.id),"data-context-id":ea(re.id),style:Yt,role:"row","aria-rowindex":Te,"aria-expanded":re.open,"aria-level":Y?re.$level+1:void 0,"aria-selected":Y?Pe:void 0,tabIndex:-1,children:Ce.data.map(st=>st.collapsed?r.jsx("div",{className:"wx-4VuBwK2D wx-cell wx-collapsed"},st.id):Q?.id===re.id&&Q.column===st.id?r.jsx(eM,{row:re,column:st},st.id):r.jsx(HA,{row:re,column:st,columnStyle:h,cellStyle:g,reorder:Z,focusable:B?.row===re.id&&B?.column===st.id},st.id))},re.id)})})]}),i&&(T||[]).length?r.jsx(Sb,{type:"footer",contentWidth:pe,deltaLeft:Ce.df,columns:Ce.footer,columnStyle:h}):null]})})}),ye?r.jsx(nM,{config:ye,rowStyle:m,columnStyle:h,cellStyle:g,header:a,footer:i,reorder:Z}):null]})}const sM=n=>n.split("-").map(a=>a?a.charAt(0).toUpperCase()+a.slice(1):"").join(""),rM=u.forwardRef(function({data:n=[],columns:a=[],rowStyle:i=null,columnStyle:l=null,cellStyle:c=null,selectedRows:d,select:m=!0,multiselect:h=!1,header:g=!0,footer:y=!1,dynamic:x=null,overlay:b=null,reorder:w=!1,onReorder:A=null,autoRowHeight:j=!1,sizes:k,split:N,tree:M=!1,autoConfig:T=!1,init:D=null,responsive:F=null,sortMarks:$,undo:G=!1,hotkeys:L=null,filterValues:Q,...q},P){const Y=u.useRef();Y.current=q;const H=u.useMemo(()=>new bA(uw),[]),ye=u.useMemo(()=>H.in,[H]),de=u.useRef(null);de.current===null&&(de.current=new sw((He,ne)=>{const qe="on"+sM(He);Y.current&&Y.current[qe]&&Y.current[qe](ne)}),ye.setNext(de.current));const Z=u.useMemo(()=>({getState:H.getState.bind(H),getReactiveState:H.getReactive.bind(H),getStores:()=>({data:H}),exec:ye.exec,setNext:He=>(de.current=de.current.setNext(He),de.current),intercept:ye.intercept.bind(ye),on:ye.on.bind(ye),detach:ye.detach.bind(ye),getRow:H.getRow.bind(H),getColumn:H.getColumn.bind(H)}),[H,ye]),[z,se]=u.useState(0),[W,O]=u.useState(0),[le,ce]=u.useState(null),[K,be]=u.useState(null),he=u.useMemo(()=>{if(T&&!a.length&&n.length){const He=n[0],ne=[];for(let qe in He)if(qe!=="id"&&qe[0]!=="$"){let mt={id:qe,header:qe[0].toUpperCase()+qe.slice(1)};typeof T=="object"&&(mt={...mt,...T}),ne.push(mt)}return ne}return(K&&K.columns)??a},[T,a,n,K]),fe=u.useMemo(()=>(K&&K.sizes)??k,[K,k]),ee=u.useCallback(He=>{if(se(He.width),O(He.height),F){const ne=Object.keys(F).map(Number).sort((qe,mt)=>qe-mt).find(qe=>He.width<=qe)??null;ne!==le&&(be(F[ne]),ce(ne))}},[F,le]),we=u.useContext(na.theme),Me=u.useRef(0);return u.useEffect(()=>{if(!Me.current)D&&D(Z);else{const He=H.getState();H.init({data:n,columns:he,split:N||He.split,sizes:fe||He.sizes,selectedRows:d||He.selectedRows,dynamic:x,tree:M,sortMarks:$||He.sortMarks,filterValues:Q||He.filterValues,undo:G,reorder:w,_skin:we,_select:m})}Me.current++},[H,n,he,N,fe,d,x,M,$,Q,G,w,we,m,D,Z]),Me.current===0&&H.init({data:n,columns:he,split:N||{left:0},sizes:fe||{},selectedRows:d||[],dynamic:x,tree:M,sortMarks:$||{},filterValues:Q||{},undo:G,reorder:w,_skin:we,select:m}),u.useImperativeHandle(P,()=>({...Z}),[Z]),r.jsx(xs.Provider,{value:Z,children:r.jsx(Fp,{words:$p,optional:!0,children:r.jsx(aM,{header:g,footer:y,overlay:b,rowStyle:i,columnStyle:l,cellStyle:c,onReorder:A,multiselect:h,autoRowHeight:j,clientWidth:z,clientHeight:W,responsiveLevel:le,resize:ee,hotkeys:L})})})});Dp(ls);const ta=u.createContext(null),Up=u.createContext(null),qp=u.createContext(null);function iM({children:n}){const a=u.useContext(na.i18n),i=u.useMemo(()=>a.getGroup("filemanager"),[a]),l=u.useContext(ta),[c]=Us(l,"panels"),d=gt(l,"activePanel"),m=c[d].path,[h,g]=u.useState(null),[y,x]=u.useState(null),[b,w]=u.useState(""),[A,j]=u.useState(""),[k,N]=u.useState(!1);function M(){const $=b.trim();if(!$){N(!0);return}h.add?l.exec("create-file",{file:{...h.item,name:$},parent:m}):A!==$&&l.exec("rename-file",{id:h.item.id,name:$}),T()}function T(){g(null),N(null),j(""),w("")}function D(){l.exec("delete-files",{ids:y.selected}),x(null)}const F=u.useMemo(()=>({showPrompt($){const G=$.item.name||($.item.type==="folder"?i("New folder"):`${i("New file")}.txt`);j(G),w(G),g({...$})},showConfirm($){x({...$})}}),[i]);return r.jsxs(Up.Provider,{value:F,children:[r.jsx(ij,{children:n}),h?r.jsx(mp,{title:i(`Enter ${h.item.type} name`),onConfirm:M,onCancel:T,children:r.jsx(Op,{error:k,select:!0,focus:!0,value:b,onChange:({value:$})=>w($)})}):null,y?r.jsx(mp,{title:i("Are you sure you want to delete these items:"),onConfirm:D,onCancel:()=>x(null),children:y.selected?r.jsx("ul",{className:"wx-gq7BMzEP wx-list",children:y.selected.map(($,G)=>r.jsx("li",{children:$},G))}):null}):null]})}let kb={"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 lM(n){const a=n.lastIndexOf("."),i=a>0&&a<n.length-1?Math.min(10,n.length-a):Math.min(5,n.length),l=n.slice(0,-i),c=n.slice(-i);return[l,c]}function oM({item:n}){const a=u.useContext(ta),i=u.useContext(na.i18n).getGroup("filemanager"),l=u.useContext(ta).templates,[c]=Us(a,"panels"),d=gt(a,"activePanel"),m=gt(a,"mode"),h=c[d].selected,g=u.useMemo(()=>l.preview(n,214,163),[l,n]),y=u.useMemo(()=>l.icon(n,"big"),[l,n]),[x,b]=u.useMemo(()=>lM(n.name),[n.name]);return r.jsx(r.Fragment,{children:n.id==="/wx-filemanager-parent-link"?m!=="search"?r.jsx("div",{className:"wx-GAOa4kDV wx-back-item",children:r.jsxs("div",{className:`wx-GAOa4kDV wx-back ${n.navigation?"wx-selected":""}`,"data-id":ea("/wx-filemanager-parent-link"),children:[r.jsx("i",{className:"wx-GAOa4kDV wxi-arrow-left"}),r.jsx("span",{children:i("Back to parent folder")})]})}):null:r.jsxs("div",{className:`wx-GAOa4kDV wx-item ${h?.length&&h.indexOf(n.id)>=0?"wx-selected":""}`,"data-id":ea(n.id),children:[g?r.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-preview",children:r.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:i("A miniature file preview"),src:g})}):y?r.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-icon",children:r.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:"",src:y})}):r.jsx("div",{className:"wx-GAOa4kDV wx-preview",children:r.jsx("i",{className:`wx-GAOa4kDV wxi-${n.type}`})}),n.type==="folder"?r.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[r.jsxs("div",{className:"wx-GAOa4kDV wx-folder-name",children:[r.jsx("span",{className:"wx-GAOa4kDV wx-type",children:i("Folder")}),r.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[r.jsx("span",{children:x}),r.jsx("span",{children:b})]})]}),r.jsx("div",{"data-action-id":ea(n.id),className:"wx-GAOa4kDV wx-more",children:r.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]}):r.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[r.jsx("div",{className:"wx-GAOa4kDV wx-file-name",children:r.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[r.jsx("span",{children:x}),r.jsx("span",{children:b})]})}),r.jsx("div",{"data-action-id":ea(n.id),className:"wx-GAOa4kDV wx-more",children:r.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]})]})})}function jw(){const n=u.useContext(ta),a=u.useContext(na.i18n),i=u.useMemo(()=>a.getGroup("filemanager"),[a]),[l]=Us(n,"panels"),c=gt(n,"activePanel"),d=gt(n,"mode"),m=l[c]._files,h=l[c].selected,g=l[c].path,y=l[c]._crumbs,x=l[c]._selectNavigation,b=u.useCallback((T,D)=>{const F=D&&(D.ctrlKey||D.metaKey),$=D&&D.shiftKey;if(T==="/wx-filemanager-parent-link"){if(h.length&&(F||$))return;n.exec("select-file",{type:"navigation"});return}let G=T==="body"&&D?null:T;const L=D.target.className.indexOf("wx-more")!==-1||D.target.className.indexOf("wxi-dots-v")!==-1;setTimeout(()=>{n.exec("select-file",{id:G,toggle:F&&!L,range:$&&!L,panel:c})},1)},[n,h,c]),w=u.useCallback(()=>{y.length>1&&n.exec("set-path",{id:y[y.length-2].id,panel:c,selected:[y[y.length-1].id]})},[n,y,c]),A=u.useCallback(T=>{if(T==="/wx-filemanager-parent-link")return w();d==="search"&&n.exec("filter-files",{text:""});const D=m.find(F=>F.id===T);D&&(D.type=="folder"?n.exec("set-path",{id:D.id,panel:c}):n.exec("open-file",{id:D.id}))},[n,w,d,m,c]),j=u.useCallback((T,D)=>{(!h?.length||!h.filter(F=>F?.id===T).length>0)&&b(T,D)},[h,b]),k=u.useMemo(()=>g!=="/"?[{id:"/wx-filemanager-parent-link",name:i("Back to parent folder"),navigation:x},...m]:m,[g,i,x,m]),N=u.useRef(null),M=u.useRef();return u.useEffect(()=>{N.current&&(M.current?(M.current.click=b,M.current._dblclick=A,M.current.context=j):(M.current={click:b,dblclick:T=>M.current._dblclick(T),_dblclick:A,context:j},Ac(N.current,M.current)))},[b,A,j]),d=="search"&&!k.length?r.jsx("div",{className:"wx-iyjASZCY wx-not-found",children:r.jsx("div",{className:"wx-iyjASZCY wx-not-found-text",children:i("Looks like nothing is here")})}):r.jsx("div",{tabIndex:0,className:"wx-iyjASZCY "+("wx-cards"+(g!=="/"&&d!=="search"?" wx-has-back-link":"")),"data-id":ea("body"),ref:N,children:k.map(T=>r.jsx(oM,{item:T},T.id))})}function po({name:n="",spin:a=!1,onClick:i}){return r.jsx("i",{"data-menu-ignore":"true",className:`wx-uwcvNSAG wx-icon wxi-${n} ${a?"wx-spin":""} ${i?"wx-clickable":""}`,onClick:()=>{i&&i()}})}function cM(){const n=u.useContext(na.i18n).getGroup("filemanager"),a=u.useContext(ta),i=gt(a,"activePanel"),[l]=Us(a,"panels"),c=u.useMemo(()=>l[i]._crumbs,[l,i]);function d(){a.exec("filter-files",{text:""})}return r.jsxs("div",{className:"wx-GDJvtROw wx-search",children:[r.jsxs("div",{className:"wx-GDJvtROw wx-toolbar",children:[r.jsx("div",{className:"wx-GDJvtROw wx-back-icon",children:r.jsx(po,{name:"angle-left",onClick:d})}),r.jsxs("div",{className:"wx-GDJvtROw wx-text",children:[n("Search results in")," ",Array.isArray(c)&&c.map((m,h)=>r.jsxs(u.Fragment,{children:[h?"/":null,m.id=="/"?n(m.name):m.name]},h))]})]}),r.jsx(jw,{})]})}function Dh({narrowMode:n,extraInfo:a}){const i=u.useContext(ta),{preview:l,icon:c}=i.templates,d=u.useContext(na.i18n),m=u.useMemo(()=>d.getGroup("filemanager"),[d]),h=u.useMemo(()=>bc("%D, %d %F %Y, %H:%i",d.getRaw().calendar),[d]),[g,y]=Us(i,"panels"),x=gt(i,"activePanel"),b=gt(i,"preview"),w=gt(i,"search"),A=u.useMemo(()=>{const L=g&&x!=null&&g[x]?._selected?.length||0;return w&&!L},[w,y,x]),j=u.useMemo(()=>{const L=g&&x!=null?g[x]:null;return L?A?L._files:L._selected:[]},[A,y,x]),k=u.useCallback((L,Q)=>(L?`${L} ${m(L>1?"folders":"folder")} `:"")+(Q?`${Q} ${m(Q>1?"files":"file")}`:""),[m]),N=u.useCallback(()=>{i.exec("show-preview",{mode:!b})},[i,b]),M=u.useCallback(L=>L.type==="folder"?m("Folder"):L.ext||m("Unknown file"),[m]),T=u.useMemo(()=>{let L,Q,q,P,Y,H,ye,de;if(j.length===1&&!A){Q=j[0],L=Q.name;const Z=l(Q,400,500);Z?(q=Z,P=""):(P=c(Q,"big"),q=""),Y=Q.type!=="folder"}else{if(Q=Y=null,L="",j.length){let Z=0,z=0,se=0,W=[],O;j.forEach(ce=>{typeof ce.size>"u"&&(O=!0,Z=void 0),O||(Z+=ce.size),W.push(M(ce)),ce.type==="folder"?z++:se++});const le=new Set(W);H=le.size>1?m("multiple"):[...le][0],ye=k(z,se),de=Z,A||(L=m("Multiple files"))}P=c({type:A?"search":j.length?"multiple":"none"},"big"),q=""}return{name:L,item:Q,previewSrc:q,iconSrc:P,showDownloadIcon:Y,type:H,totalCount:ye,totalSize:de}},[j,A,l,c,m,M,k]),D=u.useCallback(()=>{i.exec("download-file",{id:j[0].id})},[i,j]),F=u.useCallback(async L=>{if(!a||!L)return null;try{return await a(L)}catch(Q){return console.log(Q),null}},[a]),[$,G]=u.useState(null);return u.useEffect(()=>{let L=!1;return G(null),Promise.resolve(F(T.item)).then(Q=>{L||G(Q)}).catch(()=>{L||G(null)}),()=>{L=!0}},[F,T.item]),r.jsx("div",{className:"wx-O0BTtRrH wx-wrapper",children:j&&j.length?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"wx-O0BTtRrH wx-preview",children:[r.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[r.jsx("div",{className:"wx-O0BTtRrH wx-name",children:T.name}),r.jsxs("div",{className:"wx-O0BTtRrH wx-icons",children:[T.showDownloadIcon?r.jsx(po,{name:"download",onClick:D}):null,n?r.jsx(po,{name:"close",onClick:N}):null]})]}),T.previewSrc?r.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:r.jsx("img",{src:T.previewSrc,alt:m("A miniature file preview")})}):T.iconSrc?r.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:r.jsx("img",{src:T.iconSrc,alt:m("A miniature file preview")})}):r.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:T.item?r.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${T.item.type}`}):r.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${A?"search":"file-multiple-outline"}`})})]}),r.jsxs("div",{className:"wx-O0BTtRrH wx-info-panel",children:[r.jsx("div",{className:"wx-O0BTtRrH wx-title",children:m(A?"Found":"Information")}),r.jsxs("div",{className:"wx-O0BTtRrH wx-list",children:[T.item?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Type")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:M(T.item)}),typeof T.item.size<"u"?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Size")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:Wu(T.item.size)})]}):null,r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Date")}),r.jsxs("span",{className:"wx-O0BTtRrH wx-value",children:[h(T.item.date)," "]})]}):r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Count")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:T.totalCount}),r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Type")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:T.type}),typeof T.totalSize<"u"?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Size")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:Wu(T.totalSize)})]}):null]}),$?Object.entries($).map(([L,Q])=>r.jsxs(kp.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:L}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:Q})]},L)):null]})]})]}):r.jsxs("div",{className:"wx-O0BTtRrH wx-no-info-panel",children:[r.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[r.jsx("div",{className:"wx-O0BTtRrH wx-name",children:T.name}),r.jsx("div",{className:"wx-O0BTtRrH wx-icons",children:n?r.jsx(po,{name:"close",onClick:N}):null})]}),r.jsx("div",{className:"wx-O0BTtRrH wx-no-info-wrapper",children:r.jsxs("div",{className:"wx-O0BTtRrH wx-no-info",children:[T.previewSrc?r.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:r.jsx("img",{src:T.previewSrc,alt:m("A miniature file preview")})}):T.iconSrc?r.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:r.jsx("img",{src:T.iconSrc,alt:m("A miniature file preview")})}):r.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:r.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${A?"search":"message-question-outline"}`})}),r.jsx("span",{className:"wx-O0BTtRrH wx-text",children:A?"":m("Select file or folder to view details")})]})})]})})}function Aw({panel:n}){const a=u.useContext(ta),i=u.useContext(na.i18n),l=u.useMemo(()=>i.getGroup("filemanager"),[i]),[c,d]=Us(a,"panels"),m=u.useMemo(()=>c[n]._files,[d,n]),h=u.useMemo(()=>c[n]._crumbs||[],[d,n]);function g(j){const k=Bp(j,h);a.exec("set-path",{id:j,panel:n,...k&&{selected:[k]}})}const[y,x]=u.useState(null);u.useEffect(()=>{m&&x(null)},[m]);function b(){x(!0),a.exec("request-data",{id:h[h.length-1].id}),setTimeout(()=>{x(null)},5e3)}const w=u.useRef(null),A=u.useRef();return u.useEffect(()=>{A.current?A.current.click=g:(A.current={click:g},Ac(w.current,A.current))},[g]),r.jsxs("div",{className:"wx-SNY5LTYx wx-breadcrumbs","data-menu-ignore":"true",ref:w,children:[r.jsx("div",{className:"wx-SNY5LTYx wx-refresh-icon",children:r.jsx(po,{name:"refresh",spin:!!y,onClick:b})}),h.map((j,k)=>r.jsxs(kp.Fragment,{children:[k?r.jsx(po,{name:"angle-right"}):null,r.jsx("div",{className:"wx-SNY5LTYx wx-item","data-id":ea(j.id),"data-menu-ignore":"true",children:j.id=="/"?l(j.name):j.name})]},k))]})}function uM({row:n}){const a=u.useContext(na.i18n),[i]=u.useState(()=>a.getGroup("filemanager")),l=u.useContext(ta).templates,[c]=u.useState(()=>l.icon(n,"small"));return r.jsx("div",{className:"wx-qgAqG6sL wx-name-cell",children:n.id==="/wx-filemanager-parent-link"?r.jsxs(r.Fragment,{children:[r.jsx("i",{className:"wx-qgAqG6sL wxi-arrow-left"}),r.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",i("Back to parent folder")]})]}):r.jsxs(r.Fragment,{children:[c?r.jsx("img",{className:"wx-qgAqG6sL wx-icon",alt:"",src:c,height:"24px",width:"24px"}):r.jsx("i",{className:`wx-qgAqG6sL wxi-${n.type}`}),r.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",n.name," "]})]})})}function Mw({children:n}){const a=u.useContext(ta),i=gt(a,"activePanel"),l=u.useContext(qp),c=u.useRef(null);let d=u.useRef({});return d.current.drop=()=>{const m=c.current,h=mk(m,"data-panel");h&&h!=i&&a.exec("set-active-panel",{panel:h*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)},[]),r.jsx("div",{className:"wx-LT9X7tb7 wx-upload-area",ref:c,children:n})}function gp({panel:n,active:a=!1,onClick:i,onContextMenu:l}){const c=u.useContext(ta),d=u.useContext(na.i18n),m=u.useMemo(()=>d.getGroup("filemanager"),[d]),h=u.useMemo(()=>bc("%d %M %Y",d.getRaw().calendar),[d]),[g]=Us(c,"panels"),y=g[n].selected,x=g[n].path,b=g[n]._crumbs,w=g[n]._sorts,A=g[n]._selectNavigation,j=g[n]._files,k=u.useMemo(()=>[{id:"name",header:m("Name"),flexgrow:3,sort:!0,resize:!0,cell:uM},{id:"size",header:m("Size"),width:100,sort:!0,resize:!0,template:H=>typeof H=="number"?Wu(H):""},{id:"date",header:m("Date"),width:120,sort:!0,resize:!0,template:H=>H?h(H):""}],[m,h]),N=u.useRef(null),M=u.useRef(null),T=u.useMemo(()=>A?["/wx-filemanager-parent-link"]:[...y],[A,y]);function D(H,ye){if(ye&&ye.target&&ye.target.className&&ye.target.className.indexOf("wx-grip")!==-1)return;const de=ye&&(ye.ctrlKey||ye.metaKey),Z=ye&&ye.shiftKey;if(H==="/wx-filemanager-parent-link"){if(y.length&&(de||Z))return;c.exec("select-file",{type:"navigation"});return}let z=H==="body"&&ye?null:H;!N.current&&!M.current?c.exec("select-file",{id:z,toggle:de,range:Z,panel:n}):(N.current=null,M.current=null)}function F(){b.length>1&&c.exec("set-path",{id:b[b.length-2].id,panel:n,selected:[b[b.length-1].id]})}function $(H){if(H==="/wx-filemanager-parent-link")return F();const ye=j.find(de=>de.id===H);ye&&(ye.type==="folder"?c.exec("set-path",{id:ye.id,panel:n}):c.exec("open-file",{id:ye.id}))}function G(H){const ye=H.key,de=w[x];let Z=de?"asc":"desc";de&&de.key===ye&&(Z=de.order==="asc"?"desc":"asc"),c.exec("sort-files",{key:ye,order:Z,panel:n,path:x})}function L(H){H.intercept("sort-rows",ye=>(N.current=!0,G(ye),!1)),H.intercept("select-row",()=>!1),H.on("resize-column",()=>M.current=!0),H.intercept("hotkey",()=>!1)}const Q=u.useMemo(()=>x!=="/"?[{id:"/wx-filemanager-parent-link",name:m("Back to parent folder")},...j]:j,[x,j,m]),q=u.useMemo(()=>{if(Q&&w&&w[x]){const{key:H,order:ye}=w[x];return{[H]:{order:ye}}}},[Q,w,x]),P=u.useRef(null),Y=u.useRef();return u.useEffect(()=>{Y.current?(Y.current.click=D,Y.current._dblclick=$):(Y.current={click:D,dblclick:H=>Y.current._dblclick(H),_dblclick:$},Ac(P.current,Y.current))},[D,$]),r.jsxs("div",{onClick:i,onContextMenu:l,className:"wx-SSaVhET7 wx-wrapper",children:[r.jsx(Aw,{panel:n}),r.jsx("div",{"data-id":ea("body"),className:`wx-SSaVhET7 wx-list ${a?"wx-active":""}`,ref:P,children:r.jsx(Mw,{children:r.jsx(rM,{init:L,data:Q,columns:k,selectedRows:T,columnStyle:()=>"wx-SSaVhET7 wx-each-cell",sizes:{rowHeight:42,headerHeight:42},sortMarks:q})})})]})}function dM(){const n=u.useContext(ta),a=gt(n,"activePanel");function i(l){n.exec("set-active-panel",{panel:l})}return r.jsxs("div",{className:"wx-L55BfJa2 wx-panels","data-id":ea("body"),children:[r.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":0,children:r.jsx(gp,{panel:0,active:a==0,onClick:()=>i(0),onContextMenu:()=>i(0)})}),r.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":1,children:r.jsx(gp,{panel:1,active:a==1,onClick:()=>i(1),onContextMenu:()=>i(1)})})]})}function Nw({folderIcon:n=!1,folder:a={}}){const i=u.useContext(ta),[l,c]=Us(i,"panels"),d=gt(i,"activePanel"),m=u.useMemo(()=>l[d].path,[c,d]),h=u.useContext(na.i18n),g=u.useMemo(()=>h.getGroup("filemanager"),[h]),y=u.useMemo(()=>!!a.data?.find(A=>A.type==="folder"),[a]),x=u.useMemo(()=>a.id=="/"?g(a.name):a.name,[a,g]),b=u.useMemo(()=>a.$level>1?(a.$level-1)*20:0,[a]),w=a.open;return r.jsxs(r.Fragment,{children:[r.jsxs("li",{"data-id":ea(a.id),className:`wx-NYfhvGIt wx-folder${m===a.id?" wx-selected":""}`,style:{paddingLeft:`${b}px`},children:[y?r.jsx("i",{className:`wx-NYfhvGIt wx-toggle wxi-${w?"angle-down":"angle-right"}`,"data-action":"toggle"}):r.jsx("span",{className:"wx-NYfhvGIt wx-toggle-placeholder"}),r.jsx("i",{className:"wx-NYfhvGIt "+(n||"wxi-folder")}),r.jsxs("span",{className:"wx-NYfhvGIt wx-name",children:[" ",x," "]})]}),w&&a.data&&a.data.length&&y?r.jsx(r.Fragment,{children:a.data.map(A=>A.type==="folder"?r.jsx(Nw,{folder:A},A.id):null)}):null]})}function fM(){const n=u.useContext(ta),[a,i]=Us(n,"data"),[l,c]=Us(n,"panels"),d=gt(n,"activePanel"),m=u.useMemo(()=>l[d]._crumbs,[c,d]),h=u.useCallback(A=>{n.exec("open-tree-folder",{id:A,mode:!a.byId(A).open})},[n,i]),g=u.useCallback(A=>{const j=Bp(A,m);n.exec("set-path",{id:A,panel:d,...j&&{selected:[j]}})},[n,m,d]),[y,x]=u.useState([]);u.useEffect(()=>{x(a.byId(0).data)},[i]);const b=u.useRef(null),w=u.useRef();return u.useEffect(()=>{w.current?(w.current.click=g,w.current.toggle=h):(w.current={click:g,toggle:h},Ac(b.current,w.current))},[g,h]),r.jsx("ul",{ref:b,className:"wx-LyHJ6R6A",children:y.map(A=>A.type==="folder"?r.jsx(Nw,{folder:A},A.id):null)})}function mM(){const n=u.useContext(ta),a=u.useContext(na.i18n),i=u.useMemo(()=>a.getGroup("filemanager"),[a]),l=gt(n,"drive"),c=l?l.used:"",d=l?l.total:"";return c&&d?r.jsxs("div",{className:"wx-DetSyKGG wx-drive",children:[r.jsx("progress",{value:c,max:d,className:"wx-DetSyKGG wx-progress"}),r.jsxs("p",{children:[Wu(c)," ",i("of")," ",Wu(d)," ",i("used")]})]}):null}function hM({option:n}){const a=u.useContext(na.i18n).getGroup("filemanager"),i=u.useContext(qp),l=u.useCallback(()=>{i.open({})},[i]);return r.jsx("div",{className:"wx-9XiKcxq5 wx-upload-button",onClick:l,children:r.jsx("span",{children:a(n.text)})})}function pM({readonly:n,menuOptions:a}){const i=u.useContext(na.i18n).getGroup("filemanager"),{showPrompt:l}=u.useContext(Up);u.useEffect(()=>{Lj("upload",hM)},[]);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=i(m.text),m)),[a,i]);return r.jsxs("div",{className:"wx-FlucfALM wx-wrapper",children:[!n&&r.jsx("div",{className:"wx-FlucfALM wx-button",children:r.jsx(Ij,{options:d,at:"bottom-fit",onClick:c,children:r.jsx(Fu,{type:"primary block",children:i("Add New")})})}),r.jsx("div",{className:"wx-FlucfALM wx-tree",children:r.jsx(fM,{})}),r.jsx(mM,{})]})}function gM({value:n="",onSearch:a}){const[i,l]=ow(n),c=u.useContext(na.i18n).getGroup("filemanager"),d=u.useRef(null),m=u.useMemo(()=>i!==""?"wxi-close":"wxi-search",[i]);function h(y){const x=y.target.value;l(x),a&&a({value:x})}function g(){l(""),d.current&&d.current.focus(),a&&a({value:""})}return r.jsxs("div",{className:"wx-lUZMtgT1 wx-search-input",children:[r.jsx("i",{className:`wx-lUZMtgT1 wx-icon ${m}`,onClick:g}),r.jsx("input",{type:"text",className:"wx-lUZMtgT1 wx-text",ref:d,value:i,onInput:h,placeholder:c("Search")})]})}function vM({narrowMode:n=!1,onShowTree:a}){const i=u.useContext(ta),l=u.useContext(na.i18n).getGroup("filemanager"),c=gt(i,"mode"),d=gt(i,"preview"),m=gt(i,"search"),h=[{icon:"wxi-view-sequential",id:"table"},{icon:"wxi-view-grid",id:"cards"},{icon:"wxi-view-column",id:"panels"}];function g({value:b}){i.exec("set-mode",{mode:b})}function y(b){b.preventDefault(),i.exec("show-preview",{mode:!d})}function x(b){i.exec("filter-files",{text:b.value})}return r.jsxs("div",{className:"wx-5PZQQztG wx-toolbar",children:[r.jsxs("div",{className:"wx-5PZQQztG wx-left "+(n?"wx-left-narrow":""),children:[n?c==="panels"||c==="search"?null:r.jsx("div",{className:"wx-5PZQQztG wx-sidebar-icon","data-id":ea("toggle-tree"),children:r.jsx(po,{onClick:()=>a&&a(),name:"subtask"})}):r.jsx("div",{className:"wx-5PZQQztG wx-name",children:l("Files")}),r.jsx(gM,{onSearch:x,value:m})]}),r.jsxs("div",{className:"wx-5PZQQztG wx-right",children:[n?null:r.jsx("div",{className:"wx-5PZQQztG wx-preview-icon",children:r.jsx(lj,{onClick:y,value:d,children:r.jsx("i",{className:"wx-5PZQQztG wxi-eye"})})}),r.jsx("div",{className:"wx-5PZQQztG wx-modes",children:r.jsx(tj,{value:c,options:h,onChange:g})})]})]})}function yM(){const n=u.useContext(ta),a=gt(n,"activePanel");return r.jsxs("div",{className:"wx-NwohNJzN wx-wrapper",children:[r.jsx(Aw,{panel:a}),r.jsx(Mw,{children:r.jsx(jw,{})})]})}function bM({readonly:n=!1,menuOptions:a,extraInfo:i}){const l=u.useRef(null),c=u.useRef(null),[d,m]=u.useState(void 0),[h,g]=u.useState(void 0),[y,x]=u.useState(!1),b=pw(),w=u.useContext(ta),{showPrompt:A,showConfirm:j}=u.useContext(Up),k=u.useContext(na.i18n),N=u.useMemo(()=>k.getGroup("filemanager"),[k]),M=gt(w,"mode"),T=gt(w,"preview"),D=gt(w,"activePanel"),[F,$]=Us(w,"panels"),G=u.useMemo(()=>(F&&D!=null?F[D]:null)?.selected??[],[$,D]),L=u.useMemo(()=>(F&&D!=null?F[D]:null)?.path,[$,D]),[Q,q]=u.useState([]);u.useEffect(()=>{const le=l.current;if(!le)return;const ce=new ResizeObserver(K=>{const be=K[0]?.borderBoxSize?.[0]?.inlineSize;typeof be=="number"&&g(be<768)});return ce.observe(le),()=>{ce.disconnect()}},[]);const P=u.useCallback(()=>{x(le=>!le)},[]),Y=u.useCallback(le=>{h&&Vu(le)!=="toggle-tree"&&x(!1)},[h]);u.useEffect(()=>{const le=c.current;if(le)return Hr(le,Y).destroy},[Y]),u.useEffect(()=>{const le=c.current;if(!le)return;const ce=new ResizeObserver(()=>{le&&m(le.clientWidth)});return ce.observe(le),le&&m(le.clientWidth),()=>{ce.disconnect()}},[]);const H=u.useMemo(()=>({icon:"wxi-eye",text:"Preview",id:"preview"}),[]),ye=u.useCallback(le=>{let ce=h?[H]:[];return le==="file"&&(ce=[...ce,...a().filter(K=>K.id==="download")]),ce},[h,H,a]),de=u.useRef(null),Z=u.useCallback((le,ce,K)=>{const be=K?[ce.id]:G;switch(le){case"download":w.exec("download-file",{id:ce.id});break;case"copy":case"move":de.current={action:le,ids:be};break;case"paste":de.current&&w.exec(de.current.action==="copy"?"copy-files":"move-files",{ids:de.current.ids,target:ce?.type==="folder"?ce.id:L});break;case"rename":A({item:ce});break;case"delete":j({selected:be});break;case"preview":w.exec("show-preview",{mode:!T});break}},[w,G,L,A,j,T]),z=u.useCallback(()=>F?.[D],[F,D]);u.useEffect(()=>{const le=l.current;if(!le)return;const ce=Sj(le,{api:w,menuOptions:n?ye:a,performAction:Z,getPanel:z});return()=>{typeof ce=="function"?ce():ce&&typeof ce.destroy=="function"&&ce.destroy()}},[w,n,ye,a,Z,z]);const se=u.useCallback((le,ce)=>{const K=le?w.getFile(le):null,be=ce.target.closest(".tree-item.folder");let he;if(n)he=ye(K?.type);else{switch(le){case"body":he=a(le);break;default:if(K)if(!be&&G.length>1)he=h?[H,...a("multiselect")]:a("multiselect");else if(le==="/")he=a("folder",K).filter(fe=>fe.id==="paste");else{const fe=a(K.type,K);fe&&(he=h?[H,...fe]:fe)}}M==="search"&&(he=he?.filter(fe=>fe.id!=="paste"))}if(K?.id&&(!G.length||!G.some(fe=>fe===K.id))&&!be&&w.exec("select-file",{id:K.id}),he?.length)return he.forEach(fe=>{be&&(fe.hotkey=""),fe.text&&(fe.text=N(fe.text)),fe.hotkey&&(fe.subtext=fe.hotkey)}),q(he),K||{}},[w,n,ye,a,G,h,H,M,N]),W=u.useCallback(le=>{const{action:ce,context:K}=le;ce&&Z(ce.id,K,!ce.hotkey)},[Z]);async function O(le){await Promise.resolve();const{name:ce,size:K}=le.file;w.exec("create-file",{file:{name:ce,size:K,date:new Date,file:le.file},parent:L})}return r.jsx("div",{className:"wx-RJbNonjJ wx-filemanager wx-flex",ref:l,"data-menu-ignore":"false",children:h&&T?r.jsx("div",{className:"wx-RJbNonjJ wx-info-narrow",children:r.jsx(Dh,{narrowMode:h,extraInfo:i})}):r.jsxs(r.Fragment,{children:[r.jsx(vM,{narrowMode:h,onShowTree:P}),r.jsx(zj,{dataKey:"id",at:"point",options:Q,resolver:se,onClick:W,children:r.jsxs(hw,{dataKey:"actionId",options:Q,resolver:se,onClick:W,children:[r.jsx(Bj,{data:b,apiOnly:!0,uploadURL:O}),r.jsx(qp.Provider,{value:b,children:r.jsx("div",{className:"wx-RJbNonjJ wx-content-wrapper wx-flex",children:M!=="panels"&&M!=="search"?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-RJbNonjJ "+["wx-sidebar",h?"wx-sidebar-narrow":"",y?"wx-sidebar-visible":""].filter(Boolean).join(" "),ref:c,children:r.jsx(pM,{readonly:n,menuOptions:a})}),r.jsxs("div",{className:"wx-RJbNonjJ wx-content",style:{width:`calc(100% - ${d||0}px - 10px)`},children:[r.jsx("div",{className:`wx-RJbNonjJ wx-content-item${T?"":"-fit"}`,"data-id":ea("body"),children:M==="table"?r.jsx(gp,{panel:D}):r.jsx(yM,{})}),T?r.jsx("div",{className:"wx-RJbNonjJ wx-info",children:r.jsx(Dh,{extraInfo:i})}):null]})]}):r.jsxs(r.Fragment,{children:[r.jsx("div",{className:`wx-RJbNonjJ wx-content-item${T?"":"-fit"}`,children:M==="panels"?r.jsx(dM,{}):r.jsx(cM,{})}),T?r.jsx("div",{className:"wx-RJbNonjJ wx-info",children:r.jsx(Dh,{extraInfo:i})}):null]})})})]})})]})})}const xM=n=>n.split("-").map(a=>a?a.charAt(0).toUpperCase()+a.slice(1):"").join("");function wM(n,a){const{type:i,ext:l}=n;if(i==="folder")return!1;let c;return i&&i!=="file"&&kb[i]?c=i:l?c=kb[l]?l:"file":c="unknown",`https://cdn.svar.dev/icons/filemanager/vivid/${a}/${c}.svg`}const SM=u.forwardRef(function(n,a){const{data:i=[],mode:l="cards",drive:c=null,preview:d=!1,panels:m=null,activePanel:h=0,readonly:g=!1,menuOptions:y=bj,extraInfo:x=null,init:b=null,icons:w=wM,previews:A=null,...j}=n,k=u.useRef();k.current=j;const N=u.useMemo(()=>new yj(uw),[]),M=u.useMemo(()=>N.in,[N]),T=u.useRef(null);T.current===null&&(T.current=new sw(($,G)=>{const L="on"+xM($);k.current&&k.current[L]&&k.current[L](G)}),M.setNext(T.current));const D=u.useMemo(()=>({getState:N.getState.bind(N),getReactiveState:N.getReactive.bind(N),getStores:()=>({data:N}),exec:M.exec,setNext:$=>(T.current=T.current.setNext($),T.current),intercept:M.intercept.bind(M),on:M.on.bind(M),detach:M.detach.bind(M),getFile:N.getFile.bind(N),serialize:N.serialize.bind(N),templates:{preview:A||(()=>null),icon:w==="simple"?(()=>null):w}}),[N,M]),F=u.useRef(0);return u.useEffect(()=>{if(!F.current)b&&b(D);else{const $=N.getState();N.init({data:i,mode:l,drive:c,preview:d,panels:m||$.panels||[],activePanel:h})}F.current++},[N,i,l,c,d,m,h,b,D]),F.current===0&&N.init({data:i,mode:l,drive:c,preview:d,panels:m||[],activePanel:h}),u.useImperativeHandle(a,()=>({...D}),[D]),r.jsx(ta.Provider,{value:D,children:r.jsx(Fp,{words:$p,optional:!0,children:r.jsx(iM,{children:r.jsx(bM,{readonly:g,menuOptions:y,extraInfo:x})})})})});function CM({fonts:n=!0,children:a}){return a?r.jsx(cb,{fonts:n,children:a}):r.jsx(cb,{fonts:n})}Dp(ls);function Gp(n,a){if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`Invalid Hub ${a} response.`);return n}function Ku(n,a,i){const l=Gp(n,i);if(!Array.isArray(l[a]))throw new Error(`Invalid Hub ${i} response: ${a} must be an array.`);return l[a]}function kM(n,a,i){const l=Gp(n,i);if(!l[a]||typeof l[a]!="object"||Array.isArray(l[a]))throw new Error(`Invalid Hub ${i} response: ${a} must be an object.`);return l[a]}async function jM(n,a=!1){return Ku(await Ve(`/api/remote/filesystem/roots${a?"?refresh=1":""}`,void 0,n),"roots","filesystem roots")}async function Lh(n,a){const i=await Ve(`/api/remote/filesystem/entries?id=${encodeURIComponent(n)}`,void 0,a);return{folder:kM(i,"folder","filesystem entries"),entries:Ku(i,"entries","filesystem entries")}}async function AM(n,a){return Ve("/api/remote/filesystem/selection/scan",{method:"POST",body:JSON.stringify({itemIds:n})},a)}async function MM(n,a,i,l){return Ve("/api/remote/files/from-hub",{method:"POST",body:JSON.stringify({itemIds:n,deviceIds:a,remoteDirectory:i})},l)}async function NM(n,a=!1){const i=await Ve(`/api/remote/files/jobs?active=${a?"1":"0"}`,void 0,n);return{jobs:Ku(i,"jobs","file transfer jobs")}}async function TM(n,a){return Ve(`/api/remote/files/jobs/${encodeURIComponent(n)}`,void 0,a)}async function RM(n,a){return Ve(`/api/remote/files/jobs/${encodeURIComponent(n)}/cancel`,{method:"POST"},a)}async function jb(n){return Ku(await Ve("/api/remote/filesystem/shared-folders",void 0,n),"folders","shared folders")}async function EM(n,a){return Ve("/api/remote/filesystem/shared-folders",{method:"POST",body:JSON.stringify({sourceId:n})},a)}async function DM(n,a,i){return Ve(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)},i)}async function LM(n,a){return Ve(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}`,{method:"DELETE"},a)}async function _M(n,a,i,l){const c=await Ve(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}/sync`,{method:"POST",body:JSON.stringify({deviceIds:a,remoteDirectory:i})},l),d=Gp(c,"shared folder sync");return{ok:d.ok===!0,jobs:Ku(c,"jobs","shared folder sync"),files:Number(d.files||0),totalBytes:Number(d.totalBytes||0)}}function IM(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 Ab(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let i=n,l=0;for(;i>=1024&&l<a.length-1;)i/=1024,l+=1;return`${i.toFixed(l===0||i>=100?0:1)} ${a[l]}`}function Mf(n){return n.driveType==="network"?"network":n.driveType==="removable"?"removable":"local"}function zM(n){const a=n.filter(i=>Mf(i)==="local");return a.find(i=>/\bC:/i.test(`${i.name} ${i.displayPath||""}`))||a[0]||n[0]||null}function OM({hubUrl:n,roots:a,loading:i,error:l,onRefreshRoots:c,onImportFiles:d,onImportFolder:m,onSelectionChange:h,onShareItem:g,onAddSyncFolder:y,onNotice:x}){const b=u.useRef(null),w=u.useRef("/"),A=u.useRef(0),j=u.useRef([]),k=u.useRef(new Map),[N,M]=u.useState(null),[T,D]=u.useState([]),[F,$]=u.useState([]),[G,L]=u.useState(0),[Q,q]=u.useState(null),[P,Y]=u.useState(!1),[H,ye]=u.useState(""),[de,Z]=u.useState(new Set),z=a.find(J=>J.id===N)||null,se=T[T.length-1]||null,W=z?se?.svarPath||`/${z.name}`:null,O=W;u.useEffect(()=>{j.current=T,w.current=O||"/"},[O,T]);const le=u.useMemo(()=>(k.current.clear(),!z||!O||T.length===0?[]:(T.forEach(J=>k.current.set(J.svarPath,J.hubId)),[...T.map((J,Ce)=>({id:J.svarPath,parent:Ce===0?"/":T[Ce-1].svarPath,type:"folder",name:J.name,date:J.modifiedAt?new Date(J.modifiedAt):void 0,lazy:!1})),...F.map(J=>{const Ce=`${O}/${J.name}`;return k.current.set(Ce,J.id),{id:Ce,parent:O,name:J.name,type:J.type==="file"?"file":"folder",...J.type==="file"?{size:J.size}:{},date:J.modifiedAt?new Date(J.modifiedAt):void 0,lazy:J.type!=="file"&&J.hasChildren===!0,displayPath:J.displayPath,locked:J.locked,driveType:J.driveType,totalBytes:J.totalBytes,freeBytes:J.freeBytes}})])),[z,F,O,T]),ce=J=>k.current.get(String(J))||String(J),K=J=>IM({...J,id:ce(String(J.id)),parent:ce(String(J.parent))}),be=async(J,Ce)=>{const Le=J[J.length-1];if(!Le)return;const Fe=++A.current;Y(!0),ye("");try{const _e=await Lh(Le.hubId,n);if(Fe!==A.current)return;if(!Array.isArray(_e.entries))throw new Error("Invalid Hub filesystem entries response.");const Xe={...Le,displayPath:_e.folder.displayPath||Le.displayPath,modifiedAt:_e.folder.modifiedAt||Le.modifiedAt},We=[...J.slice(0,-1),Xe];j.current=We,D(We),$(_e.entries),L(Ze=>Ze+1)}catch(_e){if(Fe!==A.current)return;console.error("[LiveDesk FS] folder navigation failed",{folderId:Le.hubId,error:_e}),ye(_e instanceof Error?`${Ce}: ${_e.message}`:`${Ce}: Unable to read this folder.`)}finally{Fe===A.current&&Y(!1)}},he=async J=>{const Ce={svarPath:`/${J.name}`,hubId:J.id,name:J.name,displayPath:J.displayPath,modifiedAt:J.modifiedAt},Le=++A.current;M(J.id),j.current=[Ce],D([Ce]),w.current=Ce.svarPath,$([]),ye(""),Y(!0),q(J.id),Z(Fe=>{const _e=new Set(Fe);return _e.delete(J.id),_e});try{const Fe=await Lh(J.id,n);if(Le!==A.current)return;if(!Array.isArray(Fe.entries))throw new Error("Invalid Hub filesystem entries response.");const _e={...Ce,displayPath:Fe.folder.displayPath||Ce.displayPath,modifiedAt:Fe.folder.modifiedAt||Ce.modifiedAt};j.current=[_e],D([_e]),$(Fe.entries),L(Xe=>Xe+1)}catch(Fe){if(Le!==A.current)return;console.error("[LiveDesk FS] getEntries failed",{rootId:J.id,error:Fe}),Z(_e=>new Set(_e).add(J.id)),ye(Fe instanceof Error?`${J.name}: ${Fe.message}`:`${J.name}: Unable to read this drive.`),x(Fe instanceof Error?`${J.name}: ${Fe.message}`:`${J.name}: Unable to read this drive.`)}finally{Le===A.current&&(q(null),Y(!1))}},fe=J=>{const Ce=j.current;J<0||J>=Ce.length||J===Ce.length-1||be(Ce.slice(0,J+1),Ce[J].name)},ee=(J,Ce)=>{if(J.type!=="folder")return;const Le=j.current,Fe=Le.findIndex(Xe=>Xe.svarPath===Ce);if(Fe<0)return;const _e={svarPath:`${Ce}/${J.name}`,hubId:J.id,name:J.name,displayPath:J.displayPath,modifiedAt:J.modifiedAt};be([...Le.slice(0,Fe+1),_e],J.name)},we=()=>fe(j.current.length-2),Me=J=>{if(J.key!=="Enter"&&J.code!=="Enter"&&J.code!=="NumpadEnter"||J.target?.closest('button, input, textarea, [contenteditable="true"]'))return;const Le=b.current;if(!Le)return;const Fe=Le.getState().panels?.flatMap(Xe=>Xe.selected||[])||[];if(Fe.length!==1)return;const _e=Le.getFile(String(Fe[0]));_e?.type==="folder"&&(J.preventDefault(),J.stopPropagation(),ee(K(_e),String(_e.parent||w.current)))};u.useEffect(()=>{const J=a.find(Ce=>Ce.id===N)||zM(a);if(Z(Ce=>new Set([...Ce].filter(Le=>a.some(Fe=>Fe.id===Le)))),!J){M(null),j.current=[],D([]),$([]);return}he(J)},[a]);const He=J=>{b.current=J,J.on("request-data",async({id:Ce})=>{const Le=String(Ce),Fe=ce(Le);try{const _e=await Lh(Fe,n);if(!Array.isArray(_e.entries))throw new Error("Invalid Hub filesystem entries response.");const Xe=_e.entries.map(We=>{const Ze=`${Le}/${We.name}`;return k.current.set(Ze,We.id),{id:Ze,parent:Le,name:We.name,type:We.type==="file"?"file":"folder",...We.type==="file"?{size:We.size}:{},date:We.modifiedAt?new Date(We.modifiedAt):void 0,lazy:We.type!=="file"&&We.hasChildren===!0,displayPath:We.displayPath,locked:We.locked,driveType:We.driveType,totalBytes:We.totalBytes,freeBytes:We.freeBytes}});await J.exec("provide-data",{id:Le,data:Xe})}catch(_e){console.error("[LiveDesk FS] nested getEntries failed",{id:Fe,error:_e}),x(_e instanceof Error?_e.message:"Unable to read this folder.")}}),J.intercept("set-path",({id:Ce})=>{const Le=String(Ce),Fe=j.current.findIndex(Xe=>Xe.svarPath===Le);if(Fe>=0)return fe(Fe),!1;const _e=J.getFile(Le);if(_e?.type==="folder")return ee(K(_e),String(_e.parent||w.current)),!1}),J.intercept("open-file",()=>!1),J.on("select-file",()=>{window.setTimeout(()=>{const Fe=(J.getState().panels?.flatMap(_e=>_e.selected||[])||[]).map(_e=>J.getFile(_e)).filter(Boolean).map(_e=>K(_e));h(Fe.map(_e=>_e.id),Fe)},0)})},ne=(J,Ce)=>{const Le=Ce?K(Ce):null,Fe=()=>{const _e=Le?.type==="file"?String(Ce?.parent||w.current):String(Ce?.id||w.current);b.current?.exec("request-data",{id:_e})};return J==="body"?[{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Fe},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>x("Select a file or folder to view its properties.")}]:J==="multiselect"?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>{(b.current?.getState().panels?.flatMap(Xe=>Xe.selected||[])||[]).forEach(Xe=>{const We=b.current?.getFile(Xe);We&&g(K(We))})}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Fe}]:Le?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>g(Le)},...Le.type==="folder"?[{id:"sync",text:"Add folder to Sync",icon:"mdi mdi-folder-sync-outline",handler:()=>y(Le)}]:[],{id:"copy-path",text:"Copy path",icon:"mdi mdi-content-copy",handler:()=>{Cf(Le.displayPath||Le.name)}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Fe},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>x(`${Le.name}
14
- ${Le.displayPath||""}`)}]:[]},qe=async()=>{try{await c()}catch(J){x(J instanceof Error?J.message:"Unable to refresh Hub drives.")}},mt=[{id:"local",label:"Local drives",icon:co,roots:a.filter(J=>Mf(J)==="local")},{id:"removable",label:"Removable drives",icon:x0,roots:a.filter(J=>Mf(J)==="removable")},{id:"network",label:"Network drives",icon:jp,roots:a.filter(J=>Mf(J)==="network")}];return r.jsxs("section",{className:"hub-file-explorer-panel","aria-label":"Hub file explorer",children:[r.jsxs("div",{className:"hub-file-explorer-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Hub file explorer"}),r.jsxs("strong",{children:[r.jsx(co,{size:16})," Browse files on this Hub"]})]}),r.jsxs("div",{className:"hub-file-explorer-heading-actions",children:[r.jsx("button",{className:"icon-button",onClick:d,title:"Import files from this browser",type:"button",children:r.jsx(hx,{size:16})}),r.jsx("button",{className:"icon-button",onClick:m,title:"Import folder from this browser",type:"button",children:r.jsx(w0,{size:16})}),r.jsx("button",{className:"icon-button",onClick:()=>{qe()},title:"Refresh drives",type:"button",children:r.jsx(Sc,{size:16})})]})]}),i?r.jsxs("div",{className:"hub-file-explorer-state",children:[r.jsx(co,{size:24}),r.jsx("strong",{children:"Connecting to LiveDesk Hub file system..."})]}):l?r.jsxs("div",{className:"hub-file-explorer-state error",role:"alert",children:[r.jsx(Ti,{size:24}),r.jsx("strong",{children:l})]}):r.jsxs("div",{className:"hub-file-explorer-content",children:[r.jsxs("aside",{className:"hub-file-explorer-drive-sidebar","aria-label":"Hub drives",children:[r.jsxs("div",{className:"hub-drive-sidebar-title",children:[r.jsx(co,{size:15}),r.jsx("strong",{children:"This PC"})]}),mt.map(J=>J.roots.length>0&&r.jsxs("section",{className:"hub-drive-group",children:[r.jsxs("h3",{children:[r.jsx(J.icon,{size:13}),J.label]}),r.jsx("div",{className:"hub-drive-list",children:J.roots.map(Ce=>{const Le=J.icon,Fe=de.has(Ce.id)||Ce.locked===!0;return r.jsxs("button",{className:`hub-drive-item ${N===Ce.id?"active":""} ${Fe?"unavailable":""}`,onClick:()=>{he(Ce)},"aria-pressed":N===Ce.id,type:"button",children:[r.jsx("span",{className:"hub-drive-item-icon",children:r.jsx(Le,{size:16})}),r.jsxs("span",{className:"hub-drive-item-copy",children:[r.jsx("strong",{children:Ce.name}),r.jsx("small",{children:Ce.displayPath||Ce.name}),r.jsxs("em",{children:[Ab(Ce.freeBytes||0)," free / ",Ab(Ce.totalBytes||0)]})]}),Q===Ce.id?r.jsx(Lr,{className:"hub-drive-item-status spin",size:15}):Fe?r.jsx(hy,{className:"hub-drive-item-status",size:15}):null]},Ce.id)})})]},J.id)),a.length===0&&r.jsxs("div",{className:"hub-drive-sidebar-empty",children:[r.jsx(Ti,{size:17}),r.jsx("span",{children:"No drives available."})]})]}),r.jsxs("div",{className:"hub-file-explorer-browser",children:[r.jsxs("div",{className:"hub-file-explorer-navigation",children:[r.jsx("nav",{className:"hub-file-explorer-breadcrumbs","aria-label":"Current Hub folder",children:T.map((J,Ce)=>r.jsxs("span",{className:"hub-file-explorer-breadcrumb-item",children:[Ce>0&&r.jsx(Ap,{size:13,"aria-hidden":"true"}),r.jsx("button",{className:`hub-file-explorer-breadcrumb ${Ce===T.length-1?"current":""}`,onClick:()=>fe(Ce),"aria-current":Ce===T.length-1?"location":void 0,type:"button",children:J.name})]},J.svarPath))}),r.jsxs("div",{className:"hub-file-explorer-navigation-actions",children:[P&&r.jsx(Lr,{className:"hub-file-explorer-loading-icon spin",size:15,"aria-label":"Loading folder"}),r.jsx("button",{className:"icon-button",onClick:we,disabled:T.length<=1||P,title:"Back to parent folder",type:"button",children:r.jsx(lx,{size:16})})]})]}),H&&r.jsxs("div",{className:"hub-file-explorer-folder-error",role:"alert",children:[r.jsx(hy,{size:15}),r.jsx("span",{children:H})]}),r.jsx("div",{className:"hub-file-explorer-svar",onKeyDownCapture:Me,children:r.jsx(CM,{fonts:!1,children:r.jsx(SM,{data:le,panels:W?[{path:W,selected:[]}]:void 0,readonly:!0,mode:"table",preview:!1,init:He,icons:"simple",menuOptions:ne},`${z?.id||"no-root"}:${G}`)})})]})]})]})}class HM extends u.Component{state={error:null};static getDerivedStateFromError(a){return{error:a}}componentDidCatch(a,i){console.error("[LiveDesk] Share Files runtime error",a,i.componentStack)}render(){return this.state.error?r.jsxs("section",{className:"file-share-error-boundary",role:"alert",children:[r.jsx(Bf,{size:24}),r.jsx("strong",{children:"Share Files could not be opened."}),r.jsx("span",{children:this.state.error.message||"An unexpected file explorer error occurred."}),r.jsxs("button",{className:"text-button",onClick:this.props.onRetry,type:"button",children:[r.jsx(Sc,{size:15})," Retry"]})]}):this.props.children}}function FM(n){return n.deviceName||n.hostname||n.deviceId}function $M({devices:n,mode:a,selectedIds:i,onModeChange:l,onToggle:c}){const d=new Set(i);return r.jsxs("section",{className:"distribution-targets",children:[r.jsxs("div",{className:"file-share-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Target"}),r.jsx("strong",{children:a==="all"?`${n.length} connected`:`${i.length} selected`})]}),r.jsxs("div",{className:"file-share-tabs compact","aria-label":"File transfer targets",children:[r.jsxs("button",{className:a==="all"?"active":"",onClick:()=>l("all"),type:"button",children:[r.jsx(Pu,{size:14})," All connected"]}),r.jsxs("button",{className:a==="selected"?"active":"",onClick:()=>l("selected"),type:"button",children:[r.jsx(Ta,{size:14})," Selected"]})]})]}),r.jsx("div",{className:"file-share-device-list","aria-label":"Connected Client targets",children:n.length===0?r.jsx("div",{className:"file-share-empty-inline",children:"No connected Clients."}):n.map(m=>{const h=a==="all"||d.has(m.deviceId);return r.jsxs("label",{className:`file-share-device-option ${h?"selected":""}`,children:[r.jsx("input",{type:"checkbox",checked:h,disabled:a==="all",onChange:()=>c(m.deviceId)}),r.jsx(Ta,{size:20,"aria-hidden":"true"}),r.jsxs("span",{children:[r.jsx("strong",{children:FM(m)}),r.jsxs("small",{children:["Slot ",m.slotNumber?String(m.slotNumber).padStart(3,"0"):"-"," / ",m.platform||"unknown OS"]})]}),r.jsx(Zn,{size:17,"aria-hidden":"true"})]},m.deviceId)})})]})}function BM(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let i=n,l=0;for(;i>=1024&&l<a.length-1;)i/=1024,l+=1;return`${i.toFixed(l===0||i>=100?0:1)} ${a[l]}`}function PM({folders:n,loading:a,busy:i,canSync:l,onSyncAll:c,onSync:d,onToggleAuto:m,onRemove:h,onAdd:g}){return r.jsxs("section",{className:"file-share-sync-panel",children:[r.jsxs("div",{className:"file-share-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Hub folders"}),r.jsx("strong",{children:"Continuous sync"})]}),r.jsxs("button",{className:"text-button compact",onClick:c,disabled:i||!l||n.length===0,type:"button",children:[r.jsx(Sf,{size:15})," ",i?"Syncing":"Sync all"]})]}),a?r.jsx("div",{className:"file-share-empty-state",children:"Loading Hub sync folders..."}):n.length===0?r.jsxs("button",{className:"file-share-empty-state interactive",onClick:g,type:"button",children:[r.jsx(Sf,{size:28}),r.jsx("strong",{children:"Add a selected Hub folder"}),r.jsx("span",{children:"Hub keeps the manifest and can sync while this browser is closed."})]}):r.jsx("div",{className:"file-share-sync-list",children:n.map(y=>r.jsxs("article",{className:`file-share-sync-row state-${y.status}`,children:[r.jsx("div",{className:"file-share-sync-icon",children:r.jsx(Sf,{size:19})}),r.jsxs("div",{className:"file-share-sync-info",children:[r.jsx("strong",{children:y.name}),r.jsx("span",{children:y.displayPath}),r.jsxs("small",{children:[y.fileCount," files / ",BM(y.totalBytes)," · ",y.lastSyncedAt?`Last sync ${Cx(y.lastSyncedAt)} ago`:y.message||"Not synced yet"]})]}),r.jsxs("label",{className:"file-share-auto-sync",children:[r.jsx("input",{type:"checkbox",checked:y.autoSync,onChange:()=>m(y)}),r.jsx("span",{children:"Auto"})]}),r.jsxs("button",{className:"text-button compact",onClick:()=>d(y),disabled:i||!l||y.status==="syncing",type:"button",children:[r.jsx(Sc,{size:14})," Sync now"]}),r.jsx("button",{className:"icon-button",onClick:()=>h(y),title:"Remove sync folder",type:"button",children:r.jsx(Sp,{size:15})})]},y.id))})]})}function UM(n){const i=(n.targetMode==="all"?n.devices.map(l=>l.deviceId):n.selectedTargetIds).length>0;return r.jsxs("aside",{className:"file-share-distribution-panel",children:[r.jsxs("div",{className:"file-share-distribution-head",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Distribution"}),r.jsx("strong",{children:"Hub → Clients"})]}),r.jsx(Bu,{size:18})]}),r.jsxs("div",{className:"file-share-tabs",role:"tablist","aria-label":"Distribution mode",children:[r.jsx("button",{className:n.tab==="send"?"active":"",onClick:()=>n.onTabChange("send"),role:"tab","aria-selected":n.tab==="send",type:"button",children:"Send"}),r.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"?r.jsxs(r.Fragment,{children:[r.jsx($M,{devices:n.devices,mode:n.targetMode,selectedIds:n.selectedTargetIds,onModeChange:n.onTargetModeChange,onToggle:n.onTargetToggle}),r.jsxs("label",{className:"file-share-destination",children:[r.jsx("span",{children:"Destination folder"}),r.jsxs("div",{children:[r.jsx(gc,{size:15}),r.jsx("input",{value:n.remoteDirectory,onChange:l=>n.onRemoteDirectoryChange(l.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),r.jsx("small",{children:"Blank uses Desktop/LiveDeskFiles."})]}),r.jsxs("div",{className:"file-share-selection-summary",children:[r.jsx("span",{children:"Selected"}),r.jsx("strong",{children:n.selectedSummary})]}),r.jsxs("button",{className:"file-share-share-button",onClick:n.onShare,disabled:!n.canShare,type:"button",children:[r.jsx(Bu,{size:17})," Share selected"]}),r.jsxs("button",{className:"file-share-secondary-button",onClick:n.onAddSync,disabled:!n.canAddSync,type:"button",children:[r.jsx(gc,{size:16})," Add selected folder to Sync"]})]}):r.jsx(PM,{folders:n.folders,loading:n.foldersLoading,busy:n.syncBusy,canSync:i,onSyncAll:n.onSyncAll,onSync:n.onSync,onToggleAuto:n.onToggleAuto,onRemove:n.onRemove,onAdd:n.onAddFolder})]})}function qM(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let i=n,l=0;for(;i>=1024&&l<a.length-1;)i/=1024,l+=1;return`${i.toFixed(l===0||i>=100?0:1)} ${a[l]}`}function Mb(n){if(n.state==="completed")return 100;const a=n.totalBytes>0?Math.round(n.sentBytes/n.totalBytes*100):n.totalFiles>0?Math.round(n.completedFiles/n.totalFiles*100):0;return Math.max(0,Math.min(vp(n.state)?100:99,a))}function Nb(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} Client${n.targetCount===1?"":"s"}`:n.state==="partially-failed"?`${n.failedTargets.length} Client${n.failedTargets.length===1?"":"s"} failed`:n.state==="cancelled"?"Transfer cancelled":n.error||"Transfer failed"}function vp(n){return["completed","partially-failed","failed","cancelled"].includes(n)}function GM({hubUrl:n,devices:a,localFeatureAccess:i,upgradeNotice:l,remoteDirectory:c,onRemoteDirectoryChange:d,targetMode:m,selectedTargetIds:h,onTargetModeChange:g,onTargetToggle:y,filePickerRef:x,folderPickerRef:b,onBrowserFileImport:w,onBrowserFolderImport:A,onNotice:j,onTransferChange:k}){const N=Array.isArray(a)?a:[],[M,T]=u.useState([]),[D,F]=u.useState(!0),[$,G]=u.useState(""),[L,Q]=u.useState([]),[q,P]=u.useState([]),[Y,H]=u.useState(null),[ye,de]=u.useState(!1),[Z,z]=u.useState([]),[se,W]=u.useState(!0),[O,le]=u.useState(!1),[ce,K]=u.useState("send"),[be,he]=u.useState([]),fe=u.useRef(new Set),ee=u.useRef(!1),we=u.useMemo(()=>m==="all"?N.map(U=>U.deviceId):h.filter(U=>N.some(ve=>ve.deviceId===U)),[N,h,m]),Me=be.find(U=>!vp(U.state)),He=q.length===1&&q[0].type==="folder"?q[0]:null,ne=q.length===0?"Select files or folders from the Hub explorer.":ye?"Calculating selection size...":Y?`${Y.files} files, ${Y.folders} folders · ${qM(Y.totalBytes)}`:`${q.length} item${q.length===1?"":"s"} selected`,qe=U=>{k({id:U.jobId,state:U.state,progress:Mb(U),message:Nb(U)})},mt=u.useCallback(async()=>{const U=await jM(n,!0);return T(U),G(""),U},[n]),J=async()=>{if(!ee.current){ee.current=!0;try{const ve=(await NM(n,!0)).jobs||[],Ae=await Promise.all([...fe.current].map(async it=>{try{return await TM(it,n)}catch{return null}})),Be=[...ve,...Ae.filter(Boolean)],ft=[...new Map(Be.map(it=>[it.jobId,it])).values()];he(ft),ft.forEach(qe),ft.filter(it=>vp(it.state)).forEach(it=>fe.current.delete(it.jobId))}catch{}finally{ee.current=!1}}};u.useEffect(()=>{let U=!0;F(!0),G(""),Promise.all([mt(),jb(n).then(Ae=>{U&&z(Ae)})]).catch(Ae=>{U&&(G(Ae instanceof Error?"Hub file system is unavailable. Make sure LiveDesk Hub is running on this computer.":"Hub file system is unavailable."),j(Ae instanceof Error?Ae.message:"Hub file system is unavailable."))}).finally(()=>{U&&(F(!1),W(!1))}),J();const ve=window.setInterval(()=>{J()},800);return()=>{U=!1,window.clearInterval(ve)}},[n,mt]),u.useEffect(()=>{if(L.length===0){H(null);return}let U=!1;return de(!0),AM(L,n).then(ve=>{U||H(ve)}).catch(ve=>{U||j(ve instanceof Error?ve.message:"Unable to calculate selected size.")}).finally(()=>{U||de(!1)}),()=>{U=!0}},[n,L.join("|")]);const Ce=(U,ve)=>{Q(U),P(ve)},Le=U=>{U.forEach(ve=>fe.current.add(ve.jobId)),he(ve=>[...new Map([...ve,...U].map(Ae=>[Ae.jobId,Ae])).values()]),U.forEach(qe)},Fe=async()=>{if(!i){j(l);return}if(L.length===0){j("Select files or folders from the Hub explorer.");return}if(we.length===0){j("Choose at least one connected Client.");return}if(Me){j("A Hub transfer is already running.");return}try{const U=await MM(L,we,c.trim(),n);fe.current.add(U.jobId),j("Hub transfer queued."),await J()}catch(U){j(U instanceof Error?U.message:"Unable to start Hub transfer.")}},_e=async U=>{const ve=U||He;if(!ve||ve.type!=="folder"){j("Select one folder to add it to Sync.");return}try{const Ae=await EM(ve.id,n);z(Be=>[...Be.filter(ft=>ft.id!==Ae.folder.id),Ae.folder]),K("sync"),j(`${ve.name} is ready for Hub sync.`)}catch(Ae){j(Ae instanceof Error?Ae.message:"Unable to add the Hub folder to Sync.")}},Xe=async U=>{if(we.length===0){j("Choose at least one connected Client.");return}le(!0),z(ve=>ve.map(Ae=>Ae.id===U.id?{...Ae,status:"syncing"}:Ae));try{const ve=await _M(U.id,we,c.trim(),n);Le(ve.jobs||[]),j(ve.jobs?.length?"Hub sync queued.":"No changed files to sync.");const Ae=await jb(n);z(Ae)}catch(ve){j(ve instanceof Error?ve.message:"Unable to sync the Hub folder."),z(Ae=>Ae.map(Be=>Be.id===U.id?{...Be,status:"error",message:"Sync failed"}:Be))}finally{le(!1)}},We=async()=>{le(!0);try{for(const U of Z)await Xe(U)}finally{le(!1)}},Ze=async U=>{try{const ve=await DM(U.id,{autoSync:!U.autoSync},n);z(Ae=>Ae.map(Be=>Be.id===U.id?ve.folder:Be))}catch(ve){j(ve instanceof Error?ve.message:"Unable to update auto sync.")}},dt=async U=>{try{await LM(U.id,n),z(ve=>ve.filter(Ae=>Ae.id!==U.id))}catch(ve){j(ve instanceof Error?ve.message:"Unable to remove the sync folder.")}};return r.jsxs("section",{className:"livedesk-file-explorer",children:[r.jsx("input",{ref:x,className:"hidden-file-input",type:"file",multiple:!0,onChange:U=>{U.currentTarget.files&&w(U.currentTarget.files),U.currentTarget.value=""}}),r.jsx("input",{ref:b,className:"hidden-file-input",type:"file",multiple:!0,webkitdirectory:"",directory:"",onChange:U=>{U.currentTarget.files&&A(U.currentTarget.files),U.currentTarget.value=""}}),r.jsx("div",{className:"file-share-workspace",children:r.jsxs(HM,{onRetry:()=>window.location.reload(),children:[r.jsx(OM,{hubUrl:n,roots:M,loading:D,error:$,onRefreshRoots:mt,onImportFiles:()=>x.current?.click(),onImportFolder:()=>b.current?.click(),onSelectionChange:Ce,onShareItem:U=>{Q([U.id]),P([U]),K("send")},onAddSyncFolder:U=>{Q([U.id]),P([U]),_e(U)},onNotice:j}),r.jsx(UM,{devices:N,targetMode:m,selectedTargetIds:h,onTargetModeChange:g,onTargetToggle:y,remoteDirectory:c,onRemoteDirectoryChange:d,selectedEntries:q,selectedSummary:ne,canShare:i&&!Me&&L.length>0&&we.length>0&&!ye,onShare:()=>{Fe()},canAddSync:!!He,onAddSync:()=>{_e()},tab:ce,onTabChange:K,folders:Z,foldersLoading:se,syncBusy:O,onSyncAll:()=>{We()},onSync:U=>{Xe(U)},onToggleAuto:U=>{Ze(U)},onRemove:U=>{dt(U)},onAddFolder:()=>{_e()}})]})}),Me&&r.jsx("footer",{className:"file-share-workspace-footer",children:r.jsxs("span",{children:[Nb(Me)," · ",Mb(Me),"% ",r.jsx("button",{className:"icon-button",onClick:()=>{RM(Me.jobId,n).then(U=>{he(ve=>ve.map(Ae=>Ae.jobId===U.jobId?U:Ae)),qe(U)})},title:"Cancel transfer",type:"button",children:r.jsx(Na,{size:14})})]})})]})}const VM=u.forwardRef(function({value:a,onChange:i,onSubmit:l,onOpenSuggestedTasks:c,suggestedOpen:d=!1,suggestedTaskCount:m,disabled:h=!1,placeholder:g="Ask LiveDesk to work across your machines...",compact:y=!1},x){return r.jsxs("form",{className:"agents-composer",onSubmit:b=>{b.preventDefault(),l()},children:[r.jsx("button",{className:`agents-suggested-trigger ${d?"active":""}`,type:"button","aria-label":m===void 0?"Open Suggested tasks":`Open Suggested tasks (${m} available)`,"aria-expanded":d,onClick:c,disabled:h,children:r.jsx(S0,{size:17})}),r.jsx("textarea",{ref:x,value:a,onChange:b=>i(b.target.value.slice(0,4e3)),placeholder:g,"aria-label":"Ask LiveDesk",rows:y?1:2,disabled:h}),r.jsxs("button",{className:"agents-run-button",type:"submit",disabled:h||!a.trim(),children:[h?r.jsx(Lr,{className:"spin",size:16}):r.jsx(Bu,{size:16}),h?"Running":"Run"]})]})}),WM=["read","processControl","serviceControl","applicationControl","fileRead","fileWrite","fileDelete","shell","script","softwareInstall","network","systemPower","systemConfiguration","userAccount"];function Of(n){return n.deviceName?.trim()||n.hostname?.trim()||n.deviceId}function Hf(n){return n.connected!==!0?!1:n.synthetic===!0?!0:!n.channels||n.channels.control===!0}function YM(n){return n==="running"||n==="completed"||n==="failed"||n==="cancelled"?n:"queued"}function KM(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 QM(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:null}function vs(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function hf(n){const a=vs(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 XM(n){const a=vs(n);return a===null?"":`${Math.round((a<=1?a:a/100)*100)}%`}function ZM(n){return!n||/^(?:[\w .-]+ )?collected(?:\.)?$/i.test(n.trim())?"":n.trim()}function Ff(n,a){if(a.error)return a.error;const i=QM(a.data),l=ZM(a.result||"");if(!i)return l||a.stage||a.status;if(n==="system.health"){const c=typeof i.machine=="string"?i.machine:"",d=hf(i.freeMemoryBytes),m=hf(i.totalMemoryBytes),h=vs(i.totalMemoryBytes)&&vs(i.freeMemoryBytes)!==null?`${Math.round(vs(i.freeMemoryBytes)/vs(i.totalMemoryBytes)*100)}% RAM free`:"";return[c,d&&m?`RAM ${d}/${m}`:"",h,typeof i.platform=="string"?i.platform:""].filter(Boolean).join(" · ")||l||a.status}if(n==="disk.status"){const c=typeof i.root=="string"?i.root:"",d=hf(i.freeBytes),m=vs(i.totalBytes)&&vs(i.freeBytes)!==null?`${Math.round(vs(i.freeBytes)/vs(i.totalBytes)*100)}% free`:"";return[c,d&&`${d} free`,m].filter(Boolean).join(" · ")||l||a.status}if(n==="gpu.status"){const c=typeof i.name=="string"&&i.name?i.name:"No GPU provider",d=XM(i.usageRatio),m=vs(i.temperatureC)!==null?`${Math.round(vs(i.temperatureC))}°C`:"",h=hf(i.freeMemoryBytes);return[c,d&&`GPU ${d}`,m,h&&`${h} free`].filter(Boolean).join(" · ")||l||a.status}if(n==="process.list"){const c=vs(i.count);return c!==null?`${c} matching process${c===1?"":"es"}`:l||a.status}if(n==="network.status"){const c=Array.isArray(i.adapters)?i.adapters.length:null;return c!==null?`${c} active adapter${c===1?"":"s"}`:l||a.status}return l||a.stage||a.status}function Tb(n,a){const i=Ff(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||""} ${i}`)}function JM({state:n,operation:a}){const i=n.status==="completed"?Ir:n.status==="failed"||n.status==="cancelled"?Na:n.status==="running"?Lr:px,l=n.status==="running"?n.stage||"Working":n.status==="completed"?a?Ff(a,n):n.result||"Completed":n.status==="failed"?n.error||"Failed":n.status==="cancelled"?"Cancelled":"Queued";return r.jsxs("div",{className:`agent-target-row status-${n.status}`,"data-agent-target-id":n.deviceId,children:[r.jsx("span",{className:"agent-target-status","aria-hidden":"true",children:r.jsx(i,{size:15})}),r.jsx("strong",{children:n.deviceName}),r.jsx("span",{className:"agent-target-state",children:n.status[0].toUpperCase()+n.status.slice(1)}),r.jsx("small",{children:l})]})}function eN({operation:n,states:a,status:i,onCancel:l,onRetry:c,busy:d=!1}){const m=["running","queued"].includes(i),[h,g]=u.useState(!1),[y,x]=u.useState("all"),b=u.useMemo(()=>({total:a.length,completed:a.filter(D=>D.status==="completed").length,failed:a.filter(D=>D.status==="failed").length,running:a.filter(D=>D.status==="running").length,queued:a.filter(D=>D.status==="queued").length,cancelled:a.filter(D=>D.status==="cancelled").length}),[a]),w=a.filter(D=>Tb(n,D)),A=w.filter(D=>D.status==="completed").length,j=b.failed>0,k=w.length>0,N=a.filter(D=>y==="issues"?Tb(n,D):y==="running"?D.status==="running"||D.status==="queued":y==="completed"?D.status==="completed":y==="failed"?D.status==="failed":!0),M=k&&!m||i==="completed-with-failures"?"Completed with issues":i[0]?.toUpperCase()+i.slice(1),T=a.filter(D=>D.status==="completed").map(D=>Ff(n,D)).filter(Boolean).filter((D,F,$)=>$.indexOf(D)===F).slice(0,2);return r.jsxs("section",{className:"agent-task-block","aria-label":"Task execution",children:[r.jsxs("div",{className:"agent-task-head",children:[r.jsxs("div",{children:[r.jsx("span",{children:"LiveDesk Agent"}),r.jsx("strong",{children:KM(n)})]}),r.jsx("span",{className:`agent-task-status status-${k?"completed-with-failures":i}`,children:M})]}),r.jsxs("div",{className:"agent-task-summary","aria-label":"Task summary",children:[r.jsxs("strong",{children:[b.total," targets"]}),r.jsxs("span",{className:"summary-completed",children:[b.completed," completed"]}),b.running>0&&r.jsxs("span",{className:"summary-running",children:[b.running," running"]}),b.queued>0&&r.jsxs("span",{children:[b.queued," queued"]}),j&&r.jsxs("span",{className:"summary-failed",children:[b.failed," failed"]}),A>0&&r.jsxs("span",{className:"summary-cancelled",children:[A," warning"]}),b.cancelled>0&&r.jsxs("span",{className:"summary-cancelled",children:[b.cancelled," cancelled"]})]}),T.length>0&&r.jsxs("div",{className:"agent-task-result-preview",title:T.join(" · "),children:[r.jsx("span",{children:"Result"}),T.join(" · ")]}),r.jsx("div",{className:"agent-target-chips","aria-label":"Target status overview",children:a.map((D,F)=>{const $=D.status==="completed"?"✓":D.status==="failed"?"×":D.status==="cancelled"?"!":D.status==="running"?"…":"·";return r.jsxs("span",{className:`agent-target-chip status-${D.status}`,title:`${D.deviceName}: ${Ff(n,D)}`,"aria-label":`${F+1}. ${D.deviceName}: ${D.status}`,children:[r.jsx("b",{children:String(F+1).padStart(2,"0")}),r.jsx("span",{children:$})]},D.deviceId)})}),a.length>0&&r.jsx("div",{className:"agent-task-details-toggle",children:r.jsxs("button",{type:"button",onClick:()=>g(D=>!D),"aria-expanded":h,children:[h?r.jsx(C0,{size:14}):r.jsx(gx,{size:14}),h?"Hide details":"Show details"]})}),h&&r.jsxs("div",{className:"agent-task-details",children:[r.jsx("div",{className:"agent-task-filters",role:"tablist","aria-label":"Task result filter",children:["all","issues","running","completed","failed"].map(D=>r.jsx("button",{className:y===D?"active":"",onClick:()=>x(D),role:"tab","aria-selected":y===D,type:"button",children:D==="all"?"All":D==="issues"?"Issues only":D[0].toUpperCase()+D.slice(1)},D))}),r.jsx("div",{className:"agent-task-rows",children:N.length>0?N.map(D=>r.jsx(JM,{operation:n,state:D},D.deviceId)):r.jsx("small",{className:"agent-task-no-results",children:"No targets match this filter."})})]}),(m||j)&&r.jsxs("div",{className:"agent-task-actions",children:[m&&l&&r.jsxs("button",{onClick:l,disabled:d,type:"button",children:[r.jsx(k0,{size:14})," Cancel"]}),!m&&j&&c&&r.jsxs("button",{onClick:c,disabled:d,type:"button",children:[r.jsx(Cp,{size:14})," Retry failed"]})]})]})}function tN(n){try{return JSON.stringify(n,null,2).slice(0,6e3)}catch{return"{}"}}function nN({approval:n,busy:a=!1,onApprove:i,onReject:l}){return r.jsxs("article",{className:"agent-approval-card","aria-label":"Agent approval required",children:[r.jsxs("div",{className:"agent-approval-head",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Approval required"}),r.jsx("strong",{children:n.toolName})]}),r.jsx("span",{className:`agent-approval-risk risk-${n.risk}`,children:n.risk})]}),r.jsx("p",{children:n.description}),r.jsx("pre",{children:tN(n.arguments)}),r.jsxs("small",{children:["Permission: ",n.permissionMode," · Scope: selected devices only · Expires in 5 minutes"]}),r.jsxs("div",{className:"agent-approval-actions",children:[r.jsxs("button",{className:"reject",disabled:a,onClick:l,type:"button",children:[r.jsx(Na,{size:14})," Reject"]}),r.jsxs("button",{disabled:a,onClick:()=>i("once"),type:"button",children:[r.jsx(Ir,{size:14})," Once"]}),r.jsx("button",{disabled:a,onClick:()=>i("same-action-this-run"),type:"button",children:"Allow same action"}),r.jsx("button",{disabled:a,onClick:()=>i("category-this-run"),type:"button",children:"Allow category"})]}),r.jsxs("div",{className:"agent-approval-scope",children:[r.jsx(Bf,{size:13})," Approval is bound to this run, tool, arguments, selected devices, and policy hash."]})]})}function aN(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 sN({items:n,onCancel:a,onRetry:i,busyBatchId:l,approvals:c,onApprove:d,onReject:m,busyApprovalId:h,progress:g,emptyTitle:y="Ask LiveDesk to work across your machines.",emptyBody:x="Start with a read-only request such as “모든 PC에서 ComfyUI가 실행 중인지 확인해줘”."}){const b=u.useRef(null),w=u.useRef(!0),A=u.useRef(""),j=n[n.length-1];return u.useLayoutEffect(()=>{const k=b.current;k&&(j?.type==="user"&&j.id!==A.current&&(w.current=!0),A.current=j?.id||"",w.current&&(k.scrollTop=k.scrollHeight))},[c,n,j?.id,j?.type,g?.message,g?.stage]),r.jsxs("section",{className:"agents-conversation","aria-live":"polite",ref:b,onScroll:k=>{const N=k.currentTarget;w.current=N.scrollHeight-N.scrollTop-N.clientHeight<72},children:[c.filter(k=>k.status==="pending").map(k=>r.jsx(nN,{approval:k,busy:h===k.approvalId,onApprove:N=>d(k,N),onReject:()=>m(k)},k.approvalId)),n.length===0&&r.jsxs("div",{className:"agents-empty-conversation",children:[r.jsx("strong",{children:y}),r.jsx("span",{children:x})]}),n.map(k=>{if(k.type==="task"){const N=k;return r.jsx(eN,{operation:N.operation,states:N.states,status:N.status,onCancel:()=>a(N.batchId,N.agentRunId),onRetry:()=>i(N.batchId),busy:l===N.batchId},N.id)}return r.jsxs("article",{className:`agents-message ${k.type}`,children:[r.jsx("span",{children:k.type==="user"?"You":"LiveDesk Agent"}),r.jsx("p",{children:k.text})]},k.id)}),g&&r.jsxs("article",{className:"agents-message agent agents-progress-message",role:"status",children:[r.jsxs("span",{children:[r.jsx(Lr,{"aria-hidden":"true",size:15}),aN(g.stage)]}),r.jsx("p",{children:g.message})]})]})}const Rb=["Recommended","Health & capacity","Processes & services","AI workloads","Files & configuration","Software & automation","Network & connectivity","Power & maintenance","Troubleshooting & recovery"],jn=["windows","macos","linux"],gl={"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(gl));const rN={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","문제해결","복구","장애"]},Eb=["low","medium","high","critical"];function iN(n){return n.reduce((a,i)=>{const l=gl[i].risk;return Eb.indexOf(l)>Eb.indexOf(a)?l:a},"low")}function lN(n){return jn.filter(a=>n.every(i=>gl[i].supportedPlatforms.includes(a)))}function Ge(n,a,i,l,c,d,m={}){const h=m.description||l,g=c.flatMap(x=>x.split(".")),y=[...new Set([...rN[a],...d,...g])];return{id:n,category:a,title:i,prompt:l,description:h,requiredOperations:c,risk:m.risk||iN(c),targetSupport:m.targetSupport||"single-or-multiple",supportedPlatforms:m.supportedPlatforms||lN(c),keywords:y,recommended:m.recommended??!1,enabled:!0}}const Tw=[Ge("recommended-fleet-health","Recommended","Summarize current target health","Summarize system health, GPU, and disk capacity for the current target Clients.",["system.health","gpu.status","disk.status"],["summary","overview"],{recommended:!0}),Ge("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}),Ge("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}),Ge("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}),Ge("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}),Ge("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}),Ge("recommended-recover-ai","Recommended","Recover stopped AI workers","Find stopped AI workers and relaunch the registered worker application or service on the target Client.",["process.list","application.launch","service.control"],["recover","start","ai worker"],{targetSupport:"single",recommended:!0}),Ge("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}),Ge("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","높은 사용량"]),Ge("health-uptime","Health & capacity","Review Client uptime","Show uptime, boot time, and current system health for the target Clients.",["system.health"],["uptime","boot","가동시간"]),Ge("health-gpu-temperature","Health & capacity","Check GPU temperature","Check GPU temperature and thermal warnings on the current targets.",["gpu.status"],["thermal","temperature","발열"]),Ge("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"]),Ge("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","디스크"]),Ge("health-gpu-compare","Health & capacity","Compare GPU capacity","Compare GPU model, memory, temperature, and utilization across the current targets.",["gpu.status"],["compare","graphics","capacity"]),Ge("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","경고"]),Ge("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"]),Ge("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","실행 중"]),Ge("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"]),Ge("process-stop-named","Processes & services","Stop a named process","Stop process named [process name] on the target Client after checking its current state.",["process.list","process.control"],["stop","terminate","종료"],{targetSupport:"single"}),Ge("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"}),Ge("process-launch-app","Processes & services","Launch a registered application","Launch the registered application [application] on the target Client with [arguments].",["application.launch"],["launch","open","실행"],{targetSupport:"single"}),Ge("process-close-app","Processes & services","Close an application","Close application [application] on the target Client and report whether it exited cleanly.",["application.close","process.list"],["close","exit","앱 종료"],{targetSupport:"single"}),Ge("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","서비스 상태"]),Ge("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"}),Ge("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"]),Ge("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"}),Ge("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"}),Ge("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"]),Ge("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"]),Ge("ai-worker-logs","AI workloads","Collect AI worker logs","Collect recent logs and relevant log files for the AI worker on the target Client.",["logs.collect","file.list","file.read"],["logs","diagnostics","worker"],{targetSupport:"single"}),Ge("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"]),Ge("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"}),Ge("files-list-directory","Files & configuration","List a directory","List files and folders under [path] on the target Client.",["file.list"],["directory","folder","list","목록"],{targetSupport:"single"}),Ge("files-read-config","Files & configuration","Read a configuration file","Read the relevant settings from configuration file [path] on the target Client.",["file.read"],["config","settings","read","구성"]),Ge("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"]),Ge("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"}),Ge("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"}),Ge("files-compare-config","Files & configuration","Compare configuration files","Read configuration file [path] on the target Client and compare it with [reference path].",["file.read"],["compare","diff","configuration"]),Ge("files-set-environment","Files & configuration","Set an environment variable","Set environment variable [name] to [value] for the target Client and verify the resulting configuration.",["system.configure","file.read"],["environment","variable","env","환경변수"],{targetSupport:"single"}),Ge("files-archive-diagnostics","Files & configuration","Write a diagnostic manifest","Collect selected diagnostics and write a manifest file to [path] on the target Client.",["diagnostics.collect","file.write"],["manifest","export","diagnostic file"],{targetSupport:"single"}),Ge("software-winget-install","Software & automation","Install software with winget","Install package [package name] with winget on the Windows target Client, then verify it.",["software.install","process.list"],["winget","windows","install","설치"],{targetSupport:"single",supportedPlatforms:["windows"]}),Ge("software-apt-install","Software & automation","Install software with apt","Install package [package name] with apt on the Linux target Client, then verify it.",["software.install","process.list"],["apt","linux","package","설치"],{targetSupport:"single",supportedPlatforms:["linux"]}),Ge("software-brew-install","Software & automation","Install software with Homebrew","Install package [package name] with brew on the macOS target Client, then verify it.",["software.install","process.list"],["brew","homebrew","macos","설치"],{targetSupport:"single",supportedPlatforms:["macos"]}),Ge("software-npm-install","Software & automation","Install an npm package","Install npm package [package name] on the target Client and verify the installed version.",["software.install","command.run"],["npm","node","package"],{targetSupport:"single"}),Ge("software-run-script","Software & automation","Run a registered script","Run the registered script [script path] on the target Client and report its result.",["script.run"],["script","automation","registered"],{targetSupport:"single"}),Ge("software-run-command","Software & automation","Run a command on one target","Run command [command] on the target Client and return its exit status and output.",["command.run"],["command","shell","terminal"],{targetSupport:"single"}),Ge("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"]),Ge("software-toolchain-setup","Software & automation","Set up a toolchain","Install the requested package [package name], configure [change], and verify the toolchain on the target Client.",["software.install","system.configure","process.list"],["toolchain","setup","developer"],{targetSupport:"single"}),Ge("network-adapter-status","Network & connectivity","Check network adapters","Show adapter state, address, and link information for the current targets.",["network.status"],["adapter","ethernet","wifi","네트워크 상태"]),Ge("network-disconnected","Network & connectivity","Find disconnected targets","Find current targets with disconnected or degraded network adapters.",["network.status"],["disconnected","offline","연결 끊김"]),Ge("network-link-speed","Network & connectivity","Check link speed","Report network link speed and duplex information for the current targets.",["network.status"],["speed","bandwidth","duplex"]),Ge("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"]),Ge("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"]),Ge("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"]),Ge("network-compare","Network & connectivity","Compare target connectivity","Compare adapter state, addresses, and link speed across the current targets.",["network.status"],["compare","inventory","connectivity"]),Ge("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"]),Ge("power-lock","Power & maintenance","Lock the Client","Lock the target Client and report the resulting power action status.",["system.power"],["lock","security","잠금"],{targetSupport:"single",risk:"critical"}),Ge("power-logoff","Power & maintenance","Log off the Client","Log off the target Client after warning that interactive sessions will close.",["system.power"],["logoff","session","로그오프"],{targetSupport:"single",risk:"critical"}),Ge("power-sleep","Power & maintenance","Put the Client to sleep","Put the target Client to sleep after confirming the requested delay of [delay].",["system.power"],["sleep","suspend","절전"],{targetSupport:"single",risk:"critical"}),Ge("power-restart","Power & maintenance","Restart the Client","Restart the target Client after confirming that active work may be interrupted.",["system.power"],["restart","reboot","재부팅"],{targetSupport:"single",risk:"critical"}),Ge("power-shutdown","Power & maintenance","Shut down the Client","Shut down the target Client after confirming that active work may be interrupted.",["system.power"],["shutdown","power off","종료"],{targetSupport:"single",risk:"critical"}),Ge("power-maintenance-restart","Power & maintenance","Restart after maintenance","Check the target Client, restart it after maintenance, and verify that it returns online.",["system.health","system.power","network.status"],["maintenance","reboot","verify"],{targetSupport:"single",risk:"critical"}),Ge("power-timezone","Power & maintenance","Set the Client timezone","Set the target Client timezone to [timezone] and verify the resulting system configuration.",["system.configure"],["timezone","clock","시간대"],{targetSupport:"single",risk:"critical"}),Ge("power-persistent-environment","Power & maintenance","Persist an environment variable","Persist environment variable [name] with value [value] for the target Client and verify it.",["system.configure"],["environment","persistent","환경변수"],{targetSupport:"single",risk:"critical"}),Ge("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"}),Ge("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"}),Ge("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"}),Ge("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"}),Ge("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"}),Ge("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"}),Ge("recovery-network-instability","Troubleshooting & recovery","Recover network instability","Collect network diagnostics, inspect network services, and report the safest recovery action for the target Client.",["network.status","service.status","diagnostics.collect"],["network","unstable","네트워크 복구"],{targetSupport:"single"}),Ge("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","장애 보고서"])],_h={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 oN(n,a){return n==="safe-auto"?_h:n==="full-access"?{..._h,processControl:"allow",serviceControl:"allow",applicationControl:"allow",fileDelete:"allow",shell:"allow",script:"allow",softwareInstall:"allow",systemPower:"allow",systemConfiguration:"allow"}:n==="custom"&&a?a:{..._h,processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileWrite:"ask",network:"ask"}}function cN(n,a,i){const l=oN(a,i),c=n.requiredOperations.map(d=>l[gl[d].permissionCategory]);if(c.includes("deny")){const d=n.requiredOperations.find(m=>l[gl[m].permissionCategory]==="deny");return{state:"blocked",label:"Blocked",reason:`This task requires ${gl[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 Client."}:n.requiredOperations.every(d=>gl[d].readOnly)?{state:"read-only",label:"Read only"}:a==="full-access"?{state:"full-access",label:"Full Access"}:{state:"auto",label:"Auto allowed"}}function uN(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 dN(n,a,i){const l=new Set(i);return n.filter(c=>c.connected&&(a==="all"||a==="auto"||l.has(c.deviceId)))}function fN(n,a){const i=uN(n.platform);if(!i||!a.supportedPlatforms.includes(i))return!1;const l=n.capabilities?.agentTools;return!Array.isArray(l)||l.length===0?a.requiredOperations.every(c=>gl[c].readOnly):a.requiredOperations.every(c=>l.includes(c))}function Rw(n,a,i,l,c,d){const m=cN(n,c,d),h=dN(a,i,l),g=h.map(A=>A.deviceId),y={...m,available:!1,availableDeviceIds:[],unsupportedDeviceIds:g,risk:n.risk,supportedPlatforms:n.supportedPlatforms};if(h.length===0)return{...y,reason:"Select at least one connected Client."};if(n.targetSupport==="single"&&h.length!==1)return{...y,reason:"This task supports one Client at a time."};if(m.state==="blocked")return y;const x=h.filter(A=>fN(A,n)),b=x.map(A=>A.deviceId),w=g.filter(A=>!b.includes(A));return x.length===0?{...y,unsupportedDeviceIds:w,reason:"No current target supports the required platform and client capabilities."}:{...y,available:!0,availableDeviceIds:b,unsupportedDeviceIds:w}}function mN(n,a,i,l,c,d){return n.filter(m=>m.enabled&&Rw(m,a,i,l,c,d).available).length}const Ih="livedesk.agentPromptRecent",zh="livedesk.agentPromptFavorites",hN={Recommended:yl,"Health & capacity":ho,"Processes & services":N0,"AI workloads":Yh,"Files & configuration":M0,"Software & automation":mx,"Network & connectivity":jp,"Power & maintenance":Wn,"Troubleshooting & recovery":A0};function Db(n){if(typeof window>"u")return[];try{const a=JSON.parse(window.localStorage.getItem(n)||"[]");return Array.isArray(a)?a.filter(i=>typeof i=="string"):[]}catch{return[]}}function pf(n,a){try{window.localStorage.setItem(n,JSON.stringify(a))}catch{}}function Oh(n){return n==="all"?"All tasks":n==="recent"?"Recent":n==="favorites"?"Favorites":n==="read-only"?"Read only":n==="auto"?"Auto allowed":n==="approval"?"Approval required":n==="full-access"?"Full Access":n==="available"?"Available":n==="unavailable"?"Unavailable":n}function pN(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 gN(n,a,i){if(!i.trim())return!0;const l=i.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 vN(n){return`permission-${n}`}function yN(n){return n==="low"?"Low risk":n==="medium"?"Medium risk":n==="high"?"High risk":"Critical risk"}function bN(n){return n==="windows"?"Windows":n==="macos"?"macOS":"Linux"}function xN({devices:n,targetMode:a,selectedIds:i,permissionMode:l,customCategories:c,onSelectPrompt:d,onClose:m}){const[h,g]=u.useState(""),[y,x]=u.useState("all"),[b,w]=u.useState(()=>Db(Ih)),[A,j]=u.useState(()=>Db(zh)),[k,N]=u.useState(0),[M,T]=u.useState(""),D=u.useRef(null),F=u.useRef(null),$=u.useMemo(()=>Tw.filter(Z=>Z.enabled),[]),G=u.useMemo(()=>new Map($.map(Z=>[Z.id,Rw(Z,n,a,i,l,c)])),[c,n,l,i,a,$]),L=u.useMemo(()=>[...G.values()].filter(Z=>Z.available).length,[G]),Q=u.useMemo(()=>n.filter(Z=>Z.connected&&(a==="all"||a==="auto"||i.includes(Z.deviceId))).length,[n,i,a]),q=u.useMemo(()=>{const Z=$.filter(z=>gN(z,G.get(z.id),h));return y==="recent"?b.map(z=>Z.find(se=>se.id===z)).filter(z=>!!z):y==="favorites"?A.map(z=>Z.find(se=>se.id===z)).filter(z=>!!z):y==="all"?Z:Z.filter(z=>{const se=G.get(z.id);return y==="read-only"?se.state==="read-only":y==="auto"?se.state==="auto":y==="approval"?se.state==="approval":y==="full-access"?se.state==="full-access":y==="available"?se.available:y==="unavailable"?!se.available:z.category===y})},[G,A,y,b,h,$]),P=u.useMemo(()=>y!=="all"?[{category:Oh(y),templates:q}]:Rb.map(Z=>({category:Z,templates:q.filter(z=>z.category===Z)})).filter(Z=>Z.templates.length>0),[y,q]);u.useEffect(()=>{N(Z=>Math.min(Z,Math.max(0,q.length-1)))},[q.length]),u.useEffect(()=>{pf(Ih,b)},[b]),u.useEffect(()=>{pf(zh,A)},[A]),u.useEffect(()=>{F.current?.focus();const Z=se=>{se.target instanceof Node&&!D.current?.contains(se.target)&&m()},z=se=>{se.key==="Escape"&&(se.preventDefault(),m())};return document.addEventListener("pointerdown",Z),document.addEventListener("keydown",z),()=>{document.removeEventListener("pointerdown",Z),document.removeEventListener("keydown",z)}},[m]);const Y=Z=>{const z=G.get(Z.id);if(!z.available){T(z.reason||"This task is not available for the current targets and permission policy.");return}const se=[Z.id,...b.filter(W=>W!==Z.id)].slice(0,10);w(se),pf(Ih,se),d(Z.prompt),m()},H=Z=>{j(z=>{const se=z.includes(Z)?z.filter(W=>W!==Z):[Z,...z];return pf(zh,se),se})},ye=Z=>{Z.key==="ArrowDown"?(Z.preventDefault(),N(z=>Math.min(z+1,Math.max(0,q.length-1)))):Z.key==="ArrowUp"?(Z.preventDefault(),N(z=>Math.max(z-1,0))):Z.key==="Enter"&&q[k]&&(Z.preventDefault(),Y(q[k]))};let de=-1;return r.jsxs("section",{className:"agents-suggested-tasks",ref:D,"aria-label":"Suggested tasks",children:[r.jsxs("header",{className:"agents-suggested-header",children:[r.jsxs("div",{children:[r.jsxs("span",{className:"agents-suggested-title",children:[r.jsx(yl,{size:15})," Suggested tasks"]}),r.jsxs("small",{children:[L," available · ",$.length," total. Choose a task, edit it, then run it."]})]}),r.jsx("button",{className:"agents-suggested-close",type:"button","aria-label":"Close suggested tasks",onClick:m,children:r.jsx(Na,{size:16})})]}),r.jsxs("label",{className:"agents-suggested-search",children:[r.jsx(j0,{size:15,"aria-hidden":"true"}),r.jsx("input",{ref:F,value:h,onChange:Z=>g(Z.target.value),onKeyDown:ye,placeholder:"Search tasks...","aria-label":"Search suggested tasks"})]}),r.jsx("div",{className:"agents-suggested-filters","aria-label":"Task categories and availability filters",children:["all","recent","favorites","read-only","auto","approval","full-access","available","unavailable",...Rb].map(Z=>{const z=Z==="recent"?dx:Z==="favorites"?Qh:Z==="all"?yl:Z==="available"?Zn:Z==="unavailable"?vx:Z==="read-only"||Z==="auto"||Z==="approval"||Z==="full-access"?Wn:hN[Z];return r.jsxs("button",{className:y===Z?"active":"",type:"button",title:Oh(Z),"aria-label":Oh(Z),"aria-pressed":y===Z,onClick:()=>{x(Z),N(0),T("")},children:[r.jsx(z,{size:12})," ",pN(Z)]},Z)})}),M&&r.jsx("div",{className:"agents-suggested-notice",role:"status",children:M}),r.jsxs("div",{className:"agents-suggested-list",role:"listbox","aria-label":"Suggested tasks",children:[P.map(Z=>r.jsxs("div",{className:"agents-suggested-group",children:[r.jsx("strong",{children:Z.category}),Z.templates.map(z=>{de+=1;const se=de===k,W=A.includes(z.id),O=G.get(z.id),le=O.availableDeviceIds.length+O.unsupportedDeviceIds.length||Q,ce=O.available?`Available on ${O.availableDeviceIds.length} of ${le} target${le===1?"":"s"}`:`Unavailable: ${O.reason||"not supported by the current targets"}`;return r.jsxs("div",{className:`agents-suggested-item ${se?"active":""} ${O.available?"":"unavailable"}`,children:[r.jsxs("button",{className:"agents-suggested-prompt",type:"button",role:"option","aria-selected":se,"aria-disabled":!O.available,onClick:()=>Y(z),children:[r.jsx("span",{children:z.title}),r.jsx("small",{className:"agents-suggested-description",children:z.description}),r.jsxs("span",{className:"agents-suggested-meta",children:[r.jsx("em",{children:z.category}),r.jsx("em",{className:vN(O.state),children:O.label}),r.jsx("em",{className:`risk-${z.risk}`,children:yN(z.risk)}),r.jsx("em",{children:z.supportedPlatforms.map(bN).join(" · ")}),r.jsx("em",{className:O.available?"availability-ok":"availability-unavailable",children:ce}),O.available&&O.unsupportedDeviceIds.length>0&&r.jsxs("em",{className:"availability-warning",children:["Unsupported on ",O.unsupportedDeviceIds.length]})]})]}),r.jsx("button",{className:`agents-suggested-favorite ${W?"favorite":""}`,type:"button","aria-label":W?`Remove ${z.title} from favorites`:`Add ${z.title} to favorites`,"aria-pressed":W,onClick:()=>H(z.id),children:r.jsx(Qh,{size:14,fill:W?"currentColor":"none"})})]},z.id)})]},Z.category)),q.length===0&&r.jsx("p",{className:"agents-suggested-empty",children:"No tasks match this search or current filter."})]})]})}function wN({devices:n,mode:a,selectedIds:i,onModeChange:l,onToggle:c,permissionMode:d,onPermissionModeChange:m}){const h=n.filter(Hf),g=i.filter(y=>h.some(x=>x.deviceId===y)).length;return r.jsxs("section",{className:"agents-target-picker","aria-label":"Agent targets",children:[r.jsxs("div",{className:"agents-target-toolbar",children:[r.jsx("span",{className:"agents-section-label",children:"Targets"}),r.jsxs("div",{className:"agents-target-modes",children:[r.jsxs("button",{className:a==="all"?"active":"",onClick:()=>l("all"),type:"button",children:[r.jsx(Pu,{size:14})," All connected ",r.jsx("small",{children:h.length})]}),r.jsxs("button",{className:a==="selected"?"active":"",onClick:()=>l("selected"),type:"button",children:[r.jsx(Ir,{size:14})," Selected ",g]}),r.jsxs("button",{className:a==="auto"?"active":"",onClick:()=>l("auto"),type:"button",children:[r.jsx(yl,{size:14})," Auto"]}),r.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[r.jsx(Pu,{size:14})," Group ",r.jsx("small",{children:"Soon"})]})]}),r.jsxs("label",{className:`agents-permission-picker permission-${d}`,children:[r.jsx(Bf,{size:14}),r.jsx("span",{children:"Permission"}),r.jsxs("select",{value:d,onChange:y=>m(y.target.value),"aria-label":"Agent permission mode",children:[r.jsx("option",{value:"ask",children:"Ask"}),r.jsx("option",{value:"safe-auto",children:"Safe Auto"}),r.jsx("option",{value:"full-access",children:"Full Access"}),r.jsx("option",{value:"custom",children:"Custom"})]}),r.jsx(gx,{size:13,"aria-hidden":"true"})]})]}),r.jsx("div",{className:"agents-target-list",children:n.length===0?r.jsx("span",{className:"agents-target-empty",children:"No Clients discovered."}):n.map(y=>{const x=Hf(y),b=a==="all"||a==="auto"?x:i.includes(y.deviceId);return r.jsxs("label",{className:`agents-target-option ${b?"selected":""} ${x?"":"offline"}`,children:[r.jsx("input",{type:"checkbox",checked:b,disabled:!x||a!=="selected",onChange:()=>c(y.deviceId)}),r.jsx("span",{className:"agents-target-icon",children:r.jsx(Ta,{size:15})}),r.jsxs("span",{children:[r.jsx("strong",{children:Of(y)}),r.jsx("small",{children:x?"Ready":y.connected?"Agent reconnecting":"Offline"})]}),b&&r.jsx(Ir,{className:"agents-target-check",size:15,"aria-hidden":"true"})]},y.deviceId)})})]})}async function SN(n,a){return Ve("/api/settings/agent/plan",{method:"POST",body:JSON.stringify({instruction:a})},n)}async function CN(n,a){return Ve("/api/settings/agent/run",{method:"POST",body:JSON.stringify(a)},n)}async function kN(n,a){return Ve(`/api/settings/agent/runs/${encodeURIComponent(a)}`,void 0,n)}async function jN(n,a){return Ve(`/api/settings/agent/runs/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})},n)}async function AN(n){return Ve("/api/settings/agent/runs/cancel-all",{method:"POST",body:JSON.stringify({})},n)}async function MN(n,a,i,l){return Ve(`/api/settings/agent/runs/${encodeURIComponent(a)}/approvals/${encodeURIComponent(i)}/approve`,{method:"POST",body:JSON.stringify({scope:l})},n)}async function NN(n,a,i,l="User rejected this action."){return Ve(`/api/settings/agent/runs/${encodeURIComponent(a)}/approvals/${encodeURIComponent(i)}/reject`,{method:"POST",body:JSON.stringify({reason:l})},n)}async function TN(n,a,i){return Ve(`/api/settings/agent/policies/${encodeURIComponent(a)}`,{method:"PUT",body:JSON.stringify({categories:i})},n)}async function RN(n,a){return Ve("/api/settings/agent/summary",{method:"POST",body:JSON.stringify(a)},n)}async function EN(n,a){return Ve("/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 DN(n,a){return Ve(`/api/remote/tasks/${encodeURIComponent(a)}`,void 0,n)}async function LN(n,a){return Ve(`/api/remote/tasks/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})},n)}async function _N(n,a){return Ve(`/api/remote/tasks/${encodeURIComponent(a)}/retry`,{method:"POST",body:JSON.stringify({failedOnly:!0})},n)}function no(n){return`${n}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function gf(n,a){const i=new Map(a.map(l=>[l.deviceId,Of(l)]));return n.results.map(l=>({deviceId:l.deviceId,deviceName:l.deviceName||i.get(l.deviceId)||l.deviceId,status:YM(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 IN(n,a){const i=new Map(a.map(l=>[l.deviceId,l]));return n.map(l=>{const c=i.get(l.deviceId);return!c||c.sequence<=l.sequence?l:c})}function zN(n,a){const i=a.filter(d=>d.status==="completed"),l=a.filter(d=>d.status==="failed");if(n.operation==="process.list"){const m=`${i.filter(h=>{const g=h.result||"";return!/not running|no process/i.test(g)&&/running|online|found/i.test(g)}).length}대에서 요청한 프로세스가 실행 중입니다.`;return l.length>0?`${m}
8
+ `+o.stack}}var Ye=Object.prototype.hasOwnProperty,Ze=n.unstable_scheduleCallback,ut=n.unstable_cancelCallback,U=n.unstable_shouldYield,ve=n.unstable_requestPaint,je=n.unstable_now,$e=n.unstable_getCurrentPriorityLevel,dt=n.unstable_ImmediatePriority,it=n.unstable_UserBlockingPriority,pt=n.unstable_NormalPriority,ct=n.unstable_LowPriority,kt=n.unstable_IdlePriority,pe=n.log,De=n.unstable_setDisableYieldValue,Oe=null,Ae=null;function ft(e){if(typeof pe=="function"&&De(e),Ae&&typeof Ae.setStrictMode=="function")try{Ae.setStrictMode(Oe,e)}catch{}}var xt=Math.clz32?Math.clz32:wn,Ie=Math.log,na=Math.LN2;function wn(e){return e>>>=0,e===0?32:31-(Ie(e)/na|0)|0}var at=256,Ot=262144,aa=4194304;function pa(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 He(e,t,s){var o=e.pendingLanes;if(o===0)return 0;var f=0,p=e.suspendedLanes,S=e.pingedLanes;e=e.warmLanes;var R=o&134217727;return R!==0?(o=R&~p,o!==0?f=pa(o):(S&=R,S!==0?f=pa(S):s||(s=R&~e,s!==0&&(f=pa(s))))):(R=o&~p,R!==0?f=pa(R):S!==0?f=pa(S):s||(s=o&~e,s!==0&&(f=pa(s)))),f===0?0:t!==0&&t!==f&&(t&p)===0&&(p=f&-f,s=t&-t,p>=s||p===32&&(s&4194048)!==0)?t:f}function Sn(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function zn(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 ws(){var e=aa;return aa<<=1,(aa&62914560)===0&&(aa=4194304),e}function pn(e){for(var t=[],s=0;31>s;s++)t.push(e);return t}function qs(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function Wn(e,t,s,o,f,p){var S=e.pendingLanes;e.pendingLanes=s,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=s,e.entangledLanes&=s,e.errorRecoveryDisabledLanes&=s,e.shellSuspendCounter=0;var R=e.entanglements,V=e.expirationTimes,ue=e.hiddenUpdates;for(s=S&~s;0<s;){var xe=31-xt(s),Ce=1<<xe;R[xe]=0,V[xe]=-1;var me=ue[xe];if(me!==null)for(ue[xe]=null,xe=0;xe<me.length;xe++){var ge=me[xe];ge!==null&&(ge.lane&=-536870913)}s&=~Ce}o!==0&&Gs(e,o,0),p!==0&&f===0&&e.tag!==0&&(e.suspendedLanes|=p&~(S&~t))}function Gs(e,t,s){e.pendingLanes|=t,e.suspendedLanes&=~t;var o=31-xt(t);e.entangledLanes|=t,e.entanglements[o]=e.entanglements[o]|1073741824|s&261930}function B(e,t){var s=e.entangledLanes|=t;for(e=e.entanglements;s;){var o=31-xt(s),f=1<<o;f&t|e[o]&t&&(e[o]|=t),s&=~f}}function Ke(e,t){var s=t&-t;return s=(s&42)!==0?1:ht(s),(s&(e.suspendedLanes|t))!==0?0:s}function ht(e){switch(e){case 2:e=1;break;case 8:e=4;break;case 32:e=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:e=128;break;case 268435456:e=134217728;break;default:e=0}return e}function fn(e){return e&=-e,2<e?8<e?(e&134217727)!==0?32:268435456:8:2}function Fa(){var e=se.p;return e!==0?e:(e=window.event,e===void 0?32:sy(e.type))}function Di(e,t){var s=se.p;try{return se.p=e,t()}finally{se.p=s}}var Ss=Math.random().toString(36).slice(2),re="__reactFiber$"+Ss,Te="__reactProps$"+Ss,Ue="__reactContainer$"+Ss,yt="__reactEvents$"+Ss,qt="__reactListeners$"+Ss,Yt="__reactHandles$"+Ss,st="__reactResources$"+Ss,Mt="__reactMarker$"+Ss;function sa(e){delete e[re],delete e[Te],delete e[yt],delete e[qt],delete e[Yt]}function On(e){var t=e[re];if(t)return t;for(var s=e.parentNode;s;){if(t=s[Ue]||s[re]){if(s=t.alternate,t.child!==null||s!==null&&s.child!==null)for(e=Pv(e);e!==null;){if(s=e[re])return s;e=Pv(e)}return t}e=s,s=e.parentNode}return null}function gn(e){if(e=e[re]||e[Ue]){var t=e.tag;if(t===5||t===6||t===13||t===31||t===26||t===27||t===3)return e}return null}function nn(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e.stateNode;throw Error(l(33))}function We(e){var t=e[st];return t||(t=e[st]={hoistableStyles:new Map,hoistableScripts:new Map}),t}function At(e){e[Mt]=!0}var Vs=new Set,zt={};function Cn(e,t){Tn(e,t),Tn(e+"Capture",t)}function Tn(e,t){for(zt[e]=t,e=0;e<t.length;e++)Vs.add(t[e])}var go=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"),Nt={},ga={};function Mc(e){return Ye.call(ga,e)?!0:Ye.call(Nt,e)?!1:go.test(e)?ga[e]=!0:(Nt[e]=!0,!1)}function Fr(e,t,s){if(Mc(t))if(s===null)e.removeAttribute(t);else{switch(typeof s){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,""+s)}}function Hn(e,t,s){if(s===null)e.removeAttribute(t);else{switch(typeof s){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(t);return}e.setAttribute(t,""+s)}}function $a(e,t,s,o){if(o===null)e.removeAttribute(s);else{switch(typeof o){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(s);return}e.setAttributeNS(t,s,""+o)}}function Yn(e){switch(typeof e){case"bigint":case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Qu(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Qf(e,t,s){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,p=o.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return f.call(this)},set:function(S){s=""+S,p.call(this,S)}}),Object.defineProperty(e,t,{enumerable:o.enumerable}),{getValue:function(){return s},setValue:function(S){s=""+S},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Nc(e){if(!e._valueTracker){var t=Qu(e)?"checked":"value";e._valueTracker=Qf(e,t,""+e[t])}}function Xu(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var s=t.getValue(),o="";return e&&(o=Qu(e)?e.checked?"true":"false":e.value),e=o,e!==s?(t.setValue(e),!0):!1}function Sl(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 Xf=/[\n"\\]/g;function Ba(e){return e.replace(Xf,function(t){return"\\"+t.charCodeAt(0).toString(16)+" "})}function vo(e,t,s,o,f,p,S,R){e.name="",S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"?e.type=S:e.removeAttribute("type"),t!=null?S==="number"?(t===0&&e.value===""||e.value!=t)&&(e.value=""+Yn(t)):e.value!==""+Yn(t)&&(e.value=""+Yn(t)):S!=="submit"&&S!=="reset"||e.removeAttribute("value"),t!=null?Fn(e,S,Yn(t)):s!=null?Fn(e,S,Yn(s)):o!=null&&e.removeAttribute("value"),f==null&&p!=null&&(e.defaultChecked=!!p),f!=null&&(e.checked=f&&typeof f!="function"&&typeof f!="symbol"),R!=null&&typeof R!="function"&&typeof R!="symbol"&&typeof R!="boolean"?e.name=""+Yn(R):e.removeAttribute("name")}function Li(e,t,s,o,f,p,S,R){if(p!=null&&typeof p!="function"&&typeof p!="symbol"&&typeof p!="boolean"&&(e.type=p),t!=null||s!=null){if(!(p!=="submit"&&p!=="reset"||t!=null)){Nc(e);return}s=s!=null?""+Yn(s):"",t=t!=null?""+Yn(t):s,R||t===e.value||(e.value=t),e.defaultValue=t}o=o??f,o=typeof o!="function"&&typeof o!="symbol"&&!!o,e.checked=R?e.checked:!!o,e.defaultChecked=!!o,S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"&&(e.name=S),Nc(e)}function Fn(e,t,s){t==="number"&&Sl(e.ownerDocument)===e||e.defaultValue===""+s||(e.defaultValue=""+s)}function Ra(e,t,s,o){if(e=e.options,t){t={};for(var f=0;f<s.length;f++)t["$"+s[f]]=!0;for(s=0;s<e.length;s++)f=t.hasOwnProperty("$"+e[s].value),e[s].selected!==f&&(e[s].selected=f),f&&o&&(e[s].defaultSelected=!0)}else{for(s=""+Yn(s),t=null,f=0;f<e.length;f++){if(e[f].value===s){e[f].selected=!0,o&&(e[f].defaultSelected=!0);return}t!==null||e[f].disabled||(t=e[f])}t!==null&&(t.selected=!0)}}function Ws(e,t,s){if(t!=null&&(t=""+Yn(t),t!==e.value&&(e.value=t),s==null)){e.defaultValue!==t&&(e.defaultValue=t);return}e.defaultValue=s!=null?""+Yn(s):""}function $r(e,t,s,o){if(t==null){if(o!=null){if(s!=null)throw Error(l(92));if(Z(o)){if(1<o.length)throw Error(l(93));o=o[0]}s=o}s==null&&(s=""),t=s}s=Yn(t),e.defaultValue=s,o=e.textContent,o===s&&o!==""&&o!==null&&(e.value=o),Nc(e)}function kn(e,t){if(t){var s=e.firstChild;if(s&&s===e.lastChild&&s.nodeType===3){s.nodeValue=t;return}}e.textContent=t}var Cl=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 Ys(e,t,s){var o=t.indexOf("--")===0;s==null||typeof s=="boolean"||s===""?o?e.setProperty(t,""):t==="float"?e.cssFloat="":e[t]="":o?e.setProperty(t,s):typeof s!="number"||s===0||Cl.has(t)?t==="float"?e.cssFloat=s:e[t]=(""+s).trim():e[t]=s+"px"}function kl(e,t,s){if(t!=null&&typeof t!="object")throw Error(l(62));if(e=e.style,s!=null){for(var o in s)!s.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)&&s[f]!==o&&Ys(e,f,o)}else for(var p in t)t.hasOwnProperty(p)&&Ys(e,p,t[p])}function Br(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 os=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"]]),Zu=/^[\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 Pr(e){return Zu.test(""+e)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":e}function ra(){}var Cs=null;function _i(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var vr=null,Ks=null;function jl(e){var t=gn(e);if(t&&(e=t.stateNode)){var s=e[Te]||null;e:switch(e=t.stateNode,t.type){case"input":if(vo(e,s.value,s.defaultValue,s.defaultValue,s.checked,s.defaultChecked,s.type,s.name),t=s.name,s.type==="radio"&&t!=null){for(s=e;s.parentNode;)s=s.parentNode;for(s=s.querySelectorAll('input[name="'+Ba(""+t)+'"][type="radio"]'),t=0;t<s.length;t++){var o=s[t];if(o!==e&&o.form===e.form){var f=o[Te]||null;if(!f)throw Error(l(90));vo(o,f.value,f.defaultValue,f.defaultValue,f.checked,f.defaultChecked,f.type,f.name)}}for(t=0;t<s.length;t++)o=s[t],o.form===e.form&&Xu(o)}break e;case"textarea":Ws(e,s.value,s.defaultValue);break e;case"select":t=s.value,t!=null&&Ra(e,!!s.multiple,t,!1)}}}var yo=!1;function Al(e,t,s){if(yo)return e(t,s);yo=!0;try{var o=e(t);return o}finally{if(yo=!1,(vr!==null||Ks!==null)&&(Nd(),vr&&(t=vr,e=Ks,Ks=vr=null,jl(t),e)))for(t=0;t<e.length;t++)jl(e[t])}}function yr(e,t){var s=e.stateNode;if(s===null)return null;var o=s[Te]||null;if(o===null)return null;s=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(s&&typeof s!="function")throw Error(l(231,t,typeof s));return s}var ks=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),bo=!1;if(ks)try{var ia={};Object.defineProperty(ia,"passive",{get:function(){bo=!0}}),window.addEventListener("test",ia,ia),window.removeEventListener("test",ia,ia)}catch{bo=!1}var js=null,Pa=null,va=null;function la(){if(va)return va;var e,t=Pa,s=t.length,o,f="value"in js?js.value:js.textContent,p=f.length;for(e=0;e<s&&t[e]===f[e];e++);var S=s-e;for(o=1;o<=S&&t[s-o]===f[p-o];o++);return va=f.slice(e,1<o?1-o:void 0)}function Ml(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 Nl(){return!0}function Tt(){return!1}function Zt(e){function t(s,o,f,p,S){this._reactName=s,this._targetInst=f,this.type=o,this.nativeEvent=p,this.target=S,this.currentTarget=null;for(var R in e)e.hasOwnProperty(R)&&(s=e[R],this[R]=s?s(p):p[R]);return this.isDefaultPrevented=(p.defaultPrevented!=null?p.defaultPrevented:p.returnValue===!1)?Nl:Tt,this.isPropagationStopped=Tt,this}return b(t.prototype,{preventDefault:function(){this.defaultPrevented=!0;var s=this.nativeEvent;s&&(s.preventDefault?s.preventDefault():typeof s.returnValue!="unknown"&&(s.returnValue=!1),this.isDefaultPrevented=Nl)},stopPropagation:function(){var s=this.nativeEvent;s&&(s.stopPropagation?s.stopPropagation():typeof s.cancelBubble!="unknown"&&(s.cancelBubble=!0),this.isPropagationStopped=Nl)},persist:function(){},isPersistent:Nl}),t}var Ea={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Qs=Zt(Ea),Xs=b({},Ea,{view:0,detail:0}),br=Zt(Xs),Zs,Ii,As,Ms=b({},Xs,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:ed,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!==As&&(As&&e.type==="mousemove"?(Zs=e.screenX-As.screenX,Ii=e.screenY-As.screenY):Ii=Zs=0,As=e),Zs)},movementY:function(e){return"movementY"in e?e.movementY:Ii}}),xr=Zt(Ms),zi=b({},Ms,{dataTransfer:0}),xo=Zt(zi),Tl=b({},Xs,{relatedTarget:0}),Oi=Zt(Tl),wo=b({},Ea,{animationName:0,elapsedTime:0,pseudoElement:0}),So=Zt(wo),Tc=b({},Ea,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),Ju=Zt(Tc),Js=b({},Ea,{data:0}),cs=Zt(Js),Ur={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},wr={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"},Zf={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Rc(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):(e=Zf[e])?!!t[e]:!1}function ed(){return Rc}var Jf=b({},Xs,{key:function(e){if(e.key){var t=Ur[e.key]||e.key;if(t!=="Unidentified")return t}return e.type==="keypress"?(e=Ml(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?wr[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:ed,charCode:function(e){return e.type==="keypress"?Ml(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?Ml(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),Hi=Zt(Jf),em=b({},Ms,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),qr=Zt(em),Ec=b({},Xs,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:ed}),Wp=Zt(Ec),Yp=b({},Ea,{propertyName:0,elapsedTime:0,pseudoElement:0}),Kp=Zt(Yp),tm=b({},Ms,{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}),td=Zt(tm),nd=b({},Ea,{newState:0,oldState:0}),nm=Zt(nd),am=[9,13,27,32],Dc=ks&&"CompositionEvent"in window,Gr=null;ks&&"documentMode"in document&&(Gr=document.documentMode);var Lc=ks&&"TextEvent"in window&&!Gr,Fi=ks&&(!Dc||Gr&&8<Gr&&11>=Gr),er=" ",Rl=!1;function _c(e,t){switch(e){case"keyup":return am.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Ic(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Vr=!1;function El(e,t){switch(e){case"compositionend":return Ic(t);case"keypress":return t.which!==32?null:(Rl=!0,er);case"textInput":return e=t.data,e===er&&Rl?null:e;default:return null}}function zc(e,t){if(Vr)return e==="compositionend"||!Dc&&_c(e,t)?(e=la(),va=Pa=js=null,Vr=!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 Fi&&t.locale!=="ko"?null:t.data;default:return null}}var Dl={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 gt(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t==="input"?!!Dl[e.type]:t==="textarea"}function Rt(e,t,s,o){vr?Ks?Ks.push(o):Ks=[o]:vr=o,t=Id(t,"onChange"),0<t.length&&(s=new Qs("onChange","change",null,s,o),e.push({event:s,listeners:t}))}var $n=null,tr=null;function sm(e){Nv(e,0)}function Ll(e){var t=nn(e);if(Xu(t))return e}function Wr(e,t){if(e==="change")return t}var lt=!1;if(ks){var Co;if(ks){var Oc="oninput"in document;if(!Oc){var ko=document.createElement("div");ko.setAttribute("oninput","return;"),Oc=typeof ko.oninput=="function"}Co=Oc}else Co=!1;lt=Co&&(!document.documentMode||9<document.documentMode)}function Sr(){$n&&($n.detachEvent("onpropertychange",Hc),tr=$n=null)}function Hc(e){if(e.propertyName==="value"&&Ll(tr)){var t=[];Rt(t,tr,e,_i(e)),Al(sm,t)}}function Fc(e,t,s){e==="focusin"?(Sr(),$n=t,tr=s,$n.attachEvent("onpropertychange",Hc)):e==="focusout"&&Sr()}function Yr(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return Ll(tr)}function Da(e,t){if(e==="click")return Ll(t)}function $i(e,t){if(e==="input"||e==="change")return Ll(t)}function oa(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var an=typeof Object.is=="function"?Object.is:oa;function Ee(e,t){if(an(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;var s=Object.keys(e),o=Object.keys(t);if(s.length!==o.length)return!1;for(o=0;o<s.length;o++){var f=s[o];if(!Ye.call(t,f)||!an(e[f],t[f]))return!1}return!0}function $c(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function ad(e,t){var s=$c(e);e=0;for(var o;s;){if(s.nodeType===3){if(o=e+s.textContent.length,e<=t&&o>=t)return{node:s,offset:t-e};e=o}e:{for(;s;){if(s.nextSibling){s=s.nextSibling;break e}s=s.parentNode}s=void 0}s=$c(s)}}function sd(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?sd(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function jo(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Sl(e.document);t instanceof e.HTMLIFrameElement;){try{var s=typeof t.contentWindow.location.href=="string"}catch{s=!1}if(s)e=t.contentWindow;else break;t=Sl(e.document)}return t}function Kr(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 Qp=ks&&"documentMode"in document&&11>=document.documentMode,Qr=null,un=null,Bi=null,Pi=!1;function Xr(e,t,s){var o=s.window===s?s.document:s.nodeType===9?s:s.ownerDocument;Pi||Qr==null||Qr!==Sl(o)||(o=Qr,"selectionStart"in o&&Kr(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}),Bi&&Ee(Bi,o)||(Bi=o,o=Id(un,"onSelect"),0<o.length&&(t=new Qs("onSelect","select",null,t,s),e.push({event:t,listeners:o}),t.target=Qr)))}function Zr(e,t){var s={};return s[e.toLowerCase()]=t.toLowerCase(),s["Webkit"+e]="webkit"+t,s["Moz"+e]="moz"+t,s}var Ui={animationend:Zr("Animation","AnimationEnd"),animationiteration:Zr("Animation","AnimationIteration"),animationstart:Zr("Animation","AnimationStart"),transitionrun:Zr("Transition","TransitionRun"),transitionstart:Zr("Transition","TransitionStart"),transitioncancel:Zr("Transition","TransitionCancel"),transitionend:Zr("Transition","TransitionEnd")},Kt={},Jr={};ks&&(Jr=document.createElement("div").style,"AnimationEvent"in window||(delete Ui.animationend.animation,delete Ui.animationiteration.animation,delete Ui.animationstart.animation),"TransitionEvent"in window||delete Ui.transitionend.transition);function ei(e){if(Kt[e])return Kt[e];if(!Ui[e])return e;var t=Ui[e],s;for(s in t)if(t.hasOwnProperty(s)&&s in Jr)return Kt[e]=t[s];return e}var Ns=ei("animationend"),Bc=ei("animationiteration"),qi=ei("animationstart"),Pc=ei("transitionrun"),Ao=ei("transitionstart"),Mo=ei("transitioncancel"),Ua=ei("transitionend"),nr=new Map,Gi="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(" ");Gi.push("scrollEnd");function vn(e,t){nr.set(e,t),Cn(t,[e])}var Bn=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)},sn=[],Vi=0,No=0;function ar(){for(var e=Vi,t=No=Vi=0;t<e;){var s=sn[t];sn[t++]=null;var o=sn[t];sn[t++]=null;var f=sn[t];sn[t++]=null;var p=sn[t];if(sn[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}p!==0&&Ro(s,f,p)}}function To(e,t,s,o){sn[Vi++]=e,sn[Vi++]=t,sn[Vi++]=s,sn[Vi++]=o,No|=o,e.lanes|=o,e=e.alternate,e!==null&&(e.lanes|=o)}function La(e,t,s,o){return To(e,t,s,o),Rn(e)}function _a(e,t){return To(e,null,null,t),Rn(e)}function Ro(e,t,s){e.lanes|=s;var o=e.alternate;o!==null&&(o.lanes|=s);for(var f=!1,p=e.return;p!==null;)p.childLanes|=s,o=p.alternate,o!==null&&(o.childLanes|=s),p.tag===22&&(e=p.stateNode,e===null||e._visibility&1||(f=!0)),e=p,p=p.return;return e.tag===3?(p=e.stateNode,f&&t!==null&&(f=31-xt(s),e=p.hiddenUpdates,o=e[f],o===null?e[f]=[t]:o.push(t),t.lane=s|536870912),p):null}function Rn(e){if(50<fu)throw fu=0,zm=null,Error(l(185));for(var t=e.return;t!==null;)e=t,t=e.return;return e.tag===3?e.stateNode:null}var ca={};function Eo(e,t,s,o){this.tag=e,this.key=s,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=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 En(e,t,s,o){return new Eo(e,t,s,o)}function Ts(e){return e=e.prototype,!(!e||!e.isReactComponent)}function ya(e,t){var s=e.alternate;return s===null?(s=En(e.tag,t,e.key,e.mode),s.elementType=e.elementType,s.type=e.type,s.stateNode=e.stateNode,s.alternate=e,e.alternate=s):(s.pendingProps=t,s.type=e.type,s.flags=0,s.subtreeFlags=0,s.deletions=null),s.flags=e.flags&65011712,s.childLanes=e.childLanes,s.lanes=e.lanes,s.child=e.child,s.memoizedProps=e.memoizedProps,s.memoizedState=e.memoizedState,s.updateQueue=e.updateQueue,t=e.dependencies,s.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},s.sibling=e.sibling,s.index=e.index,s.ref=e.ref,s.refCleanup=e.refCleanup,s}function _l(e,t){e.flags&=65011714;var s=e.alternate;return s===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=s.childLanes,e.lanes=s.lanes,e.child=s.child,e.subtreeFlags=0,e.deletions=null,e.memoizedProps=s.memoizedProps,e.memoizedState=s.memoizedState,e.updateQueue=s.updateQueue,e.type=s.type,t=s.dependencies,e.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext}),e}function qa(e,t,s,o,f,p){var S=0;if(o=e,typeof e=="function")Ts(e)&&(S=1);else if(typeof e=="string")S=WS(e,s,he.current)?26:e==="html"||e==="head"||e==="body"?27:5;else e:switch(e){case G:return e=En(31,s,t,f),e.elementType=G,e.lanes=p,e;case k:return Cr(s.children,f,p,t);case N:S=8,f|=24;break;case M:return e=En(12,s,t,f|2),e.elementType=M,e.lanes=p,e;case $:return e=En(13,s,t,f),e.elementType=$,e.lanes=p,e;case q:return e=En(19,s,t,f),e.elementType=q,e.lanes=p,e;default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case D:S=10;break e;case T:S=9;break e;case F:S=11;break e;case L:S=14;break e;case Y:S=16,o=null;break e}S=29,s=Error(l(130,e===null?"null":typeof e,"")),o=null}return t=En(S,s,t,f),t.elementType=e,t.type=o,t.lanes=p,t}function Cr(e,t,s,o){return e=En(7,e,o,t),e.lanes=s,e}function Uc(e,t,s){return e=En(6,e,null,t),e.lanes=s,e}function Il(e){var t=En(18,null,null,0);return t.stateNode=e,t}function Wi(e,t,s){return t=En(4,e.children!==null?e.children:[],e.key,t),t.lanes=s,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}var qc=new WeakMap;function Pn(e,t){if(typeof e=="object"&&e!==null){var s=qc.get(e);return s!==void 0?s:(t={value:e,source:t,stack:Qe(t)},qc.set(e,t),t)}return{value:e,source:t,stack:Qe(t)}}var ti=[],ni=0,Do=null,Rs=0,Ga=[],Ia=0,kr=null,Es=1,us="";function Va(e,t){ti[ni++]=Rs,ti[ni++]=Do,Do=e,Rs=t}function rd(e,t,s){Ga[Ia++]=Es,Ga[Ia++]=us,Ga[Ia++]=kr,kr=e;var o=Es;e=us;var f=32-xt(o)-1;o&=~(1<<f),s+=1;var p=32-xt(t)+f;if(30<p){var S=f-f%5;p=(o&(1<<S)-1).toString(32),o>>=S,f-=S,Es=1<<32-xt(t)+f|s<<f|o,us=p+e}else Es=1<<p|s<<f|o,us=e}function Lo(e){e.return!==null&&(Va(e,1),rd(e,1,0))}function ai(e){for(;e===Do;)Do=ti[--ni],ti[ni]=null,Rs=ti[--ni],ti[ni]=null;for(;e===kr;)kr=Ga[--Ia],Ga[Ia]=null,us=Ga[--Ia],Ga[Ia]=null,Es=Ga[--Ia],Ga[Ia]=null}function Gc(e,t){Ga[Ia++]=Es,Ga[Ia++]=us,Ga[Ia++]=kr,Es=t.id,us=t.overflow,kr=e}var rn=null,Gt=null,wt=!1,ba=null,xa=!1,Vc=Error(l(519));function sr(e){var t=Error(l(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw Ki(Pn(t,e)),Vc}function zl(e){var t=e.stateNode,s=e.type,o=e.memoizedProps;switch(t[re]=e,t[Te]=o,s){case"dialog":Dt("cancel",t),Dt("close",t);break;case"iframe":case"object":case"embed":Dt("load",t);break;case"video":case"audio":for(s=0;s<hu.length;s++)Dt(hu[s],t);break;case"source":Dt("error",t);break;case"img":case"image":case"link":Dt("error",t),Dt("load",t);break;case"details":Dt("toggle",t);break;case"input":Dt("invalid",t),Li(t,o.value,o.defaultValue,o.checked,o.defaultChecked,o.type,o.name,!0);break;case"select":Dt("invalid",t);break;case"textarea":Dt("invalid",t),$r(t,o.value,o.defaultValue,o.children)}s=o.children,typeof s!="string"&&typeof s!="number"&&typeof s!="bigint"||t.textContent===""+s||o.suppressHydrationWarning===!0||Dv(t.textContent,s)?(o.popover!=null&&(Dt("beforetoggle",t),Dt("toggle",t)),o.onScroll!=null&&Dt("scroll",t),o.onScrollEnd!=null&&Dt("scrollend",t),o.onClick!=null&&(t.onclick=ra),t=!0):t=!1,t||sr(e,!0)}function _o(e){for(rn=e.return;rn;)switch(rn.tag){case 5:case 31:case 13:xa=!1;return;case 27:case 3:xa=!0;return;default:rn=rn.return}}function Ds(e){if(e!==rn)return!1;if(!wt)return _o(e),wt=!0,!1;var t=e.tag,s;if((s=t!==3&&t!==27)&&((s=t===5)&&(s=e.type,s=!(s!=="form"&&s!=="button")||Xm(e.type,e.memoizedProps)),s=!s),s&&Gt&&sr(e),_o(e),t===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(l(317));Gt=Bv(e)}else if(t===31){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(l(317));Gt=Bv(e)}else t===27?(t=Gt,ol(e.type)?(e=nh,nh=null,Gt=e):Gt=t):Gt=rn?$s(e.stateNode.nextSibling):null;return!0}function si(){Gt=rn=null,wt=!1}function Yi(){var e=ba;return e!==null&&(ns===null?ns=e:ns.push.apply(ns,e),ba=null),e}function Ki(e){ba===null?ba=[e]:ba.push(e)}var ri=ce(null),rr=null,Wa=null;function ds(e,t,s){be(ri,t._currentValue),t._currentValue=s}function Ya(e){e._currentValue=ri.current,Q(ri)}function ir(e,t,s){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===s)break;e=e.return}}function Io(e,t,s,o){var f=e.child;for(f!==null&&(f.return=e);f!==null;){var p=f.dependencies;if(p!==null){var S=f.child;p=p.firstContext;e:for(;p!==null;){var R=p;p=f;for(var V=0;V<t.length;V++)if(R.context===t[V]){p.lanes|=s,R=p.alternate,R!==null&&(R.lanes|=s),ir(p.return,s,e),o||(S=null);break e}p=R.next}}else if(f.tag===18){if(S=f.return,S===null)throw Error(l(341));S.lanes|=s,p=S.alternate,p!==null&&(p.lanes|=s),ir(S,s,e),S=null}else S=f.child;if(S!==null)S.return=f;else for(S=f;S!==null;){if(S===e){S=null;break}if(f=S.sibling,f!==null){f.return=S.return,S=f;break}S=S.return}f=S}}function ii(e,t,s,o){e=null;for(var f=t,p=!1;f!==null;){if(!p){if((f.flags&524288)!==0)p=!0;else if((f.flags&262144)!==0)break}if(f.tag===10){var S=f.alternate;if(S===null)throw Error(l(387));if(S=S.memoizedProps,S!==null){var R=f.type;an(f.pendingProps.value,S.value)||(e!==null?e.push(R):e=[R])}}else if(f===Se.current){if(S=f.alternate,S===null)throw Error(l(387));S.memoizedState.memoizedState!==f.memoizedState.memoizedState&&(e!==null?e.push(bu):e=[bu])}f=f.return}e!==null&&Io(t,e,s,o),t.flags|=262144}function lr(e){for(e=e.firstContext;e!==null;){if(!an(e.context._currentValue,e.memoizedValue))return!0;e=e.next}return!1}function Ka(e){rr=e,Wa=null,e=e.dependencies,e!==null&&(e.firstContext=null)}function ln(e){return li(rr,e)}function za(e,t){return rr===null&&Ka(e),li(e,t)}function li(e,t){var s=t._currentValue;if(t={context:t,memoizedValue:s,next:null},Wa===null){if(e===null)throw Error(l(308));Wa=t,e.dependencies={lanes:0,firstContext:t},e.flags|=524288}else Wa=Wa.next=t;return s}var id=typeof AbortController<"u"?AbortController:function(){var e=[],t=this.signal={aborted:!1,addEventListener:function(s,o){e.push(o)}};this.abort=function(){t.aborted=!0,e.forEach(function(s){return s()})}},zo=n.unstable_scheduleCallback,jr=n.unstable_NormalPriority,jn={$$typeof:D,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function Oo(){return{controller:new id,data:new Map,refCount:0}}function or(e){e.refCount--,e.refCount===0&&zo(jr,function(){e.controller.abort()})}var Ar=null,Ol=0,oi=0,ua=null;function ld(e,t){if(Ar===null){var s=Ar=[];Ol=0,oi=Pm(),ua={status:"pending",value:void 0,then:function(o){s.push(o)}}}return Ol++,t.then(Ho,Ho),t}function Ho(){if(--Ol===0&&Ar!==null){ua!==null&&(ua.status="fulfilled");var e=Ar;Ar=null,oi=0,ua=null;for(var t=0;t<e.length;t++)(0,e[t])()}}function Wc(e,t){var s=[],o={status:"pending",value:null,reason:null,then:function(f){s.push(f)}};return e.then(function(){o.status="fulfilled",o.value=t;for(var f=0;f<s.length;f++)(0,s[f])(t)},function(f){for(o.status="rejected",o.reason=f,f=0;f<s.length;f++)(0,s[f])(void 0)}),o}var Fo=z.S;z.S=function(e,t){nv=je(),typeof t=="object"&&t!==null&&typeof t.then=="function"&&ld(e,t),Fo!==null&&Fo(e,t)};var cr=ce(null);function $o(){var e=cr.current;return e!==null?e:tn.pooledCache}function Mr(e,t){t===null?be(cr,cr.current):be(cr,t.pool)}function Ls(){var e=$o();return e===null?null:{parent:jn._currentValue,pool:e}}var Nr=Error(l(460)),Yc=Error(l(474)),Hl=Error(l(542)),Dn={then:function(){}};function Kc(e){return e=e.status,e==="fulfilled"||e==="rejected"}function Fl(e,t,s){switch(s=e[s],s===void 0?e.push(t):s!==t&&(t.then(ra,ra),t=s),t.status){case"fulfilled":return t.value;case"rejected":throw e=t.reason,Bo(e),e;default:if(typeof t.status=="string")t.then(ra,ra);else{if(e=tn,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,Bo(e),e}throw Tr=t,Nr}}function _s(e){try{var t=e._init;return t(e._payload)}catch(s){throw s!==null&&typeof s=="object"&&typeof s.then=="function"?(Tr=s,Nr):s}}var Tr=null;function Qi(){if(Tr===null)throw Error(l(459));var e=Tr;return Tr=null,e}function Bo(e){if(e===Nr||e===Hl)throw Error(l(483))}var Is=null,$l=0;function Bl(e){var t=$l;return $l+=1,Is===null&&(Is=[]),Fl(Is,e,t)}function ur(e,t){t=t.props.ref,e.ref=t!==void 0?t:null}function Po(e,t){throw t.$$typeof===w?Error(l(525)):(e=Object.prototype.toString.call(t),Error(l(31,e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)))}function od(e){function t(ae,X){if(e){var oe=ae.deletions;oe===null?(ae.deletions=[X],ae.flags|=16):oe.push(X)}}function s(ae,X){if(!e)return null;for(;X!==null;)t(ae,X),X=X.sibling;return null}function o(ae){for(var X=new Map;ae!==null;)ae.key!==null?X.set(ae.key,ae):X.set(ae.index,ae),ae=ae.sibling;return X}function f(ae,X){return ae=ya(ae,X),ae.index=0,ae.sibling=null,ae}function p(ae,X,oe){return ae.index=oe,e?(oe=ae.alternate,oe!==null?(oe=oe.index,oe<X?(ae.flags|=67108866,X):oe):(ae.flags|=67108866,X)):(ae.flags|=1048576,X)}function S(ae){return e&&ae.alternate===null&&(ae.flags|=67108866),ae}function R(ae,X,oe,we){return X===null||X.tag!==6?(X=Uc(oe,ae.mode,we),X.return=ae,X):(X=f(X,oe),X.return=ae,X)}function V(ae,X,oe,we){var rt=oe.type;return rt===k?xe(ae,X,oe.props.children,we,oe.key):X!==null&&(X.elementType===rt||typeof rt=="object"&&rt!==null&&rt.$$typeof===Y&&_s(rt)===X.type)?(X=f(X,oe.props),ur(X,oe),X.return=ae,X):(X=qa(oe.type,oe.key,oe.props,null,ae.mode,we),ur(X,oe),X.return=ae,X)}function ue(ae,X,oe,we){return X===null||X.tag!==4||X.stateNode.containerInfo!==oe.containerInfo||X.stateNode.implementation!==oe.implementation?(X=Wi(oe,ae.mode,we),X.return=ae,X):(X=f(X,oe.children||[]),X.return=ae,X)}function xe(ae,X,oe,we,rt){return X===null||X.tag!==7?(X=Cr(oe,ae.mode,we,rt),X.return=ae,X):(X=f(X,oe),X.return=ae,X)}function Ce(ae,X,oe){if(typeof X=="string"&&X!==""||typeof X=="number"||typeof X=="bigint")return X=Uc(""+X,ae.mode,oe),X.return=ae,X;if(typeof X=="object"&&X!==null){switch(X.$$typeof){case A:return oe=qa(X.type,X.key,X.props,null,ae.mode,oe),ur(oe,X),oe.return=ae,oe;case j:return X=Wi(X,ae.mode,oe),X.return=ae,X;case Y:return X=_s(X),Ce(ae,X,oe)}if(Z(X)||H(X))return X=Cr(X,ae.mode,oe,null),X.return=ae,X;if(typeof X.then=="function")return Ce(ae,Bl(X),oe);if(X.$$typeof===D)return Ce(ae,za(ae,X),oe);Po(ae,X)}return null}function me(ae,X,oe,we){var rt=X!==null?X.key:null;if(typeof oe=="string"&&oe!==""||typeof oe=="number"||typeof oe=="bigint")return rt!==null?null:R(ae,X,""+oe,we);if(typeof oe=="object"&&oe!==null){switch(oe.$$typeof){case A:return oe.key===rt?V(ae,X,oe,we):null;case j:return oe.key===rt?ue(ae,X,oe,we):null;case Y:return oe=_s(oe),me(ae,X,oe,we)}if(Z(oe)||H(oe))return rt!==null?null:xe(ae,X,oe,we,null);if(typeof oe.then=="function")return me(ae,X,Bl(oe),we);if(oe.$$typeof===D)return me(ae,X,za(ae,oe),we);Po(ae,oe)}return null}function ge(ae,X,oe,we,rt){if(typeof we=="string"&&we!==""||typeof we=="number"||typeof we=="bigint")return ae=ae.get(oe)||null,R(X,ae,""+we,rt);if(typeof we=="object"&&we!==null){switch(we.$$typeof){case A:return ae=ae.get(we.key===null?oe:we.key)||null,V(X,ae,we,rt);case j:return ae=ae.get(we.key===null?oe:we.key)||null,ue(X,ae,we,rt);case Y:return we=_s(we),ge(ae,X,oe,we,rt)}if(Z(we)||H(we))return ae=ae.get(oe)||null,xe(X,ae,we,rt,null);if(typeof we.then=="function")return ge(ae,X,oe,Bl(we),rt);if(we.$$typeof===D)return ge(ae,X,oe,za(X,we),rt);Po(X,we)}return null}function Xe(ae,X,oe,we){for(var rt=null,Ht=null,Je=X,jt=X=0,_t=null;Je!==null&&jt<oe.length;jt++){Je.index>jt?(_t=Je,Je=null):_t=Je.sibling;var Ft=me(ae,Je,oe[jt],we);if(Ft===null){Je===null&&(Je=_t);break}e&&Je&&Ft.alternate===null&&t(ae,Je),X=p(Ft,X,jt),Ht===null?rt=Ft:Ht.sibling=Ft,Ht=Ft,Je=_t}if(jt===oe.length)return s(ae,Je),wt&&Va(ae,jt),rt;if(Je===null){for(;jt<oe.length;jt++)Je=Ce(ae,oe[jt],we),Je!==null&&(X=p(Je,X,jt),Ht===null?rt=Je:Ht.sibling=Je,Ht=Je);return wt&&Va(ae,jt),rt}for(Je=o(Je);jt<oe.length;jt++)_t=ge(Je,ae,jt,oe[jt],we),_t!==null&&(e&&_t.alternate!==null&&Je.delete(_t.key===null?jt:_t.key),X=p(_t,X,jt),Ht===null?rt=_t:Ht.sibling=_t,Ht=_t);return e&&Je.forEach(function(ml){return t(ae,ml)}),wt&&Va(ae,jt),rt}function ot(ae,X,oe,we){if(oe==null)throw Error(l(151));for(var rt=null,Ht=null,Je=X,jt=X=0,_t=null,Ft=oe.next();Je!==null&&!Ft.done;jt++,Ft=oe.next()){Je.index>jt?(_t=Je,Je=null):_t=Je.sibling;var ml=me(ae,Je,Ft.value,we);if(ml===null){Je===null&&(Je=_t);break}e&&Je&&ml.alternate===null&&t(ae,Je),X=p(ml,X,jt),Ht===null?rt=ml:Ht.sibling=ml,Ht=ml,Je=_t}if(Ft.done)return s(ae,Je),wt&&Va(ae,jt),rt;if(Je===null){for(;!Ft.done;jt++,Ft=oe.next())Ft=Ce(ae,Ft.value,we),Ft!==null&&(X=p(Ft,X,jt),Ht===null?rt=Ft:Ht.sibling=Ft,Ht=Ft);return wt&&Va(ae,jt),rt}for(Je=o(Je);!Ft.done;jt++,Ft=oe.next())Ft=ge(Je,ae,jt,Ft.value,we),Ft!==null&&(e&&Ft.alternate!==null&&Je.delete(Ft.key===null?jt:Ft.key),X=p(Ft,X,jt),Ht===null?rt=Ft:Ht.sibling=Ft,Ht=Ft);return e&&Je.forEach(function(s0){return t(ae,s0)}),wt&&Va(ae,jt),rt}function Xt(ae,X,oe,we){if(typeof oe=="object"&&oe!==null&&oe.type===k&&oe.key===null&&(oe=oe.props.children),typeof oe=="object"&&oe!==null){switch(oe.$$typeof){case A:e:{for(var rt=oe.key;X!==null;){if(X.key===rt){if(rt=oe.type,rt===k){if(X.tag===7){s(ae,X.sibling),we=f(X,oe.props.children),we.return=ae,ae=we;break e}}else if(X.elementType===rt||typeof rt=="object"&&rt!==null&&rt.$$typeof===Y&&_s(rt)===X.type){s(ae,X.sibling),we=f(X,oe.props),ur(we,oe),we.return=ae,ae=we;break e}s(ae,X);break}else t(ae,X);X=X.sibling}oe.type===k?(we=Cr(oe.props.children,ae.mode,we,oe.key),we.return=ae,ae=we):(we=qa(oe.type,oe.key,oe.props,null,ae.mode,we),ur(we,oe),we.return=ae,ae=we)}return S(ae);case j:e:{for(rt=oe.key;X!==null;){if(X.key===rt)if(X.tag===4&&X.stateNode.containerInfo===oe.containerInfo&&X.stateNode.implementation===oe.implementation){s(ae,X.sibling),we=f(X,oe.children||[]),we.return=ae,ae=we;break e}else{s(ae,X);break}else t(ae,X);X=X.sibling}we=Wi(oe,ae.mode,we),we.return=ae,ae=we}return S(ae);case Y:return oe=_s(oe),Xt(ae,X,oe,we)}if(Z(oe))return Xe(ae,X,oe,we);if(H(oe)){if(rt=H(oe),typeof rt!="function")throw Error(l(150));return oe=rt.call(oe),ot(ae,X,oe,we)}if(typeof oe.then=="function")return Xt(ae,X,Bl(oe),we);if(oe.$$typeof===D)return Xt(ae,X,za(ae,oe),we);Po(ae,oe)}return typeof oe=="string"&&oe!==""||typeof oe=="number"||typeof oe=="bigint"?(oe=""+oe,X!==null&&X.tag===6?(s(ae,X.sibling),we=f(X,oe),we.return=ae,ae=we):(s(ae,X),we=Uc(oe,ae.mode,we),we.return=ae,ae=we),S(ae)):s(ae,X)}return function(ae,X,oe,we){try{$l=0;var rt=Xt(ae,X,oe,we);return Is=null,rt}catch(Je){if(Je===Nr||Je===Hl)throw Je;var Ht=En(29,Je,null,ae.mode);return Ht.lanes=we,Ht.return=ae,Ht}}}var ci=od(!0),cd=od(!1),zs=!1;function Pl(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function ui(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 dr(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Os(e,t,s){var o=e.updateQueue;if(o===null)return null;if(o=o.shared,(Pt&2)!==0){var f=o.pending;return f===null?t.next=t:(t.next=f.next,f.next=t),o.pending=t,t=Rn(e),Ro(e,null,s),t}return To(e,o,t,s),Rn(e)}function Ul(e,t,s){if(t=t.updateQueue,t!==null&&(t=t.shared,(s&4194048)!==0)){var o=t.lanes;o&=e.pendingLanes,s|=o,t.lanes=s,B(e,s)}}function di(e,t){var s=e.updateQueue,o=e.alternate;if(o!==null&&(o=o.updateQueue,s===o)){var f=null,p=null;if(s=s.firstBaseUpdate,s!==null){do{var S={lane:s.lane,tag:s.tag,payload:s.payload,callback:null,next:null};p===null?f=p=S:p=p.next=S,s=s.next}while(s!==null);p===null?f=p=t:p=p.next=t}else f=p=t;s={baseState:o.baseState,firstBaseUpdate:f,lastBaseUpdate:p,shared:o.shared,callbacks:o.callbacks},e.updateQueue=s;return}e=s.lastBaseUpdate,e===null?s.firstBaseUpdate=t:e.next=t,s.lastBaseUpdate=t}var Qc=!1;function ql(){if(Qc){var e=ua;if(e!==null)throw e}}function Gl(e,t,s,o){Qc=!1;var f=e.updateQueue;zs=!1;var p=f.firstBaseUpdate,S=f.lastBaseUpdate,R=f.shared.pending;if(R!==null){f.shared.pending=null;var V=R,ue=V.next;V.next=null,S===null?p=ue:S.next=ue,S=V;var xe=e.alternate;xe!==null&&(xe=xe.updateQueue,R=xe.lastBaseUpdate,R!==S&&(R===null?xe.firstBaseUpdate=ue:R.next=ue,xe.lastBaseUpdate=V))}if(p!==null){var Ce=f.baseState;S=0,xe=ue=V=null,R=p;do{var me=R.lane&-536870913,ge=me!==R.lane;if(ge?(Lt&me)===me:(o&me)===me){me!==0&&me===oi&&(Qc=!0),xe!==null&&(xe=xe.next={lane:0,tag:R.tag,payload:R.payload,callback:null,next:null});e:{var Xe=e,ot=R;me=t;var Xt=s;switch(ot.tag){case 1:if(Xe=ot.payload,typeof Xe=="function"){Ce=Xe.call(Xt,Ce,me);break e}Ce=Xe;break e;case 3:Xe.flags=Xe.flags&-65537|128;case 0:if(Xe=ot.payload,me=typeof Xe=="function"?Xe.call(Xt,Ce,me):Xe,me==null)break e;Ce=b({},Ce,me);break e;case 2:zs=!0}}me=R.callback,me!==null&&(e.flags|=64,ge&&(e.flags|=8192),ge=f.callbacks,ge===null?f.callbacks=[me]:ge.push(me))}else ge={lane:me,tag:R.tag,payload:R.payload,callback:R.callback,next:null},xe===null?(ue=xe=ge,V=Ce):xe=xe.next=ge,S|=me;if(R=R.next,R===null){if(R=f.shared.pending,R===null)break;ge=R,R=ge.next,ge.next=null,f.lastBaseUpdate=ge,f.shared.pending=null}}while(!0);xe===null&&(V=Ce),f.baseState=V,f.firstBaseUpdate=ue,f.lastBaseUpdate=xe,p===null&&(f.shared.lanes=0),al|=S,e.lanes=S,e.memoizedState=Ce}}function Uo(e,t){if(typeof e!="function")throw Error(l(191,e));e.call(t)}function Xc(e,t){var s=e.callbacks;if(s!==null)for(e.callbacks=null,e=0;e<s.length;e++)Uo(s[e],t)}var fi=ce(null),Vl=ce(0);function ud(e,t){e=ki,be(Vl,e),be(fi,t),ki=e|t.baseLanes}function Wl(){be(Vl,ki),be(fi,fi.current)}function Xi(){ki=Vl.current,Q(fi),Q(Vl)}var wa=ce(null),Sa=null;function Hs(e){var t=e.alternate;be(yn,yn.current&1),be(wa,e),Sa===null&&(t===null||fi.current!==null||t.memoizedState!==null)&&(Sa=e)}function ze(e){be(yn,yn.current),be(wa,e),Sa===null&&(Sa=e)}function Yl(e){e.tag===22?(be(yn,yn.current),be(wa,e),Sa===null&&(Sa=e)):fr()}function fr(){be(yn,yn.current),be(wa,wa.current)}function Oa(e){Q(wa),Sa===e&&(Sa=null),Q(yn)}var yn=ce(0);function Zi(e){for(var t=e;t!==null;){if(t.tag===13){var s=t.memoizedState;if(s!==null&&(s=s.dehydrated,s===null||eh(s)||th(s)))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 Qa=0,et=null,St=null,nt=null,qo=!1,fs=!1,Xa=!1,Kl=0,Ji=0,mi=null,Ql=0;function Jt(){throw Error(l(321))}function Zc(e,t){if(t===null)return!1;for(var s=0;s<t.length&&s<e.length;s++)if(!an(e[s],t[s]))return!1;return!0}function Go(e,t,s,o,f,p){return Qa=p,et=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,z.H=e===null||e.memoizedState===null?mg:dm,Xa=!1,p=s(o,f),Xa=!1,fs&&(p=dd(t,s,o,f)),Vo(e),p}function Vo(e){z.H=au;var t=St!==null&&St.next!==null;if(Qa=0,nt=St=et=null,qo=!1,Ji=0,mi=null,t)throw Error(l(300));e===null||Ln||(e=e.dependencies,e!==null&&lr(e)&&(Ln=!0))}function dd(e,t,s,o){et=e;var f=0;do{if(fs&&(mi=null),Ji=0,fs=!1,25<=f)throw Error(l(301));if(f+=1,nt=St=null,e.updateQueue!=null){var p=e.updateQueue;p.lastEffect=null,p.events=null,p.stores=null,p.memoCache!=null&&(p.memoCache.index=0)}z.H=hg,p=t(s,o)}while(fs);return p}function rm(){var e=z.H,t=e.useState()[0];return t=typeof t.then=="function"?Yo(t):t,e=e.useState()[0],(St!==null?St.memoizedState:null)!==e&&(et.flags|=1024),t}function Xl(){var e=Kl!==0;return Kl=0,e}function Jc(e,t,s){t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~s}function eu(e){if(qo){for(e=e.memoizedState;e!==null;){var t=e.queue;t!==null&&(t.pending=null),e=e.next}qo=!1}Qa=0,nt=St=et=null,fs=!1,Ji=Kl=0,mi=null}function $t(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return nt===null?et.memoizedState=nt=e:nt=nt.next=e,nt}function on(){if(St===null){var e=et.alternate;e=e!==null?e.memoizedState:null}else e=St.next;var t=nt===null?et.memoizedState:nt.next;if(t!==null)nt=t,St=e;else{if(e===null)throw et.alternate===null?Error(l(467)):Error(l(310));St=e,e={memoizedState:St.memoizedState,baseState:St.baseState,baseQueue:St.baseQueue,queue:St.queue,next:null},nt===null?et.memoizedState=nt=e:nt=nt.next=e}return nt}function Wo(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function Yo(e){var t=Ji;return Ji+=1,mi===null&&(mi=[]),e=Fl(mi,e,t),t=et,(nt===null?t.memoizedState:nt.next)===null&&(t=t.alternate,z.H=t===null||t.memoizedState===null?mg:dm),e}function Ko(e){if(e!==null&&typeof e=="object"){if(typeof e.then=="function")return Yo(e);if(e.$$typeof===D)return ln(e)}throw Error(l(438,String(e)))}function tu(e){var t=null,s=et.updateQueue;if(s!==null&&(t=s.memoCache),t==null){var o=et.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}),s===null&&(s=Wo(),et.updateQueue=s),s.memoCache=t,s=t.data[t.index],s===void 0)for(s=t.data[t.index]=Array(e),o=0;o<e;o++)s[o]=P;return t.index++,s}function Fs(e,t){return typeof t=="function"?t(e):t}function hi(e){var t=on();return pi(t,St,e)}function pi(e,t,s){var o=e.queue;if(o===null)throw Error(l(311));o.lastRenderedReducer=s;var f=e.baseQueue,p=o.pending;if(p!==null){if(f!==null){var S=f.next;f.next=p.next,p.next=S}t.baseQueue=f=p,o.pending=null}if(p=e.baseState,f===null)e.memoizedState=p;else{t=f.next;var R=S=null,V=null,ue=t,xe=!1;do{var Ce=ue.lane&-536870913;if(Ce!==ue.lane?(Lt&Ce)===Ce:(Qa&Ce)===Ce){var me=ue.revertLane;if(me===0)V!==null&&(V=V.next={lane:0,revertLane:0,gesture:null,action:ue.action,hasEagerState:ue.hasEagerState,eagerState:ue.eagerState,next:null}),Ce===oi&&(xe=!0);else if((Qa&me)===me){ue=ue.next,me===oi&&(xe=!0);continue}else Ce={lane:0,revertLane:ue.revertLane,gesture:null,action:ue.action,hasEagerState:ue.hasEagerState,eagerState:ue.eagerState,next:null},V===null?(R=V=Ce,S=p):V=V.next=Ce,et.lanes|=me,al|=me;Ce=ue.action,Xa&&s(p,Ce),p=ue.hasEagerState?ue.eagerState:s(p,Ce)}else me={lane:Ce,revertLane:ue.revertLane,gesture:ue.gesture,action:ue.action,hasEagerState:ue.hasEagerState,eagerState:ue.eagerState,next:null},V===null?(R=V=me,S=p):V=V.next=me,et.lanes|=Ce,al|=Ce;ue=ue.next}while(ue!==null&&ue!==t);if(V===null?S=p:V.next=R,!an(p,e.memoizedState)&&(Ln=!0,xe&&(s=ua,s!==null)))throw s;e.memoizedState=p,e.baseState=S,e.baseQueue=V,o.lastRenderedState=p}return f===null&&(o.lanes=0),[e.memoizedState,o.dispatch]}function Qo(e){var t=on(),s=t.queue;if(s===null)throw Error(l(311));s.lastRenderedReducer=e;var o=s.dispatch,f=s.pending,p=t.memoizedState;if(f!==null){s.pending=null;var S=f=f.next;do p=e(p,S.action),S=S.next;while(S!==f);an(p,t.memoizedState)||(Ln=!0),t.memoizedState=p,t.baseQueue===null&&(t.baseState=p),s.lastRenderedState=p}return[p,o]}function fd(e,t,s){var o=et,f=on(),p=wt;if(p){if(s===void 0)throw Error(l(407));s=s()}else s=t();var S=!an((St||f).memoizedState,s);if(S&&(f.memoizedState=s,Ln=!0),f=f.queue,el(Xo.bind(null,o,f,e),[e]),f.getSnapshot!==t||S||nt!==null&&nt.memoizedState.tag&1){if(o.flags|=2048,en(9,{destroy:void 0},hd.bind(null,o,f,s,t),null),tn===null)throw Error(l(349));p||(Qa&127)!==0||md(o,t,s)}return s}function md(e,t,s){e.flags|=16384,e={getSnapshot:t,value:s},t=et.updateQueue,t===null?(t=Wo(),et.updateQueue=t,t.stores=[e]):(s=t.stores,s===null?t.stores=[e]:s.push(e))}function hd(e,t,s,o){t.value=s,t.getSnapshot=o,gi(t)&&pd(e)}function Xo(e,t,s){return s(function(){gi(t)&&pd(e)})}function gi(e){var t=e.getSnapshot;e=e.value;try{var s=t();return!an(e,s)}catch{return!0}}function pd(e){var t=_a(e,2);t!==null&&as(t,e,2)}function mr(e){var t=$t();if(typeof e=="function"){var s=e;if(e=s(),Xa){ft(!0);try{s()}finally{ft(!1)}}}return t.memoizedState=t.baseState=e,t.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Fs,lastRenderedState:e},t}function Zo(e,t,s,o){return e.baseState=s,pi(e,St,typeof o=="function"?o:Fs)}function v(e,t,s,o,f){if(gd(e))throw Error(l(485));if(e=t.action,e!==null){var p={payload:f,action:e,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(S){p.listeners.push(S)}};z.T!==null?s(!0):p.isTransition=!1,o(p),s=t.pending,s===null?(p.next=t.pending=p,C(t,p)):(p.next=s.next,t.pending=s.next=p)}}function C(e,t){var s=t.action,o=t.payload,f=e.state;if(t.isTransition){var p=z.T,S={};z.T=S;try{var R=s(f,o),V=z.S;V!==null&&V(S,R),E(e,t,R)}catch(ue){_(e,t,ue)}finally{p!==null&&S.types!==null&&(p.types=S.types),z.T=p}}else try{p=s(f,o),E(e,t,p)}catch(ue){_(e,t,ue)}}function E(e,t,s){s!==null&&typeof s=="object"&&typeof s.then=="function"?s.then(function(o){I(e,t,o)},function(o){return _(e,t,o)}):I(e,t,s)}function I(e,t,s){t.status="fulfilled",t.value=s,te(t),e.state=s,t=e.pending,t!==null&&(s=t.next,s===t?e.pending=null:(s=s.next,t.next=s,C(e,s)))}function _(e,t,s){var o=e.pending;if(e.pending=null,o!==null){o=o.next;do t.status="rejected",t.reason=s,te(t),t=t.next;while(t!==o)}e.action=null}function te(e){e=e.listeners;for(var t=0;t<e.length;t++)(0,e[t])()}function ie(e,t){return t}function Me(e,t){if(wt){var s=tn.formState;if(s!==null){e:{var o=et;if(wt){if(Gt){t:{for(var f=Gt,p=xa;f.nodeType!==8;){if(!p){f=null;break t}if(f=$s(f.nextSibling),f===null){f=null;break t}}p=f.data,f=p==="F!"||p==="F"?f:null}if(f){Gt=$s(f.nextSibling),o=f.data==="F!";break e}}sr(o)}o=!1}o&&(t=s[0])}}return s=$t(),s.memoizedState=s.baseState=t,o={pending:null,lanes:0,dispatch:null,lastRenderedReducer:ie,lastRenderedState:t},s.queue=o,s=ug.bind(null,et,o),o.dispatch=s,o=mr(!1),p=um.bind(null,et,!1,o.queue),o=$t(),f={state:t,dispatch:null,action:e,pending:null},o.queue=f,s=v.bind(null,et,f,p,s),f.dispatch=s,o.memoizedState=e,[t,s,!1]}function Re(e){var t=on();return qe(t,St,e)}function qe(e,t,s){if(t=pi(e,t,ie)[0],e=hi(Fs)[0],typeof t=="object"&&t!==null&&typeof t.then=="function")try{var o=Yo(t)}catch(S){throw S===Nr?Hl:S}else o=t;t=on();var f=t.queue,p=f.dispatch;return s!==t.memoizedState&&(et.flags|=2048,en(9,{destroy:void 0},Bt.bind(null,f,s),null)),[o,p,e]}function Bt(e,t){e.action=t}function bt(e){var t=on(),s=St;if(s!==null)return qe(t,s,e);on(),t=t.memoizedState,s=on();var o=s.queue.dispatch;return s.memoizedState=e,[t,o,!1]}function en(e,t,s,o){return e={tag:e,create:s,deps:o,inst:t,next:null},t=et.updateQueue,t===null&&(t=Wo(),et.updateQueue=t),s=t.lastEffect,s===null?t.lastEffect=e.next=e:(o=s.next,s.next=e,e.next=o,t.lastEffect=e),e}function Ca(){return on().memoizedState}function Kn(e,t,s,o){var f=$t();et.flags|=e,f.memoizedState=en(1|t,{destroy:void 0},s,o===void 0?null:o)}function Za(e,t,s,o){var f=on();o=o===void 0?null:o;var p=f.memoizedState.inst;St!==null&&o!==null&&Zc(o,St.memoizedState.deps)?f.memoizedState=en(t,p,s,o):(et.flags|=e,f.memoizedState=en(1|t,p,s,o))}function vi(e,t){Kn(8390656,8,e,t)}function el(e,t){Za(2048,8,e,t)}function Zw(e){et.flags|=4;var t=et.updateQueue;if(t===null)t=Wo(),et.updateQueue=t,t.events=[e];else{var s=t.events;s===null?t.events=[e]:s.push(e)}}function Xp(e){var t=on().memoizedState;return Zw({ref:t,nextImpl:e}),function(){if((Pt&2)!==0)throw Error(l(440));return t.impl.apply(void 0,arguments)}}function Zp(e,t){return Za(4,2,e,t)}function Jp(e,t){return Za(4,4,e,t)}function eg(e,t){if(typeof t=="function"){e=e();var s=t(e);return function(){typeof s=="function"?s():t(null)}}if(t!=null)return e=e(),t.current=e,function(){t.current=null}}function tg(e,t,s){s=s!=null?s.concat([e]):null,Za(4,4,eg.bind(null,t,e),s)}function im(){}function ng(e,t){var s=on();t=t===void 0?null:t;var o=s.memoizedState;return t!==null&&Zc(t,o[1])?o[0]:(s.memoizedState=[e,t],e)}function ag(e,t){var s=on();t=t===void 0?null:t;var o=s.memoizedState;if(t!==null&&Zc(t,o[1]))return o[0];if(o=e(),Xa){ft(!0);try{e()}finally{ft(!1)}}return s.memoizedState=[o,t],o}function lm(e,t,s){return s===void 0||(Qa&1073741824)!==0&&(Lt&261930)===0?e.memoizedState=t:(e.memoizedState=s,e=sv(),et.lanes|=e,al|=e,s)}function sg(e,t,s,o){return an(s,t)?s:fi.current!==null?(e=lm(e,s,o),an(e,t)||(Ln=!0),e):(Qa&42)===0||(Qa&1073741824)!==0&&(Lt&261930)===0?(Ln=!0,e.memoizedState=s):(e=sv(),et.lanes|=e,al|=e,t)}function rg(e,t,s,o,f){var p=se.p;se.p=p!==0&&8>p?p:8;var S=z.T,R={};z.T=R,um(e,!1,t,s);try{var V=f(),ue=z.S;if(ue!==null&&ue(R,V),V!==null&&typeof V=="object"&&typeof V.then=="function"){var xe=Wc(V,o);nu(e,t,xe,ps(e))}else nu(e,t,o,ps(e))}catch(Ce){nu(e,t,{then:function(){},status:"rejected",reason:Ce},ps())}finally{se.p=p,S!==null&&R.types!==null&&(S.types=R.types),z.T=S}}function Jw(){}function om(e,t,s,o){if(e.tag!==5)throw Error(l(476));var f=ig(e).queue;rg(e,f,t,W,s===null?Jw:function(){return lg(e),s(o)})}function ig(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:W,baseState:W,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Fs,lastRenderedState:W},next:null};var s={};return t.next={memoizedState:s,baseState:s,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Fs,lastRenderedState:s},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function lg(e){var t=ig(e);t.next===null&&(t=e.alternate.memoizedState),nu(e,t.next.queue,{},ps())}function cm(){return ln(bu)}function og(){return on().memoizedState}function cg(){return on().memoizedState}function eS(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var s=ps();e=dr(s);var o=Os(t,e,s);o!==null&&(as(o,t,s),Ul(o,t,s)),t={cache:Oo()},e.payload=t;return}t=t.return}}function tS(e,t,s){var o=ps();s={lane:o,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null},gd(e)?dg(t,s):(s=La(e,t,s,o),s!==null&&(as(s,e,o),fg(s,t,o)))}function ug(e,t,s){var o=ps();nu(e,t,s,o)}function nu(e,t,s,o){var f={lane:o,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null};if(gd(e))dg(t,f);else{var p=e.alternate;if(e.lanes===0&&(p===null||p.lanes===0)&&(p=t.lastRenderedReducer,p!==null))try{var S=t.lastRenderedState,R=p(S,s);if(f.hasEagerState=!0,f.eagerState=R,an(R,S))return To(e,t,f,0),tn===null&&ar(),!1}catch{}if(s=La(e,t,f,o),s!==null)return as(s,e,o),fg(s,t,o),!0}return!1}function um(e,t,s,o){if(o={lane:2,revertLane:Pm(),gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null},gd(e)){if(t)throw Error(l(479))}else t=La(e,s,o,2),t!==null&&as(t,e,2)}function gd(e){var t=e.alternate;return e===et||t!==null&&t===et}function dg(e,t){fs=qo=!0;var s=e.pending;s===null?t.next=t:(t.next=s.next,s.next=t),e.pending=t}function fg(e,t,s){if((s&4194048)!==0){var o=t.lanes;o&=e.pendingLanes,s|=o,t.lanes=s,B(e,s)}}var au={readContext:ln,use:Ko,useCallback:Jt,useContext:Jt,useEffect:Jt,useImperativeHandle:Jt,useLayoutEffect:Jt,useInsertionEffect:Jt,useMemo:Jt,useReducer:Jt,useRef:Jt,useState:Jt,useDebugValue:Jt,useDeferredValue:Jt,useTransition:Jt,useSyncExternalStore:Jt,useId:Jt,useHostTransitionStatus:Jt,useFormState:Jt,useActionState:Jt,useOptimistic:Jt,useMemoCache:Jt,useCacheRefresh:Jt};au.useEffectEvent=Jt;var mg={readContext:ln,use:Ko,useCallback:function(e,t){return $t().memoizedState=[e,t===void 0?null:t],e},useContext:ln,useEffect:vi,useImperativeHandle:function(e,t,s){s=s!=null?s.concat([e]):null,Kn(4194308,4,eg.bind(null,t,e),s)},useLayoutEffect:function(e,t){return Kn(4194308,4,e,t)},useInsertionEffect:function(e,t){Kn(4,2,e,t)},useMemo:function(e,t){var s=$t();t=t===void 0?null:t;var o=e();if(Xa){ft(!0);try{e()}finally{ft(!1)}}return s.memoizedState=[o,t],o},useReducer:function(e,t,s){var o=$t();if(s!==void 0){var f=s(t);if(Xa){ft(!0);try{s(t)}finally{ft(!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=tS.bind(null,et,e),[o.memoizedState,e]},useRef:function(e){var t=$t();return e={current:e},t.memoizedState=e},useState:function(e){e=mr(e);var t=e.queue,s=ug.bind(null,et,t);return t.dispatch=s,[e.memoizedState,s]},useDebugValue:im,useDeferredValue:function(e,t){var s=$t();return lm(s,e,t)},useTransition:function(){var e=mr(!1);return e=rg.bind(null,et,e.queue,!0,!1),$t().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,s){var o=et,f=$t();if(wt){if(s===void 0)throw Error(l(407));s=s()}else{if(s=t(),tn===null)throw Error(l(349));(Lt&127)!==0||md(o,t,s)}f.memoizedState=s;var p={value:s,getSnapshot:t};return f.queue=p,vi(Xo.bind(null,o,p,e),[e]),o.flags|=2048,en(9,{destroy:void 0},hd.bind(null,o,p,s,t),null),s},useId:function(){var e=$t(),t=tn.identifierPrefix;if(wt){var s=us,o=Es;s=(o&~(1<<32-xt(o)-1)).toString(32)+s,t="_"+t+"R_"+s,s=Kl++,0<s&&(t+="H"+s.toString(32)),t+="_"}else s=Ql++,t="_"+t+"r_"+s.toString(32)+"_";return e.memoizedState=t},useHostTransitionStatus:cm,useFormState:Me,useActionState:Me,useOptimistic:function(e){var t=$t();t.memoizedState=t.baseState=e;var s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return t.queue=s,t=um.bind(null,et,!0,s),s.dispatch=t,[e,t]},useMemoCache:tu,useCacheRefresh:function(){return $t().memoizedState=eS.bind(null,et)},useEffectEvent:function(e){var t=$t(),s={impl:e};return t.memoizedState=s,function(){if((Pt&2)!==0)throw Error(l(440));return s.impl.apply(void 0,arguments)}}},dm={readContext:ln,use:Ko,useCallback:ng,useContext:ln,useEffect:el,useImperativeHandle:tg,useInsertionEffect:Zp,useLayoutEffect:Jp,useMemo:ag,useReducer:hi,useRef:Ca,useState:function(){return hi(Fs)},useDebugValue:im,useDeferredValue:function(e,t){var s=on();return sg(s,St.memoizedState,e,t)},useTransition:function(){var e=hi(Fs)[0],t=on().memoizedState;return[typeof e=="boolean"?e:Yo(e),t]},useSyncExternalStore:fd,useId:og,useHostTransitionStatus:cm,useFormState:Re,useActionState:Re,useOptimistic:function(e,t){var s=on();return Zo(s,St,e,t)},useMemoCache:tu,useCacheRefresh:cg};dm.useEffectEvent=Xp;var hg={readContext:ln,use:Ko,useCallback:ng,useContext:ln,useEffect:el,useImperativeHandle:tg,useInsertionEffect:Zp,useLayoutEffect:Jp,useMemo:ag,useReducer:Qo,useRef:Ca,useState:function(){return Qo(Fs)},useDebugValue:im,useDeferredValue:function(e,t){var s=on();return St===null?lm(s,e,t):sg(s,St.memoizedState,e,t)},useTransition:function(){var e=Qo(Fs)[0],t=on().memoizedState;return[typeof e=="boolean"?e:Yo(e),t]},useSyncExternalStore:fd,useId:og,useHostTransitionStatus:cm,useFormState:bt,useActionState:bt,useOptimistic:function(e,t){var s=on();return St!==null?Zo(s,St,e,t):(s.baseState=e,[e,s.queue.dispatch])},useMemoCache:tu,useCacheRefresh:cg};hg.useEffectEvent=Xp;function fm(e,t,s,o){t=e.memoizedState,s=s(o,t),s=s==null?t:b({},t,s),e.memoizedState=s,e.lanes===0&&(e.updateQueue.baseState=s)}var mm={enqueueSetState:function(e,t,s){e=e._reactInternals;var o=ps(),f=dr(o);f.payload=t,s!=null&&(f.callback=s),t=Os(e,f,o),t!==null&&(as(t,e,o),Ul(t,e,o))},enqueueReplaceState:function(e,t,s){e=e._reactInternals;var o=ps(),f=dr(o);f.tag=1,f.payload=t,s!=null&&(f.callback=s),t=Os(e,f,o),t!==null&&(as(t,e,o),Ul(t,e,o))},enqueueForceUpdate:function(e,t){e=e._reactInternals;var s=ps(),o=dr(s);o.tag=2,t!=null&&(o.callback=t),t=Os(e,o,s),t!==null&&(as(t,e,s),Ul(t,e,s))}};function pg(e,t,s,o,f,p,S){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(o,p,S):t.prototype&&t.prototype.isPureReactComponent?!Ee(s,o)||!Ee(f,p):!0}function gg(e,t,s,o){e=t.state,typeof t.componentWillReceiveProps=="function"&&t.componentWillReceiveProps(s,o),typeof t.UNSAFE_componentWillReceiveProps=="function"&&t.UNSAFE_componentWillReceiveProps(s,o),t.state!==e&&mm.enqueueReplaceState(t,t.state,null)}function Zl(e,t){var s=t;if("ref"in t){s={};for(var o in t)o!=="ref"&&(s[o]=t[o])}if(e=e.defaultProps){s===t&&(s=b({},s));for(var f in e)s[f]===void 0&&(s[f]=e[f])}return s}function vg(e){Bn(e)}function yg(e){console.error(e)}function bg(e){Bn(e)}function vd(e,t){try{var s=e.onUncaughtError;s(t.value,{componentStack:t.stack})}catch(o){setTimeout(function(){throw o})}}function xg(e,t,s){try{var o=e.onCaughtError;o(s.value,{componentStack:s.stack,errorBoundary:t.tag===1?t.stateNode:null})}catch(f){setTimeout(function(){throw f})}}function hm(e,t,s){return s=dr(s),s.tag=3,s.payload={element:null},s.callback=function(){vd(e,t)},s}function wg(e){return e=dr(e),e.tag=3,e}function Sg(e,t,s,o){var f=s.type.getDerivedStateFromError;if(typeof f=="function"){var p=o.value;e.payload=function(){return f(p)},e.callback=function(){xg(t,s,o)}}var S=s.stateNode;S!==null&&typeof S.componentDidCatch=="function"&&(e.callback=function(){xg(t,s,o),typeof f!="function"&&(sl===null?sl=new Set([this]):sl.add(this));var R=o.stack;this.componentDidCatch(o.value,{componentStack:R!==null?R:""})})}function nS(e,t,s,o,f){if(s.flags|=32768,o!==null&&typeof o=="object"&&typeof o.then=="function"){if(t=s.alternate,t!==null&&ii(t,s,f,!0),s=wa.current,s!==null){switch(s.tag){case 31:case 13:return Sa===null?Td():s.alternate===null&&bn===0&&(bn=3),s.flags&=-257,s.flags|=65536,s.lanes=f,o===Dn?s.flags|=16384:(t=s.updateQueue,t===null?s.updateQueue=new Set([o]):t.add(o),Fm(e,o,f)),!1;case 22:return s.flags|=65536,o===Dn?s.flags|=16384:(t=s.updateQueue,t===null?(t={transitions:null,markerInstances:null,retryQueue:new Set([o])},s.updateQueue=t):(s=t.retryQueue,s===null?t.retryQueue=new Set([o]):s.add(o)),Fm(e,o,f)),!1}throw Error(l(435,s.tag))}return Fm(e,o,f),Td(),!1}if(wt)return t=wa.current,t!==null?((t.flags&65536)===0&&(t.flags|=256),t.flags|=65536,t.lanes=f,o!==Vc&&(e=Error(l(422),{cause:o}),Ki(Pn(e,s)))):(o!==Vc&&(t=Error(l(423),{cause:o}),Ki(Pn(t,s))),e=e.current.alternate,e.flags|=65536,f&=-f,e.lanes|=f,o=Pn(o,s),f=hm(e.stateNode,o,f),di(e,f),bn!==4&&(bn=2)),!1;var p=Error(l(520),{cause:o});if(p=Pn(p,s),du===null?du=[p]:du.push(p),bn!==4&&(bn=2),t===null)return!0;o=Pn(o,s),s=t;do{switch(s.tag){case 3:return s.flags|=65536,e=f&-f,s.lanes|=e,e=hm(s.stateNode,o,e),di(s,e),!1;case 1:if(t=s.type,p=s.stateNode,(s.flags&128)===0&&(typeof t.getDerivedStateFromError=="function"||p!==null&&typeof p.componentDidCatch=="function"&&(sl===null||!sl.has(p))))return s.flags|=65536,f&=-f,s.lanes|=f,f=wg(f),Sg(f,e,s,o),di(s,f),!1}s=s.return}while(s!==null);return!1}var pm=Error(l(461)),Ln=!1;function da(e,t,s,o){t.child=e===null?cd(t,null,s,o):ci(t,e.child,s,o)}function Cg(e,t,s,o,f){s=s.render;var p=t.ref;if("ref"in o){var S={};for(var R in o)R!=="ref"&&(S[R]=o[R])}else S=o;return Ka(t),o=Go(e,t,s,S,p,f),R=Xl(),e!==null&&!Ln?(Jc(e,t,f),yi(e,t,f)):(wt&&R&&Lo(t),t.flags|=1,da(e,t,o,f),t.child)}function kg(e,t,s,o,f){if(e===null){var p=s.type;return typeof p=="function"&&!Ts(p)&&p.defaultProps===void 0&&s.compare===null?(t.tag=15,t.type=p,jg(e,t,p,o,f)):(e=qa(s.type,null,o,t,t.mode,f),e.ref=t.ref,e.return=t,t.child=e)}if(p=e.child,!Cm(e,f)){var S=p.memoizedProps;if(s=s.compare,s=s!==null?s:Ee,s(S,o)&&e.ref===t.ref)return yi(e,t,f)}return t.flags|=1,e=ya(p,o),e.ref=t.ref,e.return=t,t.child=e}function jg(e,t,s,o,f){if(e!==null){var p=e.memoizedProps;if(Ee(p,o)&&e.ref===t.ref)if(Ln=!1,t.pendingProps=o=p,Cm(e,f))(e.flags&131072)!==0&&(Ln=!0);else return t.lanes=e.lanes,yi(e,t,f)}return gm(e,t,s,o,f)}function Ag(e,t,s,o){var f=o.children,p=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(p=p!==null?p.baseLanes|s:s,e!==null){for(o=t.child=e.child,f=0;o!==null;)f=f|o.lanes|o.childLanes,o=o.sibling;o=f&~p}else o=0,t.child=null;return Mg(e,t,p,s,o)}if((s&536870912)!==0)t.memoizedState={baseLanes:0,cachePool:null},e!==null&&Mr(t,p!==null?p.cachePool:null),p!==null?ud(t,p):Wl(),Yl(t);else return o=t.lanes=536870912,Mg(e,t,p!==null?p.baseLanes|s:s,s,o)}else p!==null?(Mr(t,p.cachePool),ud(t,p),fr(),t.memoizedState=null):(e!==null&&Mr(t,null),Wl(),fr());return da(e,t,f,s),t.child}function su(e,t){return e!==null&&e.tag===22||t.stateNode!==null||(t.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),t.sibling}function Mg(e,t,s,o,f){var p=$o();return p=p===null?null:{parent:jn._currentValue,pool:p},t.memoizedState={baseLanes:s,cachePool:p},e!==null&&Mr(t,null),Wl(),Yl(t),e!==null&&ii(e,t,o,!0),t.childLanes=f,null}function yd(e,t){return t=xd({mode:t.mode,children:t.children},e.mode),t.ref=e.ref,e.child=t,t.return=e,t}function Ng(e,t,s){return ci(t,e.child,null,s),e=yd(t,t.pendingProps),e.flags|=2,Oa(t),t.memoizedState=null,e}function aS(e,t,s){var o=t.pendingProps,f=(t.flags&128)!==0;if(t.flags&=-129,e===null){if(wt){if(o.mode==="hidden")return e=yd(t,o),t.lanes=536870912,su(null,e);if(ze(t),(e=Gt)?(e=$v(e,xa),e=e!==null&&e.data==="&"?e:null,e!==null&&(t.memoizedState={dehydrated:e,treeContext:kr!==null?{id:Es,overflow:us}:null,retryLane:536870912,hydrationErrors:null},s=Il(e),s.return=t,t.child=s,rn=t,Gt=null)):e=null,e===null)throw sr(t);return t.lanes=536870912,null}return yd(t,o)}var p=e.memoizedState;if(p!==null){var S=p.dehydrated;if(ze(t),f)if(t.flags&256)t.flags&=-257,t=Ng(e,t,s);else if(t.memoizedState!==null)t.child=e.child,t.flags|=128,t=null;else throw Error(l(558));else if(Ln||ii(e,t,s,!1),f=(s&e.childLanes)!==0,Ln||f){if(o=tn,o!==null&&(S=Ke(o,s),S!==0&&S!==p.retryLane))throw p.retryLane=S,_a(e,S),as(o,e,S),pm;Td(),t=Ng(e,t,s)}else e=p.treeContext,Gt=$s(S.nextSibling),rn=t,wt=!0,ba=null,xa=!1,e!==null&&Gc(t,e),t=yd(t,o),t.flags|=4096;return t}return e=ya(e.child,{mode:o.mode,children:o.children}),e.ref=t.ref,t.child=e,e.return=t,e}function bd(e,t){var s=t.ref;if(s===null)e!==null&&e.ref!==null&&(t.flags|=4194816);else{if(typeof s!="function"&&typeof s!="object")throw Error(l(284));(e===null||e.ref!==s)&&(t.flags|=4194816)}}function gm(e,t,s,o,f){return Ka(t),s=Go(e,t,s,o,void 0,f),o=Xl(),e!==null&&!Ln?(Jc(e,t,f),yi(e,t,f)):(wt&&o&&Lo(t),t.flags|=1,da(e,t,s,f),t.child)}function Tg(e,t,s,o,f,p){return Ka(t),t.updateQueue=null,s=dd(t,o,s,f),Vo(e),o=Xl(),e!==null&&!Ln?(Jc(e,t,p),yi(e,t,p)):(wt&&o&&Lo(t),t.flags|=1,da(e,t,s,p),t.child)}function Rg(e,t,s,o,f){if(Ka(t),t.stateNode===null){var p=ca,S=s.contextType;typeof S=="object"&&S!==null&&(p=ln(S)),p=new s(o,p),t.memoizedState=p.state!==null&&p.state!==void 0?p.state:null,p.updater=mm,t.stateNode=p,p._reactInternals=t,p=t.stateNode,p.props=o,p.state=t.memoizedState,p.refs={},Pl(t),S=s.contextType,p.context=typeof S=="object"&&S!==null?ln(S):ca,p.state=t.memoizedState,S=s.getDerivedStateFromProps,typeof S=="function"&&(fm(t,s,S,o),p.state=t.memoizedState),typeof s.getDerivedStateFromProps=="function"||typeof p.getSnapshotBeforeUpdate=="function"||typeof p.UNSAFE_componentWillMount!="function"&&typeof p.componentWillMount!="function"||(S=p.state,typeof p.componentWillMount=="function"&&p.componentWillMount(),typeof p.UNSAFE_componentWillMount=="function"&&p.UNSAFE_componentWillMount(),S!==p.state&&mm.enqueueReplaceState(p,p.state,null),Gl(t,o,p,f),ql(),p.state=t.memoizedState),typeof p.componentDidMount=="function"&&(t.flags|=4194308),o=!0}else if(e===null){p=t.stateNode;var R=t.memoizedProps,V=Zl(s,R);p.props=V;var ue=p.context,xe=s.contextType;S=ca,typeof xe=="object"&&xe!==null&&(S=ln(xe));var Ce=s.getDerivedStateFromProps;xe=typeof Ce=="function"||typeof p.getSnapshotBeforeUpdate=="function",R=t.pendingProps!==R,xe||typeof p.UNSAFE_componentWillReceiveProps!="function"&&typeof p.componentWillReceiveProps!="function"||(R||ue!==S)&&gg(t,p,o,S),zs=!1;var me=t.memoizedState;p.state=me,Gl(t,o,p,f),ql(),ue=t.memoizedState,R||me!==ue||zs?(typeof Ce=="function"&&(fm(t,s,Ce,o),ue=t.memoizedState),(V=zs||pg(t,s,V,o,me,ue,S))?(xe||typeof p.UNSAFE_componentWillMount!="function"&&typeof p.componentWillMount!="function"||(typeof p.componentWillMount=="function"&&p.componentWillMount(),typeof p.UNSAFE_componentWillMount=="function"&&p.UNSAFE_componentWillMount()),typeof p.componentDidMount=="function"&&(t.flags|=4194308)):(typeof p.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=o,t.memoizedState=ue),p.props=o,p.state=ue,p.context=S,o=V):(typeof p.componentDidMount=="function"&&(t.flags|=4194308),o=!1)}else{p=t.stateNode,ui(e,t),S=t.memoizedProps,xe=Zl(s,S),p.props=xe,Ce=t.pendingProps,me=p.context,ue=s.contextType,V=ca,typeof ue=="object"&&ue!==null&&(V=ln(ue)),R=s.getDerivedStateFromProps,(ue=typeof R=="function"||typeof p.getSnapshotBeforeUpdate=="function")||typeof p.UNSAFE_componentWillReceiveProps!="function"&&typeof p.componentWillReceiveProps!="function"||(S!==Ce||me!==V)&&gg(t,p,o,V),zs=!1,me=t.memoizedState,p.state=me,Gl(t,o,p,f),ql();var ge=t.memoizedState;S!==Ce||me!==ge||zs||e!==null&&e.dependencies!==null&&lr(e.dependencies)?(typeof R=="function"&&(fm(t,s,R,o),ge=t.memoizedState),(xe=zs||pg(t,s,xe,o,me,ge,V)||e!==null&&e.dependencies!==null&&lr(e.dependencies))?(ue||typeof p.UNSAFE_componentWillUpdate!="function"&&typeof p.componentWillUpdate!="function"||(typeof p.componentWillUpdate=="function"&&p.componentWillUpdate(o,ge,V),typeof p.UNSAFE_componentWillUpdate=="function"&&p.UNSAFE_componentWillUpdate(o,ge,V)),typeof p.componentDidUpdate=="function"&&(t.flags|=4),typeof p.getSnapshotBeforeUpdate=="function"&&(t.flags|=1024)):(typeof p.componentDidUpdate!="function"||S===e.memoizedProps&&me===e.memoizedState||(t.flags|=4),typeof p.getSnapshotBeforeUpdate!="function"||S===e.memoizedProps&&me===e.memoizedState||(t.flags|=1024),t.memoizedProps=o,t.memoizedState=ge),p.props=o,p.state=ge,p.context=V,o=xe):(typeof p.componentDidUpdate!="function"||S===e.memoizedProps&&me===e.memoizedState||(t.flags|=4),typeof p.getSnapshotBeforeUpdate!="function"||S===e.memoizedProps&&me===e.memoizedState||(t.flags|=1024),o=!1)}return p=o,bd(e,t),o=(t.flags&128)!==0,p||o?(p=t.stateNode,s=o&&typeof s.getDerivedStateFromError!="function"?null:p.render(),t.flags|=1,e!==null&&o?(t.child=ci(t,e.child,null,f),t.child=ci(t,null,s,f)):da(e,t,s,f),t.memoizedState=p.state,e=t.child):e=yi(e,t,f),e}function Eg(e,t,s,o){return si(),t.flags|=256,da(e,t,s,o),t.child}var vm={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function ym(e){return{baseLanes:e,cachePool:Ls()}}function bm(e,t,s){return e=e!==null?e.childLanes&~s:0,t&&(e|=hs),e}function Dg(e,t,s){var o=t.pendingProps,f=!1,p=(t.flags&128)!==0,S;if((S=p)||(S=e!==null&&e.memoizedState===null?!1:(yn.current&2)!==0),S&&(f=!0,t.flags&=-129),S=(t.flags&32)!==0,t.flags&=-33,e===null){if(wt){if(f?Hs(t):fr(),(e=Gt)?(e=$v(e,xa),e=e!==null&&e.data!=="&"?e:null,e!==null&&(t.memoizedState={dehydrated:e,treeContext:kr!==null?{id:Es,overflow:us}:null,retryLane:536870912,hydrationErrors:null},s=Il(e),s.return=t,t.child=s,rn=t,Gt=null)):e=null,e===null)throw sr(t);return th(e)?t.lanes=32:t.lanes=536870912,null}var R=o.children;return o=o.fallback,f?(fr(),f=t.mode,R=xd({mode:"hidden",children:R},f),o=Cr(o,f,s,null),R.return=t,o.return=t,R.sibling=o,t.child=R,o=t.child,o.memoizedState=ym(s),o.childLanes=bm(e,S,s),t.memoizedState=vm,su(null,o)):(Hs(t),xm(t,R))}var V=e.memoizedState;if(V!==null&&(R=V.dehydrated,R!==null)){if(p)t.flags&256?(Hs(t),t.flags&=-257,t=wm(e,t,s)):t.memoizedState!==null?(fr(),t.child=e.child,t.flags|=128,t=null):(fr(),R=o.fallback,f=t.mode,o=xd({mode:"visible",children:o.children},f),R=Cr(R,f,s,null),R.flags|=2,o.return=t,R.return=t,o.sibling=R,t.child=o,ci(t,e.child,null,s),o=t.child,o.memoizedState=ym(s),o.childLanes=bm(e,S,s),t.memoizedState=vm,t=su(null,o));else if(Hs(t),th(R)){if(S=R.nextSibling&&R.nextSibling.dataset,S)var ue=S.dgst;S=ue,o=Error(l(419)),o.stack="",o.digest=S,Ki({value:o,source:null,stack:null}),t=wm(e,t,s)}else if(Ln||ii(e,t,s,!1),S=(s&e.childLanes)!==0,Ln||S){if(S=tn,S!==null&&(o=Ke(S,s),o!==0&&o!==V.retryLane))throw V.retryLane=o,_a(e,o),as(S,e,o),pm;eh(R)||Td(),t=wm(e,t,s)}else eh(R)?(t.flags|=192,t.child=e.child,t=null):(e=V.treeContext,Gt=$s(R.nextSibling),rn=t,wt=!0,ba=null,xa=!1,e!==null&&Gc(t,e),t=xm(t,o.children),t.flags|=4096);return t}return f?(fr(),R=o.fallback,f=t.mode,V=e.child,ue=V.sibling,o=ya(V,{mode:"hidden",children:o.children}),o.subtreeFlags=V.subtreeFlags&65011712,ue!==null?R=ya(ue,R):(R=Cr(R,f,s,null),R.flags|=2),R.return=t,o.return=t,o.sibling=R,t.child=o,su(null,o),o=t.child,R=e.child.memoizedState,R===null?R=ym(s):(f=R.cachePool,f!==null?(V=jn._currentValue,f=f.parent!==V?{parent:V,pool:V}:f):f=Ls(),R={baseLanes:R.baseLanes|s,cachePool:f}),o.memoizedState=R,o.childLanes=bm(e,S,s),t.memoizedState=vm,su(e.child,o)):(Hs(t),s=e.child,e=s.sibling,s=ya(s,{mode:"visible",children:o.children}),s.return=t,s.sibling=null,e!==null&&(S=t.deletions,S===null?(t.deletions=[e],t.flags|=16):S.push(e)),t.child=s,t.memoizedState=null,s)}function xm(e,t){return t=xd({mode:"visible",children:t},e.mode),t.return=e,e.child=t}function xd(e,t){return e=En(22,e,null,t),e.lanes=0,e}function wm(e,t,s){return ci(t,e.child,null,s),e=xm(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function Lg(e,t,s){e.lanes|=t;var o=e.alternate;o!==null&&(o.lanes|=t),ir(e.return,t,s)}function Sm(e,t,s,o,f,p){var S=e.memoizedState;S===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:o,tail:s,tailMode:f,treeForkCount:p}:(S.isBackwards=t,S.rendering=null,S.renderingStartTime=0,S.last=o,S.tail=s,S.tailMode=f,S.treeForkCount=p)}function _g(e,t,s){var o=t.pendingProps,f=o.revealOrder,p=o.tail;o=o.children;var S=yn.current,R=(S&2)!==0;if(R?(S=S&1|2,t.flags|=128):S&=1,be(yn,S),da(e,t,o,s),o=wt?Rs:0,!R&&e!==null&&(e.flags&128)!==0)e:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&Lg(e,s,t);else if(e.tag===19)Lg(e,s,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(s=t.child,f=null;s!==null;)e=s.alternate,e!==null&&Zi(e)===null&&(f=s),s=s.sibling;s=f,s===null?(f=t.child,t.child=null):(f=s.sibling,s.sibling=null),Sm(t,!1,f,s,p,o);break;case"backwards":case"unstable_legacy-backwards":for(s=null,f=t.child,t.child=null;f!==null;){if(e=f.alternate,e!==null&&Zi(e)===null){t.child=f;break}e=f.sibling,f.sibling=s,s=f,f=e}Sm(t,!0,s,null,p,o);break;case"together":Sm(t,!1,null,null,void 0,o);break;default:t.memoizedState=null}return t.child}function yi(e,t,s){if(e!==null&&(t.dependencies=e.dependencies),al|=t.lanes,(s&t.childLanes)===0)if(e!==null){if(ii(e,t,s,!1),(s&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,s=ya(e,e.pendingProps),t.child=s,s.return=t;e.sibling!==null;)e=e.sibling,s=s.sibling=ya(e,e.pendingProps),s.return=t;s.sibling=null}return t.child}function Cm(e,t){return(e.lanes&t)!==0?!0:(e=e.dependencies,!!(e!==null&&lr(e)))}function sS(e,t,s){switch(t.tag){case 3:Ne(t,t.stateNode.containerInfo),ds(t,jn,e.memoizedState.cache),si();break;case 27:case 5:ne(t);break;case 4:Ne(t,t.stateNode.containerInfo);break;case 10:ds(t,t.type,t.memoizedProps.value);break;case 31:if(t.memoizedState!==null)return t.flags|=128,ze(t),null;break;case 13:var o=t.memoizedState;if(o!==null)return o.dehydrated!==null?(Hs(t),t.flags|=128,null):(s&t.child.childLanes)!==0?Dg(e,t,s):(Hs(t),e=yi(e,t,s),e!==null?e.sibling:null);Hs(t);break;case 19:var f=(e.flags&128)!==0;if(o=(s&t.childLanes)!==0,o||(ii(e,t,s,!1),o=(s&t.childLanes)!==0),f){if(o)return _g(e,t,s);t.flags|=128}if(f=t.memoizedState,f!==null&&(f.rendering=null,f.tail=null,f.lastEffect=null),be(yn,yn.current),o)break;return null;case 22:return t.lanes=0,Ag(e,t,s,t.pendingProps);case 24:ds(t,jn,e.memoizedState.cache)}return yi(e,t,s)}function Ig(e,t,s){if(e!==null)if(e.memoizedProps!==t.pendingProps)Ln=!0;else{if(!Cm(e,s)&&(t.flags&128)===0)return Ln=!1,sS(e,t,s);Ln=(e.flags&131072)!==0}else Ln=!1,wt&&(t.flags&1048576)!==0&&rd(t,Rs,t.index);switch(t.lanes=0,t.tag){case 16:e:{var o=t.pendingProps;if(e=_s(t.elementType),t.type=e,typeof e=="function")Ts(e)?(o=Zl(e,o),t.tag=1,t=Rg(null,t,e,o,s)):(t.tag=0,t=gm(null,t,e,o,s));else{if(e!=null){var f=e.$$typeof;if(f===F){t.tag=11,t=Cg(null,t,e,o,s);break e}else if(f===L){t.tag=14,t=kg(null,t,e,o,s);break e}}throw t=de(e)||e,Error(l(306,t,""))}}return t;case 0:return gm(e,t,t.type,t.pendingProps,s);case 1:return o=t.type,f=Zl(o,t.pendingProps),Rg(e,t,o,f,s);case 3:e:{if(Ne(t,t.stateNode.containerInfo),e===null)throw Error(l(387));o=t.pendingProps;var p=t.memoizedState;f=p.element,ui(e,t),Gl(t,o,null,s);var S=t.memoizedState;if(o=S.cache,ds(t,jn,o),o!==p.cache&&Io(t,[jn],s,!0),ql(),o=S.element,p.isDehydrated)if(p={element:o,isDehydrated:!1,cache:S.cache},t.updateQueue.baseState=p,t.memoizedState=p,t.flags&256){t=Eg(e,t,o,s);break e}else if(o!==f){f=Pn(Error(l(424)),t),Ki(f),t=Eg(e,t,o,s);break e}else for(e=t.stateNode.containerInfo,e.nodeType===9?e=e.body:e=e.nodeName==="HTML"?e.ownerDocument.body:e,Gt=$s(e.firstChild),rn=t,wt=!0,ba=null,xa=!0,s=cd(t,null,o,s),t.child=s;s;)s.flags=s.flags&-3|4096,s=s.sibling;else{if(si(),o===f){t=yi(e,t,s);break e}da(e,t,o,s)}t=t.child}return t;case 26:return bd(e,t),e===null?(s=Vv(t.type,null,t.pendingProps,null))?t.memoizedState=s:wt||(s=t.type,e=t.pendingProps,o=zd(ee.current).createElement(s),o[re]=t,o[Te]=e,fa(o,s,e),At(o),t.stateNode=o):t.memoizedState=Vv(t.type,e.memoizedProps,t.pendingProps,e.memoizedState),null;case 27:return ne(t),e===null&&wt&&(o=t.stateNode=Uv(t.type,t.pendingProps,ee.current),rn=t,xa=!0,f=Gt,ol(t.type)?(nh=f,Gt=$s(o.firstChild)):Gt=f),da(e,t,t.pendingProps.children,s),bd(e,t),e===null&&(t.flags|=4194304),t.child;case 5:return e===null&&wt&&((f=o=Gt)&&(o=_S(o,t.type,t.pendingProps,xa),o!==null?(t.stateNode=o,rn=t,Gt=$s(o.firstChild),xa=!1,f=!0):f=!1),f||sr(t)),ne(t),f=t.type,p=t.pendingProps,S=e!==null?e.memoizedProps:null,o=p.children,Xm(f,p)?o=null:S!==null&&Xm(f,S)&&(t.flags|=32),t.memoizedState!==null&&(f=Go(e,t,rm,null,null,s),bu._currentValue=f),bd(e,t),da(e,t,o,s),t.child;case 6:return e===null&&wt&&((e=s=Gt)&&(s=IS(s,t.pendingProps,xa),s!==null?(t.stateNode=s,rn=t,Gt=null,e=!0):e=!1),e||sr(t)),null;case 13:return Dg(e,t,s);case 4:return Ne(t,t.stateNode.containerInfo),o=t.pendingProps,e===null?t.child=ci(t,null,o,s):da(e,t,o,s),t.child;case 11:return Cg(e,t,t.type,t.pendingProps,s);case 7:return da(e,t,t.pendingProps,s),t.child;case 8:return da(e,t,t.pendingProps.children,s),t.child;case 12:return da(e,t,t.pendingProps.children,s),t.child;case 10:return o=t.pendingProps,ds(t,t.type,o.value),da(e,t,o.children,s),t.child;case 9:return f=t.type._context,o=t.pendingProps.children,Ka(t),f=ln(f),o=o(f),t.flags|=1,da(e,t,o,s),t.child;case 14:return kg(e,t,t.type,t.pendingProps,s);case 15:return jg(e,t,t.type,t.pendingProps,s);case 19:return _g(e,t,s);case 31:return aS(e,t,s);case 22:return Ag(e,t,s,t.pendingProps);case 24:return Ka(t),o=ln(jn),e===null?(f=$o(),f===null&&(f=tn,p=Oo(),f.pooledCache=p,p.refCount++,p!==null&&(f.pooledCacheLanes|=s),f=p),t.memoizedState={parent:o,cache:f},Pl(t),ds(t,jn,f)):((e.lanes&s)!==0&&(ui(e,t),Gl(t,null,null,s),ql()),f=e.memoizedState,p=t.memoizedState,f.parent!==o?(f={parent:o,cache:o},t.memoizedState=f,t.lanes===0&&(t.memoizedState=t.updateQueue.baseState=f),ds(t,jn,o)):(o=p.cache,ds(t,jn,o),o!==f.cache&&Io(t,[jn],s,!0))),da(e,t,t.pendingProps.children,s),t.child;case 29:throw t.pendingProps}throw Error(l(156,t.tag))}function bi(e){e.flags|=4}function km(e,t,s,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(ov())e.flags|=8192;else throw Tr=Dn,Yc}else e.flags&=-16777217}function zg(e,t){if(t.type!=="stylesheet"||(t.state.loading&4)!==0)e.flags&=-16777217;else if(e.flags|=16777216,!Xv(t))if(ov())e.flags|=8192;else throw Tr=Dn,Yc}function wd(e,t){t!==null&&(e.flags|=4),e.flags&16384&&(t=e.tag!==22?ws():536870912,e.lanes|=t,nc|=t)}function ru(e,t){if(!wt)switch(e.tailMode){case"hidden":t=e.tail;for(var s=null;t!==null;)t.alternate!==null&&(s=t),t=t.sibling;s===null?e.tail=null:s.sibling=null;break;case"collapsed":s=e.tail;for(var o=null;s!==null;)s.alternate!==null&&(o=s),s=s.sibling;o===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:o.sibling=null}}function cn(e){var t=e.alternate!==null&&e.alternate.child===e.child,s=0,o=0;if(t)for(var f=e.child;f!==null;)s|=f.lanes|f.childLanes,o|=f.subtreeFlags&65011712,o|=f.flags&65011712,f.return=e,f=f.sibling;else for(f=e.child;f!==null;)s|=f.lanes|f.childLanes,o|=f.subtreeFlags,o|=f.flags,f.return=e,f=f.sibling;return e.subtreeFlags|=o,e.childLanes=s,t}function rS(e,t,s){var o=t.pendingProps;switch(ai(t),t.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return cn(t),null;case 1:return cn(t),null;case 3:return s=t.stateNode,o=null,e!==null&&(o=e.memoizedState.cache),t.memoizedState.cache!==o&&(t.flags|=2048),Ya(jn),Fe(),s.pendingContext&&(s.context=s.pendingContext,s.pendingContext=null),(e===null||e.child===null)&&(Ds(t)?bi(t):e===null||e.memoizedState.isDehydrated&&(t.flags&256)===0||(t.flags|=1024,Yi())),cn(t),null;case 26:var f=t.type,p=t.memoizedState;return e===null?(bi(t),p!==null?(cn(t),zg(t,p)):(cn(t),km(t,f,null,o,s))):p?p!==e.memoizedState?(bi(t),cn(t),zg(t,p)):(cn(t),t.flags&=-16777217):(e=e.memoizedProps,e!==o&&bi(t),cn(t),km(t,f,e,o,s)),null;case 27:if(Pe(t),s=ee.current,f=t.type,e!==null&&t.stateNode!=null)e.memoizedProps!==o&&bi(t);else{if(!o){if(t.stateNode===null)throw Error(l(166));return cn(t),null}e=he.current,Ds(t)?zl(t):(e=Uv(f,o,s),t.stateNode=e,bi(t))}return cn(t),null;case 5:if(Pe(t),f=t.type,e!==null&&t.stateNode!=null)e.memoizedProps!==o&&bi(t);else{if(!o){if(t.stateNode===null)throw Error(l(166));return cn(t),null}if(p=he.current,Ds(t))zl(t);else{var S=zd(ee.current);switch(p){case 1:p=S.createElementNS("http://www.w3.org/2000/svg",f);break;case 2:p=S.createElementNS("http://www.w3.org/1998/Math/MathML",f);break;default:switch(f){case"svg":p=S.createElementNS("http://www.w3.org/2000/svg",f);break;case"math":p=S.createElementNS("http://www.w3.org/1998/Math/MathML",f);break;case"script":p=S.createElement("div"),p.innerHTML="<script><\/script>",p=p.removeChild(p.firstChild);break;case"select":p=typeof o.is=="string"?S.createElement("select",{is:o.is}):S.createElement("select"),o.multiple?p.multiple=!0:o.size&&(p.size=o.size);break;default:p=typeof o.is=="string"?S.createElement(f,{is:o.is}):S.createElement(f)}}p[re]=t,p[Te]=o;e:for(S=t.child;S!==null;){if(S.tag===5||S.tag===6)p.appendChild(S.stateNode);else if(S.tag!==4&&S.tag!==27&&S.child!==null){S.child.return=S,S=S.child;continue}if(S===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=p;e:switch(fa(p,f,o),f){case"button":case"input":case"select":case"textarea":o=!!o.autoFocus;break e;case"img":o=!0;break e;default:o=!1}o&&bi(t)}}return cn(t),km(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,s),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==o&&bi(t);else{if(typeof o!="string"&&t.stateNode===null)throw Error(l(166));if(e=ee.current,Ds(t)){if(e=t.stateNode,s=t.memoizedProps,o=null,f=rn,f!==null)switch(f.tag){case 27:case 5:o=f.memoizedProps}e[re]=t,e=!!(e.nodeValue===s||o!==null&&o.suppressHydrationWarning===!0||Dv(e.nodeValue,s)),e||sr(t,!0)}else e=zd(e).createTextNode(o),e[re]=t,t.stateNode=e}return cn(t),null;case 31:if(s=t.memoizedState,e===null||e.memoizedState!==null){if(o=Ds(t),s!==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[re]=t}else si(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;cn(t),e=!1}else s=Yi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=s),e=!0;if(!e)return t.flags&256?(Oa(t),t):(Oa(t),null);if((t.flags&128)!==0)throw Error(l(558))}return cn(t),null;case 13:if(o=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(f=Ds(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[re]=t}else si(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;cn(t),f=!1}else f=Yi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=f),f=!0;if(!f)return t.flags&256?(Oa(t),t):(Oa(t),null)}return Oa(t),(t.flags&128)!==0?(t.lanes=s,t):(s=o!==null,e=e!==null&&e.memoizedState!==null,s&&(o=t.child,f=null,o.alternate!==null&&o.alternate.memoizedState!==null&&o.alternate.memoizedState.cachePool!==null&&(f=o.alternate.memoizedState.cachePool.pool),p=null,o.memoizedState!==null&&o.memoizedState.cachePool!==null&&(p=o.memoizedState.cachePool.pool),p!==f&&(o.flags|=2048)),s!==e&&s&&(t.child.flags|=8192),wd(t,t.updateQueue),cn(t),null);case 4:return Fe(),e===null&&Vm(t.stateNode.containerInfo),cn(t),null;case 10:return Ya(t.type),cn(t),null;case 19:if(Q(yn),o=t.memoizedState,o===null)return cn(t),null;if(f=(t.flags&128)!==0,p=o.rendering,p===null)if(f)ru(o,!1);else{if(bn!==0||e!==null&&(e.flags&128)!==0)for(e=t.child;e!==null;){if(p=Zi(e),p!==null){for(t.flags|=128,ru(o,!1),e=p.updateQueue,t.updateQueue=e,wd(t,e),t.subtreeFlags=0,e=s,s=t.child;s!==null;)_l(s,e),s=s.sibling;return be(yn,yn.current&1|2),wt&&Va(t,o.treeForkCount),t.child}e=e.sibling}o.tail!==null&&je()>Ad&&(t.flags|=128,f=!0,ru(o,!1),t.lanes=4194304)}else{if(!f)if(e=Zi(p),e!==null){if(t.flags|=128,f=!0,e=e.updateQueue,t.updateQueue=e,wd(t,e),ru(o,!0),o.tail===null&&o.tailMode==="hidden"&&!p.alternate&&!wt)return cn(t),null}else 2*je()-o.renderingStartTime>Ad&&s!==536870912&&(t.flags|=128,f=!0,ru(o,!1),t.lanes=4194304);o.isBackwards?(p.sibling=t.child,t.child=p):(e=o.last,e!==null?e.sibling=p:t.child=p,o.last=p)}return o.tail!==null?(e=o.tail,o.rendering=e,o.tail=e.sibling,o.renderingStartTime=je(),e.sibling=null,s=yn.current,be(yn,f?s&1|2:s&1),wt&&Va(t,o.treeForkCount),e):(cn(t),null);case 22:case 23:return Oa(t),Xi(),o=t.memoizedState!==null,e!==null?e.memoizedState!==null!==o&&(t.flags|=8192):o&&(t.flags|=8192),o?(s&536870912)!==0&&(t.flags&128)===0&&(cn(t),t.subtreeFlags&6&&(t.flags|=8192)):cn(t),s=t.updateQueue,s!==null&&wd(t,s.retryQueue),s=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(s=e.memoizedState.cachePool.pool),o=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(o=t.memoizedState.cachePool.pool),o!==s&&(t.flags|=2048),e!==null&&Q(cr),null;case 24:return s=null,e!==null&&(s=e.memoizedState.cache),t.memoizedState.cache!==s&&(t.flags|=2048),Ya(jn),cn(t),null;case 25:return null;case 30:return null}throw Error(l(156,t.tag))}function iS(e,t){switch(ai(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ya(jn),Fe(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return Pe(t),null;case 31:if(t.memoizedState!==null){if(Oa(t),t.alternate===null)throw Error(l(340));si()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(Oa(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(l(340));si()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Q(yn),null;case 4:return Fe(),null;case 10:return Ya(t.type),null;case 22:case 23:return Oa(t),Xi(),e!==null&&Q(cr),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Ya(jn),null;case 25:return null;default:return null}}function Og(e,t){switch(ai(t),t.tag){case 3:Ya(jn),Fe();break;case 26:case 27:case 5:Pe(t);break;case 4:Fe();break;case 31:t.memoizedState!==null&&Oa(t);break;case 13:Oa(t);break;case 19:Q(yn);break;case 10:Ya(t.type);break;case 22:case 23:Oa(t),Xi(),e!==null&&Q(cr);break;case 24:Ya(jn)}}function iu(e,t){try{var s=t.updateQueue,o=s!==null?s.lastEffect:null;if(o!==null){var f=o.next;s=f;do{if((s.tag&e)===e){o=void 0;var p=s.create,S=s.inst;o=p(),S.destroy=o}s=s.next}while(s!==f)}}catch(R){Wt(t,t.return,R)}}function tl(e,t,s){try{var o=t.updateQueue,f=o!==null?o.lastEffect:null;if(f!==null){var p=f.next;o=p;do{if((o.tag&e)===e){var S=o.inst,R=S.destroy;if(R!==void 0){S.destroy=void 0,f=t;var V=s,ue=R;try{ue()}catch(xe){Wt(f,V,xe)}}}o=o.next}while(o!==p)}}catch(xe){Wt(t,t.return,xe)}}function Hg(e){var t=e.updateQueue;if(t!==null){var s=e.stateNode;try{Xc(t,s)}catch(o){Wt(e,e.return,o)}}}function Fg(e,t,s){s.props=Zl(e.type,e.memoizedProps),s.state=e.memoizedState;try{s.componentWillUnmount()}catch(o){Wt(e,t,o)}}function lu(e,t){try{var s=e.ref;if(s!==null){switch(e.tag){case 26:case 27:case 5:var o=e.stateNode;break;case 30:o=e.stateNode;break;default:o=e.stateNode}typeof s=="function"?e.refCleanup=s(o):s.current=o}}catch(f){Wt(e,t,f)}}function Rr(e,t){var s=e.ref,o=e.refCleanup;if(s!==null)if(typeof o=="function")try{o()}catch(f){Wt(e,t,f)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof s=="function")try{s(null)}catch(f){Wt(e,t,f)}else s.current=null}function $g(e){var t=e.type,s=e.memoizedProps,o=e.stateNode;try{e:switch(t){case"button":case"input":case"select":case"textarea":s.autoFocus&&o.focus();break e;case"img":s.src?o.src=s.src:s.srcSet&&(o.srcset=s.srcSet)}}catch(f){Wt(e,e.return,f)}}function jm(e,t,s){try{var o=e.stateNode;NS(o,e.type,s,t),o[Te]=t}catch(f){Wt(e,e.return,f)}}function Bg(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&ol(e.type)||e.tag===4}function Am(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Bg(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&&ol(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 Mm(e,t,s){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?(s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s).insertBefore(e,t):(t=s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s,t.appendChild(e),s=s._reactRootContainer,s!=null||t.onclick!==null||(t.onclick=ra));else if(o!==4&&(o===27&&ol(e.type)&&(s=e.stateNode,t=null),e=e.child,e!==null))for(Mm(e,t,s),e=e.sibling;e!==null;)Mm(e,t,s),e=e.sibling}function Sd(e,t,s){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?s.insertBefore(e,t):s.appendChild(e);else if(o!==4&&(o===27&&ol(e.type)&&(s=e.stateNode),e=e.child,e!==null))for(Sd(e,t,s),e=e.sibling;e!==null;)Sd(e,t,s),e=e.sibling}function Pg(e){var t=e.stateNode,s=e.memoizedProps;try{for(var o=e.type,f=t.attributes;f.length;)t.removeAttributeNode(f[0]);fa(t,o,s),t[re]=e,t[Te]=s}catch(p){Wt(e,e.return,p)}}var xi=!1,_n=!1,Nm=!1,Ug=typeof WeakSet=="function"?WeakSet:Set,Qn=null;function lS(e,t){if(e=e.containerInfo,Km=Ud,e=jo(e),Kr(e)){if("selectionStart"in e)var s={start:e.selectionStart,end:e.selectionEnd};else e:{s=(s=e.ownerDocument)&&s.defaultView||window;var o=s.getSelection&&s.getSelection();if(o&&o.rangeCount!==0){s=o.anchorNode;var f=o.anchorOffset,p=o.focusNode;o=o.focusOffset;try{s.nodeType,p.nodeType}catch{s=null;break e}var S=0,R=-1,V=-1,ue=0,xe=0,Ce=e,me=null;t:for(;;){for(var ge;Ce!==s||f!==0&&Ce.nodeType!==3||(R=S+f),Ce!==p||o!==0&&Ce.nodeType!==3||(V=S+o),Ce.nodeType===3&&(S+=Ce.nodeValue.length),(ge=Ce.firstChild)!==null;)me=Ce,Ce=ge;for(;;){if(Ce===e)break t;if(me===s&&++ue===f&&(R=S),me===p&&++xe===o&&(V=S),(ge=Ce.nextSibling)!==null)break;Ce=me,me=Ce.parentNode}Ce=ge}s=R===-1||V===-1?null:{start:R,end:V}}else s=null}s=s||{start:0,end:0}}else s=null;for(Qm={focusedElem:e,selectionRange:s},Ud=!1,Qn=t;Qn!==null;)if(t=Qn,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Qn=e;else for(;Qn!==null;){switch(t=Qn,p=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(s=0;s<e.length;s++)f=e[s],f.ref.impl=f.nextImpl;break;case 11:case 15:break;case 1:if((e&1024)!==0&&p!==null){e=void 0,s=t,f=p.memoizedProps,p=p.memoizedState,o=s.stateNode;try{var Xe=Zl(s.type,f);e=o.getSnapshotBeforeUpdate(Xe,p),o.__reactInternalSnapshotBeforeUpdate=e}catch(ot){Wt(s,s.return,ot)}}break;case 3:if((e&1024)!==0){if(e=t.stateNode.containerInfo,s=e.nodeType,s===9)Jm(e);else if(s===1)switch(e.nodeName){case"HEAD":case"HTML":case"BODY":Jm(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,Qn=e;break}Qn=t.return}}function qg(e,t,s){var o=s.flags;switch(s.tag){case 0:case 11:case 15:Si(e,s),o&4&&iu(5,s);break;case 1:if(Si(e,s),o&4)if(e=s.stateNode,t===null)try{e.componentDidMount()}catch(S){Wt(s,s.return,S)}else{var f=Zl(s.type,t.memoizedProps);t=t.memoizedState;try{e.componentDidUpdate(f,t,e.__reactInternalSnapshotBeforeUpdate)}catch(S){Wt(s,s.return,S)}}o&64&&Hg(s),o&512&&lu(s,s.return);break;case 3:if(Si(e,s),o&64&&(e=s.updateQueue,e!==null)){if(t=null,s.child!==null)switch(s.child.tag){case 27:case 5:t=s.child.stateNode;break;case 1:t=s.child.stateNode}try{Xc(e,t)}catch(S){Wt(s,s.return,S)}}break;case 27:t===null&&o&4&&Pg(s);case 26:case 5:Si(e,s),t===null&&o&4&&$g(s),o&512&&lu(s,s.return);break;case 12:Si(e,s);break;case 31:Si(e,s),o&4&&Wg(e,s);break;case 13:Si(e,s),o&4&&Yg(e,s),o&64&&(e=s.memoizedState,e!==null&&(e=e.dehydrated,e!==null&&(s=gS.bind(null,s),zS(e,s))));break;case 22:if(o=s.memoizedState!==null||xi,!o){t=t!==null&&t.memoizedState!==null||_n,f=xi;var p=_n;xi=o,(_n=t)&&!p?Ci(e,s,(s.subtreeFlags&8772)!==0):Si(e,s),xi=f,_n=p}break;case 30:break;default:Si(e,s)}}function Gg(e){var t=e.alternate;t!==null&&(e.alternate=null,Gg(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&sa(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 dn=null,Ja=!1;function wi(e,t,s){for(s=s.child;s!==null;)Vg(e,t,s),s=s.sibling}function Vg(e,t,s){if(Ae&&typeof Ae.onCommitFiberUnmount=="function")try{Ae.onCommitFiberUnmount(Oe,s)}catch{}switch(s.tag){case 26:_n||Rr(s,t),wi(e,t,s),s.memoizedState?s.memoizedState.count--:s.stateNode&&(s=s.stateNode,s.parentNode.removeChild(s));break;case 27:_n||Rr(s,t);var o=dn,f=Ja;ol(s.type)&&(dn=s.stateNode,Ja=!1),wi(e,t,s),gu(s.stateNode),dn=o,Ja=f;break;case 5:_n||Rr(s,t);case 6:if(o=dn,f=Ja,dn=null,wi(e,t,s),dn=o,Ja=f,dn!==null)if(Ja)try{(dn.nodeType===9?dn.body:dn.nodeName==="HTML"?dn.ownerDocument.body:dn).removeChild(s.stateNode)}catch(p){Wt(s,t,p)}else try{dn.removeChild(s.stateNode)}catch(p){Wt(s,t,p)}break;case 18:dn!==null&&(Ja?(e=dn,Hv(e.nodeType===9?e.body:e.nodeName==="HTML"?e.ownerDocument.body:e,s.stateNode),uc(e)):Hv(dn,s.stateNode));break;case 4:o=dn,f=Ja,dn=s.stateNode.containerInfo,Ja=!0,wi(e,t,s),dn=o,Ja=f;break;case 0:case 11:case 14:case 15:tl(2,s,t),_n||tl(4,s,t),wi(e,t,s);break;case 1:_n||(Rr(s,t),o=s.stateNode,typeof o.componentWillUnmount=="function"&&Fg(s,t,o)),wi(e,t,s);break;case 21:wi(e,t,s);break;case 22:_n=(o=_n)||s.memoizedState!==null,wi(e,t,s),_n=o;break;default:wi(e,t,s)}}function Wg(e,t){if(t.memoizedState===null&&(e=t.alternate,e!==null&&(e=e.memoizedState,e!==null))){e=e.dehydrated;try{uc(e)}catch(s){Wt(t,t.return,s)}}}function Yg(e,t){if(t.memoizedState===null&&(e=t.alternate,e!==null&&(e=e.memoizedState,e!==null&&(e=e.dehydrated,e!==null))))try{uc(e)}catch(s){Wt(t,t.return,s)}}function oS(e){switch(e.tag){case 31:case 13:case 19:var t=e.stateNode;return t===null&&(t=e.stateNode=new Ug),t;case 22:return e=e.stateNode,t=e._retryCache,t===null&&(t=e._retryCache=new Ug),t;default:throw Error(l(435,e.tag))}}function Cd(e,t){var s=oS(e);t.forEach(function(o){if(!s.has(o)){s.add(o);var f=vS.bind(null,e,o);o.then(f,f)}})}function es(e,t){var s=t.deletions;if(s!==null)for(var o=0;o<s.length;o++){var f=s[o],p=e,S=t,R=S;e:for(;R!==null;){switch(R.tag){case 27:if(ol(R.type)){dn=R.stateNode,Ja=!1;break e}break;case 5:dn=R.stateNode,Ja=!1;break e;case 3:case 4:dn=R.stateNode.containerInfo,Ja=!0;break e}R=R.return}if(dn===null)throw Error(l(160));Vg(p,S,f),dn=null,Ja=!1,p=f.alternate,p!==null&&(p.return=null),f.return=null}if(t.subtreeFlags&13886)for(t=t.child;t!==null;)Kg(t,e),t=t.sibling}var hr=null;function Kg(e,t){var s=e.alternate,o=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:es(t,e),ts(e),o&4&&(tl(3,e,e.return),iu(3,e),tl(5,e,e.return));break;case 1:es(t,e),ts(e),o&512&&(_n||s===null||Rr(s,s.return)),o&64&&xi&&(e=e.updateQueue,e!==null&&(o=e.callbacks,o!==null&&(s=e.shared.hiddenCallbacks,e.shared.hiddenCallbacks=s===null?o:s.concat(o))));break;case 26:var f=hr;if(es(t,e),ts(e),o&512&&(_n||s===null||Rr(s,s.return)),o&4){var p=s!==null?s.memoizedState:null;if(o=e.memoizedState,s===null)if(o===null)if(e.stateNode===null){e:{o=e.type,s=e.memoizedProps,f=f.ownerDocument||f;t:switch(o){case"title":p=f.getElementsByTagName("title")[0],(!p||p[Mt]||p[re]||p.namespaceURI==="http://www.w3.org/2000/svg"||p.hasAttribute("itemprop"))&&(p=f.createElement(o),f.head.insertBefore(p,f.querySelector("head > title"))),fa(p,o,s),p[re]=e,At(p),o=p;break e;case"link":var S=Kv("link","href",f).get(o+(s.href||""));if(S){for(var R=0;R<S.length;R++)if(p=S[R],p.getAttribute("href")===(s.href==null||s.href===""?null:s.href)&&p.getAttribute("rel")===(s.rel==null?null:s.rel)&&p.getAttribute("title")===(s.title==null?null:s.title)&&p.getAttribute("crossorigin")===(s.crossOrigin==null?null:s.crossOrigin)){S.splice(R,1);break t}}p=f.createElement(o),fa(p,o,s),f.head.appendChild(p);break;case"meta":if(S=Kv("meta","content",f).get(o+(s.content||""))){for(R=0;R<S.length;R++)if(p=S[R],p.getAttribute("content")===(s.content==null?null:""+s.content)&&p.getAttribute("name")===(s.name==null?null:s.name)&&p.getAttribute("property")===(s.property==null?null:s.property)&&p.getAttribute("http-equiv")===(s.httpEquiv==null?null:s.httpEquiv)&&p.getAttribute("charset")===(s.charSet==null?null:s.charSet)){S.splice(R,1);break t}}p=f.createElement(o),fa(p,o,s),f.head.appendChild(p);break;default:throw Error(l(468,o))}p[re]=e,At(p),o=p}e.stateNode=o}else Qv(f,e.type,e.stateNode);else e.stateNode=Yv(f,o,e.memoizedProps);else p!==o?(p===null?s.stateNode!==null&&(s=s.stateNode,s.parentNode.removeChild(s)):p.count--,o===null?Qv(f,e.type,e.stateNode):Yv(f,o,e.memoizedProps)):o===null&&e.stateNode!==null&&jm(e,e.memoizedProps,s.memoizedProps)}break;case 27:es(t,e),ts(e),o&512&&(_n||s===null||Rr(s,s.return)),s!==null&&o&4&&jm(e,e.memoizedProps,s.memoizedProps);break;case 5:if(es(t,e),ts(e),o&512&&(_n||s===null||Rr(s,s.return)),e.flags&32){f=e.stateNode;try{kn(f,"")}catch(Xe){Wt(e,e.return,Xe)}}o&4&&e.stateNode!=null&&(f=e.memoizedProps,jm(e,f,s!==null?s.memoizedProps:f)),o&1024&&(Nm=!0);break;case 6:if(es(t,e),ts(e),o&4){if(e.stateNode===null)throw Error(l(162));o=e.memoizedProps,s=e.stateNode;try{s.nodeValue=o}catch(Xe){Wt(e,e.return,Xe)}}break;case 3:if(Fd=null,f=hr,hr=Od(t.containerInfo),es(t,e),hr=f,ts(e),o&4&&s!==null&&s.memoizedState.isDehydrated)try{uc(t.containerInfo)}catch(Xe){Wt(e,e.return,Xe)}Nm&&(Nm=!1,Qg(e));break;case 4:o=hr,hr=Od(e.stateNode.containerInfo),es(t,e),ts(e),hr=o;break;case 12:es(t,e),ts(e);break;case 31:es(t,e),ts(e),o&4&&(o=e.updateQueue,o!==null&&(e.updateQueue=null,Cd(e,o)));break;case 13:es(t,e),ts(e),e.child.flags&8192&&e.memoizedState!==null!=(s!==null&&s.memoizedState!==null)&&(jd=je()),o&4&&(o=e.updateQueue,o!==null&&(e.updateQueue=null,Cd(e,o)));break;case 22:f=e.memoizedState!==null;var V=s!==null&&s.memoizedState!==null,ue=xi,xe=_n;if(xi=ue||f,_n=xe||V,es(t,e),_n=xe,xi=ue,ts(e),o&8192)e:for(t=e.stateNode,t._visibility=f?t._visibility&-2:t._visibility|1,f&&(s===null||V||xi||_n||Jl(e)),s=null,t=e;;){if(t.tag===5||t.tag===26){if(s===null){V=s=t;try{if(p=V.stateNode,f)S=p.style,typeof S.setProperty=="function"?S.setProperty("display","none","important"):S.display="none";else{R=V.stateNode;var Ce=V.memoizedProps.style,me=Ce!=null&&Ce.hasOwnProperty("display")?Ce.display:null;R.style.display=me==null||typeof me=="boolean"?"":(""+me).trim()}}catch(Xe){Wt(V,V.return,Xe)}}}else if(t.tag===6){if(s===null){V=t;try{V.stateNode.nodeValue=f?"":V.memoizedProps}catch(Xe){Wt(V,V.return,Xe)}}}else if(t.tag===18){if(s===null){V=t;try{var ge=V.stateNode;f?Fv(ge,!0):Fv(V.stateNode,!1)}catch(Xe){Wt(V,V.return,Xe)}}}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;s===t&&(s=null),t=t.return}s===t&&(s=null),t.sibling.return=t.return,t=t.sibling}o&4&&(o=e.updateQueue,o!==null&&(s=o.retryQueue,s!==null&&(o.retryQueue=null,Cd(e,s))));break;case 19:es(t,e),ts(e),o&4&&(o=e.updateQueue,o!==null&&(e.updateQueue=null,Cd(e,o)));break;case 30:break;case 21:break;default:es(t,e),ts(e)}}function ts(e){var t=e.flags;if(t&2){try{for(var s,o=e.return;o!==null;){if(Bg(o)){s=o;break}o=o.return}if(s==null)throw Error(l(160));switch(s.tag){case 27:var f=s.stateNode,p=Am(e);Sd(e,p,f);break;case 5:var S=s.stateNode;s.flags&32&&(kn(S,""),s.flags&=-33);var R=Am(e);Sd(e,R,S);break;case 3:case 4:var V=s.stateNode.containerInfo,ue=Am(e);Mm(e,ue,V);break;default:throw Error(l(161))}}catch(xe){Wt(e,e.return,xe)}e.flags&=-3}t&4096&&(e.flags&=-4097)}function Qg(e){if(e.subtreeFlags&1024)for(e=e.child;e!==null;){var t=e;Qg(t),t.tag===5&&t.flags&1024&&t.stateNode.reset(),e=e.sibling}}function Si(e,t){if(t.subtreeFlags&8772)for(t=t.child;t!==null;)qg(e,t.alternate,t),t=t.sibling}function Jl(e){for(e=e.child;e!==null;){var t=e;switch(t.tag){case 0:case 11:case 14:case 15:tl(4,t,t.return),Jl(t);break;case 1:Rr(t,t.return);var s=t.stateNode;typeof s.componentWillUnmount=="function"&&Fg(t,t.return,s),Jl(t);break;case 27:gu(t.stateNode);case 26:case 5:Rr(t,t.return),Jl(t);break;case 22:t.memoizedState===null&&Jl(t);break;case 30:Jl(t);break;default:Jl(t)}e=e.sibling}}function Ci(e,t,s){for(s=s&&(t.subtreeFlags&8772)!==0,t=t.child;t!==null;){var o=t.alternate,f=e,p=t,S=p.flags;switch(p.tag){case 0:case 11:case 15:Ci(f,p,s),iu(4,p);break;case 1:if(Ci(f,p,s),o=p,f=o.stateNode,typeof f.componentDidMount=="function")try{f.componentDidMount()}catch(ue){Wt(o,o.return,ue)}if(o=p,f=o.updateQueue,f!==null){var R=o.stateNode;try{var V=f.shared.hiddenCallbacks;if(V!==null)for(f.shared.hiddenCallbacks=null,f=0;f<V.length;f++)Uo(V[f],R)}catch(ue){Wt(o,o.return,ue)}}s&&S&64&&Hg(p),lu(p,p.return);break;case 27:Pg(p);case 26:case 5:Ci(f,p,s),s&&o===null&&S&4&&$g(p),lu(p,p.return);break;case 12:Ci(f,p,s);break;case 31:Ci(f,p,s),s&&S&4&&Wg(f,p);break;case 13:Ci(f,p,s),s&&S&4&&Yg(f,p);break;case 22:p.memoizedState===null&&Ci(f,p,s),lu(p,p.return);break;case 30:break;default:Ci(f,p,s)}t=t.sibling}}function Tm(e,t){var s=null;e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(s=e.memoizedState.cachePool.pool),e=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(e=t.memoizedState.cachePool.pool),e!==s&&(e!=null&&e.refCount++,s!=null&&or(s))}function Rm(e,t){e=null,t.alternate!==null&&(e=t.alternate.memoizedState.cache),t=t.memoizedState.cache,t!==e&&(t.refCount++,e!=null&&or(e))}function pr(e,t,s,o){if(t.subtreeFlags&10256)for(t=t.child;t!==null;)Xg(e,t,s,o),t=t.sibling}function Xg(e,t,s,o){var f=t.flags;switch(t.tag){case 0:case 11:case 15:pr(e,t,s,o),f&2048&&iu(9,t);break;case 1:pr(e,t,s,o);break;case 3:pr(e,t,s,o),f&2048&&(e=null,t.alternate!==null&&(e=t.alternate.memoizedState.cache),t=t.memoizedState.cache,t!==e&&(t.refCount++,e!=null&&or(e)));break;case 12:if(f&2048){pr(e,t,s,o),e=t.stateNode;try{var p=t.memoizedProps,S=p.id,R=p.onPostCommit;typeof R=="function"&&R(S,t.alternate===null?"mount":"update",e.passiveEffectDuration,-0)}catch(V){Wt(t,t.return,V)}}else pr(e,t,s,o);break;case 31:pr(e,t,s,o);break;case 13:pr(e,t,s,o);break;case 23:break;case 22:p=t.stateNode,S=t.alternate,t.memoizedState!==null?p._visibility&2?pr(e,t,s,o):ou(e,t):p._visibility&2?pr(e,t,s,o):(p._visibility|=2,Jo(e,t,s,o,(t.subtreeFlags&10256)!==0||!1)),f&2048&&Tm(S,t);break;case 24:pr(e,t,s,o),f&2048&&Rm(t.alternate,t);break;default:pr(e,t,s,o)}}function Jo(e,t,s,o,f){for(f=f&&((t.subtreeFlags&10256)!==0||!1),t=t.child;t!==null;){var p=e,S=t,R=s,V=o,ue=S.flags;switch(S.tag){case 0:case 11:case 15:Jo(p,S,R,V,f),iu(8,S);break;case 23:break;case 22:var xe=S.stateNode;S.memoizedState!==null?xe._visibility&2?Jo(p,S,R,V,f):ou(p,S):(xe._visibility|=2,Jo(p,S,R,V,f)),f&&ue&2048&&Tm(S.alternate,S);break;case 24:Jo(p,S,R,V,f),f&&ue&2048&&Rm(S.alternate,S);break;default:Jo(p,S,R,V,f)}t=t.sibling}}function ou(e,t){if(t.subtreeFlags&10256)for(t=t.child;t!==null;){var s=e,o=t,f=o.flags;switch(o.tag){case 22:ou(s,o),f&2048&&Tm(o.alternate,o);break;case 24:ou(s,o),f&2048&&Rm(o.alternate,o);break;default:ou(s,o)}t=t.sibling}}var cu=8192;function ec(e,t,s){if(e.subtreeFlags&cu)for(e=e.child;e!==null;)Zg(e,t,s),e=e.sibling}function Zg(e,t,s){switch(e.tag){case 26:ec(e,t,s),e.flags&cu&&e.memoizedState!==null&&YS(s,hr,e.memoizedState,e.memoizedProps);break;case 5:ec(e,t,s);break;case 3:case 4:var o=hr;hr=Od(e.stateNode.containerInfo),ec(e,t,s),hr=o;break;case 22:e.memoizedState===null&&(o=e.alternate,o!==null&&o.memoizedState!==null?(o=cu,cu=16777216,ec(e,t,s),cu=o):ec(e,t,s));break;default:ec(e,t,s)}}function Jg(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 uu(e){var t=e.deletions;if((e.flags&16)!==0){if(t!==null)for(var s=0;s<t.length;s++){var o=t[s];Qn=o,tv(o,e)}Jg(e)}if(e.subtreeFlags&10256)for(e=e.child;e!==null;)ev(e),e=e.sibling}function ev(e){switch(e.tag){case 0:case 11:case 15:uu(e),e.flags&2048&&tl(9,e,e.return);break;case 3:uu(e);break;case 12:uu(e);break;case 22:var t=e.stateNode;e.memoizedState!==null&&t._visibility&2&&(e.return===null||e.return.tag!==13)?(t._visibility&=-3,kd(e)):uu(e);break;default:uu(e)}}function kd(e){var t=e.deletions;if((e.flags&16)!==0){if(t!==null)for(var s=0;s<t.length;s++){var o=t[s];Qn=o,tv(o,e)}Jg(e)}for(e=e.child;e!==null;){switch(t=e,t.tag){case 0:case 11:case 15:tl(8,t,t.return),kd(t);break;case 22:s=t.stateNode,s._visibility&2&&(s._visibility&=-3,kd(t));break;default:kd(t)}e=e.sibling}}function tv(e,t){for(;Qn!==null;){var s=Qn;switch(s.tag){case 0:case 11:case 15:tl(8,s,t);break;case 23:case 22:if(s.memoizedState!==null&&s.memoizedState.cachePool!==null){var o=s.memoizedState.cachePool.pool;o!=null&&o.refCount++}break;case 24:or(s.memoizedState.cache)}if(o=s.child,o!==null)o.return=s,Qn=o;else e:for(s=e;Qn!==null;){o=Qn;var f=o.sibling,p=o.return;if(Gg(o),o===s){Qn=null;break e}if(f!==null){f.return=p,Qn=f;break e}Qn=p}}}var cS={getCacheForType:function(e){var t=ln(jn),s=t.data.get(e);return s===void 0&&(s=e(),t.data.set(e,s)),s},cacheSignal:function(){return ln(jn).controller.signal}},uS=typeof WeakMap=="function"?WeakMap:Map,Pt=0,tn=null,Et=null,Lt=0,Vt=0,ms=null,nl=!1,tc=!1,Em=!1,ki=0,bn=0,al=0,eo=0,Dm=0,hs=0,nc=0,du=null,ns=null,Lm=!1,jd=0,nv=0,Ad=1/0,Md=null,sl=null,Un=0,rl=null,ac=null,ji=0,_m=0,Im=null,av=null,fu=0,zm=null;function ps(){return(Pt&2)!==0&&Lt!==0?Lt&-Lt:z.T!==null?Pm():Fa()}function sv(){if(hs===0)if((Lt&536870912)===0||wt){var e=Ot;Ot<<=1,(Ot&3932160)===0&&(Ot=262144),hs=e}else hs=536870912;return e=wa.current,e!==null&&(e.flags|=32),hs}function as(e,t,s){(e===tn&&(Vt===2||Vt===9)||e.cancelPendingCommit!==null)&&(sc(e,0),il(e,Lt,hs,!1)),qs(e,s),((Pt&2)===0||e!==tn)&&(e===tn&&((Pt&2)===0&&(eo|=s),bn===4&&il(e,Lt,hs,!1)),Er(e))}function rv(e,t,s){if((Pt&6)!==0)throw Error(l(327));var o=!s&&(t&127)===0&&(t&e.expiredLanes)===0||Sn(e,t),f=o?mS(e,t):Hm(e,t,!0),p=o;do{if(f===0){tc&&!o&&il(e,t,0,!1);break}else{if(s=e.current.alternate,p&&!dS(s)){f=Hm(e,t,!1),p=!1;continue}if(f===2){if(p=t,e.errorRecoveryDisabledLanes&p)var S=0;else S=e.pendingLanes&-536870913,S=S!==0?S:S&536870912?536870912:0;if(S!==0){t=S;e:{var R=e;f=du;var V=R.current.memoizedState.isDehydrated;if(V&&(sc(R,S).flags|=256),S=Hm(R,S,!1),S!==2){if(Em&&!V){R.errorRecoveryDisabledLanes|=p,eo|=p,f=4;break e}p=ns,ns=f,p!==null&&(ns===null?ns=p:ns.push.apply(ns,p))}f=S}if(p=!1,f!==2)continue}}if(f===1){sc(e,0),il(e,t,0,!0);break}e:{switch(o=e,p=f,p){case 0:case 1:throw Error(l(345));case 4:if((t&4194048)!==t)break;case 6:il(o,t,hs,!nl);break e;case 2:ns=null;break;case 3:case 5:break;default:throw Error(l(329))}if((t&62914560)===t&&(f=jd+300-je(),10<f)){if(il(o,t,hs,!nl),He(o,0,!0)!==0)break e;ji=t,o.timeoutHandle=zv(iv.bind(null,o,s,ns,Md,Lm,t,hs,eo,nc,nl,p,"Throttled",-0,0),f);break e}iv(o,s,ns,Md,Lm,t,hs,eo,nc,nl,p,null,-0,0)}}break}while(!0);Er(e)}function iv(e,t,s,o,f,p,S,R,V,ue,xe,Ce,me,ge){if(e.timeoutHandle=-1,Ce=t.subtreeFlags,Ce&8192||(Ce&16785408)===16785408){Ce={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:ra},Zg(t,p,Ce);var Xe=(p&62914560)===p?jd-je():(p&4194048)===p?nv-je():0;if(Xe=KS(Ce,Xe),Xe!==null){ji=p,e.cancelPendingCommit=Xe(hv.bind(null,e,t,p,s,o,f,S,R,V,xe,Ce,null,me,ge)),il(e,p,S,!ue);return}}hv(e,t,p,s,o,f,S,R,V)}function dS(e){for(var t=e;;){var s=t.tag;if((s===0||s===11||s===15)&&t.flags&16384&&(s=t.updateQueue,s!==null&&(s=s.stores,s!==null)))for(var o=0;o<s.length;o++){var f=s[o],p=f.getSnapshot;f=f.value;try{if(!an(p(),f))return!1}catch{return!1}}if(s=t.child,t.subtreeFlags&16384&&s!==null)s.return=t,t=s;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 il(e,t,s,o){t&=~Dm,t&=~eo,e.suspendedLanes|=t,e.pingedLanes&=~t,o&&(e.warmLanes|=t),o=e.expirationTimes;for(var f=t;0<f;){var p=31-xt(f),S=1<<p;o[p]=-1,f&=~S}s!==0&&Gs(e,s,t)}function Nd(){return(Pt&6)===0?(mu(0),!1):!0}function Om(){if(Et!==null){if(Vt===0)var e=Et.return;else e=Et,Wa=rr=null,eu(e),Is=null,$l=0,e=Et;for(;e!==null;)Og(e.alternate,e),e=e.return;Et=null}}function sc(e,t){var s=e.timeoutHandle;s!==-1&&(e.timeoutHandle=-1,ES(s)),s=e.cancelPendingCommit,s!==null&&(e.cancelPendingCommit=null,s()),ji=0,Om(),tn=e,Et=s=ya(e.current,null),Lt=t,Vt=0,ms=null,nl=!1,tc=Sn(e,t),Em=!1,nc=hs=Dm=eo=al=bn=0,ns=du=null,Lm=!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-xt(o),p=1<<f;t|=e[f],o&=~p}return ki=t,ar(),s}function lv(e,t){et=null,z.H=au,t===Nr||t===Hl?(t=Qi(),Vt=3):t===Yc?(t=Qi(),Vt=4):Vt=t===pm?8:t!==null&&typeof t=="object"&&typeof t.then=="function"?6:1,ms=t,Et===null&&(bn=1,vd(e,Pn(t,e.current)))}function ov(){var e=wa.current;return e===null?!0:(Lt&4194048)===Lt?Sa===null:(Lt&62914560)===Lt||(Lt&536870912)!==0?e===Sa:!1}function cv(){var e=z.H;return z.H=au,e===null?au:e}function uv(){var e=z.A;return z.A=cS,e}function Td(){bn=4,nl||(Lt&4194048)!==Lt&&wa.current!==null||(tc=!0),(al&134217727)===0&&(eo&134217727)===0||tn===null||il(tn,Lt,hs,!1)}function Hm(e,t,s){var o=Pt;Pt|=2;var f=cv(),p=uv();(tn!==e||Lt!==t)&&(Md=null,sc(e,t)),t=!1;var S=bn;e:do try{if(Vt!==0&&Et!==null){var R=Et,V=ms;switch(Vt){case 8:Om(),S=6;break e;case 3:case 2:case 9:case 6:wa.current===null&&(t=!0);var ue=Vt;if(Vt=0,ms=null,rc(e,R,V,ue),s&&tc){S=0;break e}break;default:ue=Vt,Vt=0,ms=null,rc(e,R,V,ue)}}fS(),S=bn;break}catch(xe){lv(e,xe)}while(!0);return t&&e.shellSuspendCounter++,Wa=rr=null,Pt=o,z.H=f,z.A=p,Et===null&&(tn=null,Lt=0,ar()),S}function fS(){for(;Et!==null;)dv(Et)}function mS(e,t){var s=Pt;Pt|=2;var o=cv(),f=uv();tn!==e||Lt!==t?(Md=null,Ad=je()+500,sc(e,t)):tc=Sn(e,t);e:do try{if(Vt!==0&&Et!==null){t=Et;var p=ms;t:switch(Vt){case 1:Vt=0,ms=null,rc(e,t,p,1);break;case 2:case 9:if(Kc(p)){Vt=0,ms=null,fv(t);break}t=function(){Vt!==2&&Vt!==9||tn!==e||(Vt=7),Er(e)},p.then(t,t);break e;case 3:Vt=7;break e;case 4:Vt=5;break e;case 7:Kc(p)?(Vt=0,ms=null,fv(t)):(Vt=0,ms=null,rc(e,t,p,7));break;case 5:var S=null;switch(Et.tag){case 26:S=Et.memoizedState;case 5:case 27:var R=Et;if(S?Xv(S):R.stateNode.complete){Vt=0,ms=null;var V=R.sibling;if(V!==null)Et=V;else{var ue=R.return;ue!==null?(Et=ue,Rd(ue)):Et=null}break t}}Vt=0,ms=null,rc(e,t,p,5);break;case 6:Vt=0,ms=null,rc(e,t,p,6);break;case 8:Om(),bn=6;break e;default:throw Error(l(462))}}hS();break}catch(xe){lv(e,xe)}while(!0);return Wa=rr=null,z.H=o,z.A=f,Pt=s,Et!==null?0:(tn=null,Lt=0,ar(),bn)}function hS(){for(;Et!==null&&!U();)dv(Et)}function dv(e){var t=Ig(e.alternate,e,ki);e.memoizedProps=e.pendingProps,t===null?Rd(e):Et=t}function fv(e){var t=e,s=t.alternate;switch(t.tag){case 15:case 0:t=Tg(s,t,t.pendingProps,t.type,void 0,Lt);break;case 11:t=Tg(s,t,t.pendingProps,t.type.render,t.ref,Lt);break;case 5:eu(t);default:Og(s,t),t=Et=_l(t,ki),t=Ig(s,t,ki)}e.memoizedProps=e.pendingProps,t===null?Rd(e):Et=t}function rc(e,t,s,o){Wa=rr=null,eu(t),Is=null,$l=0;var f=t.return;try{if(nS(e,f,t,s,Lt)){bn=1,vd(e,Pn(s,e.current)),Et=null;return}}catch(p){if(f!==null)throw Et=f,p;bn=1,vd(e,Pn(s,e.current)),Et=null;return}t.flags&32768?(wt||o===1?e=!0:tc||(Lt&536870912)!==0?e=!1:(nl=e=!0,(o===2||o===9||o===3||o===6)&&(o=wa.current,o!==null&&o.tag===13&&(o.flags|=16384))),mv(t,e)):Rd(t)}function Rd(e){var t=e;do{if((t.flags&32768)!==0){mv(t,nl);return}e=t.return;var s=rS(t.alternate,t,ki);if(s!==null){Et=s;return}if(t=t.sibling,t!==null){Et=t;return}Et=t=e}while(t!==null);bn===0&&(bn=5)}function mv(e,t){do{var s=iS(e.alternate,e);if(s!==null){s.flags&=32767,Et=s;return}if(s=e.return,s!==null&&(s.flags|=32768,s.subtreeFlags=0,s.deletions=null),!t&&(e=e.sibling,e!==null)){Et=e;return}Et=e=s}while(e!==null);bn=6,Et=null}function hv(e,t,s,o,f,p,S,R,V){e.cancelPendingCommit=null;do Ed();while(Un!==0);if((Pt&6)!==0)throw Error(l(327));if(t!==null){if(t===e.current)throw Error(l(177));if(p=t.lanes|t.childLanes,p|=No,Wn(e,s,p,S,R,V),e===tn&&(Et=tn=null,Lt=0),ac=t,rl=e,ji=s,_m=p,Im=f,av=o,(t.subtreeFlags&10256)!==0||(t.flags&10256)!==0?(e.callbackNode=null,e.callbackPriority=0,yS(pt,function(){return bv(),null})):(e.callbackNode=null,e.callbackPriority=0),o=(t.flags&13878)!==0,(t.subtreeFlags&13878)!==0||o){o=z.T,z.T=null,f=se.p,se.p=2,S=Pt,Pt|=4;try{lS(e,t,s)}finally{Pt=S,se.p=f,z.T=o}}Un=1,pv(),gv(),vv()}}function pv(){if(Un===1){Un=0;var e=rl,t=ac,s=(t.flags&13878)!==0;if((t.subtreeFlags&13878)!==0||s){s=z.T,z.T=null;var o=se.p;se.p=2;var f=Pt;Pt|=4;try{Kg(t,e);var p=Qm,S=jo(e.containerInfo),R=p.focusedElem,V=p.selectionRange;if(S!==R&&R&&R.ownerDocument&&sd(R.ownerDocument.documentElement,R)){if(V!==null&&Kr(R)){var ue=V.start,xe=V.end;if(xe===void 0&&(xe=ue),"selectionStart"in R)R.selectionStart=ue,R.selectionEnd=Math.min(xe,R.value.length);else{var Ce=R.ownerDocument||document,me=Ce&&Ce.defaultView||window;if(me.getSelection){var ge=me.getSelection(),Xe=R.textContent.length,ot=Math.min(V.start,Xe),Xt=V.end===void 0?ot:Math.min(V.end,Xe);!ge.extend&&ot>Xt&&(S=Xt,Xt=ot,ot=S);var ae=ad(R,ot),X=ad(R,Xt);if(ae&&X&&(ge.rangeCount!==1||ge.anchorNode!==ae.node||ge.anchorOffset!==ae.offset||ge.focusNode!==X.node||ge.focusOffset!==X.offset)){var oe=Ce.createRange();oe.setStart(ae.node,ae.offset),ge.removeAllRanges(),ot>Xt?(ge.addRange(oe),ge.extend(X.node,X.offset)):(oe.setEnd(X.node,X.offset),ge.addRange(oe))}}}}for(Ce=[],ge=R;ge=ge.parentNode;)ge.nodeType===1&&Ce.push({element:ge,left:ge.scrollLeft,top:ge.scrollTop});for(typeof R.focus=="function"&&R.focus(),R=0;R<Ce.length;R++){var we=Ce[R];we.element.scrollLeft=we.left,we.element.scrollTop=we.top}}Ud=!!Km,Qm=Km=null}finally{Pt=f,se.p=o,z.T=s}}e.current=t,Un=2}}function gv(){if(Un===2){Un=0;var e=rl,t=ac,s=(t.flags&8772)!==0;if((t.subtreeFlags&8772)!==0||s){s=z.T,z.T=null;var o=se.p;se.p=2;var f=Pt;Pt|=4;try{qg(e,t.alternate,t)}finally{Pt=f,se.p=o,z.T=s}}Un=3}}function vv(){if(Un===4||Un===3){Un=0,ve();var e=rl,t=ac,s=ji,o=av;(t.subtreeFlags&10256)!==0||(t.flags&10256)!==0?Un=5:(Un=0,ac=rl=null,yv(e,e.pendingLanes));var f=e.pendingLanes;if(f===0&&(sl=null),fn(s),t=t.stateNode,Ae&&typeof Ae.onCommitFiberRoot=="function")try{Ae.onCommitFiberRoot(Oe,t,void 0,(t.current.flags&128)===128)}catch{}if(o!==null){t=z.T,f=se.p,se.p=2,z.T=null;try{for(var p=e.onRecoverableError,S=0;S<o.length;S++){var R=o[S];p(R.value,{componentStack:R.stack})}}finally{z.T=t,se.p=f}}(ji&3)!==0&&Ed(),Er(e),f=e.pendingLanes,(s&261930)!==0&&(f&42)!==0?e===zm?fu++:(fu=0,zm=e):fu=0,mu(0)}}function yv(e,t){(e.pooledCacheLanes&=t)===0&&(t=e.pooledCache,t!=null&&(e.pooledCache=null,or(t)))}function Ed(){return pv(),gv(),vv(),bv()}function bv(){if(Un!==5)return!1;var e=rl,t=_m;_m=0;var s=fn(ji),o=z.T,f=se.p;try{se.p=32>s?32:s,z.T=null,s=Im,Im=null;var p=rl,S=ji;if(Un=0,ac=rl=null,ji=0,(Pt&6)!==0)throw Error(l(331));var R=Pt;if(Pt|=4,ev(p.current),Xg(p,p.current,S,s),Pt=R,mu(0,!1),Ae&&typeof Ae.onPostCommitFiberRoot=="function")try{Ae.onPostCommitFiberRoot(Oe,p)}catch{}return!0}finally{se.p=f,z.T=o,yv(e,t)}}function xv(e,t,s){t=Pn(s,t),t=hm(e.stateNode,t,2),e=Os(e,t,2),e!==null&&(qs(e,2),Er(e))}function Wt(e,t,s){if(e.tag===3)xv(e,e,s);else for(;t!==null;){if(t.tag===3){xv(t,e,s);break}else if(t.tag===1){var o=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof o.componentDidCatch=="function"&&(sl===null||!sl.has(o))){e=Pn(s,e),s=wg(2),o=Os(t,s,2),o!==null&&(Sg(s,o,t,e),qs(o,2),Er(o));break}}t=t.return}}function Fm(e,t,s){var o=e.pingCache;if(o===null){o=e.pingCache=new uS;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(s)||(Em=!0,f.add(s),e=pS.bind(null,e,t,s),t.then(e,e))}function pS(e,t,s){var o=e.pingCache;o!==null&&o.delete(t),e.pingedLanes|=e.suspendedLanes&s,e.warmLanes&=~s,tn===e&&(Lt&s)===s&&(bn===4||bn===3&&(Lt&62914560)===Lt&&300>je()-jd?(Pt&2)===0&&sc(e,0):Dm|=s,nc===Lt&&(nc=0)),Er(e)}function wv(e,t){t===0&&(t=ws()),e=_a(e,t),e!==null&&(qs(e,t),Er(e))}function gS(e){var t=e.memoizedState,s=0;t!==null&&(s=t.retryLane),wv(e,s)}function vS(e,t){var s=0;switch(e.tag){case 31:case 13:var o=e.stateNode,f=e.memoizedState;f!==null&&(s=f.retryLane);break;case 19:o=e.stateNode;break;case 22:o=e.stateNode._retryCache;break;default:throw Error(l(314))}o!==null&&o.delete(t),wv(e,s)}function yS(e,t){return Ze(e,t)}var Dd=null,ic=null,$m=!1,Ld=!1,Bm=!1,ll=0;function Er(e){e!==ic&&e.next===null&&(ic===null?Dd=ic=e:ic=ic.next=e),Ld=!0,$m||($m=!0,xS())}function mu(e,t){if(!Bm&&Ld){Bm=!0;do for(var s=!1,o=Dd;o!==null;){if(e!==0){var f=o.pendingLanes;if(f===0)var p=0;else{var S=o.suspendedLanes,R=o.pingedLanes;p=(1<<31-xt(42|e)+1)-1,p&=f&~(S&~R),p=p&201326741?p&201326741|1:p?p|2:0}p!==0&&(s=!0,jv(o,p))}else p=Lt,p=He(o,o===tn?p:0,o.cancelPendingCommit!==null||o.timeoutHandle!==-1),(p&3)===0||Sn(o,p)||(s=!0,jv(o,p));o=o.next}while(s);Bm=!1}}function bS(){Sv()}function Sv(){Ld=$m=!1;var e=0;ll!==0&&RS()&&(e=ll);for(var t=je(),s=null,o=Dd;o!==null;){var f=o.next,p=Cv(o,t);p===0?(o.next=null,s===null?Dd=f:s.next=f,f===null&&(ic=s)):(s=o,(e!==0||(p&3)!==0)&&(Ld=!0)),o=f}Un!==0&&Un!==5||mu(e),ll!==0&&(ll=0)}function Cv(e,t){for(var s=e.suspendedLanes,o=e.pingedLanes,f=e.expirationTimes,p=e.pendingLanes&-62914561;0<p;){var S=31-xt(p),R=1<<S,V=f[S];V===-1?((R&s)===0||(R&o)!==0)&&(f[S]=zn(R,t)):V<=t&&(e.expiredLanes|=R),p&=~R}if(t=tn,s=Lt,s=He(e,e===t?s:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),o=e.callbackNode,s===0||e===t&&(Vt===2||Vt===9)||e.cancelPendingCommit!==null)return o!==null&&o!==null&&ut(o),e.callbackNode=null,e.callbackPriority=0;if((s&3)===0||Sn(e,s)){if(t=s&-s,t===e.callbackPriority)return t;switch(o!==null&&ut(o),fn(s)){case 2:case 8:s=it;break;case 32:s=pt;break;case 268435456:s=kt;break;default:s=pt}return o=kv.bind(null,e),s=Ze(s,o),e.callbackPriority=t,e.callbackNode=s,t}return o!==null&&o!==null&&ut(o),e.callbackPriority=2,e.callbackNode=null,2}function kv(e,t){if(Un!==0&&Un!==5)return e.callbackNode=null,e.callbackPriority=0,null;var s=e.callbackNode;if(Ed()&&e.callbackNode!==s)return null;var o=Lt;return o=He(e,e===tn?o:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),o===0?null:(rv(e,o,t),Cv(e,je()),e.callbackNode!=null&&e.callbackNode===s?kv.bind(null,e):null)}function jv(e,t){if(Ed())return null;rv(e,t,!0)}function xS(){DS(function(){(Pt&6)!==0?Ze(dt,bS):Sv()})}function Pm(){if(ll===0){var e=oi;e===0&&(e=at,at<<=1,(at&261888)===0&&(at=256)),ll=e}return ll}function Av(e){return e==null||typeof e=="symbol"||typeof e=="boolean"?null:typeof e=="function"?e:Pr(""+e)}function Mv(e,t){var s=t.ownerDocument.createElement("input");return s.name=t.name,s.value=t.value,e.id&&s.setAttribute("form",e.id),t.parentNode.insertBefore(s,t),e=new FormData(e),s.parentNode.removeChild(s),e}function wS(e,t,s,o,f){if(t==="submit"&&s&&s.stateNode===f){var p=Av((f[Te]||null).action),S=o.submitter;S&&(t=(t=S[Te]||null)?Av(t.formAction):S.getAttribute("formAction"),t!==null&&(p=t,S=null));var R=new Qs("action","action",null,o,f);e.push({event:R,listeners:[{instance:null,listener:function(){if(o.defaultPrevented){if(ll!==0){var V=S?Mv(f,S):new FormData(f);om(s,{pending:!0,data:V,method:f.method,action:p},null,V)}}else typeof p=="function"&&(R.preventDefault(),V=S?Mv(f,S):new FormData(f),om(s,{pending:!0,data:V,method:f.method,action:p},p,V))},currentTarget:f}]})}}for(var Um=0;Um<Gi.length;Um++){var qm=Gi[Um],SS=qm.toLowerCase(),CS=qm[0].toUpperCase()+qm.slice(1);vn(SS,"on"+CS)}vn(Ns,"onAnimationEnd"),vn(Bc,"onAnimationIteration"),vn(qi,"onAnimationStart"),vn("dblclick","onDoubleClick"),vn("focusin","onFocus"),vn("focusout","onBlur"),vn(Pc,"onTransitionRun"),vn(Ao,"onTransitionStart"),vn(Mo,"onTransitionCancel"),vn(Ua,"onTransitionEnd"),Tn("onMouseEnter",["mouseout","mouseover"]),Tn("onMouseLeave",["mouseout","mouseover"]),Tn("onPointerEnter",["pointerout","pointerover"]),Tn("onPointerLeave",["pointerout","pointerover"]),Cn("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),Cn("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),Cn("onBeforeInput",["compositionend","keypress","textInput","paste"]),Cn("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),Cn("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),Cn("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var hu="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(" "),kS=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(hu));function Nv(e,t){t=(t&4)!==0;for(var s=0;s<e.length;s++){var o=e[s],f=o.event;o=o.listeners;e:{var p=void 0;if(t)for(var S=o.length-1;0<=S;S--){var R=o[S],V=R.instance,ue=R.currentTarget;if(R=R.listener,V!==p&&f.isPropagationStopped())break e;p=R,f.currentTarget=ue;try{p(f)}catch(xe){Bn(xe)}f.currentTarget=null,p=V}else for(S=0;S<o.length;S++){if(R=o[S],V=R.instance,ue=R.currentTarget,R=R.listener,V!==p&&f.isPropagationStopped())break e;p=R,f.currentTarget=ue;try{p(f)}catch(xe){Bn(xe)}f.currentTarget=null,p=V}}}}function Dt(e,t){var s=t[yt];s===void 0&&(s=t[yt]=new Set);var o=e+"__bubble";s.has(o)||(Tv(t,e,2,!1),s.add(o))}function Gm(e,t,s){var o=0;t&&(o|=4),Tv(s,e,o,t)}var _d="_reactListening"+Math.random().toString(36).slice(2);function Vm(e){if(!e[_d]){e[_d]=!0,Vs.forEach(function(s){s!=="selectionchange"&&(kS.has(s)||Gm(s,!1,e),Gm(s,!0,e))});var t=e.nodeType===9?e:e.ownerDocument;t===null||t[_d]||(t[_d]=!0,Gm("selectionchange",!1,t))}}function Tv(e,t,s,o){switch(sy(t)){case 2:var f=ZS;break;case 8:f=JS;break;default:f=lh}s=f.bind(null,t,s,e),f=void 0,!bo||t!=="touchstart"&&t!=="touchmove"&&t!=="wheel"||(f=!0),o?f!==void 0?e.addEventListener(t,s,{capture:!0,passive:f}):e.addEventListener(t,s,!0):f!==void 0?e.addEventListener(t,s,{passive:f}):e.addEventListener(t,s,!1)}function Wm(e,t,s,o,f){var p=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 R=o.stateNode.containerInfo;if(R===f)break;if(S===4)for(S=o.return;S!==null;){var V=S.tag;if((V===3||V===4)&&S.stateNode.containerInfo===f)return;S=S.return}for(;R!==null;){if(S=On(R),S===null)return;if(V=S.tag,V===5||V===6||V===26||V===27){o=p=S;continue e}R=R.parentNode}}o=o.return}Al(function(){var ue=p,xe=_i(s),Ce=[];e:{var me=nr.get(e);if(me!==void 0){var ge=Qs,Xe=e;switch(e){case"keypress":if(Ml(s)===0)break e;case"keydown":case"keyup":ge=Hi;break;case"focusin":Xe="focus",ge=Oi;break;case"focusout":Xe="blur",ge=Oi;break;case"beforeblur":case"afterblur":ge=Oi;break;case"click":if(s.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":ge=xr;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":ge=xo;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":ge=Wp;break;case Ns:case Bc:case qi:ge=So;break;case Ua:ge=Kp;break;case"scroll":case"scrollend":ge=br;break;case"wheel":ge=td;break;case"copy":case"cut":case"paste":ge=Ju;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":ge=qr;break;case"toggle":case"beforetoggle":ge=nm}var ot=(t&4)!==0,Xt=!ot&&(e==="scroll"||e==="scrollend"),ae=ot?me!==null?me+"Capture":null:me;ot=[];for(var X=ue,oe;X!==null;){var we=X;if(oe=we.stateNode,we=we.tag,we!==5&&we!==26&&we!==27||oe===null||ae===null||(we=yr(X,ae),we!=null&&ot.push(pu(X,we,oe))),Xt)break;X=X.return}0<ot.length&&(me=new ge(me,Xe,null,s,xe),Ce.push({event:me,listeners:ot}))}}if((t&7)===0){e:{if(me=e==="mouseover"||e==="pointerover",ge=e==="mouseout"||e==="pointerout",me&&s!==Cs&&(Xe=s.relatedTarget||s.fromElement)&&(On(Xe)||Xe[Ue]))break e;if((ge||me)&&(me=xe.window===xe?xe:(me=xe.ownerDocument)?me.defaultView||me.parentWindow:window,ge?(Xe=s.relatedTarget||s.toElement,ge=ue,Xe=Xe?On(Xe):null,Xe!==null&&(Xt=d(Xe),ot=Xe.tag,Xe!==Xt||ot!==5&&ot!==27&&ot!==6)&&(Xe=null)):(ge=null,Xe=ue),ge!==Xe)){if(ot=xr,we="onMouseLeave",ae="onMouseEnter",X="mouse",(e==="pointerout"||e==="pointerover")&&(ot=qr,we="onPointerLeave",ae="onPointerEnter",X="pointer"),Xt=ge==null?me:nn(ge),oe=Xe==null?me:nn(Xe),me=new ot(we,X+"leave",ge,s,xe),me.target=Xt,me.relatedTarget=oe,we=null,On(xe)===ue&&(ot=new ot(ae,X+"enter",Xe,s,xe),ot.target=oe,ot.relatedTarget=Xt,we=ot),Xt=we,ge&&Xe)t:{for(ot=jS,ae=ge,X=Xe,oe=0,we=ae;we;we=ot(we))oe++;we=0;for(var rt=X;rt;rt=ot(rt))we++;for(;0<oe-we;)ae=ot(ae),oe--;for(;0<we-oe;)X=ot(X),we--;for(;oe--;){if(ae===X||X!==null&&ae===X.alternate){ot=ae;break t}ae=ot(ae),X=ot(X)}ot=null}else ot=null;ge!==null&&Rv(Ce,me,ge,ot,!1),Xe!==null&&Xt!==null&&Rv(Ce,Xt,Xe,ot,!0)}}e:{if(me=ue?nn(ue):window,ge=me.nodeName&&me.nodeName.toLowerCase(),ge==="select"||ge==="input"&&me.type==="file")var Ht=Wr;else if(gt(me))if(lt)Ht=$i;else{Ht=Yr;var Je=Fc}else ge=me.nodeName,!ge||ge.toLowerCase()!=="input"||me.type!=="checkbox"&&me.type!=="radio"?ue&&Br(ue.elementType)&&(Ht=Wr):Ht=Da;if(Ht&&(Ht=Ht(e,ue))){Rt(Ce,Ht,s,xe);break e}Je&&Je(e,me,ue),e==="focusout"&&ue&&me.type==="number"&&ue.memoizedProps.value!=null&&Fn(me,"number",me.value)}switch(Je=ue?nn(ue):window,e){case"focusin":(gt(Je)||Je.contentEditable==="true")&&(Qr=Je,un=ue,Bi=null);break;case"focusout":Bi=un=Qr=null;break;case"mousedown":Pi=!0;break;case"contextmenu":case"mouseup":case"dragend":Pi=!1,Xr(Ce,s,xe);break;case"selectionchange":if(Qp)break;case"keydown":case"keyup":Xr(Ce,s,xe)}var jt;if(Dc)e:{switch(e){case"compositionstart":var _t="onCompositionStart";break e;case"compositionend":_t="onCompositionEnd";break e;case"compositionupdate":_t="onCompositionUpdate";break e}_t=void 0}else Vr?_c(e,s)&&(_t="onCompositionEnd"):e==="keydown"&&s.keyCode===229&&(_t="onCompositionStart");_t&&(Fi&&s.locale!=="ko"&&(Vr||_t!=="onCompositionStart"?_t==="onCompositionEnd"&&Vr&&(jt=la()):(js=xe,Pa="value"in js?js.value:js.textContent,Vr=!0)),Je=Id(ue,_t),0<Je.length&&(_t=new cs(_t,e,null,s,xe),Ce.push({event:_t,listeners:Je}),jt?_t.data=jt:(jt=Ic(s),jt!==null&&(_t.data=jt)))),(jt=Lc?El(e,s):zc(e,s))&&(_t=Id(ue,"onBeforeInput"),0<_t.length&&(Je=new cs("onBeforeInput","beforeinput",null,s,xe),Ce.push({event:Je,listeners:_t}),Je.data=jt)),wS(Ce,e,ue,s,xe)}Nv(Ce,t)})}function pu(e,t,s){return{instance:e,listener:t,currentTarget:s}}function Id(e,t){for(var s=t+"Capture",o=[];e!==null;){var f=e,p=f.stateNode;if(f=f.tag,f!==5&&f!==26&&f!==27||p===null||(f=yr(e,s),f!=null&&o.unshift(pu(e,f,p)),f=yr(e,t),f!=null&&o.push(pu(e,f,p))),e.tag===3)return o;e=e.return}return[]}function jS(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5&&e.tag!==27);return e||null}function Rv(e,t,s,o,f){for(var p=t._reactName,S=[];s!==null&&s!==o;){var R=s,V=R.alternate,ue=R.stateNode;if(R=R.tag,V!==null&&V===o)break;R!==5&&R!==26&&R!==27||ue===null||(V=ue,f?(ue=yr(s,p),ue!=null&&S.unshift(pu(s,ue,V))):f||(ue=yr(s,p),ue!=null&&S.push(pu(s,ue,V)))),s=s.return}S.length!==0&&e.push({event:t,listeners:S})}var AS=/\r\n?/g,MS=/\u0000|\uFFFD/g;function Ev(e){return(typeof e=="string"?e:""+e).replace(AS,`
9
+ `).replace(MS,"")}function Dv(e,t){return t=Ev(t),Ev(e)===t}function Qt(e,t,s,o,f,p){switch(s){case"children":typeof o=="string"?t==="body"||t==="textarea"&&o===""||kn(e,o):(typeof o=="number"||typeof o=="bigint")&&t!=="body"&&kn(e,""+o);break;case"className":Hn(e,"class",o);break;case"tabIndex":Hn(e,"tabindex",o);break;case"dir":case"role":case"viewBox":case"width":case"height":Hn(e,s,o);break;case"style":kl(e,o,p);break;case"data":if(t!=="object"){Hn(e,"data",o);break}case"src":case"href":if(o===""&&(t!=="a"||s!=="href")){e.removeAttribute(s);break}if(o==null||typeof o=="function"||typeof o=="symbol"||typeof o=="boolean"){e.removeAttribute(s);break}o=Pr(""+o),e.setAttribute(s,o);break;case"action":case"formAction":if(typeof o=="function"){e.setAttribute(s,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof p=="function"&&(s==="formAction"?(t!=="input"&&Qt(e,t,"name",f.name,f,null),Qt(e,t,"formEncType",f.formEncType,f,null),Qt(e,t,"formMethod",f.formMethod,f,null),Qt(e,t,"formTarget",f.formTarget,f,null)):(Qt(e,t,"encType",f.encType,f,null),Qt(e,t,"method",f.method,f,null),Qt(e,t,"target",f.target,f,null)));if(o==null||typeof o=="symbol"||typeof o=="boolean"){e.removeAttribute(s);break}o=Pr(""+o),e.setAttribute(s,o);break;case"onClick":o!=null&&(e.onclick=ra);break;case"onScroll":o!=null&&Dt("scroll",e);break;case"onScrollEnd":o!=null&&Dt("scrollend",e);break;case"dangerouslySetInnerHTML":if(o!=null){if(typeof o!="object"||!("__html"in o))throw Error(l(61));if(s=o.__html,s!=null){if(f.children!=null)throw Error(l(60));e.innerHTML=s}}break;case"multiple":e.multiple=o&&typeof o!="function"&&typeof o!="symbol";break;case"muted":e.muted=o&&typeof o!="function"&&typeof o!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(o==null||typeof o=="function"||typeof o=="boolean"||typeof o=="symbol"){e.removeAttribute("xlink:href");break}s=Pr(""+o),e.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",s);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":o!=null&&typeof o!="function"&&typeof o!="symbol"?e.setAttribute(s,""+o):e.removeAttribute(s);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":o&&typeof o!="function"&&typeof o!="symbol"?e.setAttribute(s,""):e.removeAttribute(s);break;case"capture":case"download":o===!0?e.setAttribute(s,""):o!==!1&&o!=null&&typeof o!="function"&&typeof o!="symbol"?e.setAttribute(s,o):e.removeAttribute(s);break;case"cols":case"rows":case"size":case"span":o!=null&&typeof o!="function"&&typeof o!="symbol"&&!isNaN(o)&&1<=o?e.setAttribute(s,o):e.removeAttribute(s);break;case"rowSpan":case"start":o==null||typeof o=="function"||typeof o=="symbol"||isNaN(o)?e.removeAttribute(s):e.setAttribute(s,o);break;case"popover":Dt("beforetoggle",e),Dt("toggle",e),Fr(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":Fr(e,"is",o);break;case"innerText":case"textContent":break;default:(!(2<s.length)||s[0]!=="o"&&s[0]!=="O"||s[1]!=="n"&&s[1]!=="N")&&(s=os.get(s)||s,Fr(e,s,o))}}function Ym(e,t,s,o,f,p){switch(s){case"style":kl(e,o,p);break;case"dangerouslySetInnerHTML":if(o!=null){if(typeof o!="object"||!("__html"in o))throw Error(l(61));if(s=o.__html,s!=null){if(f.children!=null)throw Error(l(60));e.innerHTML=s}}break;case"children":typeof o=="string"?kn(e,o):(typeof o=="number"||typeof o=="bigint")&&kn(e,""+o);break;case"onScroll":o!=null&&Dt("scroll",e);break;case"onScrollEnd":o!=null&&Dt("scrollend",e);break;case"onClick":o!=null&&(e.onclick=ra);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!zt.hasOwnProperty(s))e:{if(s[0]==="o"&&s[1]==="n"&&(f=s.endsWith("Capture"),t=s.slice(2,f?s.length-7:void 0),p=e[Te]||null,p=p!=null?p[s]:null,typeof p=="function"&&e.removeEventListener(t,p,f),typeof o=="function")){typeof p!="function"&&p!==null&&(s in e?e[s]=null:e.hasAttribute(s)&&e.removeAttribute(s)),e.addEventListener(t,o,f);break e}s in e?e[s]=o:o===!0?e.setAttribute(s,""):Fr(e,s,o)}}}function fa(e,t,s){switch(t){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":Dt("error",e),Dt("load",e);var o=!1,f=!1,p;for(p in s)if(s.hasOwnProperty(p)){var S=s[p];if(S!=null)switch(p){case"src":o=!0;break;case"srcSet":f=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(l(137,t));default:Qt(e,t,p,S,s,null)}}f&&Qt(e,t,"srcSet",s.srcSet,s,null),o&&Qt(e,t,"src",s.src,s,null);return;case"input":Dt("invalid",e);var R=p=S=f=null,V=null,ue=null;for(o in s)if(s.hasOwnProperty(o)){var xe=s[o];if(xe!=null)switch(o){case"name":f=xe;break;case"type":S=xe;break;case"checked":V=xe;break;case"defaultChecked":ue=xe;break;case"value":p=xe;break;case"defaultValue":R=xe;break;case"children":case"dangerouslySetInnerHTML":if(xe!=null)throw Error(l(137,t));break;default:Qt(e,t,o,xe,s,null)}}Li(e,p,R,V,ue,S,f,!1);return;case"select":Dt("invalid",e),o=S=p=null;for(f in s)if(s.hasOwnProperty(f)&&(R=s[f],R!=null))switch(f){case"value":p=R;break;case"defaultValue":S=R;break;case"multiple":o=R;default:Qt(e,t,f,R,s,null)}t=p,s=S,e.multiple=!!o,t!=null?Ra(e,!!o,t,!1):s!=null&&Ra(e,!!o,s,!0);return;case"textarea":Dt("invalid",e),p=f=o=null;for(S in s)if(s.hasOwnProperty(S)&&(R=s[S],R!=null))switch(S){case"value":o=R;break;case"defaultValue":f=R;break;case"children":p=R;break;case"dangerouslySetInnerHTML":if(R!=null)throw Error(l(91));break;default:Qt(e,t,S,R,s,null)}$r(e,o,f,p);return;case"option":for(V in s)s.hasOwnProperty(V)&&(o=s[V],o!=null)&&(V==="selected"?e.selected=o&&typeof o!="function"&&typeof o!="symbol":Qt(e,t,V,o,s,null));return;case"dialog":Dt("beforetoggle",e),Dt("toggle",e),Dt("cancel",e),Dt("close",e);break;case"iframe":case"object":Dt("load",e);break;case"video":case"audio":for(o=0;o<hu.length;o++)Dt(hu[o],e);break;case"image":Dt("error",e),Dt("load",e);break;case"details":Dt("toggle",e);break;case"embed":case"source":case"link":Dt("error",e),Dt("load",e);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(ue in s)if(s.hasOwnProperty(ue)&&(o=s[ue],o!=null))switch(ue){case"children":case"dangerouslySetInnerHTML":throw Error(l(137,t));default:Qt(e,t,ue,o,s,null)}return;default:if(Br(t)){for(xe in s)s.hasOwnProperty(xe)&&(o=s[xe],o!==void 0&&Ym(e,t,xe,o,s,void 0));return}}for(R in s)s.hasOwnProperty(R)&&(o=s[R],o!=null&&Qt(e,t,R,o,s,null))}function NS(e,t,s,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,p=null,S=null,R=null,V=null,ue=null,xe=null;for(ge in s){var Ce=s[ge];if(s.hasOwnProperty(ge)&&Ce!=null)switch(ge){case"checked":break;case"value":break;case"defaultValue":V=Ce;default:o.hasOwnProperty(ge)||Qt(e,t,ge,null,o,Ce)}}for(var me in o){var ge=o[me];if(Ce=s[me],o.hasOwnProperty(me)&&(ge!=null||Ce!=null))switch(me){case"type":p=ge;break;case"name":f=ge;break;case"checked":ue=ge;break;case"defaultChecked":xe=ge;break;case"value":S=ge;break;case"defaultValue":R=ge;break;case"children":case"dangerouslySetInnerHTML":if(ge!=null)throw Error(l(137,t));break;default:ge!==Ce&&Qt(e,t,me,ge,o,Ce)}}vo(e,S,R,V,ue,xe,p,f);return;case"select":ge=S=R=me=null;for(p in s)if(V=s[p],s.hasOwnProperty(p)&&V!=null)switch(p){case"value":break;case"multiple":ge=V;default:o.hasOwnProperty(p)||Qt(e,t,p,null,o,V)}for(f in o)if(p=o[f],V=s[f],o.hasOwnProperty(f)&&(p!=null||V!=null))switch(f){case"value":me=p;break;case"defaultValue":R=p;break;case"multiple":S=p;default:p!==V&&Qt(e,t,f,p,o,V)}t=R,s=S,o=ge,me!=null?Ra(e,!!s,me,!1):!!o!=!!s&&(t!=null?Ra(e,!!s,t,!0):Ra(e,!!s,s?[]:"",!1));return;case"textarea":ge=me=null;for(R in s)if(f=s[R],s.hasOwnProperty(R)&&f!=null&&!o.hasOwnProperty(R))switch(R){case"value":break;case"children":break;default:Qt(e,t,R,null,o,f)}for(S in o)if(f=o[S],p=s[S],o.hasOwnProperty(S)&&(f!=null||p!=null))switch(S){case"value":me=f;break;case"defaultValue":ge=f;break;case"children":break;case"dangerouslySetInnerHTML":if(f!=null)throw Error(l(91));break;default:f!==p&&Qt(e,t,S,f,o,p)}Ws(e,me,ge);return;case"option":for(var Xe in s)me=s[Xe],s.hasOwnProperty(Xe)&&me!=null&&!o.hasOwnProperty(Xe)&&(Xe==="selected"?e.selected=!1:Qt(e,t,Xe,null,o,me));for(V in o)me=o[V],ge=s[V],o.hasOwnProperty(V)&&me!==ge&&(me!=null||ge!=null)&&(V==="selected"?e.selected=me&&typeof me!="function"&&typeof me!="symbol":Qt(e,t,V,me,o,ge));return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var ot in s)me=s[ot],s.hasOwnProperty(ot)&&me!=null&&!o.hasOwnProperty(ot)&&Qt(e,t,ot,null,o,me);for(ue in o)if(me=o[ue],ge=s[ue],o.hasOwnProperty(ue)&&me!==ge&&(me!=null||ge!=null))switch(ue){case"children":case"dangerouslySetInnerHTML":if(me!=null)throw Error(l(137,t));break;default:Qt(e,t,ue,me,o,ge)}return;default:if(Br(t)){for(var Xt in s)me=s[Xt],s.hasOwnProperty(Xt)&&me!==void 0&&!o.hasOwnProperty(Xt)&&Ym(e,t,Xt,void 0,o,me);for(xe in o)me=o[xe],ge=s[xe],!o.hasOwnProperty(xe)||me===ge||me===void 0&&ge===void 0||Ym(e,t,xe,me,o,ge);return}}for(var ae in s)me=s[ae],s.hasOwnProperty(ae)&&me!=null&&!o.hasOwnProperty(ae)&&Qt(e,t,ae,null,o,me);for(Ce in o)me=o[Ce],ge=s[Ce],!o.hasOwnProperty(Ce)||me===ge||me==null&&ge==null||Qt(e,t,Ce,me,o,ge)}function Lv(e){switch(e){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function TS(){if(typeof performance.getEntriesByType=="function"){for(var e=0,t=0,s=performance.getEntriesByType("resource"),o=0;o<s.length;o++){var f=s[o],p=f.transferSize,S=f.initiatorType,R=f.duration;if(p&&R&&Lv(S)){for(S=0,R=f.responseEnd,o+=1;o<s.length;o++){var V=s[o],ue=V.startTime;if(ue>R)break;var xe=V.transferSize,Ce=V.initiatorType;xe&&Lv(Ce)&&(V=V.responseEnd,S+=xe*(V<R?1:(R-ue)/(V-ue)))}if(--o,t+=8*(p+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,Qm=null;function zd(e){return e.nodeType===9?e:e.ownerDocument}function _v(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 Iv(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 Xm(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 Zm=null;function RS(){var e=window.event;return e&&e.type==="popstate"?e===Zm?!1:(Zm=e,!0):(Zm=null,!1)}var zv=typeof setTimeout=="function"?setTimeout:void 0,ES=typeof clearTimeout=="function"?clearTimeout:void 0,Ov=typeof Promise=="function"?Promise:void 0,DS=typeof queueMicrotask=="function"?queueMicrotask:typeof Ov<"u"?function(e){return Ov.resolve(null).then(e).catch(LS)}:zv;function LS(e){setTimeout(function(){throw e})}function ol(e){return e==="head"}function Hv(e,t){var s=t,o=0;do{var f=s.nextSibling;if(e.removeChild(s),f&&f.nodeType===8)if(s=f.data,s==="/$"||s==="/&"){if(o===0){e.removeChild(f),uc(t);return}o--}else if(s==="$"||s==="$?"||s==="$~"||s==="$!"||s==="&")o++;else if(s==="html")gu(e.ownerDocument.documentElement);else if(s==="head"){s=e.ownerDocument.head,gu(s);for(var p=s.firstChild;p;){var S=p.nextSibling,R=p.nodeName;p[Mt]||R==="SCRIPT"||R==="STYLE"||R==="LINK"&&p.rel.toLowerCase()==="stylesheet"||s.removeChild(p),p=S}}else s==="body"&&gu(e.ownerDocument.body);s=f}while(s);uc(t)}function Fv(e,t){var s=e;e=0;do{var o=s.nextSibling;if(s.nodeType===1?t?(s._stashedDisplay=s.style.display,s.style.display="none"):(s.style.display=s._stashedDisplay||"",s.getAttribute("style")===""&&s.removeAttribute("style")):s.nodeType===3&&(t?(s._stashedText=s.nodeValue,s.nodeValue=""):s.nodeValue=s._stashedText||""),o&&o.nodeType===8)if(s=o.data,s==="/$"){if(e===0)break;e--}else s!=="$"&&s!=="$?"&&s!=="$~"&&s!=="$!"||e++;s=o}while(s)}function Jm(e){var t=e.firstChild;for(t&&t.nodeType===10&&(t=t.nextSibling);t;){var s=t;switch(t=t.nextSibling,s.nodeName){case"HTML":case"HEAD":case"BODY":Jm(s),sa(s);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(s.rel.toLowerCase()==="stylesheet")continue}e.removeChild(s)}}function _S(e,t,s,o){for(;e.nodeType===1;){var f=s;if(e.nodeName.toLowerCase()!==t.toLowerCase()){if(!o&&(e.nodeName!=="INPUT"||e.type!=="hidden"))break}else if(o){if(!e[Mt])switch(t){case"meta":if(!e.hasAttribute("itemprop"))break;return e;case"link":if(p=e.getAttribute("rel"),p==="stylesheet"&&e.hasAttribute("data-precedence"))break;if(p!==f.rel||e.getAttribute("href")!==(f.href==null||f.href===""?null:f.href)||e.getAttribute("crossorigin")!==(f.crossOrigin==null?null:f.crossOrigin)||e.getAttribute("title")!==(f.title==null?null:f.title))break;return e;case"style":if(e.hasAttribute("data-precedence"))break;return e;case"script":if(p=e.getAttribute("src"),(p!==(f.src==null?null:f.src)||e.getAttribute("type")!==(f.type==null?null:f.type)||e.getAttribute("crossorigin")!==(f.crossOrigin==null?null:f.crossOrigin))&&p&&e.hasAttribute("async")&&!e.hasAttribute("itemprop"))break;return e;default:return e}}else if(t==="input"&&e.type==="hidden"){var p=f.name==null?null:""+f.name;if(f.type==="hidden"&&e.getAttribute("name")===p)return e}else return e;if(e=$s(e.nextSibling),e===null)break}return null}function IS(e,t,s){if(t==="")return null;for(;e.nodeType!==3;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!s||(e=$s(e.nextSibling),e===null))return null;return e}function $v(e,t){for(;e.nodeType!==8;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!t||(e=$s(e.nextSibling),e===null))return null;return e}function eh(e){return e.data==="$?"||e.data==="$~"}function th(e){return e.data==="$!"||e.data==="$?"&&e.ownerDocument.readyState!=="loading"}function zS(e,t){var s=e.ownerDocument;if(e.data==="$~")e._reactRetry=t;else if(e.data!=="$?"||s.readyState!=="loading")t();else{var o=function(){t(),s.removeEventListener("DOMContentLoaded",o)};s.addEventListener("DOMContentLoaded",o),e._reactRetry=o}}function $s(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 nh=null;function Bv(e){e=e.nextSibling;for(var t=0;e;){if(e.nodeType===8){var s=e.data;if(s==="/$"||s==="/&"){if(t===0)return $s(e.nextSibling);t--}else s!=="$"&&s!=="$!"&&s!=="$?"&&s!=="$~"&&s!=="&"||t++}e=e.nextSibling}return null}function Pv(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var s=e.data;if(s==="$"||s==="$!"||s==="$?"||s==="$~"||s==="&"){if(t===0)return e;t--}else s!=="/$"&&s!=="/&"||t++}e=e.previousSibling}return null}function Uv(e,t,s){switch(t=zd(s),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 gu(e){for(var t=e.attributes;t.length;)e.removeAttributeNode(t[0]);sa(e)}var Bs=new Map,qv=new Set;function Od(e){return typeof e.getRootNode=="function"?e.getRootNode():e.nodeType===9?e:e.ownerDocument}var Ai=se.d;se.d={f:OS,r:HS,D:FS,C:$S,L:BS,m:PS,X:qS,S:US,M:GS};function OS(){var e=Ai.f(),t=Nd();return e||t}function HS(e){var t=gn(e);t!==null&&t.tag===5&&t.type==="form"?lg(t):Ai.r(e)}var lc=typeof document>"u"?null:document;function Gv(e,t,s){var o=lc;if(o&&typeof t=="string"&&t){var f=Ba(t);f='link[rel="'+e+'"][href="'+f+'"]',typeof s=="string"&&(f+='[crossorigin="'+s+'"]'),qv.has(f)||(qv.add(f),e={rel:e,crossOrigin:s,href:t},o.querySelector(f)===null&&(t=o.createElement("link"),fa(t,"link",e),At(t),o.head.appendChild(t)))}}function FS(e){Ai.D(e),Gv("dns-prefetch",e,null)}function $S(e,t){Ai.C(e,t),Gv("preconnect",e,t)}function BS(e,t,s){Ai.L(e,t,s);var o=lc;if(o&&e&&t){var f='link[rel="preload"][as="'+Ba(t)+'"]';t==="image"&&s&&s.imageSrcSet?(f+='[imagesrcset="'+Ba(s.imageSrcSet)+'"]',typeof s.imageSizes=="string"&&(f+='[imagesizes="'+Ba(s.imageSizes)+'"]')):f+='[href="'+Ba(e)+'"]';var p=f;switch(t){case"style":p=oc(e);break;case"script":p=cc(e)}Bs.has(p)||(e=b({rel:"preload",href:t==="image"&&s&&s.imageSrcSet?void 0:e,as:t},s),Bs.set(p,e),o.querySelector(f)!==null||t==="style"&&o.querySelector(vu(p))||t==="script"&&o.querySelector(yu(p))||(t=o.createElement("link"),fa(t,"link",e),At(t),o.head.appendChild(t)))}}function PS(e,t){Ai.m(e,t);var s=lc;if(s&&e){var o=t&&typeof t.as=="string"?t.as:"script",f='link[rel="modulepreload"][as="'+Ba(o)+'"][href="'+Ba(e)+'"]',p=f;switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":p=cc(e)}if(!Bs.has(p)&&(e=b({rel:"modulepreload",href:e},t),Bs.set(p,e),s.querySelector(f)===null)){switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(s.querySelector(yu(p)))return}o=s.createElement("link"),fa(o,"link",e),At(o),s.head.appendChild(o)}}}function US(e,t,s){Ai.S(e,t,s);var o=lc;if(o&&e){var f=We(o).hoistableStyles,p=oc(e);t=t||"default";var S=f.get(p);if(!S){var R={loading:0,preload:null};if(S=o.querySelector(vu(p)))R.loading=5;else{e=b({rel:"stylesheet",href:e,"data-precedence":t},s),(s=Bs.get(p))&&ah(e,s);var V=S=o.createElement("link");At(V),fa(V,"link",e),V._p=new Promise(function(ue,xe){V.onload=ue,V.onerror=xe}),V.addEventListener("load",function(){R.loading|=1}),V.addEventListener("error",function(){R.loading|=2}),R.loading|=4,Hd(S,t,o)}S={type:"stylesheet",instance:S,count:1,state:R},f.set(p,S)}}}function qS(e,t){Ai.X(e,t);var s=lc;if(s&&e){var o=We(s).hoistableScripts,f=cc(e),p=o.get(f);p||(p=s.querySelector(yu(f)),p||(e=b({src:e,async:!0},t),(t=Bs.get(f))&&sh(e,t),p=s.createElement("script"),At(p),fa(p,"link",e),s.head.appendChild(p)),p={type:"script",instance:p,count:1,state:null},o.set(f,p))}}function GS(e,t){Ai.M(e,t);var s=lc;if(s&&e){var o=We(s).hoistableScripts,f=cc(e),p=o.get(f);p||(p=s.querySelector(yu(f)),p||(e=b({src:e,async:!0,type:"module"},t),(t=Bs.get(f))&&sh(e,t),p=s.createElement("script"),At(p),fa(p,"link",e),s.head.appendChild(p)),p={type:"script",instance:p,count:1,state:null},o.set(f,p))}}function Vv(e,t,s,o){var f=(f=ee.current)?Od(f):null;if(!f)throw Error(l(446));switch(e){case"meta":case"title":return null;case"style":return typeof s.precedence=="string"&&typeof s.href=="string"?(t=oc(s.href),s=We(f).hoistableStyles,o=s.get(t),o||(o={type:"style",instance:null,count:0,state:null},s.set(t,o)),o):{type:"void",instance:null,count:0,state:null};case"link":if(s.rel==="stylesheet"&&typeof s.href=="string"&&typeof s.precedence=="string"){e=oc(s.href);var p=We(f).hoistableStyles,S=p.get(e);if(S||(f=f.ownerDocument||f,S={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},p.set(e,S),(p=f.querySelector(vu(e)))&&!p._p&&(S.instance=p,S.state.loading=5),Bs.has(e)||(s={rel:"preload",as:"style",href:s.href,crossOrigin:s.crossOrigin,integrity:s.integrity,media:s.media,hrefLang:s.hrefLang,referrerPolicy:s.referrerPolicy},Bs.set(e,s),p||VS(f,e,s,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=s.async,s=s.src,typeof s=="string"&&t&&typeof t!="function"&&typeof t!="symbol"?(t=cc(s),s=We(f).hoistableScripts,o=s.get(t),o||(o={type:"script",instance:null,count:0,state:null},s.set(t,o)),o):{type:"void",instance:null,count:0,state:null};default:throw Error(l(444,e))}}function oc(e){return'href="'+Ba(e)+'"'}function vu(e){return'link[rel="stylesheet"]['+e+"]"}function Wv(e){return b({},e,{"data-precedence":e.precedence,precedence:null})}function VS(e,t,s,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}),fa(t,"link",s),At(t),e.head.appendChild(t))}function cc(e){return'[src="'+Ba(e)+'"]'}function yu(e){return"script[async]"+e}function Yv(e,t,s){if(t.count++,t.instance===null)switch(t.type){case"style":var o=e.querySelector('style[data-href~="'+Ba(s.href)+'"]');if(o)return t.instance=o,At(o),o;var f=b({},s,{"data-href":s.href,"data-precedence":s.precedence,href:null,precedence:null});return o=(e.ownerDocument||e).createElement("style"),At(o),fa(o,"style",f),Hd(o,s.precedence,e),t.instance=o;case"stylesheet":f=oc(s.href);var p=e.querySelector(vu(f));if(p)return t.state.loading|=4,t.instance=p,At(p),p;o=Wv(s),(f=Bs.get(f))&&ah(o,f),p=(e.ownerDocument||e).createElement("link"),At(p);var S=p;return S._p=new Promise(function(R,V){S.onload=R,S.onerror=V}),fa(p,"link",o),t.state.loading|=4,Hd(p,s.precedence,e),t.instance=p;case"script":return p=cc(s.src),(f=e.querySelector(yu(p)))?(t.instance=f,At(f),f):(o=s,(f=Bs.get(p))&&(o=b({},s),sh(o,f)),e=e.ownerDocument||e,f=e.createElement("script"),At(f),fa(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,Hd(o,s.precedence,e));return t.instance}function Hd(e,t,s){for(var o=s.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),f=o.length?o[o.length-1]:null,p=f,S=0;S<o.length;S++){var R=o[S];if(R.dataset.precedence===t)p=R;else if(p!==f)break}p?p.parentNode.insertBefore(e,p.nextSibling):(t=s.nodeType===9?s.head:s,t.insertBefore(e,t.firstChild))}function ah(e,t){e.crossOrigin==null&&(e.crossOrigin=t.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=t.referrerPolicy),e.title==null&&(e.title=t.title)}function sh(e,t){e.crossOrigin==null&&(e.crossOrigin=t.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=t.referrerPolicy),e.integrity==null&&(e.integrity=t.integrity)}var Fd=null;function Kv(e,t,s){if(Fd===null){var o=new Map,f=Fd=new Map;f.set(s,o)}else f=Fd,o=f.get(s),o||(o=new Map,f.set(s,o));if(o.has(e))return o;for(o.set(e,null),s=s.getElementsByTagName(e),f=0;f<s.length;f++){var p=s[f];if(!(p[Mt]||p[re]||e==="link"&&p.getAttribute("rel")==="stylesheet")&&p.namespaceURI!=="http://www.w3.org/2000/svg"){var S=p.getAttribute(t)||"";S=e+S;var R=o.get(S);R?R.push(p):o.set(S,[p])}}return o}function Qv(e,t,s){e=e.ownerDocument||e,e.head.insertBefore(s,t==="title"?e.querySelector("head > title"):null)}function WS(e,t,s){if(s===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 Xv(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function YS(e,t,s,o){if(s.type==="stylesheet"&&(typeof o.media!="string"||matchMedia(o.media).matches!==!1)&&(s.state.loading&4)===0){if(s.instance===null){var f=oc(o.href),p=t.querySelector(vu(f));if(p){t=p._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(e.count++,e=$d.bind(e),t.then(e,e)),s.state.loading|=4,s.instance=p,At(p);return}p=t.ownerDocument||t,o=Wv(o),(f=Bs.get(f))&&ah(o,f),p=p.createElement("link"),At(p);var S=p;S._p=new Promise(function(R,V){S.onload=R,S.onerror=V}),fa(p,"link",o),s.instance=p}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(s,t),(t=s.state.preload)&&(s.state.loading&3)===0&&(e.count++,s=$d.bind(e),t.addEventListener("load",s),t.addEventListener("error",s))}}var rh=0;function KS(e,t){return e.stylesheets&&e.count===0&&Pd(e,e.stylesheets),0<e.count||0<e.imgCount?function(s){var o=setTimeout(function(){if(e.stylesheets&&Pd(e,e.stylesheets),e.unsuspend){var p=e.unsuspend;e.unsuspend=null,p()}},6e4+t);0<e.imgBytes&&rh===0&&(rh=62500*TS());var f=setTimeout(function(){if(e.waitingForImages=!1,e.count===0&&(e.stylesheets&&Pd(e,e.stylesheets),e.unsuspend)){var p=e.unsuspend;e.unsuspend=null,p()}},(e.imgBytes>rh?50:800)+t);return e.unsuspend=s,function(){e.unsuspend=null,clearTimeout(o),clearTimeout(f)}}:null}function $d(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Pd(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Bd=null;function Pd(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Bd=new Map,t.forEach(QS,e),Bd=null,$d.call(e))}function QS(e,t){if(!(t.state.loading&4)){var s=Bd.get(e);if(s)var o=s.get(null);else{s=new Map,Bd.set(e,s);for(var f=e.querySelectorAll("link[data-precedence],style[data-precedence]"),p=0;p<f.length;p++){var S=f[p];(S.nodeName==="LINK"||S.getAttribute("media")!=="not all")&&(s.set(S.dataset.precedence,S),o=S)}o&&s.set(null,o)}f=t.instance,S=f.getAttribute("data-precedence"),p=s.get(S)||o,p===o&&s.set(null,f),s.set(S,f),this.count++,o=$d.bind(this),f.addEventListener("load",o),f.addEventListener("error",o),p?p.parentNode.insertBefore(f,p.nextSibling):(e=e.nodeType===9?e.head:e,e.insertBefore(f,e.firstChild)),t.state.loading|=4}}var bu={$$typeof:D,Provider:null,Consumer:null,_currentValue:W,_currentValue2:W,_threadCount:0};function XS(e,t,s,o,f,p,S,R,V){this.tag=1,this.containerInfo=e,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=pn(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=pn(0),this.hiddenUpdates=pn(null),this.identifierPrefix=o,this.onUncaughtError=f,this.onCaughtError=p,this.onRecoverableError=S,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=V,this.incompleteTransitions=new Map}function Zv(e,t,s,o,f,p,S,R,V,ue,xe,Ce){return e=new XS(e,t,s,S,V,ue,xe,Ce,R),t=1,p===!0&&(t|=24),p=En(3,null,null,t),e.current=p,p.stateNode=e,t=Oo(),t.refCount++,e.pooledCache=t,t.refCount++,p.memoizedState={element:o,isDehydrated:s,cache:t},Pl(p),e}function Jv(e){return e?(e=ca,e):ca}function ey(e,t,s,o,f,p){f=Jv(f),o.context===null?o.context=f:o.pendingContext=f,o=dr(t),o.payload={element:s},p=p===void 0?null:p,p!==null&&(o.callback=p),s=Os(e,o,t),s!==null&&(as(s,e,t),Ul(s,e,t))}function ty(e,t){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var s=e.retryLane;e.retryLane=s!==0&&s<t?s:t}}function ih(e,t){ty(e,t),(e=e.alternate)&&ty(e,t)}function ny(e){if(e.tag===13||e.tag===31){var t=_a(e,67108864);t!==null&&as(t,e,67108864),ih(e,67108864)}}function ay(e){if(e.tag===13||e.tag===31){var t=ps();t=ht(t);var s=_a(e,t);s!==null&&as(s,e,t),ih(e,t)}}var Ud=!0;function ZS(e,t,s,o){var f=z.T;z.T=null;var p=se.p;try{se.p=2,lh(e,t,s,o)}finally{se.p=p,z.T=f}}function JS(e,t,s,o){var f=z.T;z.T=null;var p=se.p;try{se.p=8,lh(e,t,s,o)}finally{se.p=p,z.T=f}}function lh(e,t,s,o){if(Ud){var f=oh(o);if(f===null)Wm(e,t,o,qd,s),ry(e,o);else if(t0(f,e,t,s,o))o.stopPropagation();else if(ry(e,o),t&4&&-1<e0.indexOf(e)){for(;f!==null;){var p=gn(f);if(p!==null)switch(p.tag){case 3:if(p=p.stateNode,p.current.memoizedState.isDehydrated){var S=pa(p.pendingLanes);if(S!==0){var R=p;for(R.pendingLanes|=2,R.entangledLanes|=2;S;){var V=1<<31-xt(S);R.entanglements[1]|=V,S&=~V}Er(p),(Pt&6)===0&&(Ad=je()+500,mu(0))}}break;case 31:case 13:R=_a(p,2),R!==null&&as(R,p,2),Nd(),ih(p,2)}if(p=oh(o),p===null&&Wm(e,t,o,qd,s),p===f)break;f=p}f!==null&&o.stopPropagation()}else Wm(e,t,o,null,s)}}function oh(e){return e=_i(e),ch(e)}var qd=null;function ch(e){if(qd=null,e=On(e),e!==null){var t=d(e);if(t===null)e=null;else{var s=t.tag;if(s===13){if(e=m(t),e!==null)return e;e=null}else if(s===31){if(e=h(t),e!==null)return e;e=null}else if(s===3){if(t.stateNode.current.memoizedState.isDehydrated)return t.tag===3?t.stateNode.containerInfo:null;e=null}else t!==e&&(e=null)}}return qd=e,null}function sy(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($e()){case dt:return 2;case it:return 8;case pt:case ct:return 32;case kt:return 268435456;default:return 32}default:return 32}}var uh=!1,cl=null,ul=null,dl=null,xu=new Map,wu=new Map,fl=[],e0="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 ry(e,t){switch(e){case"focusin":case"focusout":cl=null;break;case"dragenter":case"dragleave":ul=null;break;case"mouseover":case"mouseout":dl=null;break;case"pointerover":case"pointerout":xu.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":wu.delete(t.pointerId)}}function Su(e,t,s,o,f,p){return e===null||e.nativeEvent!==p?(e={blockedOn:t,domEventName:s,eventSystemFlags:o,nativeEvent:p,targetContainers:[f]},t!==null&&(t=gn(t),t!==null&&ny(t)),e):(e.eventSystemFlags|=o,t=e.targetContainers,f!==null&&t.indexOf(f)===-1&&t.push(f),e)}function t0(e,t,s,o,f){switch(t){case"focusin":return cl=Su(cl,e,t,s,o,f),!0;case"dragenter":return ul=Su(ul,e,t,s,o,f),!0;case"mouseover":return dl=Su(dl,e,t,s,o,f),!0;case"pointerover":var p=f.pointerId;return xu.set(p,Su(xu.get(p)||null,e,t,s,o,f)),!0;case"gotpointercapture":return p=f.pointerId,wu.set(p,Su(wu.get(p)||null,e,t,s,o,f)),!0}return!1}function iy(e){var t=On(e.target);if(t!==null){var s=d(t);if(s!==null){if(t=s.tag,t===13){if(t=m(s),t!==null){e.blockedOn=t,Di(e.priority,function(){ay(s)});return}}else if(t===31){if(t=h(s),t!==null){e.blockedOn=t,Di(e.priority,function(){ay(s)});return}}else if(t===3&&s.stateNode.current.memoizedState.isDehydrated){e.blockedOn=s.tag===3?s.stateNode.containerInfo:null;return}}}e.blockedOn=null}function Gd(e){if(e.blockedOn!==null)return!1;for(var t=e.targetContainers;0<t.length;){var s=oh(e.nativeEvent);if(s===null){s=e.nativeEvent;var o=new s.constructor(s.type,s);Cs=o,s.target.dispatchEvent(o),Cs=null}else return t=gn(s),t!==null&&ny(t),e.blockedOn=s,!1;t.shift()}return!0}function ly(e,t,s){Gd(e)&&s.delete(t)}function n0(){uh=!1,cl!==null&&Gd(cl)&&(cl=null),ul!==null&&Gd(ul)&&(ul=null),dl!==null&&Gd(dl)&&(dl=null),xu.forEach(ly),wu.forEach(ly)}function Vd(e,t){e.blockedOn===t&&(e.blockedOn=null,uh||(uh=!0,n.unstable_scheduleCallback(n.unstable_NormalPriority,n0)))}var Wd=null;function oy(e){Wd!==e&&(Wd=e,n.unstable_scheduleCallback(n.unstable_NormalPriority,function(){Wd===e&&(Wd=null);for(var t=0;t<e.length;t+=3){var s=e[t],o=e[t+1],f=e[t+2];if(typeof o!="function"){if(ch(o||s)===null)continue;break}var p=gn(s);p!==null&&(e.splice(t,3),t-=3,om(p,{pending:!0,data:f,method:s.method,action:o},o,f))}}))}function uc(e){function t(V){return Vd(V,e)}cl!==null&&Vd(cl,e),ul!==null&&Vd(ul,e),dl!==null&&Vd(dl,e),xu.forEach(t),wu.forEach(t);for(var s=0;s<fl.length;s++){var o=fl[s];o.blockedOn===e&&(o.blockedOn=null)}for(;0<fl.length&&(s=fl[0],s.blockedOn===null);)iy(s),s.blockedOn===null&&fl.shift();if(s=(e.ownerDocument||e).$$reactFormReplay,s!=null)for(o=0;o<s.length;o+=3){var f=s[o],p=s[o+1],S=f[Te]||null;if(typeof p=="function")S||oy(s);else if(S){var R=null;if(p&&p.hasAttribute("formAction")){if(f=p,S=p[Te]||null)R=S.formAction;else if(ch(f)!==null)continue}else R=S.action;typeof R=="function"?s[o+1]=R:(s.splice(o,3),o-=3),oy(s)}}}function cy(){function e(p){p.canIntercept&&p.info==="react-transition"&&p.intercept({handler:function(){return new Promise(function(S){return f=S})},focusReset:"manual",scroll:"manual"})}function t(){f!==null&&(f(),f=null),o||setTimeout(s,20)}function s(){if(!o&&!navigation.transition){var p=navigation.currentEntry;p&&p.url!=null&&navigation.navigate(p.url,{state:p.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var o=!1,f=null;return navigation.addEventListener("navigate",e),navigation.addEventListener("navigatesuccess",t),navigation.addEventListener("navigateerror",t),setTimeout(s,100),function(){o=!0,navigation.removeEventListener("navigate",e),navigation.removeEventListener("navigatesuccess",t),navigation.removeEventListener("navigateerror",t),f!==null&&(f(),f=null)}}}function dh(e){this._internalRoot=e}Yd.prototype.render=dh.prototype.render=function(e){var t=this._internalRoot;if(t===null)throw Error(l(409));var s=t.current,o=ps();ey(s,o,e,t,null,null)},Yd.prototype.unmount=dh.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var t=e.containerInfo;ey(e.current,2,null,e,null,null),Nd(),t[Ue]=null}};function Yd(e){this._internalRoot=e}Yd.prototype.unstable_scheduleHydration=function(e){if(e){var t=Fa();e={blockedOn:null,target:e,priority:t};for(var s=0;s<fl.length&&t!==0&&t<fl[s].priority;s++);fl.splice(s,0,e),s===0&&iy(e)}};var uy=a.version;if(uy!=="19.2.7")throw Error(l(527,uy,"19.2.7"));se.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=y(t),e=e!==null?x(e):null,e=e===null?null:e.stateNode,e};var a0={bundleType:0,version:"19.2.7",rendererPackageName:"react-dom",currentDispatcherRef:z,reconcilerVersion:"19.2.7"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Kd=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Kd.isDisabled&&Kd.supportsFiber)try{Oe=Kd.inject(a0),Ae=Kd}catch{}}return ku.createRoot=function(e,t){if(!c(e))throw Error(l(299));var s=!1,o="",f=vg,p=yg,S=bg;return t!=null&&(t.unstable_strictMode===!0&&(s=!0),t.identifierPrefix!==void 0&&(o=t.identifierPrefix),t.onUncaughtError!==void 0&&(f=t.onUncaughtError),t.onCaughtError!==void 0&&(p=t.onCaughtError),t.onRecoverableError!==void 0&&(S=t.onRecoverableError)),t=Zv(e,1,!1,null,null,s,o,null,f,p,S,cy),e[Ue]=t.current,Vm(e),new dh(t)},ku.hydrateRoot=function(e,t,s){if(!c(e))throw Error(l(299));var o=!1,f="",p=vg,S=yg,R=bg,V=null;return s!=null&&(s.unstable_strictMode===!0&&(o=!0),s.identifierPrefix!==void 0&&(f=s.identifierPrefix),s.onUncaughtError!==void 0&&(p=s.onUncaughtError),s.onCaughtError!==void 0&&(S=s.onCaughtError),s.onRecoverableError!==void 0&&(R=s.onRecoverableError),s.formState!==void 0&&(V=s.formState)),t=Zv(e,1,!0,t,s??null,o,f,V,p,S,R,cy),t.context=Jv(null),s=t.current,o=ps(),o=ht(o),f=dr(o),f.callback=null,Os(s,f,o),s=o,t.current.lanes=s,qs(t,s),Er(t),e[Ue]=t.current,Vm(e),new Yd(t)},ku.version="19.2.7",ku}var Cy;function K0(){if(Cy)return ph.exports;Cy=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(),ph.exports=Y0(),ph.exports}var Q0=K0();const X0="https://otbyfkjxrkngvjziawki.supabase.co",Z0="sb_publishable_NpUs0RDJH2YnllsqTKO6TQ_1jTdSsNQ",J0={getItem:()=>null,setItem:()=>{},removeItem:()=>{}},ky=typeof window<"u"&&!!window.liveDesk,Ct=U0(X0,Z0,{auth:{autoRefreshToken:!0,persistSession:!ky,storage:ky?J0:void 0,detectSessionInUrl:!0,flowType:"pkce",storageKey:"livedesk.mindexec.supabase.auth"}}),eC=new Set(["browserLanguage","platform","online","viewport","timezone","screen"]),tC={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,i])=>eC.has(a)&&i!==void 0))}};function nC(n,a="Support request failed."){if(n&&typeof n=="object"&&"message"in n){const i=String(n.message||"").trim();if(i)return i.replace(/^.*Support request failed:\s*/i,"")}return n instanceof Error?n.message:a}function aC(n=tC){return n.collect()}async function sC(n,a="livedesk"){const{data:i,error:l}=await Ct.from("app_admins").select("role").eq("user_id",n).limit(1);if(l)throw l;const c=i?.[0]?.role||"user";if(c!=="owner"){const{error:A}=await Ct.rpc("register_product_access",{p_product_key:a,p_access_type:"free"});if(A)throw A}const[d,m,h]=await Promise.all([Ct.from("products").select("id, product_key, name, description, sort_order").order("sort_order"),Ct.from("product_admins").select("product_id, role").eq("user_id",n),Ct.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(h.error)throw h.error;const g=d.data||[],y=(m.data||[]).map(A=>String(A.product_id)),x=(h.data||[]).map(A=>String(A.product_id)),b=c==="owner",w=b?g.map(A=>A.id):[...new Set([...y,...x])];return{products:g,access:{userId:n,globalRole:c,accessibleProductIds:w,managedProductIds:b?g.map(A=>A.id):y,canViewAllProducts:b,canViewAllPrivatePosts:b,canManageAllProducts:b,canCreateAnnouncements:b||y.length>0}}}async function rC(n=""){const{data:a,error:i}=await Ct.rpc("search_support_posts",{p_query:n.trim()||null,p_limit:250});if(i)throw i;return a||[]}async function iC(n){const{data:a,error:i}=await Ct.from("support_attachments").select("*").eq("post_id",n).order("created_at");if(i)throw i;const l=a||[];return Promise.all(l.map(async c=>{const d=await Ct.storage.from("support-attachments").createSignedUrl(c.storage_path,3600);return{...c,signed_url:d.data?.signedUrl||void 0}}))}async function lC(){const{data:n,error:a}=await Ct.from("support_notifications").select("*").order("created_at",{ascending:!1}).limit(30);if(a)throw a;return n||[]}async function oC(n){const{error:a}=await Ct.rpc("mark_support_notification_read",{p_notification_id:n});if(a)throw a}async function jy(n){const{data:a,error:i}=await Ct.from("support_comments").select("*").eq("post_id",n).order("created_at");if(i)throw i;return a||[]}async function cC(n){const{data:a,error:i}=await Ct.from("support_votes").select("post_id").eq("user_id",n);if(i)throw i;return new Set((a||[]).map(l=>String(l.post_id)))}async function uC(n){const{data:a,error:i}=await Ct.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?aC():{}});if(i)throw i;const l=Array.isArray(a)?a[0]?.post_id:a?.post_id;if(!l)throw new Error("Support post was not created.");return String(l)}const dC=new Set(["image/png","image/jpeg","image/webp","text/plain","text/markdown","application/json","application/pdf"]);async function fC(n,a){if(!dC.has(a.type))throw new Error("This file type is not allowed.");if(a.size<=0||a.size>10*1024*1024)throw new Error("Attachments must be smaller than 10 MB.");const i=a.name.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"attachment",l=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`,c=`${n}/${l}-${i}`,d=await Ct.storage.from("support-attachments").upload(c,a,{contentType:a.type,upsert:!1});if(d.error)throw d.error;const{data:m,error:h}=await Ct.rpc("add_support_attachment",{p_post_id:n,p_storage_path:c,p_file_name:i,p_mime_type:a.type,p_size_bytes:a.size});if(h)throw await Ct.storage.from("support-attachments").remove([c]),h;const g=Array.isArray(m)?m[0]?.attachment_id:m?.attachment_id;if(!g)throw new Error("Attachment metadata was not created.");return String(g)}async function mC(n,a,i,l){const{error:c}=await Ct.rpc("update_support_post",{p_post_id:n,p_title:a,p_body:i,p_visibility:l});if(c)throw c}async function hC(n,a){const{error:i}=await Ct.rpc("add_support_comment",{p_post_id:n,p_body:a});if(i)throw i}async function pC(n){const{data:a,error:i}=await Ct.rpc("toggle_support_vote",{p_post_id:n});if(i)throw i;const l=Array.isArray(a)?a[0]:a;return{voted:!!l?.voted,totalVotes:Number(l?.total_votes||0)}}async function gC(n,a){const{error:i}=await Ct.rpc("change_support_post_status",{p_post_id:n,p_target_status:a});if(i)throw i}async function vC(n){const{error:a}=await Ct.rpc("set_support_post_hidden",{p_post_id:n,p_hidden:!0});if(a)throw a}async function yC(n,a){const{error:i}=await Ct.rpc("set_support_post_locked",{p_post_id:n,p_locked:a});if(i)throw i}async function bC(n,a){const{error:i}=await Ct.rpc("set_support_post_pinned",{p_post_id:n,p_pinned:a});if(i)throw i}async function xC(n,a){const{error:i}=await Ct.rpc("mark_support_duplicate",{p_post_id:n,p_duplicate_of_post_id:a});if(i)throw i}async function wC(n,a){const{error:i}=await Ct.rpc("accept_support_answer",{p_post_id:n,p_comment_id:a});if(i)throw i}async function SC(n,a=!0){const{error:i}=await Ct.rpc("hide_support_comment",{p_comment_id:n,p_hidden:a});if(i)throw i}const Jh=[{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"}],CC=[{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"}],kC={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"]},jC={type:"all",product:"",status:"all",visibility:"all",sort:"recent",query:""};function yh(){if(typeof window>"u")return jC;const n=new URLSearchParams(window.location.search),a=window.location.pathname.match(/^\/support\/(questions|issues|features|announcements)$/)?.[1],i=n.get("type")||a||"",l=i==="questions"||i==="question"?"question":i==="issues"||i==="issue"?"issue":i==="features"||i==="feature"?"feature":i==="announcements"||i==="announcement"?"announcement":"all",c=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 AC(n){return n==="all"?"":n==="question"?"questions":n==="issue"?"issues":n==="feature"?"features":"announcements"}function MC(n,a){const i={...n,...a},l=new URLSearchParams;i.product&&l.set("product",i.product),i.status!=="all"&&l.set("status",i.status),i.visibility!=="all"&&l.set("visibility",i.visibility),i.sort!=="recent"&&l.set("sort",i.sort),i.query&&l.set("q",i.query);const c=AC(i.type),d=l.toString();return`/support${c?`/${c}`:""}${d?`?${d}`:""}`}function Qd(n){const a=new Date(n);return Number.isFinite(a.getTime())?a.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"}):n}function bh(n){return n.replaceAll("-"," ").replace(/\b\w/g,a=>a.toUpperCase())}function Ay(n){return n==="question"?c0:n==="issue"?ox:n==="feature"?u0:d0}function My(n){return Jh.find(a=>a.id===n)?.shortLabel||n}function xh(n,a){return n.find(i=>i.id===a)?.name||"Product"}function ss(n){const a=nC(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 xx({session:n,currentProductKey:a="livedesk",appVersion:i="",onSignIn:l}){const[c,d]=u.useState(()=>yh()),[m,h]=u.useState(null),[g,y]=u.useState([]),[x,b]=u.useState([]),[w,A]=u.useState(""),[j,k]=u.useState([]),[N,M]=u.useState([]),[T,D]=u.useState([]),[F,$]=u.useState(()=>new Set),[q,L]=u.useState(!0),[Y,G]=u.useState(""),[P,K]=u.useState(""),[H,ye]=u.useState(!1),[de,Z]=u.useState(!1),[z,se]=u.useState(""),[W,O]=u.useState(()=>yh().query),[le,ce]=u.useState(!1),[Q,be]=u.useState(!1),[he,fe]=u.useState(""),[ee,Se]=u.useState(""),[Ne,Fe]=u.useState("free"),[ne,Pe]=u.useState(""),[mt,J]=u.useState(""),[ke,Le]=u.useState("admin"),[Be,_e]=u.useState(""),[Qe,Ye]=u.useState(""),[Ze,ut]=u.useState(""),[U,ve]=u.useState(""),[je,$e]=u.useState(""),[dt,it]=u.useState([]),[pt,ct]=u.useState({productId:"",postType:"question",title:"",body:"",visibility:"public",includeEnvironment:!0,files:[]}),kt=u.useCallback(B=>{const Ke={...c,...B};d(Ke),typeof window<"u"&&window.history.pushState({},"",MC(c,B))},[c]);u.useEffect(()=>{const B=()=>d(yh());return window.addEventListener("popstate",B),()=>window.removeEventListener("popstate",B)},[]);const pe=u.useCallback(async()=>{const B=await rC(c.query);return b(B),n?.user.id&&$(await cC(n.user.id)),B},[c.query,n?.user.id]),De=u.useCallback(async()=>{if(!n?.user.id){h(null),y([]),b([]),A(""),D([]),L(!1);return}L(!0),K("");try{const B=await sC(n.user.id,a);h(B.access),y(B.products),await pe(),D(await lC())}catch(B){K(ss(B))}finally{L(!1)}},[a,pe,n?.user.id]);u.useEffect(()=>{De()},[De]);const Oe=u.useMemo(()=>m?m.canViewAllProducts?g:g.filter(B=>m.accessibleProductIds.includes(B.id)):[],[m,g]),Ae=u.useMemo(()=>{const B=Oe.find(Ke=>Ke.product_key===c.product);return m?.canViewAllProducts&&!c.product||c.product==="all"&&m?.canViewAllProducts?"all":B?B.product_key:Oe.some(Ke=>Ke.product_key===a)?a:Oe[0]?.product_key||""},[m?.canViewAllProducts,Oe,a,c.product]),ft=Ae==="all"?"":Oe.find(B=>B.product_key===Ae)?.id||"",xt=u.useMemo(()=>{const B=new Map(g.map(ht=>[ht.id,ht.product_key]));return[...x.filter(ht=>c.type!=="all"&&ht.post_type!==c.type||Ae!=="all"&&ft&&ht.product_id!==ft||c.status==="needs-response"&&!["open","needs-info"].includes(ht.status)||c.status!=="all"&&c.status!=="needs-response"&&ht.status!==c.status||c.visibility!=="all"&&ht.visibility!==c.visibility?!1:B.has(ht.product_id))].sort((ht,fn)=>c.sort==="votes"?fn.vote_count-ht.vote_count||fn.updated_at.localeCompare(ht.updated_at):c.sort==="newest"?fn.created_at.localeCompare(ht.created_at):Number(fn.is_pinned)-Number(ht.is_pinned)||fn.updated_at.localeCompare(ht.updated_at))},[x,g,c.sort,c.status,c.type,c.visibility,ft,Ae]),Ie=xt.find(B=>B.id===w)||xt[0]||null,na=!!(Ie&&m&&(m.canViewAllProducts||m.managedProductIds.includes(Ie.product_id))),wn=!!(Ie&&n?.user.id===Ie.author_id)||na;u.useEffect(()=>{if(!Ie){A(""),k([]),Z(!1);return}Ie.id!==w&&A(Ie.id)},[Ie,w]),u.useEffect(()=>{let B=!0;return w?(jy(w).then(Ke=>{B&&k(Ke)}).catch(Ke=>{B&&K(ss(Ke))}),iC(w).then(Ke=>{B&&M(Ke)}).catch(Ke=>{B&&K(ss(Ke))}),()=>{B=!1}):(k([]),M([]),()=>{B=!1})},[w]),u.useEffect(()=>{!pt.productId&&Oe[0]&&ct(B=>({...B,productId:ft||Oe[0].id}))},[Oe,pt.productId,ft]),u.useEffect(()=>{O(c.query)},[c.query]),u.useEffect(()=>{!ee&&Oe[0]&&Se(Oe[0].id),!mt&&Oe[0]&&J(Oe[0].id)},[Oe,ee,mt]);const at=B=>{Ie&&b(Ke=>Ke.map(ht=>ht.id===Ie.id?{...ht,...B}:ht))},Ot=async B=>{if(B.preventDefault(),!(!n||!pt.productId)){G("create"),K("");try{const Ke=await uC({productId:pt.productId,postType:pt.postType,title:pt.title,body:pt.body,visibility:pt.postType==="announcement"?"public":pt.visibility,appVersion:i,includeEnvironment:pt.postType==="issue"&&pt.includeEnvironment});for(const fn of dt)await fC(Ke,fn);const ht=await pe();ye(!1),it([]),ct(fn=>({...fn,title:"",body:"",files:[]})),A(Ke),ht.some(fn=>fn.id===Ke)||await De()}catch(Ke){K(ss(Ke))}finally{G("")}}},aa=async B=>{if(B.preventDefault(),!!Ie){G("edit"),K("");try{await mC(Ie.id,Ie.title,Ie.body,Ie.visibility),Z(!1),await pe()}catch(Ke){K(ss(Ke))}finally{G("")}}},pa=async B=>{if(B.preventDefault(),!(!Ie||!z.trim())){G("comment"),K("");try{await hC(Ie.id,z),se(""),k(await jy(Ie.id)),await pe()}catch(Ke){K(ss(Ke))}finally{G("")}}},He=async()=>{if(!(!Ie||Ie.post_type!=="feature")){G("vote"),K("");try{const B=await pC(Ie.id);$(Ke=>{const ht=new Set(Ke);return B.voted?ht.add(Ie.id):ht.delete(Ie.id),ht}),at({vote_count:B.totalVotes})}catch(B){K(ss(B))}finally{G("")}}},Sn=async B=>{if(Ie){G("status"),K("");try{await gC(Ie.id,B),at({status:B}),await pe()}catch(Ke){K(ss(Ke))}finally{G("")}}},zn=async()=>{if(!(!Ie||!window.confirm("Hide this Support post from the board?"))){G("hide"),K("");try{await vC(Ie.id),A(""),await pe()}catch(B){K(ss(B))}finally{G("")}}},ws=async()=>{if(Ie){G("lock"),K("");try{await yC(Ie.id,!Ie.is_locked),at({is_locked:!Ie.is_locked}),await pe()}catch(B){K(ss(B))}finally{G("")}}},pn=async()=>{if(Ie){G("pin"),K("");try{await bC(Ie.id,!Ie.is_pinned),at({is_pinned:!Ie.is_pinned}),await pe()}catch(B){K(ss(B))}finally{G("")}}},qs=async B=>{if(Ie){G(`accept-${B}`),K("");try{await wC(Ie.id,B),at({accepted_comment_id:B,status:Ie.post_type==="question"?"answered":Ie.status}),await pe()}catch(Ke){K(ss(Ke))}finally{G("")}}},Wn=async()=>{if(!(!Ie||!U||U===Ie.id)){G("duplicate"),K("");try{await xC(Ie.id,U),A(""),ve(""),await pe()}catch(B){K(ss(B))}finally{G("")}}},Gs=async B=>{if(!B.read_at)try{await oC(B.id),D(Ke=>Ke.map(ht=>ht.id===B.id?{...ht,read_at:new Date().toISOString()}:ht))}catch(Ke){K(ss(Ke))}B.post_id&&A(B.post_id),ce(!1)};return n?q&&!m?r.jsxs("section",{className:"support-page support-loading",children:[r.jsx(Sc,{className:"support-spin",size:23})," Loading Support Board..."]}):r.jsxs("section",{className:"support-page",children:[r.jsx("header",{className:"support-page-header support-page-actions-only",children:r.jsxs("div",{className:"support-header-actions",children:[r.jsxs("div",{className:"support-notification-wrap",children:[r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>ce(B=>!B),title:"Notifications",children:[r.jsx(i0,{size:16})," ",T.filter(B=>!B.read_at).length>0&&r.jsx("b",{children:T.filter(B=>!B.read_at).length})]}),le&&r.jsxs("div",{className:"support-notification-popover",children:[r.jsx("strong",{children:"Notifications"}),T.length===0?r.jsx("span",{className:"support-muted",children:"No notifications yet."}):T.map(B=>r.jsxs("button",{type:"button",className:B.read_at?"":"unread",onClick:()=>{Gs(B)},children:[r.jsx("b",{children:B.title}),r.jsx("span",{children:B.body}),r.jsx("small",{children:Qd(B.created_at)})]},B.id))]})]}),m?.canViewAllProducts&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>be(B=>!B),children:[r.jsx(Vn,{size:16})," Admin"]}),r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{De()},disabled:q,children:[r.jsx(Sc,{size:16,className:q?"support-spin":""})," Refresh"]}),r.jsxs("button",{className:"support-primary-button",type:"button",onClick:()=>ye(!0),disabled:Oe.length===0,children:[r.jsx(fh,{size:17})," New request"]})]})}),P&&r.jsxs("div",{className:"support-error",role:"alert",children:[r.jsx(Na,{size:17})," ",r.jsx("span",{children:P}),r.jsx("button",{type:"button",onClick:()=>K(""),"aria-label":"Dismiss error",children:r.jsx(Na,{size:15})})]}),H&&r.jsxs("form",{className:"support-composer",onSubmit:B=>{Ot(B)},children:[r.jsxs("div",{className:"support-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"New Support request"}),r.jsx("strong",{children:"Describe one actionable problem or idea."})]}),r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>ye(!1),"aria-label":"Close composer",children:r.jsx(Na,{size:18})})]}),r.jsxs("div",{className:"support-form-grid",children:[r.jsxs("label",{children:[r.jsx("span",{children:"Product"}),r.jsx("select",{value:pt.productId,onChange:B=>ct(Ke=>({...Ke,productId:B.target.value})),children:Oe.map(B=>r.jsx("option",{value:B.id,children:B.name},B.id))})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Type"}),r.jsx("select",{value:pt.postType,onChange:B=>ct(Ke=>({...Ke,postType:B.target.value})),children:Jh.filter(B=>B.id!=="announcement"||m?.canCreateAnnouncements).map(B=>r.jsx("option",{value:B.id,children:B.label},B.id))})]}),r.jsxs("label",{className:"support-form-wide",children:[r.jsx("span",{children:"Title"}),r.jsx("input",{required:!0,minLength:3,maxLength:180,value:pt.title,onChange:B=>ct(Ke=>({...Ke,title:B.target.value})),placeholder:"A short, searchable summary"})]}),r.jsxs("label",{className:"support-form-wide",children:[r.jsx("span",{children:pt.postType==="issue"?"What happened?":pt.postType==="feature"?"Describe the desired behavior":pt.postType==="announcement"?"Announcement":"Question"}),r.jsx("textarea",{required:!0,value:pt.body,onChange:B=>ct(Ke=>({...Ke,body:B.target.value})),placeholder:"Include the context another person needs to respond.",rows:6})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Visibility"}),r.jsxs("select",{value:pt.visibility,disabled:pt.postType==="announcement",onChange:B=>ct(Ke=>({...Ke,visibility:B.target.value})),children:[r.jsx("option",{value:"public",children:"Public"}),r.jsx("option",{value:"private",children:"Private"})]})]}),pt.postType==="issue"&&r.jsxs("label",{className:"support-checkbox",children:[r.jsx("input",{type:"checkbox",checked:pt.includeEnvironment,onChange:B=>ct(Ke=>({...Ke,includeEnvironment:B.target.checked}))}),r.jsx("span",{children:"Attach safe browser/runtime details"})]}),r.jsxs("label",{className:"support-form-wide",children:[r.jsx("span",{children:"Attachments"}),r.jsx("input",{type:"file",multiple:!0,accept:"image/png,image/jpeg,image/webp,text/plain,text/markdown,application/json,application/pdf",onChange:B=>it(Array.from(B.target.files||[]).slice(0,5))}),r.jsx("small",{className:"support-muted",children:"Up to 5 files, 10 MB each. Images, text, JSON, Markdown, and PDF."})]})]}),r.jsxs("div",{className:"support-composer-footer",children:[r.jsx("span",{children:dt.length>0?`${dt.length} attachment${dt.length===1?"":"s"} selected.`:"Private posts are visible only to you and the product support staff."}),r.jsxs("button",{className:"support-primary-button",type:"submit",disabled:Y==="create",children:[r.jsx(Bu,{size:16})," ",Y==="create"?"Submitting...":"Submit request"]})]})]}),r.jsxs("div",{className:"support-tabs",role:"tablist","aria-label":"Support post type",children:[r.jsx("button",{className:c.type==="all"?"active":"",type:"button",onClick:()=>kt({type:"all"}),children:"All"}),Jh.map(B=>{const Ke=Ay(B.id);return r.jsxs("button",{className:c.type===B.id?"active":"",type:"button",onClick:()=>kt({type:B.id}),children:[r.jsx(Ke,{size:15})," ",B.label]},B.id)})]}),Q&&m?.canViewAllProducts&&r.jsxs("section",{className:"support-admin-panel",children:[r.jsxs("div",{className:"support-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Owner controls"}),r.jsx("strong",{children:"Products and access are managed by immutable user IDs behind these email lookup forms."})]}),r.jsx(Vn,{size:19})]}),r.jsxs("div",{className:"support-admin-grid",children:[r.jsxs("form",{onSubmit:B=>{},children:[r.jsx("strong",{children:"Grant product access"}),r.jsx("input",{type:"email",required:!0,placeholder:"User email",value:he,onChange:B=>fe(B.target.value)}),r.jsx("select",{value:ee,onChange:B=>Se(B.target.value),children:Oe.map(B=>r.jsx("option",{value:B.id,children:B.name},B.id))}),r.jsxs("select",{value:Ne,onChange:B=>Fe(B.target.value),children:[r.jsx("option",{value:"free",children:"Free"}),r.jsx("option",{value:"user",children:"User"}),r.jsx("option",{value:"paid",children:"Paid"}),r.jsx("option",{value:"beta",children:"Beta"}),r.jsx("option",{value:"staff",children:"Staff"})]}),r.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:je==="access",children:[r.jsx(Ir,{size:15})," Grant access"]})]}),r.jsxs("form",{onSubmit:B=>{},children:[r.jsx("strong",{children:"Assign product admin"}),r.jsx("input",{type:"email",required:!0,placeholder:"Admin email",value:ne,onChange:B=>Pe(B.target.value)}),r.jsx("select",{value:mt,onChange:B=>J(B.target.value),children:Oe.map(B=>r.jsx("option",{value:B.id,children:B.name},B.id))}),r.jsxs("select",{value:ke,onChange:B=>Le(B.target.value),children:[r.jsx("option",{value:"admin",children:"Admin"}),r.jsx("option",{value:"support",children:"Support"}),r.jsx("option",{value:"moderator",children:"Moderator"})]}),r.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:je==="product-admin",children:[r.jsx(Vn,{size:15})," Assign admin"]})]}),r.jsxs("form",{onSubmit:B=>{},children:[r.jsx("strong",{children:"Add a product"}),r.jsx("input",{required:!0,pattern:"[a-z0-9][a-z0-9_-]{1,48}",placeholder:"product-key",value:Be,onChange:B=>_e(B.target.value)}),r.jsx("input",{required:!0,placeholder:"Product name",value:Qe,onChange:B=>Ye(B.target.value)}),r.jsx("input",{placeholder:"Description",value:Ze,onChange:B=>ut(B.target.value)}),r.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:je==="product",children:[r.jsx(fh,{size:15})," Add product"]})]})]})]}),r.jsxs("form",{className:"support-search-bar",onSubmit:B=>{B.preventDefault(),kt({query:W.trim()})},children:[r.jsxs("label",{children:[r.jsx("span",{children:"Search Support"}),r.jsx("input",{value:W,onChange:B=>O(B.target.value),placeholder:"Search titles and request details"})]}),r.jsxs("button",{className:"support-secondary-button",type:"submit",children:[r.jsx(dy,{size:15})," Search"]}),c.query&&r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{O(""),kt({query:""})},"aria-label":"Clear search",children:r.jsx(Na,{size:16})})]}),r.jsxs("div",{className:"support-filter-bar",children:[r.jsxs("div",{className:"support-filter-title",children:[r.jsx(dy,{size:16}),r.jsx("span",{children:"Filter"})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Product"}),r.jsxs("select",{value:Ae,onChange:B=>kt({product:B.target.value}),disabled:!m?.canViewAllProducts&&Oe.length<=1,children:[r.jsx("option",{value:"all",children:"All products"}),Oe.map(B=>r.jsx("option",{value:B.product_key,children:B.name},B.id))]})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Status"}),r.jsx("select",{value:c.status,onChange:B=>kt({status:B.target.value}),children:CC.map(B=>r.jsx("option",{value:B.id,children:B.label},B.id))})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Visibility"}),r.jsxs("select",{value:c.visibility,onChange:B=>kt({visibility:B.target.value}),children:[r.jsx("option",{value:"all",children:"All visibility"}),r.jsx("option",{value:"public",children:"Public"}),r.jsx("option",{value:"private",children:"Private"})]})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Sort"}),r.jsxs("select",{value:c.sort,onChange:B=>kt({sort:B.target.value}),children:[r.jsx("option",{value:"recent",children:"Recently updated"}),r.jsx("option",{value:"newest",children:"Newest"}),r.jsx("option",{value:"votes",children:"Most votes"})]})]})]}),m?.canViewAllProducts&&r.jsxs("div",{className:"support-admin-shortcuts",children:[r.jsxs("span",{children:[r.jsx(Vn,{size:15})," Owner view"]}),r.jsx("button",{type:"button",onClick:()=>kt({status:"needs-response"}),children:"Needs response"}),r.jsx("button",{type:"button",onClick:()=>kt({visibility:"private"}),children:"Private requests"}),r.jsx("button",{type:"button",onClick:()=>kt({type:"feature",status:"all",sort:"votes"}),children:"High-vote features"})]}),r.jsxs("div",{className:"support-board-layout",children:[r.jsxs("section",{className:"support-post-list","aria-label":"Support posts",children:[r.jsxs("div",{className:"support-list-heading",children:[r.jsxs("span",{children:[xt.length," request",xt.length===1?"":"s"]}),r.jsx("small",{children:Ae==="all"?"All products":xh(Oe,ft)})]}),xt.length===0?r.jsxs("div",{className:"support-list-empty",children:[r.jsx(_u,{size:25}),r.jsx("strong",{children:"No posts match these filters."}),r.jsx("span",{children:"Start with a focused question, issue report, or feature request."}),Oe.length>0&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>ye(!0),children:[r.jsx(fh,{size:16})," Create the first request"]})]}):xt.map(B=>{const Ke=Ay(B.post_type);return r.jsxs("button",{type:"button",className:`support-post-row ${B.id===Ie?.id?"active":""}`,onClick:()=>{A(B.id),Z(!1)},children:[r.jsx("span",{className:"support-post-row-icon",children:r.jsx(Ke,{size:17})}),r.jsxs("span",{className:"support-post-row-copy",children:[r.jsxs("span",{className:"support-post-row-meta",children:[r.jsx("b",{children:xh(g,B.product_id)}),r.jsx("em",{children:My(B.post_type)}),B.visibility==="private"&&r.jsx(Ti,{size:13})]}),r.jsx("strong",{children:B.title}),r.jsxs("small",{children:[bh(B.status)," · ",Qd(B.updated_at)," · ",B.comment_count," comments"]})]}),B.post_type==="feature"&&r.jsxs("span",{className:"support-vote-count",children:[r.jsx(lx,{size:14})," ",B.vote_count]})]},B.id)})]}),r.jsx("section",{className:"support-post-detail","aria-label":"Support post detail",children:Ie?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"support-detail-head",children:[r.jsxs("div",{className:"support-detail-badges",children:[r.jsx("span",{className:"support-product-badge",children:xh(g,Ie.product_id)}),r.jsx("span",{className:"support-type-badge",children:My(Ie.post_type)}),r.jsx("span",{className:`support-status-badge status-${Ie.status}`,children:bh(Ie.status)}),Ie.visibility==="private"&&r.jsxs("span",{className:"support-private-badge",children:[r.jsx(Ti,{size:13})," Private"]})]}),r.jsxs("div",{className:"support-detail-actions",children:[wn&&r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>Z(B=>!B),title:"Edit post",children:r.jsx(l0,{size:16})}),na&&r.jsxs(r.Fragment,{children:[r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{pn()},disabled:Y==="pin",title:Ie.is_pinned?"Unpin post":"Pin post",children:r.jsx(fy,{size:16})}),r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{ws()},disabled:Y==="lock",title:Ie.is_locked?"Unlock post":"Lock post",children:r.jsx(Ti,{size:16})}),r.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{zn()},disabled:Y==="hide",title:"Hide post",children:r.jsx(my,{size:16})})]})]})]}),de?r.jsxs("form",{className:"support-edit-form",onSubmit:B=>{aa(B)},children:[r.jsx("input",{value:Ie.title,onChange:B=>at({title:B.target.value}),minLength:3,maxLength:180,required:!0}),r.jsx("textarea",{value:Ie.body,onChange:B=>at({body:B.target.value}),rows:9,required:!0}),r.jsxs("div",{className:"support-edit-actions",children:[r.jsxs("select",{value:Ie.visibility,onChange:B=>at({visibility:B.target.value}),children:[r.jsx("option",{value:"public",children:"Public"}),r.jsx("option",{value:"private",children:"Private"})]}),r.jsxs("button",{className:"support-primary-button",type:"submit",disabled:Y==="edit",children:[r.jsx(Ir,{size:16})," Save changes"]})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("h3",{children:Ie.title}),r.jsx("div",{className:"support-detail-body",children:Ie.body.split(`
10
+ `).map((B,Ke)=>r.jsx("p",{children:B||" "},`${Ie.id}-body-${Ke}`))})]}),r.jsxs("div",{className:"support-detail-meta",children:[r.jsxs("span",{children:["Opened ",Qd(Ie.created_at)]}),Ie.app_version&&r.jsxs("span",{children:["Version ",Ie.app_version]}),Ie.platform&&r.jsx("span",{children:Ie.platform}),Ie.is_locked&&r.jsxs("span",{children:[r.jsx(Ti,{size:13})," Locked"]}),Ie.is_pinned&&r.jsxs("span",{children:[r.jsx(fy,{size:13})," Pinned"]})]}),r.jsxs("div",{className:"support-detail-controls",children:[Ie.post_type==="feature"&&r.jsxs("button",{className:`support-vote-button ${F.has(Ie.id)?"voted":""}`,type:"button",onClick:()=>{He()},disabled:Y==="vote",children:[r.jsx(o0,{size:16})," ",F.has(Ie.id)?"Voted":"Vote"," ",r.jsx("b",{children:Ie.vote_count})]}),na&&r.jsxs("label",{className:"support-status-control",children:[r.jsx("span",{children:"Change status"}),r.jsx("select",{value:Ie.status,onChange:B=>{Sn(B.target.value)},disabled:Y==="status",children:(kC[Ie.post_type]||[]).map(B=>r.jsx("option",{value:B,children:bh(B)},B))})]}),na&&r.jsxs(r.Fragment,{children:[r.jsxs("select",{className:"support-status-control",value:U,onChange:B=>ve(B.target.value),children:[r.jsx("option",{value:"",children:"Duplicate of..."}),xt.filter(B=>B.id!==Ie.id&&B.product_id===Ie.product_id).map(B=>r.jsx("option",{value:B.id,children:B.title.slice(0,55)},B.id))]}),r.jsx("button",{className:"support-secondary-button",type:"button",onClick:()=>{Wn()},disabled:!U||Y==="duplicate",children:"Merge duplicate"})]})]}),N.length>0&&r.jsxs("div",{className:"support-attachments",children:[r.jsx("div",{className:"support-section-heading",children:r.jsxs("div",{children:[r.jsx("span",{children:"Attachments"}),r.jsxs("strong",{children:[N.length," file",N.length===1?"":"s"]})]})}),N.map(B=>r.jsxs("a",{href:B.signed_url,target:"_blank",rel:"noreferrer",children:[r.jsx(xp,{size:14})," ",B.file_name,r.jsxs("small",{children:[Math.ceil(B.size_bytes/1024)," KB"]})]},B.id))]}),r.jsxs("div",{className:"support-comments",children:[r.jsxs("div",{className:"support-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Discussion"}),r.jsxs("strong",{children:[j.length," comment",j.length===1?"":"s"]})]}),Ie.is_locked&&r.jsxs("span",{className:"support-locked-label",children:[r.jsx(Ti,{size:14})," Locked"]})]}),j.length===0?r.jsx("p",{className:"support-muted",children:"No response yet. Keep the conversation focused on this request."}):r.jsx("div",{className:"support-comment-list",children:j.map(B=>r.jsxs("article",{className:`support-comment ${B.is_staff_answer?"staff":""} ${Ie.accepted_comment_id===B.id?"accepted":""}`,children:[r.jsxs("div",{className:"support-comment-head",children:[r.jsx("strong",{children:B.is_staff_answer?"LiveDesk Support":B.author_id===n.user.id?"You":"Support user"}),B.is_staff_answer&&r.jsxs("span",{children:[r.jsx(Vn,{size:13})," Staff answer"]}),Ie.accepted_comment_id===B.id&&r.jsxs("span",{children:[r.jsx(Xn,{size:13})," Accepted"]}),r.jsx("time",{children:Qd(B.created_at)})]}),r.jsx("p",{children:B.body}),r.jsxs("div",{className:"support-comment-actions",children:[(n.user.id===Ie.author_id||na)&&Ie.post_type==="question"&&Ie.accepted_comment_id!==B.id&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{qs(B.id)},disabled:Y===`accept-${B.id}`,children:[r.jsx(Ir,{size:14})," Accept answer"]}),na&&r.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{SC(B.id)},title:"Hide comment",children:r.jsx(my,{size:14})})]})]},B.id))}),!Ie.is_locked&&r.jsxs("form",{className:"support-comment-form",onSubmit:B=>{pa(B)},children:[r.jsx("textarea",{value:z,onChange:B=>se(B.target.value),placeholder:"Add a focused reply...",rows:3}),r.jsxs("button",{className:"support-primary-button",type:"submit",disabled:Y==="comment"||!z.trim(),children:[r.jsx(Bu,{size:15})," Reply"]})]})]})]}):r.jsxs("div",{className:"support-detail-empty",children:[r.jsx(_u,{size:28}),r.jsx("strong",{children:"Select a Support request"}),r.jsx("span",{children:"Its discussion and staff actions will appear here."})]})})]})]}):r.jsx("section",{className:"support-page support-auth-page",children:r.jsxs("div",{className:"support-empty-hero",children:[r.jsx("span",{className:"support-hero-icon",children:r.jsx(_u,{size:28})}),r.jsx("p",{className:"support-eyebrow",children:"LiveDesk Support"}),r.jsx("h2",{children:"Get help, report issues, and shape the product."}),r.jsx("p",{children:"Sign in to see the products attached to your account and submit a private or public request."}),r.jsxs("button",{className:"support-primary-button",type:"button",onClick:l,children:[r.jsx(Vn,{size:17})," Sign in with Google"]})]})})}function Xd(n){return!!n&&typeof n=="object"}function wx(n){let a=n;return Xd(a)&&"data"in a&&(a=a.data),Xd(a)&&"session"in a&&(a=a.session),!Xd(a)||typeof a.access_token!="string"||!a.access_token||!Xd(a.user)||typeof a.user.id!="string"||!a.user.id?null:a}function Ny(n){return n?.access_token?n.refresh_token?"":"refresh-token-required":"access-token-required"}const zu=5179,Mn=wl(`http://127.0.0.1:${zu}`);function NC(n){const a=n.split(".").map(i=>Number(i));return a.length===4&&a.every(i=>Number.isInteger(i)&&i>=0&&i<=255)?a:[]}function TC(n){const a=n.trim().toLowerCase();return a==="localhost"||a==="127.0.0.1"||a==="::1"||a==="[::1]"}function RC(n){const a=n.trim().toLowerCase();return!a||a==="0.0.0.0"||a==="::"||a==="[::]"}function EC(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 DC(n){return n.includes(":")&&!n.startsWith("[")?`[${n}]`:n}function LC(n){const a=String(n||"").trim();if(!a)return null;const i=/^[a-z][a-z\d+.-]*:\/\//i.test(a)?a:`tcp://${a}`;try{const l=new URL(i),c=l.hostname.replace(/^\[|\]$/g,""),d=Number(l.port);return!c||!Number.isInteger(d)||d<1||d>65535||RC(c)?null:{host:c,port:d}}catch{return null}}function wl(n){const a=String(n||"").trim()||`http://127.0.0.1:${zu}`,i=/^[a-z][a-z\d+.-]*:\/\//i.test(a)?a:`http://${a}`;try{const l=new URL(i);return l.port||(l.port=String(zu)),l.hash="",l.search="",l.toString().replace(/\/+$/,"")}catch{return`http://127.0.0.1:${zu}`}}function _C(n){const a=LC(n);return a?wl(`http://${DC(a.host)}:${zu}`):""}function Ty(n){const i=[n?.endpoint,...Array.isArray(n?.endpoint_candidates)?n.endpoint_candidates:[]].map(l=>_C(String(l||""))).filter(Boolean);return[...new Set(i)]}function Ou(n=Mn){if(!(typeof window>"u"||window.location.protocol!=="https:"))try{const a=new URL(n);if(a.protocol!=="http:")return;if(TC(a.hostname))return"loopback";if(EC(a.hostname))return"local"}catch{return}}function Pf(n,a=Mn){const i=new URL(n,wl(a));return i.protocol=i.protocol==="https:"?"wss:":"ws:",i.toString()}async function Ve(n,a,i=Mn){const l=wl(i),c={...a,headers:{"Content-Type":"application/json",...a?.headers||{}},cache:"no-store"},d=Ou(l);d&&(c.targetAddressSpace=d);let m;try{m=await fetch(`${l}${n}`,c)}catch(g){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."):g}let h=null;try{h=await m.json()}catch{h=null}if(!m.ok){const g=h&&typeof h=="object"&&"error"in h?String(h.error||""):"";throw new Error(`${m.status} ${g||m.statusText}`)}return h}async function Sx({baseUrl:n=Mn,targetRole:a,previousRuntimePid:i=0,allowedStates:l=["running","waiting-auth"],timeoutMs:c=3e4}){const d=Date.now()+c;let m=null;for(;Date.now()<d;){try{const g=await Ve("/api/runtime/status",void 0,n),y=String(g.role||"").toLowerCase(),x=String(g.state||"").toLowerCase(),b=Number(g.runtimePid||0),w=i>1?b>1&&b!==i:b>1;if(y===a&&l.map(A=>A.toLowerCase()).includes(x)&&w)return g}catch(g){m=g}await new Promise(g=>setTimeout(g,300))}const h=m instanceof Error?` ${m.message}`:"";throw new Error(`LiveDesk runtime did not become ${a} with a new process.${h}`)}function IC(n,a=120){if(typeof window>"u")return;const i=new URL(window.location.href);i.port=String(n),i.pathname="/",i.search="",i.hash="";const l=i.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 Cx(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 Cf(n){await navigator.clipboard.writeText(n)}function kx({size:n=22}){return r.jsxs("svg",{width:n,height:n,viewBox:"0 0 28 28",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[r.jsx("rect",{x:"2.5",y:"4",width:"14",height:"9",rx:"1.5",stroke:"currentColor",strokeWidth:"1.7",opacity:"0.42"}),r.jsx("path",{d:"M7 16v1.5h5",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",opacity:"0.42"}),r.jsx("rect",{x:"10.5",y:"2.5",width:"14",height:"9",rx:"1.5",stroke:"currentColor",strokeWidth:"1.7",opacity:"0.62"}),r.jsx("path",{d:"M15 14.5V16h5",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",opacity:"0.62"}),r.jsx("rect",{x:"6.5",y:"8.5",width:"15",height:"10",rx:"1.7",fill:"currentColor",fillOpacity:"0.12",stroke:"currentColor",strokeWidth:"1.9"}),r.jsx("path",{d:"M12 21v1.5H9.5M16 21v1.5h2.5M9.5 22.5h9",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round"})]})}const jx={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."},ep={en:jx,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 Uf(n){const a=n?[n]:typeof navigator>"u"?["en"]:navigator.languages?.length?navigator.languages:[navigator.language];for(const i of a){const l=String(i||"").trim(),c=l.toLowerCase();if(!c)continue;if(c.startsWith("zh-tw")||c.startsWith("zh-hk"))return"zh-TW";if(c.startsWith("zh"))return"zh";if(c.startsWith("pt"))return"pt-BR";const d=c.split("-")[0];if(ep[l])return l;if(ep[d])return d}return"en"}function Rf(n,a){const i=Uf(a);return ep[i]?.[n]||jx[n]}function tp(n,a,i){return`${n}
11
+ ${Rf(a,i)}`}const Ax={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"},zC={en:Ax,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"}},Mx={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"},OC={en:Mx,ko:{eyebrow:"컴퓨터 역할",title:"이 컴퓨터를 Hub로 사용할까요?",description:"Hub는 Client 컴퓨터를 연결하고 관리합니다.",restartNotice:"다른 컴퓨터가 Hub라면 이 컴퓨터가 새 Hub가 됩니다.",cancel:"취소",confirm:"Hub로 설정",closeLabel:"Hub 설정 확인 닫기"}};function HC(n){const a=Uf(n);return zC[a]||Ax}function FC(n){const a=Uf(n);return OC[a]||Mx}const $C=[{id:"docs",label:"Doc",icon:Tf},{id:"support",label:"Support",icon:_u},{id:"pricing",label:"Pricing",icon:Iu},{id:"settings",label:"Settings",icon:wp}],Ry=[0,1e3,2e3,5e3,1e4,2e4,3e4];function BC(){return typeof window>"u"?"":window.location.port==="5179"?window.location.origin:"http://127.0.0.1:5179"}async function to(n,a=!1){const i=a?"":sessionStorage.getItem("livedesk.client.csrf");if(i)return i;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 np(n){return`${Math.max(0,Math.min(100,Number(n||0))).toFixed(0)}%`}function wh(n){return Number.isFinite(n)?`${Math.max(0,Math.min(100,Number(n))).toFixed(0)}%`:"—"}function Nx(n){return Number.isFinite(n)?np(Number(n)):"0%"}function uo(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 Ey(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 PC(n,a){const i=Number(n||0)/1073741824,l=Number(a||0)/1024**3;return l>0?`${i.toFixed(1)} / ${l.toFixed(1)} GB`:"Checking..."}function UC(n,a){return!Number.isFinite(a)||Number(a)<=0?"Dedicated memory unavailable":Number.isFinite(n)?`${uo(n)} / ${uo(a)}`:`${uo(a)} available`}function qC(n){const a=Math.max(0,Math.floor(Number(n||0)/60)),i=Math.floor(a/1440),l=Math.floor(a%1440/60),c=a%60;return i>0?`${i}d ${l}h`:l>0?`${l}h ${c}m`:`${c}m`}function Zd({icon:n,label:a,value:i,detail:l,percent:c}){return r.jsxs("article",{className:"client-resource-metric",children:[r.jsxs("div",{className:"client-resource-metric-head",children:[r.jsx(n,{size:17}),r.jsx("span",{children:a}),r.jsx("strong",{children:i})]}),r.jsx("small",{title:l,children:l}),r.jsx("i",{"aria-hidden":"true",children:r.jsx("b",{style:{width:Nx(c)}})})]})}function GC(n,a){const i=n?.user.user_metadata||{},l=i.full_name||i.name||i.preferred_username||n?.user.email||n?.user.id||a?.userName||a?.auth?.name||a?.userEmail||a?.userId||"Account";return String(l).trim()||"Account"}function VC(n,a){const i=n?.user.user_metadata||{},l=i.avatar_url||i.picture||a?.userAvatarUrl||a?.auth?.avatarUrl;return typeof l=="string"?l.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 r.jsxs("section",{className:"client-service-page",children:[r.jsx("span",{className:"client-unified-section-label",children:l.label}),r.jsx("h2",{children:l.title}),r.jsx("p",{children:l.body}),r.jsxs("div",{className:"client-service-page-card",children:[n==="docs"&&r.jsxs(r.Fragment,{children:[r.jsx("strong",{children:"Automatic connection"}),r.jsx("span",{children:"Start LiveDesk. This computer signs in, finds the Hub, and becomes available without another action."})]}),n==="pricing"&&r.jsxs(r.Fragment,{children:[r.jsx("strong",{children:"One plan, managed at the Hub"}),r.jsx("span",{children:"Computer access follows the account and plan used by the Hub."})]}),n==="settings"&&r.jsxs(r.Fragment,{children:[r.jsx("strong",{children:"Saved sign-in"}),r.jsx("span",{children:a?.auth?.persisted?"Enabled on this computer":"Sign in once to enable automatic reconnection"})]})]})]})}function YC({session:n,status:a,pin:i,error:l,roleChangeMessage:c,videoAccelerationBusy:d,slotInput:m,slotBusy:h,onSignIn:g,onPinChange:y,onSubmitPin:x,onSlotInputChange:b,onSaveSlot:w,onEnableVideoAcceleration:A}){const j=a?.connectionState==="connected",k=a?.videoAcceleration,N=d||k?.busy||k?.state==="installing",M=k?.ready?`${k.encoder||"H.264"} · ${k.driver||"VAAPI"}`:N?"Setting up…":k?.message||"Setup available",T=a?.system?.memoryTotalBytes?Number(a.system.memoryUsedBytes||0)/a.system.memoryTotalBytes*100:0,D=a?.system?.gpus||[],F=D.find(H=>Number.isFinite(H.usagePercent)||Number.isFinite(H.memoryTotalBytes))||D[0],$=Number.isFinite(F?.usagePercent)?Number(F?.usagePercent):null,q=Number.isFinite(F?.memoryTotalBytes)&&Number(F?.memoryTotalBytes)>0&&Number.isFinite(F?.memoryUsedBytes)?Number(F?.memoryUsedBytes)/Number(F?.memoryTotalBytes)*100:null,L=a?.system?.disks||[],Y=a?.system?.network,G=Y?.interfaces||[],P=[...new Set(G.map(H=>H.name).filter(Boolean))],K=G.map(H=>H.address).filter(Boolean);return r.jsxs("section",{className:"client-home-page",children:[r.jsxs("header",{className:"client-home-heading",children:[r.jsxs("div",{children:[r.jsx("p",{className:"client-unified-eyebrow",children:"THIS COMPUTER"}),r.jsx("h2",{children:a?.deviceName||"This Computer"})]}),r.jsxs("span",{className:`client-unified-role-chip ${j?"connected":""}`,children:[r.jsx(Ta,{size:15})," ",j?"Online":"Connecting"]})]}),r.jsxs("div",{className:"client-home-layout",children:[r.jsxs("section",{className:"client-main-surface","aria-label":"Client computer",children:[r.jsxs("div",{className:"client-main-surface-head",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"SYSTEM STATUS"}),r.jsx("strong",{children:"Hardware at a glance"})]}),r.jsxs("small",{children:[r.jsx(dx,{size:14})," Uptime ",qC(a?.system?.uptimeSeconds)]})]}),r.jsxs("div",{className:"client-system-dashboard",children:[r.jsxs("section",{className:"client-performance-panel","aria-label":"Performance",children:[r.jsxs("div",{className:"client-system-subhead",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"PERFORMANCE"}),r.jsx("strong",{children:"Live resources"})]}),r.jsx("small",{children:"Live updates"})]}),r.jsxs("div",{className:"client-live-metrics",children:[r.jsx(Zd,{icon:Yh,label:"CPU",value:np(a?.system?.cpuUsagePercent),detail:a?.system?.cpuLogicalCores?`${a.system.cpuLogicalCores} logical cores · Current processor usage`:"Current processor usage",percent:a?.system?.cpuUsagePercent}),r.jsx(Zd,{icon:f0,label:"Memory",value:np(T),detail:PC(a?.system?.memoryUsedBytes,a?.system?.memoryTotalBytes),percent:T}),r.jsx(Zd,{icon:m0,label:"GPU",value:wh($),detail:F?.name||(a?.system?.hardwareCollecting?"Detecting graphics hardware…":"Graphics usage unavailable"),percent:$}),r.jsx(Zd,{icon:zr,label:"VRAM",value:wh(q),detail:UC(F?.memoryUsedBytes,F?.memoryTotalBytes),percent:q})]})]}),r.jsxs("section",{className:"client-storage-panel","aria-label":"Local storage",children:[r.jsxs("div",{className:"client-system-subhead",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"STORAGE"}),r.jsx("strong",{children:"Local drives"})]}),r.jsx("small",{children:L.length>0?`${L.length} ${L.length===1?"drive":"drives"}`:a?.system?.hardwareCollecting?"Detecting…":"Unavailable"})]}),r.jsxs("div",{className:"client-disk-list",children:[L.map(H=>r.jsxs("article",{className:"client-disk-row",children:[r.jsxs("div",{className:"client-disk-row-head",children:[r.jsxs("span",{children:[r.jsx(co,{size:16}),r.jsx("strong",{children:H.mount||"Disk"}),r.jsx("small",{children:H.name||"Local disk"})]}),r.jsx("strong",{children:wh(H.usedPercent)})]}),r.jsxs("small",{children:[uo(H.freeBytes)," free · ",uo(H.totalBytes)," total"]}),r.jsx("i",{"aria-hidden":"true",children:r.jsx("b",{style:{width:Nx(H.usedPercent)}})})]},`${H.mount}-${H.name||""}`)),L.length===0&&r.jsxs("div",{className:"client-disk-empty",children:[r.jsx(co,{size:18}),r.jsx("span",{children:a?.system?.hardwareCollecting?"Detecting local drives…":"Storage information is not available."})]})]})]}),r.jsxs("section",{className:"client-network-panel","aria-label":"Network activity",children:[r.jsxs("div",{className:"client-system-subhead",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"NETWORK"}),r.jsx("strong",{children:"Live traffic"})]}),r.jsx("small",{children:P.length>0?P.join(", "):"Detecting adapter"})]}),r.jsxs("div",{className:"client-network-live",children:[r.jsxs("div",{className:"client-network-adapter",children:[r.jsx($f,{size:18}),r.jsxs("span",{children:[r.jsx("strong",{children:P.join(", ")||"Network"}),r.jsx("small",{children:K.join(" / ")||"Checking active connection"})]})]}),r.jsxs("div",{className:"client-network-rate download",children:[r.jsx(h0,{size:17}),r.jsxs("span",{children:[r.jsx("small",{children:"Receive"}),r.jsx("strong",{children:Ey(Y?.receiveBytesPerSecond)})]})]}),r.jsxs("div",{className:"client-network-rate upload",children:[r.jsx(p0,{size:17}),r.jsxs("span",{children:[r.jsx("small",{children:"Send"}),r.jsx("strong",{children:Ey(Y?.sendBytesPerSecond)})]})]}),r.jsxs("small",{className:"client-network-total",children:["Total ",uo(Y?.receivedBytes)," received / ",uo(Y?.sentBytes)," sent"]})]})]})]})]}),r.jsxs("aside",{className:"client-connection-panel",children:[r.jsx("span",{className:"client-unified-section-label",children:"LIVEDESK SERVICES"}),r.jsx("h3",{children:j?"Connected to the Hub":a?.authenticated?"Finding the Hub":"Connect this computer"}),j?r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"client-unified-copy",children:"This computer is available from the LiveDesk Hub."}),r.jsxs("div",{className:"client-service-status-list",children:[r.jsxs("div",{children:[r.jsx(Ta,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Screen sharing"}),r.jsx("small",{children:a?.permissions?.screenCapture?"Active":"Waiting"})]})]}),r.jsxs("div",{children:[r.jsx(Vn,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Remote control"}),r.jsx("small",{children:a?.permissions?.remoteInput?"Available":"Unavailable"})]})]}),r.jsxs("div",{children:[r.jsx(gc,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"File delivery"}),r.jsx("small",{children:a?.permissions?.files?"Ready to receive":"Unavailable"})]})]}),r.jsxs("div",{children:[r.jsx(ho,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Computer audio"}),r.jsx("small",{children:a?.permissions?.audio?"Available":"Unavailable"})]})]})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"client-unified-copy",children:a?.authenticated?"LiveDesk is checking the registered Hub endpoints. A temporary Hub PIN can be used as a fallback.":"Sign in once on this computer. LiveDesk saves the verified session, finds the Hub, and starts screen sharing automatically."}),!n&&!a?.authenticated?r.jsxs("button",{className:"client-unified-primary",type:"button",onClick:g,children:[r.jsx(mo,{size:16})," Sign in with Google"]}):r.jsxs("p",{className:"client-unified-success",children:[r.jsx(Xn,{size:16})," Signed in as ",n?.user.email||n?.user.id||a?.userEmail||a?.userId||"saved account"]}),r.jsxs("div",{className:"client-unified-pin-row",children:[r.jsx(fx,{size:16}),r.jsx("input",{value:i,onChange:H=>y(H.target.value),placeholder:"6-digit Hub PIN",inputMode:"numeric","aria-label":"6-digit Hub PIN"}),r.jsx("button",{className:"client-unified-secondary",type:"button",onClick:x,disabled:i.length!==6,children:"Connect"})]})]}),k?.supported&&r.jsxs("div",{className:`client-video-acceleration state-${k.ready?"ready":k.state||"setup-required"}`,children:[r.jsx(Yh,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Hardware video"}),r.jsx("small",{children:M})]}),!k.ready&&k.canInstall&&r.jsx("button",{type:"button",onClick:A,disabled:N,title:"Install and verify Linux FFmpeg hardware video support",children:N?"Setting up":"Enable"})]}),(l||a?.lastError)&&r.jsxs("p",{className:"client-unified-error",role:"alert",children:[r.jsx(ux,{size:15})," ",l||a?.lastError]}),c&&r.jsx("p",{className:"client-unified-success",children:c}),r.jsxs("div",{className:"client-slot-setting",children:[r.jsxs("label",{htmlFor:"client-slot-number",children:[r.jsx("span",{children:"Slot"}),r.jsx("input",{id:"client-slot-number",value:m,onChange:H=>b(H.target.value),inputMode:"numeric",pattern:"[0-9]*",placeholder:"1-999","aria-label":"Wall slot number",disabled:!j||h})]}),r.jsxs("button",{type:"button",onClick:w,disabled:!j||h||!m,"aria-label":"Save slot number",title:"Save slot number",children:[r.jsx(wp,{size:17}),r.jsx("span",{children:h?"Saving":"Set"})]})]})]})]})]})}function KC(){const[n,a]=u.useState(null),[i,l]=u.useState(null),[c,d]=u.useState(!1),[m,h]=u.useState(""),[g,y]=u.useState(""),[x,b]=u.useState(""),[w,A]=u.useState(!1),[j,k]=u.useState(!1),[N,M]=u.useState(""),[T,D]=u.useState(!1),[F,$]=u.useState(null),[q,L]=u.useState(!1),[Y,G]=u.useState("computer"),[P,K]=u.useState(!1),H=u.useRef(null),ye=u.useRef(null),de=u.useRef(!1),Z=u.useRef(!1),z=u.useRef(!1),se=u.useRef(0),W=u.useRef(!1),O=u.useMemo(BC,[]),le=u.useMemo(()=>GC(i,n),[i,n]),ce=u.useMemo(()=>VC(i,n),[i,n]),[Q,be]=u.useState(!1),he=le.slice(0,1).toUpperCase()||"L";u.useEffect(()=>{be(!1)},[ce]);const fe=u.useCallback(async()=>{if(y(""),window.liveDesk?.auth?.signInWithGoogle){const U=await window.liveDesk.auth.signInWithGoogle();return U?.ok===!1?(y(U.error||"LiveDesk could not open the system browser for Google sign-in."),!1):!0}return window.location.assign(`${O}/auth/google`),!0},[O]),ee=u.useCallback(async()=>{z.current||(z.current=!0,y("Your saved Google sign-in is incomplete. LiveDesk is reopening sign-in once to repair it."),await Ct.auth.signOut({scope:"local"}).catch(()=>{}),l(null),await fe()||(z.current=!1))},[fe]),Se=u.useCallback(async U=>{const ve=Ny(U);if(ve)throw new Error(ve);if(de.current)return!1;de.current=!0;try{const je=await window.liveDesk?.auth?.persistSession?.(U);if(je?.ok===!1)throw new Error(je.error||"LiveDesk could not validate the desktop session.");for(let $e=0;$e<2;$e+=1){const dt=await to(O,$e>0),it=await fetch(`${O}/api/auth/session`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":dt},signal:AbortSignal.timeout(1e4),body:JSON.stringify({accessToken:U.access_token,refreshToken:U.refresh_token,expiresAt:U.expires_at,user:{id:U.user.id,email:U.user.email}})}),pt=await it.json().catch(()=>({}));if(it.status===403&&$e===0){sessionStorage.removeItem("livedesk.client.csrf");continue}if(!it.ok)throw new Error(pt.error||`Client runtime returned HTTP ${it.status}.`);return y(""),!0}throw new Error("Client runtime rejected the session transfer.")}finally{de.current=!1}},[O]),Ne=u.useCallback(async()=>{try{const U=await fetch(`${O}/api/client/status`,{cache:"no-store"}),ve=await U.json().catch(()=>({}));if(!U.ok)throw new Error(ve.error||`Client runtime returned HTTP ${U.status}.`);if(ve.csrfToken&&sessionStorage.setItem("livedesk.client.csrf",ve.csrfToken),String(ve.role||"").toLowerCase()==="hub")throw new Error("This computer is assigned to the Hub role.");a(ve)}catch(U){y(U instanceof Error?U.message:String(U))}},[O]);u.useEffect(()=>{Ne();const U=window.setInterval(()=>{Ne()},2e3);return()=>window.clearInterval(U)},[Ne]),u.useEffect(()=>{if(W.current)return;const U=Number(n?.slotNumber||0);M(U>0?String(U):"")},[n?.slotNumber]),u.useEffect(()=>{if(!F)return;const U=window.setTimeout(()=>$(null),5e3);return()=>window.clearTimeout(U)},[F]);const Fe=u.useCallback(async()=>{const U=Date.now();if(!(!n?.authenticated||n.connectionState==="connected"||!["waiting","reconnecting"].includes(String(n.agent?.state||""))||U-se.current<4e3)){se.current=U;try{const ve=await fetch(`${O}/api/client/reconnect`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await to(O)},body:JSON.stringify({onlyIfWaiting:!0,reason:"app-active"})});if(!ve.ok)throw new Error(`Client reconnect returned HTTP ${ve.status}.`);await Ne()}catch(ve){y(ve instanceof Error?ve.message:String(ve))}}},[O,Ne,n]);u.useEffect(()=>{const U=()=>{Fe()},ve=()=>{Fe()},je=()=>{document.visibilityState==="visible"&&Fe()};return window.addEventListener("online",U),window.addEventListener("focus",ve),document.addEventListener("visibilitychange",je),()=>{window.removeEventListener("online",U),window.removeEventListener("focus",ve),document.removeEventListener("visibilitychange",je)}},[Fe]),u.useEffect(()=>{if(!c||!n||!i?.access_token||n.authenticated)return;if(Ny(i)==="refresh-token-required"){ee().catch(dt=>{z.current=!1,y(dt instanceof Error?dt.message:String(dt))});return}let U=!1,ve,je=0;const $e=async()=>{if(U)return;try{const it=await Se(i);if(await Ne(),it)return}catch(it){y(it instanceof Error?it.message:String(it))}if(U)return;const dt=Ry[Math.min(je,Ry.length-1)];je+=1,ve=window.setTimeout(()=>{$e()},dt)};return $e(),()=>{U=!0,ve!==void 0&&window.clearTimeout(ve)}},[c,Ne,ee,i,n,Se]),u.useEffect(()=>{const U=new URLSearchParams(window.location.search),ve=U.get("auth_error");if(!ve)return;y(ve),U.delete("auth_error");const je=U.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${je?`?${je}`:""}${window.location.hash}`)},[]),u.useEffect(()=>{let U=!0;if(!window.liveDesk?.auth)return l(null),d(!0),Ne(),()=>{U=!1};const ve=window.liveDesk?.auth?.onComplete?.($e=>{$e.ok&&$e.session?Ct.auth.setSession($e.session).catch(dt=>y(dt instanceof Error?dt.message:String(dt))):$e.error&&y($e.error)});(async()=>{try{const $e=window.liveDesk?.auth?.getSession?await window.liveDesk.auth.getSession():await Ct.auth.getSession();if(!U)return;const dt=wx($e);l(dt),Ne()}catch($e){U&&y($e instanceof Error?$e.message:String($e))}finally{U&&d(!0)}})();const{data:je}=Ct.auth.onAuthStateChange(($e,dt)=>{U&&(l(dt),d(!0),Ne())});return()=>{U=!1,ve?.(),je.subscription.unsubscribe()}},[Ne]),u.useEffect(()=>{if(!c||!n||Z.current||z.current||i||n.authenticated)return;const U=new URLSearchParams(window.location.search);if(!U.has("livedesk_launch"))return;Z.current=!0,U.delete("livedesk_launch");const ve=U.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${ve?`?${ve}`:""}${window.location.hash}`),fe().catch(je=>y(je instanceof Error?je.message:String(je)))},[c,i,fe,n]);const ne=async()=>{K(!1),window.liveDesk?.auth?.persistSession?(await Ct.auth.signOut(),(await window.liveDesk.auth.persistSession(null))?.runtimeCleared===!1&&y("Signed out locally. The LiveDesk runtime could not be reached to clear its session.")):await fetch(`${O}/api/auth/session`,{method:"DELETE",headers:{"X-LiveDesk-CSRF":await to(O)}}).catch(()=>{}),l(null),await Ne()};u.useEffect(()=>{if(!P)return;const U=je=>{je.target instanceof Element&&je.target.closest(".account-popover, .rail-account")||K(!1)},ve=je=>{je.key==="Escape"&&K(!1)};return window.addEventListener("pointerdown",U),window.addEventListener("keydown",ve),()=>{window.removeEventListener("pointerdown",U),window.removeEventListener("keydown",ve)}},[P]);const Pe=u.useCallback((U=!0)=>{w||(L(!1),U&&window.requestAnimationFrame(()=>ye.current?.focus()))},[w]),mt=u.useCallback(()=>{w||!n?.authenticated||(ye.current=document.activeElement instanceof HTMLElement?document.activeElement:null,b(""),L(!0))},[w,n?.authenticated]);u.useEffect(()=>{if(!q)return;const U=window.requestAnimationFrame(()=>H.current?.focus()),ve=$e=>{$e.target instanceof Element&&$e.target.closest(".client-hub-switch-popover, .client-hub-switch-trigger")||Pe(!1)},je=$e=>{$e.key==="Escape"&&Pe()};return window.addEventListener("pointerdown",ve),window.addEventListener("keydown",je),()=>{window.cancelAnimationFrame(U),window.removeEventListener("pointerdown",ve),window.removeEventListener("keydown",je)}},[Pe,q]);const J=async()=>{y("");try{const U=await fetch(`${O}/api/client/pin`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await to(O)},body:JSON.stringify({pin:m})}),ve=await U.json().catch(()=>({}));if(!U.ok||ve?.ok===!1)throw new Error(ve?.error||"PIN could not be accepted.");h(""),await Ne()}catch(U){y(U instanceof Error?U.message:String(U))}},ke=async()=>{L(!1),A(!0),b(""),y("");try{const U=await fetch(`${O}/api/runtime/switch-role`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await to(O)},body:JSON.stringify({role:"hub"})}),ve=await U.json().catch(()=>({}));if(!U.ok||ve?.ok===!1)throw new Error(ve?.error||`Role change failed with HTTP ${U.status}.`);b("Hub role accepted. LiveDesk is restarting this computer with the Hub Wall.");const je=Number(n?.runtimePid||0);await Sx({baseUrl:O,targetRole:"hub",previousRuntimePid:je,allowedStates:["running"]}),window.location.reload()}catch(U){y(U instanceof Error?U.message:String(U)),A(!1)}},Le=async()=>{if(T)return;const U=Number(N);if(!Number.isInteger(U)||U<1||U>999){$({kind:"error",message:"Enter a slot number from 1 to 999."});return}D(!0),$(null);try{const ve=await fetch(`${O}/api/client/slot`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await to(O)},body:JSON.stringify({slotNumber:U})}),je=await ve.json().catch(()=>({}));if(!ve.ok||je.ok===!1){if(je.error==="slot-taken"){const $e=je.conflict?.deviceName||je.conflict?.hostname||je.conflict?.deviceId||"another computer";throw new Error(`Slot ${String(U).padStart(3,"0")} is already used by ${$e}.`)}throw new Error(je.error||`Slot update failed with HTTP ${ve.status}.`)}W.current=!1,M(String(U)),a(je),$({kind:"success",message:`Slot ${String(U).padStart(3,"0")} saved. LiveDesk is reconnecting this Client.`})}catch(ve){$({kind:"error",message:ve instanceof Error?ve.message:String(ve)})}finally{D(!1),await Ne()}},Be=async()=>{if(!j){k(!0),y("");try{const U=await fetch(`${O}/api/client/video-acceleration/install`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await to(O)},body:JSON.stringify({confirm:!0})}),ve=await U.json().catch(()=>({}));if(a(ve),!U.ok||ve.videoAcceleration?.ready!==!0)throw new Error(ve.videoAcceleration?.error||ve.error||"Linux hardware video setup did not complete.")}catch(U){y(U instanceof Error?U.message:String(U))}finally{k(!1),await Ne()}}},_e=!!(n?.authenticated||i),Qe=u.useMemo(()=>Uf(),[]),Ye=Rf("switch-to-hub",Qe),Ze=Rf("client",Qe),ut=HC(Qe);return r.jsxs("main",{className:"app-shell client-unified-shell",children:[r.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk Client tools",children:[r.jsx("div",{className:"rail-brand",title:"LiveDesk",children:r.jsx(kx,{size:25})}),r.jsx("nav",{className:"rail-tools","aria-label":"Client navigation",children:r.jsxs("div",{className:"client-main-tool-slot",children:[r.jsxs("button",{className:"rail-tool client-main-tool client-hub-tool client-hub-switch-trigger accent-blue",type:"button",onClick:mt,disabled:w||!n?.authenticated,"aria-busy":w,"aria-expanded":q,"aria-haspopup":"dialog","aria-controls":q?"client-hub-switch-popover":void 0,"aria-label":`Hub. ${Ye}`,"data-tooltip":q?void 0:tp("Hub","switch-to-hub",Qe),children:[r.jsx(zr,{size:19}),r.jsx("span",{children:w?"Switching…":"Hub"})]}),r.jsxs("button",{className:`rail-tool client-main-tool accent-blue ${Y==="computer"?"active":""}`,type:"button",onClick:()=>G("computer"),"aria-current":Y==="computer"?"page":void 0,"aria-label":`Client. ${Ze}`,"data-tooltip":tp("Client","client",Qe),children:[r.jsx(Ta,{size:19}),r.jsx("span",{children:"Client"})]})]})}),r.jsxs("div",{className:"rail-footer",children:[$C.map(U=>{const ve=U.icon;return r.jsxs("button",{className:`rail-tool compact ${Y===U.id?"active":""}`,type:"button",onClick:()=>G(U.id),title:U.label,children:[r.jsx(ve,{size:18}),r.jsx("span",{children:U.label})]},U.id)}),r.jsxs("button",{className:`rail-account ${_e?"signed-in":""}`,type:"button",onClick:()=>K(U=>!U),"aria-expanded":P,"aria-haspopup":"dialog",title:_e?"Account":"Sign in",children:[_e&&ce&&!Q?r.jsx("img",{src:ce,alt:le,referrerPolicy:"no-referrer",onError:()=>be(!0)},ce):_e?r.jsx("span",{className:"avatar-fallback",children:he}):r.jsx(mo,{size:18}),r.jsx("span",{children:_e?"Account":"Sign in"})]})]})]}),q&&r.jsxs("section",{id:"client-hub-switch-popover",className:"client-hub-switch-popover",role:"dialog","aria-modal":"false","aria-labelledby":"client-hub-switch-title","aria-describedby":"client-hub-switch-description client-hub-switch-restart",children:[r.jsxs("header",{className:"client-hub-switch-head",children:[r.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:r.jsx(zr,{size:19})}),r.jsx("span",{className:"client-hub-switch-eyebrow",children:ut.eyebrow}),r.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>Pe(),"aria-label":ut.closeLabel,children:r.jsx(Na,{size:17})})]}),r.jsx("h2",{id:"client-hub-switch-title",children:ut.title}),r.jsx("p",{id:"client-hub-switch-description",children:ut.description}),r.jsxs("p",{id:"client-hub-switch-restart",className:"client-hub-switch-notice",children:[r.jsx(Vn,{size:16,"aria-hidden":"true"}),r.jsx("span",{children:ut.restartNotice})]}),r.jsxs("div",{className:"client-hub-switch-actions",children:[r.jsx("button",{type:"button",onClick:()=>Pe(),children:ut.cancel}),r.jsxs("button",{ref:H,className:"primary",type:"button",onClick:()=>{ke()},disabled:w||!n?.authenticated,children:[r.jsx(zr,{size:16}),ut.confirm]})]})]}),P&&r.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[r.jsxs("div",{className:"account-popover-head",children:[r.jsx("div",{className:"account-popover-avatar",children:_e&&ce&&!Q?r.jsx("img",{src:ce,alt:le,referrerPolicy:"no-referrer",onError:()=>be(!0)},ce):_e?r.jsx("span",{children:he}):r.jsx(mo,{size:18})}),r.jsxs("div",{children:[r.jsx("strong",{children:_e?le:"Account"}),r.jsx("p",{children:i?.user.email||n?.userEmail||n?.userId||"Not signed in"})]})]}),r.jsxs("dl",{className:"account-popover-facts",children:[r.jsx("dt",{children:"User"}),r.jsx("dd",{children:i?.user.email||n?.userEmail||n?.userId||"Not signed in"}),r.jsx("dt",{children:"Runtime"}),r.jsx("dd",{children:n?"Local app ready":"Checking local app"}),r.jsx("dt",{children:"Session"}),r.jsx("dd",{children:n?.auth?.persisted?"Saved on this computer":_e?"Active for this run":"Not saved"}),r.jsx("dt",{children:"Role"}),r.jsx("dd",{children:"Client"})]}),_e?r.jsxs("button",{className:"account-popover-action",onClick:()=>{ne()},type:"button",children:[r.jsx(cx,{size:16}),"Logout"]}):r.jsxs("button",{className:"account-popover-action primary",onClick:()=>{K(!1),fe()},type:"button",children:[r.jsx(mo,{size:16}),"Sign in with Google"]})]}),r.jsxs("section",{className:"desk-stage client-unified-stage",children:[r.jsx("header",{className:"topbar",children:r.jsxs("div",{className:"brand",children:[r.jsx("span",{className:"brand-mark",children:r.jsx(ho,{size:18})}),r.jsxs("div",{children:[r.jsx("h1",{children:"LiveDesk"}),r.jsx("p",{children:"Client workspace"})]})]})}),Y==="support"?r.jsx("section",{className:"client-unified-page",children:r.jsx(xx,{session:i,currentProductKey:"livedesk",appVersion:n?.appVersion||"",onSignIn:()=>{fe()}})}):Y!=="computer"?r.jsx("section",{className:"client-unified-page",children:r.jsx(WC,{page:Y,status:n})}):r.jsx(YC,{session:i,status:n,pin:m,error:g,roleChangeMessage:x,videoAccelerationBusy:j,slotInput:N,slotBusy:T,onSignIn:()=>{fe()},onPinChange:U=>h(U.replace(/\D/g,"").slice(0,6)),onSubmitPin:()=>{J()},onSlotInputChange:U=>{W.current=!0,M(U.replace(/\D/g,"").slice(0,3))},onSaveSlot:()=>{Le()},onEnableVideoAcceleration:()=>{Be()}})]}),F&&r.jsxs("div",{className:`client-side-toast ${F.kind}`,role:F.kind==="error"?"alert":"status",children:[F.kind==="error"?r.jsx(ux,{size:18}):r.jsx(Xn,{size:18}),r.jsx("span",{children:F.message}),r.jsx("button",{type:"button",onClick:()=>$(null),"aria-label":"Dismiss notification",children:r.jsx(Na,{size:16})})]})]})}function pl(n,a,i){if(i<0||a<0||a+i>n.length)throw new Error("Invalid LZO1X block: input overrun.")}function Sh(n,a,i){let l=0;for(;pl(n,a.inputIndex,1),n[a.inputIndex]===0;)l+=1,a.inputIndex+=1;const c=l*255+i+n[a.inputIndex];return a.inputIndex+=1,c}function Jd(n,a,i,l){if(pl(n,a.inputIndex,l),a.outputIndex+l>i.length)throw new Error("Invalid LZO1X block: output overrun.");i.set(n.subarray(a.inputIndex,a.inputIndex+l),a.outputIndex),a.inputIndex+=l,a.outputIndex+=l}function QC(n,a,i,l){const c=a-i;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(i,i+d),a);d<l;){const m=Math.min(d,l-d);n.copyWithin(a+d,a,a+m),d+=m}return a+l}function Tx(n,a){if(!(n instanceof Uint8Array)||n.length<3||a<0)throw new Error("Invalid LZO1X block.");const i=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,Jd(n,l,i,m),c=4}else n[l.inputIndex]>=18&&(c=n[l.inputIndex]-17,l.inputIndex+=1,Jd(n,l,i,c));for(;;){pl(n,l.inputIndex,1);const m=n[l.inputIndex];l.inputIndex+=1;let h,g;if((m&192)!==0)pl(n,l.inputIndex,1),g=l.outputIndex-((n[l.inputIndex]<<3)+(m>>2&7)+1),l.inputIndex+=1,d=(m>>5)+1,h=m&3;else if((m&32)!==0){d=(m&31)+2,d===2&&(d+=Sh(n,l,31)),pl(n,l.inputIndex,2);const y=n[l.inputIndex]|n[l.inputIndex+1]<<8;l.inputIndex+=2,g=l.outputIndex-((y>>2)+1),h=y&3}else if((m&16)!==0){d=(m&7)+2,d===2&&(d+=Sh(n,l,7)),pl(n,l.inputIndex,2);const y=n[l.inputIndex]|n[l.inputIndex+1]<<8;if(l.inputIndex+=2,g=l.outputIndex-(((m&8)<<11)+(y>>2)),h=y&3,g===l.outputIndex)break;g-=16384}else if(c===0){let y=m+3;y===3&&(y+=Sh(n,l,15)),Jd(n,l,i,y),c=4;continue}else c!==4?(pl(n,l.inputIndex,1),h=m&3,g=l.outputIndex-((m>>2)+(n[l.inputIndex]<<2)+1),l.inputIndex+=1,d=2):(pl(n,l.inputIndex,1),h=m&3,g=l.outputIndex-((m>>2)+(n[l.inputIndex]<<2)+2049),l.inputIndex+=1,d=3);if(g<0||l.outputIndex+d+h>i.length)throw new Error("Invalid LZO1X block: lookbehind overrun.");l.outputIndex=QC(i,l.outputIndex,g,d),c=h,Jd(n,l,i,h)}if(d!==3||l.inputIndex!==n.length||l.outputIndex!==i.length)throw new Error("Invalid LZO1X block: incomplete output.");return i}const Dy=16,Ly=8,XC=24*1024*1024,Rx=new Uint8Array(new Uint32Array([16909060]).buffer)[0]===4,ap=new Uint32Array(65536);for(let n=0;n<ap.length;n+=1){const a=Math.round((n>>11&31)*255/31),i=Math.round((n>>5&63)*255/63),l=Math.round((n&31)*255/31);ap[n]=Rx?(a|i<<8|l<<16|4278190080)>>>0:(a<<24|i<<16|l<<8|255)>>>0}function hl(n,a){return n[a]|n[a+1]<<8}function ZC(n,a){const i=Number(a);if(!Number.isSafeInteger(i)||i<Dy||i>XC)throw new Error(`Invalid Mode 5 packet length: ${a}.`);const l=n instanceof Uint8Array?n:new Uint8Array(n),c=Tx(l,i);if(c[0]!==76||c[1]!==68||c[2]!==53||c[3]!==68)throw new Error("Invalid Mode 5 packet magic.");if(c[4]!==1)throw new Error(`Unsupported Mode 5 packet version: ${c[4]}.`);const d=(c[5]&1)!==0,m=hl(c,6),h=hl(c,8),g=hl(c,10),y=hl(c,12);if(m<=0||h<=0||m>3840||h>2160)throw new Error(`Invalid Mode 5 frame size: ${m}x${h}.`);if(g<=0||g>256||y>8192)throw new Error(`Invalid Mode 5 tile header: ${g}/${y}.`);const x=[];let b=Dy;for(let w=0;w<y;w+=1){if(b+Ly>c.length)throw new Error("Mode 5 tile header is truncated.");const A=hl(c,b),j=hl(c,b+2),k=hl(c,b+4),N=hl(c,b+6);b+=Ly;const M=k*N*2;if(k<=0||N<=0||k>g||N>g||A+k>m||j+N>h||b+M>c.length)throw new Error(`Invalid Mode 5 tile ${w}.`);x.push({x:A,y:j,width:k,height:N,pixels:c.subarray(b,b+M)}),b+=M}if(b!==c.length)throw new Error(`Mode 5 packet has ${c.length-b} trailing bytes.`);return{keyFrame:d,width:m,height:h,tileSize:g,tiles:x}}function JC(n,a,i,l){if(!(n instanceof Uint8ClampedArray)||n.length!==a*i*4||l.width!==a||l.height!==i)throw new Error("Mode 5 canvas state does not match the packet dimensions.");let c=a,d=i,m=0,h=0;const g=new Uint32Array(n.buffer,n.byteOffset,n.byteLength>>>2);for(const y of l.tiles){const x=Rx&&(y.pixels.byteOffset&1)===0?new Uint16Array(y.pixels.buffer,y.pixels.byteOffset,y.pixels.byteLength>>>1):null;let b=0;for(let w=0;w<y.height;w+=1){let A=(y.y+w)*a+y.x;for(let j=0;j<y.width;j+=1){const k=b<<1,N=x?x[b]:y.pixels[k]|y.pixels[k+1]<<8;g[A]=ap[N],b+=1,A+=1}}c=Math.min(c,y.x),d=Math.min(d,y.y),m=Math.max(m,y.x+y.width),h=Math.max(h,y.y+y.height)}return l.tiles.length>0?{x:c,y:d,width:m-c,height:h-d}:null}const Ha=new WeakMap,Uu=new WeakMap,sp=new WeakMap,qu=new Set,fo=new Set,Cc=new WeakMap,vc=new Set,Gu=new WeakMap,rp=new WeakMap,ip=new WeakMap,Ef=new WeakMap,Ex=4,e1=2,t1=2,n1=2,a1=18,s1=40,r1=0,i1=250,Dx=80,_y=5,l1=150,o1=1200,c1=18,u1=.65,d1=2e3,f1=500,Mp=250,m1=globalThis.LIVEDESK_ENABLE_CANVAS_VISUAL_SAMPLING===!0;let Lx=1,_x=0,Ix=0,zx=0,Ox,Hx,Ei={h264DecodeAcceleration:"prefer-hardware"};function h1(n){n.h264DecodeAcceleration&&(Ei={...Ei,h264DecodeAcceleration:n.h264DecodeAcceleration})}function lp(n,a=Ei.h264DecodeAcceleration){const i=Cc.get(n);return i?.requested===a?(i.actual!=="prefer-hardware"&&(fo.delete(n),vc.add(n)),i.actual):(i&&(Cc.delete(n),vc.delete(n)),a!=="prefer-hardware"?(fo.delete(n),vc.delete(n),a):(fo.has(n)||fo.add(n),"prefer-hardware"))}function Np(n,a,i){if(a!=="prefer-hardware")return!1;const l=Cc.get(n),c=Ha.get(n),d=Date.now();return Gu.has(n)||Gu.set(n,Lx++),Cc.set(n,{requested:a,actual:"prefer-software",reason:i,failedAt:d,failureCount:(l?.requested===a?l.failureCount:0)+1,codec:c?.codec||l?.codec||"",latencyMode:c?.latencyMode||l?.latencyMode||"smooth",inputCount:c?.inputSerial??l?.inputCount??0,outputCount:c?.outputSerial??l?.outputCount??0,lastInputAt:c?.lastInputAt??l?.lastInputAt??0,lastOutputAt:c?.lastOutputAt??l?.lastOutputAt??0,lastPaintAt:c?.lastPaintAt??l?.lastPaintAt??0}),fo.delete(n),vc.add(n),zx+=1,Ox=i,Hx=d,!0}function p1(n,a,i,l=64){try{let c=rp.get(n);c||(c={canvas:document.createElement("canvas"),lastHash:"",initialized:!1},rp.set(n,c));const d=Math.max(8,Math.min(64,Math.round(l))),m=Math.max(1,Math.round(d*Math.max(1,i)/Math.max(1,a)));(c.canvas.width!==d||c.canvas.height!==m)&&(c.canvas.width=d,c.canvas.height=m);const h=c.canvas.getContext("2d",{willReadFrequently:!0});if(!h)return{visualHash:"",visualChanged:!0};h.drawImage(n,0,0,Math.max(1,a),Math.max(1,i),0,0,d,m);const g=h.getImageData(0,0,d,m).data;let y=2166136261;for(let w=0;w<g.length;w+=4)y^=g[w],y=Math.imul(y,16777619),y^=g[w+1],y=Math.imul(y,16777619),y^=g[w+2],y=Math.imul(y,16777619);const x=(y>>>0).toString(16).padStart(8,"0"),b=!c.initialized||x!==c.lastHash;return c.initialized=!0,c.lastHash=x,{visualHash:x,visualChanged:b}}catch{return{visualHash:"",visualChanged:!0}}}function op(n,a,i,l=Mp,c=64,d){if(!m1&&d)return Fx(n,d);let m=ip.get(n);m||(m={lastHash:"",initialized:!1,lastCanvasSampleAt:0},ip.set(n,m));const h=performance.now();if(m.initialized&&l>0&&h-m.lastCanvasSampleAt<l)return{visualHash:m.lastHash,visualChanged:!1};const g=p1(n,a,i,c);return m.initialized=!0,m.lastHash=g.visualHash,m.lastCanvasSampleAt=h,g}function Fx(n,a){let i=Ef.get(n);i||(i={lastHash:"",initialized:!1},Ef.set(n,i));const l=String(a.contentHash||""),c=!i.initialized||!l||l!==i.lastHash;return i.initialized=!0,i.lastHash=l,{visualHash:l,visualChanged:c}}function $x(n,a){const i=sp.get(n);if(i)return i;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 sp.set(n,d),d}return null}function g1(n){const a=String(n.frameMode||n.mode||"").toLowerCase(),i=String(n.compression||"").toLowerCase(),l=String(n.mimeType||"").toLowerCase();return a==="mode2-lzo"||i==="lzo1x"||l==="application/vnd.livedesk.lzo-rgb565"||a==="mode2-lz4"||String(n.compression||"").toLowerCase()==="lz4"||l==="application/vnd.livedesk.lz4-raw"}function v1(n){return String(n.frameMode||n.mode||"").toLowerCase()==="mode3-h264-hw"||String(n.codec||"").toLowerCase()==="h264"||String(n.mimeType||"").toLowerCase()==="video/h264"}function y1(n){const a=String(n.frameMode||n.mode||"").toLowerCase(),i=String(n.mimeType||"").toLowerCase();return a==="mode5-lzo-delta"||i==="application/vnd.livedesk.lzo-rgb565-delta"}function Iy(n,a,i){let l=i,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 b1(n,a){const i=new Uint8Array(a);let l=0,c=0;for(;l<n.length;){const d=n[l];l+=1;const m=Iy(n,l,d>>4);l=m.cursor;const h=m.length;if(l+h>n.length||c+h>i.length)throw new Error("Invalid LZ4 block: literal overrun.");if(i.set(n.subarray(l,l+h),c),l+=h,c+=h,l>=n.length)break;if(l+2>n.length)throw new Error("Invalid LZ4 block: missing offset.");const g=n[l]|n[l+1]<<8;if(l+=2,g<=0||g>c)throw new Error("Invalid LZ4 block: bad match offset.");const y=Iy(n,l,d&15);l=y.cursor;const x=y.length+4;if(c+x>i.length)throw new Error("Invalid LZ4 block: match overrun.");let b=c-g;for(let w=0;w<x;w+=1)i[c]=i[b],c+=1,b+=1}if(c!==i.length)throw new Error("Invalid LZ4 block: incomplete output.");return i}function x1(n){const a=Math.max(1,Math.floor(n.width||0)),i=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 x=Math.max(1,Math.floor(n.bytesPerPixel||2)),b=a*i*2,w=Math.floor(n.uncompressedByteLength||b);if(x!==2||w!==b)throw new Error(`Invalid mode2 RGB565 frame size: ${w} for ${a}x${i}.`);if(c&&c!=="rgb565le"&&c!=="rgb565")throw new Error(`Unsupported mode2 pixel format: ${c}`);const A=Tx(n.payload,b),j=new Uint8ClampedArray(a*i*4);for(let k=0,N=0;k<A.length;k+=2,N+=4){const M=A[k]|A[k+1]<<8,T=M>>11&31,D=M>>5&63,F=M&31;j[N]=T<<3|T>>2,j[N+1]=D<<2|D>>4,j[N+2]=F<<3|F>>2,j[N+3]=255}return new ImageData(j,a,i)}const m=Math.max(1,Math.floor(n.bytesPerPixel||4)),h=Math.max(a*i*m,Math.floor(n.uncompressedByteLength||0)),g=b1(n.payload,h);if(m!==4)throw new Error(`Unsupported mode2 pixel size: ${m}`);const y=new Uint8ClampedArray(a*i*4);if(c==="rgba32"||c==="rgba")y.set(g.subarray(0,y.length));else for(let x=0,b=0;b<y.length;x+=4,b+=4)y[b]=g[x+2],y[b+1]=g[x+1],y[b+2]=g[x],y[b+3]=g[x+3];return new ImageData(y,a,i)}function zy(n,a="smooth",i=Ei.h264DecodeAcceleration){const l=window.VideoDecoder;if(!l||!window.EncodedVideoChunk)throw new Error("WebCodecs H.264 decode is not supported in this browser.");const c=Ha.get(n);if(c&&c.decoder.state!=="closed"&&c.latencyMode===a)return c;c&&Ps(n);let d;const m=new l({output:h=>{if(Ha.get(n)!==d){h.close();return}const g=Number(h.timestamp||0);d.outputSerial+=1;let y=d.pendingFrames.get(g);if(y)d.pendingFrames.delete(g);else if(d.pendingFrames.size>0){const k=d.pendingFrames.entries().next().value;k&&(d.pendingFrames.delete(k[0]),y=k[1],d.timestampFallbacks+=1)}const x=h.displayWidth||h.codedWidth||n.width||960,b=h.displayHeight||h.codedHeight||n.height||540,w=Number(y?.frame.durationUs||0),A=Number(h.duration||0),j=Math.max(16,Math.min(250,(w>0?w:A||83333)/1e3));for(d.targetPaintIntervalMs=j,d.decodedFrames.push({videoFrame:h,pending:y,decodedAt:performance.now(),width:x,height:b,durationMs:j}),d.lastOutputAt=performance.now();d.decodedFrames.length>Tp(d);)Df(d,d.decodedFrames.shift());Px(d),d.renderTimer!==null&&d.renderScheduledAt>0&&performance.now()-d.renderScheduledAt>f1&&(typeof document>"u"||document.visibilityState==="visible")&&(window.cancelAnimationFrame(d.renderTimer),d.renderTimer=null,d.renderScheduledAt=0),d.renderTimer!==null&&d.decodedFrames.length>=Ex&&(window.cancelAnimationFrame(d.renderTimer),d.renderTimer=null,d.renderScheduledAt=0),Lf(n,d)},error:()=>{Ha.get(n)===d&&(Np(n,d.requestedAcceleration,"decoder-error"),Ps(n))}});return _x+=1,Gu.has(n)||Gu.set(n,Lx++),d={decoder:m,configured:!1,configKey:"",codec:"",requestedAcceleration:i,hardwareAcceleration:lp(n,i),latencyMode:a,keyFrameSeen:!1,droppedForLatency:0,pendingFrames:new Map,decodedFrames:[],renderTimer:null,renderScheduledAt:0,flushTimer:null,flushInFlight:!1,flushCount:0,timestampFallbacks:0,inputSerial:0,outputSerial:0,lastFlushInputSerial:0,lastOutputAt:0,lastPaintAt:0,lastInputAt:0,interactiveBufferPrimed:!1,interactiveBufferStartedAt:0,interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,lastInputFrameSeq:void 0,targetPaintIntervalMs:1e3/12,nextChunkTimestampUs:0,healthSampleStartedAt:performance.now(),healthInputSerial:0,healthOutputSerial:0},Ha.set(n,d),qu.add(n),d}function Bx(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 Df(n,a){a&&(a.videoFrame.close(),n.droppedForLatency+=1)}function Tp(n){return n.latencyMode==="interactive"?t1:String(n.decodedFrames[0]?.pending?.frame.frameMode||n.decodedFrames[0]?.pending?.frame.mode||"").toLowerCase()==="mode4-h264-atlas"?e1:Ex}function Px(n,a=performance.now()){const i=Tp(n);for(;n.decodedFrames.length>i;)Df(n,n.decodedFrames.shift());const l=n.latencyMode==="interactive"?Dx:i1;let c=n.decodedFrames[0];for(;n.decodedFrames.length>1&&c?.pending&&a-c.pending.queuedAt>l;)Df(n,n.decodedFrames.shift()),c=n.decodedFrames[0]}function Ux(n,a){if(a.hardwareAcceleration!=="prefer-hardware"||a.latencyMode==="interactive"||a.flushTimer!==null||a.flushInFlight)return;const i=l1;a.flushTimer=window.setTimeout(async()=>{a.flushTimer=null;const l=performance.now();for(const[d,m]of a.pendingFrames.entries())l-m.queuedAt>d1&&a.pendingFrames.delete(d);if(Ha.get(n)!==a||a.decoder.state!=="configured"||a.pendingFrames.size===0||a.inputSerial<=a.lastFlushInputSerial||a.lastOutputAt>0&&l-a.lastOutputAt<i)return;const c=a.inputSerial;a.flushInFlight=!0,a.flushCount+=1,a.keyFrameSeen=!1;try{await a.decoder.flush(),a.lastFlushInputSerial=Math.max(a.lastFlushInputSerial,c)}catch{Ha.get(n)===a&&kf(a)}finally{a.flushInFlight=!1,Ha.get(n)===a&&a.inputSerial>c&&a.pendingFrames.size>0&&performance.now()-a.lastOutputAt>=i&&Ux(n,a)}},i)}function Oy(n,a,i){const l=performance.now();try{(n.width!==i.width||n.height!==i.height)&&(n.width=i.width,n.height=i.height);const c=$x(n,a.latencyMode);if(c?.context.drawImage(i.videoFrame,0,0,i.width,i.height),i.pending){const d=performance.now(),h=a.latencyMode==="interactive"?Fx(n,i.pending.frame):op(n,i.width,i.height,Mp,64,i.pending.frame);try{a.onPaint?.(i.pending.frame,{deviceId:i.pending.frame.deviceId,frameSeq:i.pending.frame.frameSeq,mode:i.pending.frame.frameMode||i.pending.frame.mode||i.pending.frame.codec||i.pending.frame.mimeType,width:i.width,height:i.height,byteLength:i.pending.frame.byteLength,queuedForMs:Math.max(0,l-i.pending.queuedAt),decodedForMs:Math.max(0,i.decodedAt-i.pending.queuedAt),scheduledForMs:Math.max(0,l-i.decodedAt),drawMs:Math.max(0,d-l),queueSize:i.pending.queueSize,renderQueueSize:a.decodedFrames.length,droppedForLatency:a.droppedForLatency,h264DecodeAcceleration:a.hardwareAcceleration,decoderLabel:a.hardwareAcceleration,decoderFlushCount:a.flushCount,decoderTimestampFallbacks:a.timestampFallbacks,decoderInputCount:a.inputSerial,decoderOutputCount:a.outputSerial,targetPaintIntervalMs:a.targetPaintIntervalMs,canvasPresentation:c?.presentation||"sync",interactiveBufferWaitCount:a.interactiveBufferWaitCount,interactiveBufferWaitMs:a.interactiveBufferWaitMs,interactiveQueueDrainCount:a.interactiveQueueDrainCount,visualHash:h.visualHash,visualChanged:h.visualChanged,paintedAt:d})}catch{}}a.lastPaintAt=performance.now()}finally{i.videoFrame.close()}}function Lf(n,a){if(a.renderTimer!==null||a.decodedFrames.length===0)return;const i=Math.max(16,Math.min(250,a.targetPaintIntervalMs||1e3/12)),l=()=>{if(a.renderTimer=null,a.renderScheduledAt=0,a.decodedFrames.length===0)return;const c=performance.now();if(Px(a,c),a.decodedFrames.length===0)return;if(a.latencyMode==="interactive"){const g=a.targetPaintIntervalMs<=s1,y=a.targetPaintIntervalMs<=20;if(y&&!a.interactiveBufferPrimed){a.interactiveBufferStartedAt<=0&&(a.interactiveBufferStartedAt=c,a.interactiveBufferWaitCount+=1);const k=a.decodedFrames.length>=n1,N=c-a.interactiveBufferStartedAt>=a1;if(!k&&!N){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}a.interactiveBufferWaitMs+=Math.max(0,c-a.interactiveBufferStartedAt),a.interactiveBufferPrimed=!0}else y||(a.interactiveBufferPrimed=!0);const x=a.decodedFrames[0],b=x?.pending?Math.max(0,c-x.pending.queuedAt):0,w=a.lastPaintAt>0?a.lastPaintAt+i:c;if(!(!g||c+_y>=w||b>=Dx)){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}const j=a.decodedFrames.shift();if(j)try{Oy(n,a,j)}catch{}a.decodedFrames.length===0&&(a.interactiveQueueDrainCount+=1,a.interactiveBufferPrimed=!1,a.interactiveBufferStartedAt=0),Lf(n,a);return}const d=a.lastPaintAt>0?a.lastPaintAt+i:c+r1;if(!(c+_y>=d||a.decodedFrames.length>=Math.max(1,Tp(a)-1))){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}const h=a.decodedFrames.shift();if(h)try{Oy(n,a,h)}catch{}Lf(n,a)};a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l)}function qx(n,a){if(Ha.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;)Df(a,a.decodedFrames.shift());return a.lastPaintAt=0,a.interactiveBufferPrimed=!1,a.interactiveBufferStartedAt=0,Lf(n,a),!0}function Ch(){if(!(typeof document>"u"||document.visibilityState!=="visible"))for(const n of qu){const a=Ha.get(n);if(!a||a.decoder.state==="closed"){qu.delete(n);continue}qx(n,a)}}typeof document<"u"&&typeof window<"u"&&(document.addEventListener("visibilitychange",Ch),window.addEventListener("focus",Ch),window.addEventListener("pageshow",Ch));function Ps(n){fo.delete(n),qu.delete(n),Ef.delete(n);const a=Ha.get(n);if(a){Ha.delete(n),Ix+=1;try{Bx(a),a.decoder.state!=="closed"&&a.decoder.close()}catch{}}}function dc(n){n&&(Cc.delete(n),vc.delete(n),sp.delete(n),ip.delete(n),rp.delete(n),Ef.delete(n),Uu.delete(n),Ps(n))}function w1(n,a){const i=Ha.get(n),l=Cc.get(n);if(!i&&!l)return null;const c=d=>d>0?Math.max(0,a-d):void 0;return{canvasId:Gu.get(n)||0,canvasWidth:Math.max(0,Number(n.width||0)),canvasHeight:Math.max(0,Number(n.height||0)),decoderState:i?.decoder.state||"fallback-pending",configured:i?.configured||!1,codec:i?.codec||l?.codec||"",requestedAcceleration:i?.requestedAcceleration||l?.requested||Ei.h264DecodeAcceleration,configuredAcceleration:i?.hardwareAcceleration||l?.actual||Ei.h264DecodeAcceleration,latencyMode:i?.latencyMode||l?.latencyMode||"smooth",decodeQueueSize:Math.max(0,Number(i?.decoder.decodeQueueSize||0)),pendingFrameCount:i?.pendingFrames.size||0,renderQueueSize:i?.decodedFrames.length||0,inputCount:i?.inputSerial??l?.inputCount??0,outputCount:i?.outputSerial??l?.outputCount??0,lastInputAgeMs:c(i?.lastInputAt??l?.lastInputAt??0),lastOutputAgeMs:c(i?.lastOutputAt??l?.lastOutputAt??0),lastPaintAgeMs:c(i?.lastPaintAt??l?.lastPaintAt??0),softwareFallbackReason:l?.reason,softwareFallbackAt:l?.failedAt,softwareFallbackCount:l?.failureCount||0}}function Hy(n){const a=performance.now(),l=(n?[n]:[...new Set([...qu,...vc])]).map(c=>w1(c,a)).filter(c=>c!==null);return{capturedAt:Date.now(),hardwareRequestPolicy:"all-active",activeDecoderCount:l.filter(c=>c.decoderState!=="fallback-pending").length,hardwareLeaseCount:fo.size,activeSoftwareFallbackCount:l.filter(c=>c.configuredAcceleration==="prefer-software"&&c.requestedAcceleration==="prefer-hardware").length,decoderCreateCount:_x,decoderCloseCount:Ix,softwareFallbackEventCount:zx,lastSoftwareFallbackReason:Ox,lastSoftwareFallbackAt:Hx,canvases:l}}function kf(n,a=1){try{n.decoder.state!=="closed"&&n.decoder.reset()}catch{}n.configured=!1,n.configKey="",n.keyFrameSeen=!1,n.pendingFrames.clear(),Bx(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 S1(n,a,i,l,c){n.decoder.configure(a),n.configured=!0,n.configKey=i,n.codec=a.codec,n.requestedAcceleration=c,n.hardwareAcceleration=l,n.keyFrameSeen=!1,n.nextChunkTimestampUs=0,n.lastInputFrameSeq=void 0}function C1(n,a){if(a.latencyMode!=="interactive"||a.hardwareAcceleration!=="prefer-hardware")return!1;const i=performance.now();if(i-a.healthSampleStartedAt<o1)return!1;const l=a.inputSerial-a.healthInputSerial,c=a.outputSerial-a.healthOutputSerial;return a.healthSampleStartedAt=i,a.healthInputSerial=a.inputSerial,a.healthOutputSerial=a.outputSerial,l<c1||c/Math.max(1,l)>=u1?!1:(Np(n,a.requestedAcceleration,"interactive-health"),Ps(n),!0)}function ju(n,a=1){if(!n)return!1;const i=Ha.get(n);return i?(i.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(a))),Ps(n),!0):!1}function k1(n){if(!n)return!1;const a=Ha.get(n);return a?qx(n,a):!1}function j1(n,a,i,l="interactive"){Ps(n);const c=performance.now(),d=ZC(a.payload,a.uncompressedByteLength||0),m=String(a.streamId||"mode5");let h=Uu.get(n);if(!h||h.streamId!==m||h.width!==d.width||h.height!==d.height){const k=new Uint8ClampedArray(d.width*d.height*4);for(let N=3;N<k.length;N+=4)k[N]=255;h={streamId:m,width:d.width,height:d.height,rgba:k,imageData:new ImageData(k,d.width,d.height),keyFrameSeen:!1,inputSerial:0,outputSerial:0},Uu.set(n,h)}if(!h)throw new Error("Mode 5 canvas state could not be initialized.");h.inputSerial+=1;const y=Number(a.streamFrameSeq||0);if(y>0&&(h.lastStreamFrameSeq=y),!d.keyFrame&&!h.keyFrameSeen)return;d.keyFrame&&(h.keyFrameSeen=!0);const x=JC(h.rgba,h.width,h.height,d),b=performance.now();(n.width!==h.width||n.height!==h.height)&&(n.width=h.width,n.height=h.height);const w=$x(n,l),A=performance.now();x&&w?.context.putImageData(h.imageData,0,0,x.x,x.y,x.width,x.height);const j=performance.now();h.outputSerial+=1,i?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.mimeType,width:h.width,height:h.height,byteLength:a.byteLength,queuedForMs:Math.max(0,j-c),decodedForMs:Math.max(0,b-c),scheduledForMs:0,drawMs:Math.max(0,j-A),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:"prefer-software",decoderLabel:"lzo-rgb565-delta",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:h.inputSerial,decoderOutputCount:h.outputSerial,targetPaintIntervalMs:Math.max(1,Number(a.durationUs||0)/1e3||1e3/30),canvasPresentation:w?.presentation||"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:String(a.contentHash||""),visualChanged:Number(a.deltaVisualTileCount||0)>0,paintedAt:j})}const kh=[{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 Fy(n,a){for(let i=Math.max(0,a);i+3<n.length;i+=1)if(!(n[i]!==0||n[i+1]!==0)){if(n[i+2]===1)return{index:i,length:3};if(n[i+2]===0&&n[i+3]===1)return{index:i,length:4}}return null}function A1(n){let a=0;for(;a<n.length;){const i=Fy(n,a);if(!i)break;const l=i.index+i.length,c=Fy(n,l),d=c?.index??n.length;if(l<d&&(n[l]&31)===7){const m=[];let h=0;for(let g=l+1;g<d;g+=1){const y=n[g];if(h>=2&&y===3){h=0;continue}m.push(y),h=y===0?h+1:0}if(m.length>=3)return`avc1.${m.slice(0,3).map(g=>g.toString(16).toUpperCase().padStart(2,"0")).join("")}`}a=c?c.index:n.length}return""}function M1(n,a,i,l,c=""){const d=Math.ceil(n/16)*Math.ceil(a/16),m=i>0?1e6/i:30,h=d*m,g=kh.find(y=>d<=y.maxFrameSize&&h<=y.maxMacroblocksPerSecond)||kh[kh.length-1];return A1(l)||c||`avc1.42E0${g.code.toString(16).toUpperCase().padStart(2,"0")}`}function Gx(n,a,i,l,c="smooth",d=!0){Uu.delete(n);const m=String(a.h264Format||"").toLowerCase()==="avc"?"avc":"annexb",h=Math.max(1,Math.floor(a.width||960)),g=Math.max(1,Math.floor(a.height||540)),y=Math.max(1,Math.floor(a.durationUs||1e6/12)),x=l||Ei.h264DecodeAcceleration;let b=zy(n,c,x);const w=M1(h,g,y,a.payload,b.codec),A=a.isKeyFrame===!0||String(a.chunkType||"").toLowerCase()==="key";let j=lp(n,x),k="";const N=()=>{k=[a.streamId||"",a.commandId||"",h,g,w,m,x,j,c].join("|")};N(),b.onPaint=i,b.configured&&b.decoder.state!=="configured"&&(b.configured=!1,b.configKey=""),b.configured&&b.configKey!==k&&(Ps(n),b=zy(n,c,x),b.onPaint=i,j=lp(n,x),N());const M=()=>({codec:w,codedWidth:h,codedHeight:g,hardwareAcceleration:j,optimizeForLatency:!0,avc:{format:m}}),T=Y=>b.hardwareAcceleration!=="prefer-hardware"||!Np(n,b.requestedAcceleration,Y)?!1:(Ps(n),d&&A&&Gx(n,a,i,x,c,!1),!0),D=()=>{try{return S1(b,M(),k,j,x),!0}catch(Y){if(T("configure-error"))return!1;throw Ps(n),Y}};if(!b.configured&&!D())return;const F=Number(a.streamFrameSeq||0);if(F>0&&b.lastInputFrameSeq!==void 0&&(F<=b.lastInputFrameSeq&&(!A||F===b.lastInputFrameSeq||(kf(b,b.lastInputFrameSeq-F+1),!D()))||F>b.lastInputFrameSeq+1&&(kf(b,F-b.lastInputFrameSeq-1),!A||!D()))||(F>0&&(b.lastInputFrameSeq=F),!A&&!b.keyFrameSeen))return;A&&(b.keyFrameSeen=!0);const $=Number(b.decoder.decodeQueueSize||0);if($>8){if(b.latencyMode==="interactive"&&b.hardwareAcceleration==="prefer-hardware"){T("decode-queue-overflow");return}if(kf(b),!A||!D())return;b.keyFrameSeen=!0}const q=b.nextChunkTimestampUs;b.nextChunkTimestampUs+=y,b.pendingFrames.set(q,{frame:a,queuedAt:performance.now(),queueSize:$}),b.inputSerial+=1,b.lastInputAt=performance.now();const L=new EncodedVideoChunk({type:A?"key":"delta",timestamp:q,duration:y,data:a.payload});try{b.decoder.decode(L)}catch(Y){if(T("decode-error"))return;throw Ps(n),Y}Ux(n,b),C1(n,b)}async function jh(n,a,i,l,c,d="smooth"){if(y1(a)){i()||j1(n,a,l,d);return}if(v1(a)){i()||Gx(n,a,l,c,d);return}if(Uu.delete(n),g1(a)){Ps(n);const b=x1(a);if(i())return;(n.width!==b.width||n.height!==b.height)&&(n.width=b.width,n.height=b.height);const w=n.getContext("2d"),A=performance.now();w?.putImageData(b,0,0);const j=performance.now(),k=op(n,b.width,b.height,Mp,64,a);l?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.codec||a.mimeType,width:b.width,height:b.height,byteLength:a.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,j-A),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:Ei.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:j});return}Ps(n);const m=new Blob([a.payload],{type:a.mimeType}),h=await createImageBitmap(m);if(i()){h.close();return}const g=a.width||h.width||960,y=a.height||h.height||540;(n.width!==g||n.height!==y)&&(n.width=g,n.height=y);const x=n.getContext("2d");if(x){const b=performance.now();x.clearRect(0,0,g,y),x.drawImage(h,0,0,g,y);const w=performance.now(),A=op(n,g,y);l?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.codec||a.mimeType,width:g,height:y,byteLength:a.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,w-b),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:Ei.h264DecodeAcceleration,decoderLabel:"image",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:A.visualHash,visualChanged:A.visualChanged,paintedAt:w})}h.close()}const $y="livedesk_remote_host_targets",N1="livedesk_entitlements",Rp=new TextDecoder;function T1(n){const i=(Array.isArray(n)?n:[n||Mn]).map(l=>wl(l||Mn));return[...new Set(i.filter(Boolean))]}function R1(){const[n,a]=u.useState(null),[i,l]=u.useState(!0);return u.useEffect(()=>{let c=!0;const d=window.liveDesk?.auth?.onComplete?.(h=>{h.ok&&h.session&&Ct.auth.setSession(h.session)});(window.liveDesk?.auth?.getSession?.()||Ct.auth.getSession()).then(h=>{c&&(a(wx(h)),l(!1))});const{data:{subscription:m}}=Ct.auth.onAuthStateChange((h,g)=>{a(g),l(!1),window.liveDesk?.auth?.persistSession?.(g)});return()=>{c=!1,d?.(),m.unsubscribe()}},[]),{session:n,loading:i}}function E1(n,a=!0){const[i,l]=u.useState(null),[c,d]=u.useState([]),[m,h]=u.useState(""),[g,y]=u.useState(""),[x,b]=u.useState(0),w=u.useRef(new Map),A=Array.isArray(n)?n.join(`
12
+ `):String(n||""),j=u.useMemo(()=>T1(n),[A]),k=u.useMemo(()=>j.find(T=>Ou(T)==="loopback")||j[0]||Mn,[j]),N=u.useCallback(async()=>{if(!a){l(null),d([]),y(""),h("");return}let T=null;const D=Date.now(),F=j.filter($=>(w.current.get($)||0)<=D);if(F.length===0)throw new Error("No LiveDesk Hub endpoint is reachable. Retrying shortly.");for(const $ of F)try{const[q,L]=await Promise.all([Ve("/api/remote/status",void 0,$),Ve("/api/remote/devices",void 0,$)]);if(!Array.isArray(L.devices))throw new Error("Invalid Hub devices response.");w.current.delete($),l(q),d(L.devices),y($),h("");return}catch(q){T=q,w.current.set($,Date.now()+1e4)}throw y(""),T||new Error("No LiveDesk Hub endpoint is reachable.")},[a,j]),M=u.useCallback(()=>{w.current.clear(),N().catch(T=>{h(T instanceof Error?T.message:String(T))}),b(T=>T+1)},[N]);return u.useEffect(()=>{if(!a){l(null),d([]),y(""),h("");return}let T=!0;const D=async()=>{try{await N()}catch($){T&&h($ instanceof Error?$.message:String($))}};D();const F=window.setInterval(D,2500);return()=>{T=!1,window.clearInterval(F)}},[a,N,x]),{status:i,devices:c,error:m,refresh:M,hubBaseUrl:g||k,hubCandidates:j}}function D1(n){const[a,i]=u.useState(null),[l,c]=u.useState(""),d=n?.user?.id||"",m=u.useCallback(async()=>{if(!d){i(null);return}const{data:h,error:g}=await Ct.from($y).select("*").eq("user_id",d).maybeSingle();if(g){c(g.message);return}i(h),c("")},[d]);return u.useEffect(()=>{m()},[m]),u.useEffect(()=>{if(!d)return;const h=Ct.channel(`livedesk-remote-host-targets-${d.replace(/[^a-zA-Z0-9]/g,"")}`).on("postgres_changes",{event:"*",schema:"public",table:$y,filter:`user_id=eq.${d}`},g=>i(g.new)).subscribe();return()=>{Ct.removeChannel(h)}},[d]),{target:a,error:l,refresh:m}}function L1(n){const[a,i]=u.useState(null),[l,c]=u.useState(!1),[d,m]=u.useState(""),h=n?.user?.id||"",g=u.useCallback(async()=>{if(!h){i(null),m(""),c(!1);return}c(!0);const{data:x,error:b}=await Ct.from(N1).select("*").eq("user_id",h).eq("product_key","livedesk").maybeSingle();if(b){m(b.message),c(!1);return}i(x),m(""),c(!1)},[h]);u.useEffect(()=>{g()},[g]);const y=u.useMemo(()=>!a||a.status!=="active"?!1:a.expires_at?new Date(a.expires_at).getTime()>Date.now():!0,[a]);return{entitlement:a,licensed:y,loading:l,error:d,refresh:g}}const Hu={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},_1=2500,I1=3e4,z1=64*1024,O1=6,H1=O1,Vx=new Map;function F1(n){return Vx.get(n)}const By={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function $1(n,a,i){const l=Number(a);if(!Number.isFinite(l)||l<=0)return 0;const c=i-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>I1?(n.minimumHubClockOffsetMs=c,0):m}function Au(n){if(n==null||n==="")return;const a=Number(n);return Number.isFinite(a)?a:void 0}function Py(n,a,i=Mn,l={}){const[c,d]=u.useState(new Map),[m,h]=u.useState("idle"),[g,y]=u.useState(""),[x,b]=u.useState(Hu),w=u.useRef(new Map),A=u.useRef(new Map),j=u.useRef(0),k=u.useRef(new Map),N=u.useRef({enabled:!1,token:"",reason:""}),M=u.useRef(new Set),[T,D]=u.useState(0),F=u.useRef(l.onFrame),$=u.useRef(l.onStreamReady),q=u.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),L=u.useMemo(()=>[...n].sort().join(","),[n]),Y=Number.isFinite(l.fps)?Number(l.fps):2,G=Number.isFinite(l.maxWidth)?Number(l.maxWidth):640,P=Number.isFinite(l.maxHeight)?Number(l.maxHeight):360,K=Number.isFinite(l.quality)?Number(l.quality):45,H=String(l.frameMode||l.mode||"mode3-h264-hw").trim()||"mode3-h264-hw",ye=l.streamPurpose==="control"?"control":"wall",de=l.forceRestart===!0,Z=String(l.forceRestartToken||"").trim(),z=String(l.restartReason||"").trim();N.current={enabled:de,token:Z,reason:z};const se=u.useMemo(()=>{const he=Object.entries(l.monitorSelections||{}).filter(([fe])=>!!fe).sort(([fe],[ee])=>fe.localeCompare(ee));return JSON.stringify(Object.fromEntries(he))},[l.monitorSelections]);u.useEffect(()=>{F.current=l.onFrame},[l.onFrame]),u.useEffect(()=>{$.current=l.onStreamReady},[l.onStreamReady]);const W=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{}},[]),O=u.useCallback(()=>{const he=[...A.current.values()].map(fe=>fe.socket);if(he.length===0){h("idle");return}if(he.some(fe=>fe.readyState===WebSocket.OPEN)){h("open");return}if(he.some(fe=>fe.readyState===WebSocket.CONNECTING)){h("connecting");return}h("closed")},[]),le=u.useCallback((he,fe,ee,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:ee,restartToken:Se})),!0}catch{return!1}},[]),ce=u.useCallback((he,fe)=>{if(!he||he.byteLength<5)return;const ee=Date.now(),Ne=new DataView(he).getUint32(0,!1);if(Ne<=0||Ne+4>he.byteLength)return;const Fe=new Uint8Array(he,4,Ne),ne=JSON.parse(Rp.decode(Fe)),Pe=Au(ne.hubPacketEpochMs),mt=Pe!==void 0&&Pe>0?Pe:void 0,J=$1(fe,mt,ee);if(J>_1)return;const ke=new Uint8Array(he,4+Ne),Le={deviceId:String(ne.deviceId||""),kind:ne.kind==="thumbnail"?"thumbnail":"live",frameSeq:Number(ne.frameSeq||0),streamFrameSeq:Number(ne.streamFrameSeq||0)||void 0,streamId:String(ne.streamId||""),commandId:ne.commandId?String(ne.commandId):void 0,sessionId:ne.sessionId?String(ne.sessionId):void 0,captureGeneration:Number(ne.captureGeneration||0)||void 0,streamPurpose:ne.streamPurpose?String(ne.streamPurpose):void 0,width:Number(ne.width||0),height:Number(ne.height||0),sourceWidth:Number(ne.sourceWidth||0)||void 0,sourceHeight:Number(ne.sourceHeight||0)||void 0,mimeType:String(ne.mimeType||"image/jpeg"),mode:ne.mode?String(ne.mode):void 0,frameMode:ne.frameMode?String(ne.frameMode):void 0,frameProfile:ne.frameProfile?String(ne.frameProfile):void 0,encoding:ne.encoding?String(ne.encoding):void 0,codec:ne.codec?String(ne.codec):void 0,compression:ne.compression?String(ne.compression):void 0,pixelFormat:ne.pixelFormat?String(ne.pixelFormat):void 0,bytesPerPixel:Number(ne.bytesPerPixel||0)||0,uncompressedByteLength:Number(ne.uncompressedByteLength||0)||0,h264Format:ne.h264Format?String(ne.h264Format):void 0,isKeyFrame:ne.isKeyFrame===!0,chunkType:ne.chunkType?String(ne.chunkType):void 0,timestampUs:Number(ne.timestampUs||0)||0,durationUs:Number(ne.durationUs||0)||0,sourceGapMs:Number(ne.sourceGapMs||0)||0,agentSendGapMs:Number(ne.agentSendGapMs||0)||0,agentSendDurationMs:Number(ne.agentSendDurationMs||0)||0,agentSendDurationFrameSeq:Number(ne.agentSendDurationFrameSeq||0)||0,agentPaceMs:Number(ne.agentPaceMs||0)||0,agentQueueBeforePaceMs:Number(ne.agentQueueBeforePaceMs||0)||0,agentFrameAgeMs:Number(ne.agentFrameAgeMs||0)||0,nativeCaptureTelemetryAvailable:ne.nativeCaptureTelemetryAvailable===!0,nativeEncoderHardwareAccelerationKnown:ne.nativeEncoderHardwareAccelerationKnown===!0,nativeEncoderHardwareAccelerated:typeof ne.nativeEncoderHardwareAccelerated=="boolean"?ne.nativeEncoderHardwareAccelerated:void 0,nativeEncoderHardwareQueryStatus:ne.nativeEncoderHardwareQueryStatus?String(ne.nativeEncoderHardwareQueryStatus):void 0,nativeCaptureFps:Number(ne.nativeCaptureFps||0)||0,nativeEncodedFps:Number(ne.nativeEncodedFps||0)||0,nativeCaptureSampleCount:Number(ne.nativeCaptureSampleCount||0)||0,nativeEncodableFrameCount:Number(ne.nativeEncodableFrameCount||0)||0,nativeSkippedFrameCount:Number(ne.nativeSkippedFrameCount||0)||0,nativeEncodedFrameCount:Number(ne.nativeEncodedFrameCount||0)||0,nativeCaptureTelemetryAt:ne.nativeCaptureTelemetryAt?String(ne.nativeCaptureTelemetryAt):void 0,droppedByAgent:Number(ne.droppedByAgent||0)||0,hubIngressDropped:Number(ne.hubIngressDropped||0)||0,hubClientDropped:Number(ne.hubClientDropped||0)||0,transport:ne.transport?String(ne.transport):void 0,videoTransport:ne.videoTransport?String(ne.videoTransport):void 0,frameTransportActive:ne.frameTransportActive?String(ne.frameTransportActive):void 0,frameTransportProtocol:ne.frameTransportProtocol?String(ne.frameTransportProtocol):void 0,frameTransportState:ne.frameTransportState?String(ne.frameTransportState):void 0,frameTransportReason:ne.frameTransportReason?String(ne.frameTransportReason):void 0,frameTransportChangedAt:ne.frameTransportChangedAt?String(ne.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(ne.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(ne.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:ne.frameTransportP2pReady===!0,hubClientQueueDepth:Number(ne.hubClientQueueDepth||0)||0,hubClientQueueLimit:Number(ne.hubClientQueueLimit||0)||0,hubClientBufferedBytes:Number(ne.hubClientBufferedBytes||0)||0,udpIncompleteFrames:Number(ne.udpIncompleteFrames||0)||0,hardwareEncoder:ne.hardwareEncoder?String(ne.hardwareEncoder):void 0,platformProfile:ne.platformProfile?String(ne.platformProfile):void 0,monitorIndex:Number.isFinite(Number(ne.monitorIndex))?Number(ne.monitorIndex):void 0,monitorCount:Number.isFinite(Number(ne.monitorCount))?Number(ne.monitorCount):void 0,requestedFps:Number(ne.requestedFps||0)||0,effectiveFps:Number(ne.effectiveFps||0)||0,captureTimingAvailable:ne.captureTimingAvailable===!0,captureAverageMs:Au(ne.captureAverageMs),captureP95Ms:Au(ne.captureP95Ms),slowFrameCount:Number(ne.slowFrameCount||0)||0,captureHelperRestarts:Number(ne.captureHelperRestarts||0)||0,capturedAt:String(ne.capturedAt||""),receivedAt:String(ne.receivedAt||""),hubPacketAt:ne.hubPacketAt?String(ne.hubPacketAt):void 0,hubPacketEpochMs:mt,browserReceivedEpochMs:ee,hubPacketTransitAgeMs:mt!==void 0?J:void 0,byteLength:Number(ne.byteLength||ke.byteLength),contentHash:ne.contentHash?String(ne.contentHash):void 0,captureMs:Au(ne.captureMs),captureStageMs:Au(ne.captureStageMs),convertMs:Number(ne.convertMs||0)||0,compressMs:Number(ne.compressMs||0)||0,captureSourceSerial:Number(ne.captureSourceSerial||0)||0,captureSourceSkipped:Number(ne.captureSourceSkipped||0)||0,deltaTileSize:Number(ne.deltaTileSize||0)||0,deltaTileCount:Number(ne.deltaTileCount||0)||0,deltaVisualTileCount:Number(ne.deltaVisualTileCount||0)||0,deltaRefreshTileCount:Number(ne.deltaRefreshTileCount||0)||0,deltaTotalTiles:Number(ne.deltaTotalTiles||0)||0,payload:ke};if(!Le.deviceId)return;const Be=Number(fe.payload.monitorSelections?.[Le.deviceId]);if(Number.isFinite(Be)&&Number.isFinite(Number(Le.monitorIndex))&&Number(Le.monitorIndex)!==Be)return;const _e={streamId:fe.lastFrameStreamId,commandId:fe.lastFrameCommandId,order:fe.lastFrameOrder},Qe=Number(Le.streamFrameSeq||Le.frameSeq||0),Ye=!!_e.commandId&&!!Le.commandId,Ze=_e.streamId===Le.streamId&&(!Ye||_e.commandId===Le.commandId),ut=_e.order;if(Ze&&ut>=Qe&&(ut===Qe||Ye))return;fe.lastFrameStreamId=Le.streamId,fe.lastFrameCommandId=Le.commandId||"",fe.lastFrameOrder=Qe;const U=q.current;U.totalFrames+=1,U.totalBytes+=ke.byteLength,U.sampleFrames+=1,U.sampleBytes+=ke.byteLength;const ve=!w.current.has(Le.deviceId);w.current.set(Le.deviceId,Le),ve&&d(new Map(w.current)),F.current?.(Le)},[]);u.useEffect(()=>{const he=window.setInterval(()=>{const fe=performance.now(),ee=q.current,Se=Math.max(1,fe-ee.sampleStartedAt);b({totalFrames:ee.totalFrames,totalBytes:ee.totalBytes,framesPerSecond:ee.sampleFrames*1e3/Se,bytesPerSecond:ee.sampleBytes*1e3/Se,sampleMs:Se,lastUpdatedAt:Date.now()}),d(new Map(w.current)),ee.sampleFrames=0,ee.sampleBytes=0,ee.sampleStartedAt=fe},2e3);return()=>{window.clearInterval(he)}},[]),u.useEffect(()=>{const he=L?L.split(",").filter(Boolean):[],fe=new Set(he),ee=performance.now();for(const[Se,Ne]of A.current.entries())fe.has(Se)||(W(Ne,"livedesk-device-unsubscribed"),A.current.delete(Se),k.current.delete(Se),w.current.delete(Se));if(he.length===0){for(const Se of A.current.values())W(Se,"livedesk-no-devices");A.current.clear(),k.current.clear(),w.current=new Map,d(new Map),y(""),q.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},b(Hu),O();return}q.current.sampleStartedAt<=0&&(q.current.sampleStartedAt=ee,b({...Hu,lastUpdatedAt:Date.now()}));for(const Se of he){const Ne=Number(l.monitorSelections?.[Se]),Fe=Number.isInteger(Ne)&&Ne>=0?Ne:0,ne={[Se]:Fe},Pe={type:"subscribe",deviceIds:[Se],autoStartLive:a,fps:Y,maxWidth:G,maxHeight:P,quality:K,mode:H,frameMode:H,streamPurpose:ye,monitorSelections:ne},mt=JSON.stringify(Pe),J=A.current.get(Se),ke=Number(J?.payload.monitorSelections?.[Se]),Le=Number(ne[Se]),Be=!!J&&Number.isFinite(ke)&&Number.isFinite(Le)&&ke!==Le;if(J){const Ze=J.socket.readyState===WebSocket.CONNECTING||J.socket.readyState===WebSocket.OPEN;if(J.payloadKey===mt&&Ze&&!J.disposed)continue}const _e=J&&(J.socket.readyState===WebSocket.CONNECTING||J.socket.readyState===WebSocket.OPEN)&&!J.disposed?J.handoffFrom&&!J.handoffCompleted?J.handoffFrom:J:void 0;J&&J!==_e&&W(J,"livedesk-subscription-superseded");const Qe=new WebSocket(Pf(`/api/remote/frames/ws?devices=${encodeURIComponent(Se)}`,i));Qe.binaryType="arraybuffer";const Ye={socket:Qe,payload:Pe,payloadKey:mt,generation:j.current+1,monitorRestartToken:Be?`monitor-${Se}-${Le}-${j.current+1}`:"",disposed:!1,handoffFrom:_e,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1};j.current=Ye.generation,Be&&(w.current.delete(Se),d(new Map(w.current))),A.current.set(Se,Ye),Qe.addEventListener("open",()=>{if(Ye.disposed||A.current.get(Se)!==Ye){W(Ye,"livedesk-stale-frame-socket");return}y("");const Ze=N.current,ut=Ze.enabled&&(!Ze.token||k.current.get(Se)!==Ze.token),U=ut||Ye.monitorRestartToken!=="",ve=ut?Ze.token:Ye.monitorRestartToken,je=ut?Ze.reason:Ye.monitorRestartToken?"monitor-selection-change":"";Qe.send(JSON.stringify({...Ye.payload,forceRestart:U,restartReason:U?je:"",restartToken:U?ve:""})),ut&&Ze.token&&k.current.set(Se,Ze.token);const $e=Ye.handoffFrom;Ye.handoffFrom=void 0,Ye.handoffCompleted=!0,$e&&!$e.disposed&&W($e,"livedesk-subscription-replaced"),O()}),Qe.addEventListener("message",Ze=>{if(Ye.disposed||A.current.get(Se)!==Ye)return;if(typeof Ze.data=="string"){try{const U=JSON.parse(Ze.data);if(U?.type==="RemoteFrameSubscriptionError")y(String(U.error||"control-stream-start-failed"));else if(U?.type==="RemoteFrameLiveAutoStart"){const je=(Array.isArray(U.skipped)?U.skipped:[]).find($e=>$e?.deviceId===Se);if(je)y(String(je.reason||"control-stream-start-failed"));else if(Array.isArray(U.started)){const $e=U.started.find(dt=>dt?.deviceId===Se);$e&&(y(""),$e.ready===!0&&$e.streamPurpose==="control"&&$e.sessionId&&$e.commandId&&Number($e.captureGeneration||0)>0&&$.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)}))}}else U?.type==="RemoteFrameStreamReady"&&U.deviceId===Se&&U.streamPurpose==="control"&&U.sessionId&&U.commandId&&Number(U.captureGeneration||0)>0&&(y(""),$.current?.({deviceId:Se,sessionId:String(U.sessionId),streamId:String(U.streamId||""),streamPurpose:"control",commandId:String(U.commandId),captureGeneration:Number(U.captureGeneration),monitorIndex:Number(U.monitorIndex||0)}))}catch{}return}const ut=Ze.data instanceof ArrayBuffer?Ze.data:null;ut&&(y(""),ce(ut,Ye))}),Qe.addEventListener("error",()=>{Ye.disposed||A.current.get(Se)!==Ye||h("connecting")}),Qe.addEventListener("close",()=>{const Ze=!Ye.disposed;Ye.disposed=!0;const ut=A.current.get(Se);let U=!1;if(ut===Ye){const ve=Ye.handoffFrom;Ye.handoffFrom=void 0,ve&&!ve.disposed&&(ve.socket.readyState===WebSocket.CONNECTING||ve.socket.readyState===WebSocket.OPEN)?(A.current.set(Se,ve),U=!0):A.current.delete(Se)}if(O(),Ze&&ut===Ye&&!U){const ve=window.setTimeout(()=>{M.current.delete(ve),D(je=>je+1)},750);M.current.add(ve)}})}O()},[a,W,L,Y,H,ce,i,P,G,se,l.monitorSelections,K,T,ye,O]),u.useEffect(()=>{if(!de||!Z)return;const he=L?L.split(",").filter(Boolean):[];for(const fe of he){if(k.current.get(fe)===Z)continue;const ee=A.current.get(fe);!ee||!le(fe,ee,z,Z)||k.current.set(fe,Z)}},[L,de,Z,z,le]),u.useEffect(()=>()=>{for(const he of A.current.values())W(he,"livedesk-hook-unmount");A.current.clear();for(const he of M.current)window.clearTimeout(he);M.current.clear()},[W]);const Q=u.useCallback((he,fe="browser-stale")=>{const ee=Array.isArray(he)&&he.length>0?he:L.split(",").filter(Boolean);if(ee.length===0)return!1;let Se=!1;for(const Ne of ee){const Fe=A.current.get(Ne);!Fe||Fe.socket.readyState!==WebSocket.OPEN||(Se=le(Ne,Fe,fe,`${Date.now()}-${Math.random().toString(36).slice(2)}`)||Se)}return Se},[L,le]),be=u.useCallback((he,fe="browser-reconnect")=>{const ee=Array.isArray(he)&&he.length>0?he:L.split(",").filter(Boolean);if(ee.length===0)return!1;let Se=!1;for(const Ne of ee){const Fe=A.current.get(Ne);Fe&&(W(Fe,`livedesk-${fe}`),A.current.delete(Ne),k.current.delete(Ne),w.current.delete(Ne),Se=!0)}return Se&&d(new Map(w.current)),D(Ne=>Ne+1),O(),!0},[W,L,O]);return{frames:c,state:m,error:g,stats:x,restartLive:Q,reconnectLive:be}}function B1(n,a,i=Mn,l={}){const[c,d]=u.useState(null),[m,h]=u.useState(null),[g,y]=u.useState("idle"),[x,b]=u.useState(Hu),w=u.useRef(null),A=u.useRef(l.onFrame),j=u.useRef(null),k=u.useRef(0),N=u.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),M=u.useMemo(()=>[...new Set(n.filter(Boolean))].join(","),[n]),T=u.useMemo(()=>[...new Set((l.captureDeviceIds||n).filter(Boolean))].join(","),[n,l.captureDeviceIds]),D=u.useMemo(()=>JSON.stringify(l.monitorSelections||{}),[l.monitorSelections]),F=u.useMemo(()=>({deviceIds:M.split(",").filter(Boolean),captureDeviceIds:T.split(",").filter(Boolean),fps:Number(l.fps||20),inputFps:Number(l.inputFps||8),width:Number(l.width||1920),height:Number(l.height||1080),tileWidth:Number(l.tileWidth||320),tileHeight:Number(l.tileHeight||180),monitorSelections:l.monitorSelections||{}}),[T,M,D,l.fps,l.height,l.inputFps,l.monitorSelections,l.tileHeight,l.tileWidth,l.width]),$=u.useMemo(()=>JSON.stringify(F),[F]),q=u.useRef(F);q.current=F;const L=a&&F.deviceIds.length>0,Y=u.useCallback(P=>P.readyState!==WebSocket.OPEN?!1:(P.send(JSON.stringify({type:"configure",...q.current})),!0),[]);u.useEffect(()=>{A.current=l.onFrame},[l.onFrame]),u.useEffect(()=>{const P=window.setInterval(()=>{const K=N.current,H=performance.now(),ye=Math.max(1,H-K.sampleStartedAt);b({totalFrames:K.totalFrames,totalBytes:K.totalBytes,framesPerSecond:K.sampleFrames*1e3/ye,bytesPerSecond:K.sampleBytes*1e3/ye,sampleMs:ye,lastUpdatedAt:Date.now()});const de=j.current;de&&de.frameSeq!==k.current&&(k.current=de.frameSeq,d(de)),K.sampleFrames=0,K.sampleBytes=0,K.sampleStartedAt=H},1e3);return()=>window.clearInterval(P)},[]),u.useEffect(()=>{if(!L){w.current?.close(),w.current=null,d(null),j.current=null,k.current=0,h(null),y("idle"),b(Hu);return}let P=!1,K=0;const H=()=>{if(P)return;const ye=new WebSocket(Pf("/api/remote/atlas/ws",i));ye.binaryType="arraybuffer",w.current=ye,y("connecting"),ye.addEventListener("open",()=>{N.current.sampleStartedAt=performance.now(),y("open"),Y(ye)}),ye.addEventListener("message",de=>{if(typeof de.data=="string"){try{const z=JSON.parse(de.data);z?.type==="Mode4AtlasLayout"&&h({layoutVersion:Number(z.layoutVersion||0),width:Number(z.width||1920),height:Number(z.height||1080),columns:Number(z.columns||1),rows:Number(z.rows||1),tiles:Array.isArray(z.tiles)?z.tiles:[]})}catch{}return}const Z=de.data instanceof ArrayBuffer?de.data:null;if(!(!Z||Z.byteLength<5))try{const z=Date.now(),W=new DataView(Z).getUint32(0,!1);if(W<=0||W+4>Z.byteLength)return;const O=JSON.parse(Rp.decode(new Uint8Array(Z,4,W))),le=new Uint8Array(Z,4+W),ce={deviceId:String(O.deviceId||"__livedesk_mode4_atlas__"),kind:"live",frameSeq:Number(O.frameSeq||0),streamFrameSeq:Number(O.streamFrameSeq||0)||void 0,streamId:String(O.streamId||"mode4-atlas"),commandId:O.commandId?String(O.commandId):void 0,width:Number(O.width||1920),height:Number(O.height||1080),sourceWidth:Number(O.sourceWidth||O.width||1920),sourceHeight:Number(O.sourceHeight||O.height||1080),mimeType:String(O.mimeType||"video/h264"),mode:String(O.mode||"mode4-h264-atlas"),frameMode:String(O.frameMode||"mode4-h264-atlas"),frameProfile:String(O.frameProfile||"mode4-h264-atlas-v1"),encoding:String(O.encoding||"video-atlas"),codec:String(O.codec||"h264"),compression:String(O.compression||"video/h264"),h264Format:String(O.h264Format||"annexb"),isKeyFrame:O.isKeyFrame===!0,chunkType:String(O.chunkType||""),timestampUs:Number(O.timestampUs||0),durationUs:Number(O.durationUs||0),transport:O.transport?String(O.transport):void 0,videoTransport:O.videoTransport?String(O.videoTransport):void 0,frameTransportActive:O.frameTransportActive?String(O.frameTransportActive):void 0,frameTransportProtocol:O.frameTransportProtocol?String(O.frameTransportProtocol):void 0,frameTransportState:O.frameTransportState?String(O.frameTransportState):void 0,frameTransportReason:O.frameTransportReason?String(O.frameTransportReason):void 0,frameTransportChangedAt:O.frameTransportChangedAt?String(O.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(O.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(O.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:O.frameTransportP2pReady===!0,hubClientQueueDepth:Number(O.hubClientQueueDepth||0)||0,hubClientQueueLimit:Number(O.hubClientQueueLimit||0)||0,hubClientBufferedBytes:Number(O.hubClientBufferedBytes||0)||0,udpIncompleteFrames:Number(O.udpIncompleteFrames||0)||0,hardwareEncoder:O.hardwareEncoder?String(O.hardwareEncoder):void 0,platformProfile:O.platformProfile?String(O.platformProfile):void 0,capturedAt:String(O.capturedAt||""),receivedAt:String(O.receivedAt||""),hubPacketAt:O.hubPacketAt?String(O.hubPacketAt):void 0,hubPacketEpochMs:Number(O.hubPacketEpochMs||0)||void 0,browserReceivedEpochMs:z,byteLength:le.byteLength,layoutVersion:Number(O.layoutVersion||0),atlasComposeMs:Number(O.atlasComposeMs||0),atlasPoolStarved:Number(O.atlasPoolStarved||0),atlasReadyTiles:Number(O.atlasReadyTiles||0),atlasTileCount:Number(O.atlasTileCount||0),atlasInputRevision:Number(O.atlasInputRevision||0),atlasSourceNewestAtEpochMs:Number(O.atlasSourceNewestAtEpochMs||0),atlasSourceOldestAtEpochMs:Number(O.atlasSourceOldestAtEpochMs||0),atlasSourceMaxAgeMs:Number(O.atlasSourceMaxAgeMs||0),payload:le},Q=N.current;Q.totalFrames+=1,Q.totalBytes+=le.byteLength,Q.sampleFrames+=1,Q.sampleBytes+=le.byteLength,j.current=ce,k.current===0&&(k.current=ce.frameSeq,d(ce)),A.current?.(ce)}catch{}}),ye.addEventListener("error",()=>y("error")),ye.addEventListener("close",()=>{w.current===ye&&(w.current=null),!P&&(y("closed"),K=window.setTimeout(H,1200))})};return H(),()=>{P=!0,window.clearTimeout(K),w.current?.close(),w.current=null}},[L,i,Y]),u.useEffect(()=>{if(!L)return;const P=w.current;P&&Y(P)},[$,L,Y]);const G=u.useCallback(()=>{const P=w.current;return P?Y(P):!1},[Y]);return{frame:c,layout:m,state:g,stats:x,refreshInputs:G}}function P1(n,a=Mn){const i=u.useRef(null),l=u.useRef(0),c=u.useRef(0),d=u.useRef(new Map),m=u.useRef(""),[h,g]=u.useState("idle"),[y,x]=u.useState(""),[b,w]=u.useState(By),A=u.useRef({totalSent:0,totalDropped:0,sampleSent:0,sampleDropped:0,sampleStartedAt:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0});u.useEffect(()=>{if(!n){i.current?.close(),i.current=null,c.current=0,m.current="",d.current.clear(),g("idle"),x(""),w(By);return}let k=!1,N=0;const M=()=>{if(k)return;const T=new WebSocket(Pf("/api/remote/input/ws",a));i.current=T,A.current.sampleStartedAt=performance.now(),g("connecting"),x(""),T.addEventListener("open",()=>{k||i.current!==T||(x(""),g("open"))}),T.addEventListener("message",D=>{if(!(k||i.current!==T||typeof D.data!="string"))try{const F=JSON.parse(D.data),$=Number(F.inputSeq||F.result?.inputSeq||0),q=String(F.deviceId||F.result?.deviceId||""),L=String(F.inputEventId||F.result?.inputEventId||""),Y=d.current.get($);if(q&&(Y&&Y.deviceId!==q||!Y&&m.current&&m.current!==q)||Y?.inputEventId&&L&&Y.inputEventId!==L)return;if(F?.type==="RemoteInputError"){$>0&&d.current.delete($),x(String(F.error||F.result?.error||"Remote input failed.")),T.readyState===WebSocket.OPEN&&g("open");return}if(F?.type!=="RemoteInputApplied")return;Y&&(A.current.lastRoundTripMs=Math.max(0,performance.now()-Y.sentAt),d.current.delete($)),A.current.lastInputSeq=$,A.current.lastAgentApplyMs=Math.max(0,Number(F.agentApplyMs||0)),x(""),g("open")}catch{}}),T.addEventListener("close",()=>{k||i.current!==T||(i.current=null,g("closed"),N=window.setTimeout(M,1200))}),T.addEventListener("error",()=>{!k&&i.current===T&&g("error")})};return M(),()=>{k=!0,window.clearTimeout(N);const T=i.current;i.current=null,T?.close(),d.current.clear()}},[n,a]),u.useEffect(()=>{if(!n)return;const k=window.setInterval(()=>{const N=performance.now(),M=A.current,T=Math.max(1,N-M.sampleStartedAt);w({totalSent:M.totalSent,totalDropped:M.totalDropped,sentPerSecond:M.sampleSent*1e3/T,droppedPerSecond:M.sampleDropped*1e3/T,bufferedAmount:i.current?.bufferedAmount||0,lastInputType:M.lastInputType,lastInputSeq:M.lastInputSeq,lastRoundTripMs:M.lastRoundTripMs,lastAgentApplyMs:M.lastAgentApplyMs,lastUpdatedAt:Date.now()}),M.sampleSent=0,M.sampleDropped=0,M.sampleStartedAt=N},1e3);return()=>window.clearInterval(k)},[n]);const j=u.useCallback((k,N)=>{const M=i.current;if(!M||M.readyState!==WebSocket.OPEN||!k)return!1;const T=String(N.type||"").toLowerCase(),D=T==="pointermove",$=D||T==="wheel",q=A.current;if(D&&M.bufferedAmount>z1)return q.totalDropped+=1,q.sampleDropped+=1,q.lastInputType="pointermove-drop",!1;const L=l.current+1;l.current=L;const Y=`${L}-${crypto.randomUUID()}`,G=Date.now(),P=!$||L-c.current>=H1;for(P&&(d.current.set(L,{sentAt:performance.now(),deviceId:k,inputEventId:Y}),$&&(c.current=L)),m.current=k,D||Vx.set(k,{inputSeq:L,inputType:T||"input",sentAt:performance.now()});d.current.size>256;){const K=d.current.keys().next().value;if(K===void 0)break;d.current.delete(K)}return M.send(JSON.stringify({type:"input",requestId:$?"":crypto.randomUUID(),fireAndForget:$,deviceId:k,input:{...N,inputEventId:Y,inputSeq:L,requestAck:P,issuedAtEpochMs:G,issuedAt:new Date(G).toISOString()}})),q.totalSent+=1,q.sampleSent+=1,q.lastInputType=T||"input",!0},[]);return{state:h,sendInput:j,stats:b,error:y}}function U1(n){const a=String(n||"").toLowerCase();return a.includes("audio/pcm")||a.includes("audio/l16")||a.includes("f32le")||a.includes("s16le")}const ef={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},q1=.08,G1=.25,V1=.02,Uy=300,W1=4,tf=1500,Ah=5e3,Y1=2e3,K1=1e4,nf=[0,1e3,3e3];function qy(n){const a=Date.parse(String(n||""));return Number.isFinite(a)?Math.max(0,Date.now()-a):0}function Q1(n,a,i){const l=Math.max(1,Math.min(8,Math.floor(a.channels||2))),c=Math.max(8e3,Math.min(192e3,Math.floor(a.sampleRate||48e3))),d=String(a.mimeType||"").toLowerCase(),m=d.includes("s16le")||d.includes("audio/l16"),h=m?2:4,g=Math.floor(i.byteLength/h),y=Math.floor(g/l),x=n.createBuffer(l,y,c),b=new DataView(i);for(let w=0;w<l;w+=1){const A=x.getChannelData(w);for(let j=0;j<y;j+=1){const N=(j*l+w)*h;A[j]=m?Math.max(-1,Math.min(1,b.getInt16(N,!0)/32768)):Math.max(-1,Math.min(1,b.getFloat32(N,!0)))}}return x}function X1(n,a,i=Mn){const l=u.useRef(null),c=u.useRef(0),[d,m]=u.useState("idle"),[h,g]=u.useState(null),[y,x]=u.useState(ef),[b,w]=u.useState("");return u.useEffect(()=>{if(!a||!n){m("idle"),g(null),x(ef),w("");return}m("connecting"),g(null),x(ef),w("");const A=window.AudioContext||window.webkitAudioContext;if(!A){m("unsupported"),x(ef),w("Audio playback is not supported in this browser.");return}const j=new A;l.current=j,c.current=j.currentTime;const k=new WebSocket(Pf("/api/remote/audio/ws?devices="+encodeURIComponent(n),i));k.binaryType="arraybuffer";const N=new Set,M={browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:!1,helperAlive:!1,captureRestartCount:0,localProcessingAgeMs:0,lastPacketAt:0,lastAcceptedAt:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:String(j.state),stalledCount:0,automaticRestarts:0,activeStreamId:"",lastCaptureStatusAt:0,lastPcmAtEpochMs:0};let T=!1,D=0,F=!1,$=0,q=0;const L=(z=!0)=>{for(const se of N)try{se.stop()}catch{}N.clear(),z&&(c.current=j.currentTime+q1)},Y=()=>{M.audioContextState=String(j.state),!T&&(M.audioContextState==="suspended"||M.audioContextState==="interrupted"?m("suspended"):M.audioContextState==="closed"&&(m("error"),w("The browser audio context is closed. Toggle Remote Audio off and on to recover.")))},G=async()=>{if(T||String(j.state)==="closed")return!1;try{if(String(j.state)!=="running"&&await j.resume(),M.audioContextState=String(j.state),!T&&!F&&M.audioContextState==="running"){const z=M.lastAcceptedAt>0&&performance.now()-M.lastAcceptedAt<=tf,se=M.lastCaptureStatusAt>0&&performance.now()-M.lastCaptureStatusAt<=Ah&&M.captureAlive&&M.helperAlive;m(z?"playing":se?"silent":"open")}return M.audioContextState==="running"}catch(z){return T||(m("suspended"),w(z instanceof Error?"Audio playback is suspended: "+z.message:"Audio playback is suspended.")),!1}},P=async()=>{if(T||F||k.readyState!==WebSocket.OPEN)return;if($>=nf.length){m("error"),w("Remote audio stopped sending frames. Toggle Audio off and on to retry.");return}const z=$;$+=1,F=!0,M.stalledCount+=1,M.automaticRestarts+=1,m("reconnecting");try{const se=await Ve("/api/remote/devices/"+encodeURIComponent(n)+"/audio/stop",{method:"POST",body:JSON.stringify({})},i);if(se.ok===!1)throw new Error(se.error||"Remote audio stop failed.");if(T)return;const W=await Ve("/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})},i);if(W.ok===!1)throw new Error(W.error||"Remote audio start failed.");const O=performance.now();D=O,M.lastPacketAt=O,M.lastAcceptedAt=0,M.lastCaptureStatusAt=0,M.lastPcmAtEpochMs=0,M.captureAlive=!1,M.helperAlive=!1,M.silentForMs=0,q=O+(nf[z+1]??3e3),w(""),T||m("open")}catch(se){T||(q=performance.now()+(nf[z+1]??3e3),m("error"),w(se instanceof Error?"Remote audio restart failed: "+se.message:"Remote audio restart failed."))}finally{F=!1}},K=()=>{M.drops+=1},H=window.setInterval(()=>{if(T)return;const z=performance.now(),se=M.lastPacketAt>0?Math.max(0,z-M.lastPacketAt):D>0?Math.max(0,z-D):0,W=M.lastAcceptedAt>0?Math.max(0,z-M.lastAcceptedAt):0,O=M.lastCaptureStatusAt>0?Math.max(0,z-M.lastCaptureStatusAt):0,le=k.readyState===WebSocket.OPEN,ce=M.lastCaptureStatusAt>0,Q=ce&&O<=Ah,be=ce&&(!M.captureAlive||!M.helperAlive)&&O>Y1,he=ce&&O>Ah,fe=!ce&&D>0&&z-D>K1,ee=D>0&&(M.lastAcceptedAt<=0?z-D>tf:W>tf);le&&D>0&&(be||he||fe)?$>=nf.length&&!F?(m("error"),w("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!F&&z>=q?P():F||m("stalled"):le&&ee&&!F&&M.audioContextState!=="suspended"&&M.audioContextState!=="interrupted"&&m(Q?"silent":"open"),x({queuedMs:Math.max(0,(c.current-j.currentTime)*1e3),browserAgeMs:M.browserAgeMs,captureAgeMs:M.captureAgeMs,captureStatusAgeMs:O,silentForMs:M.silentForMs,captureAlive:M.captureAlive,helperAlive:M.helperAlive,captureRestartCount:M.captureRestartCount,localProcessingAgeMs:M.localProcessingAgeMs,lastPacketAgeMs:se,lastAcceptedAgeMs:W,framesReceived:M.framesReceived,drops:M.drops,resyncs:M.resyncs,pendingDecodes:M.pendingDecodes,lastFrameSeq:M.lastFrameSeq,audioContextState:M.audioContextState,stalledCount:M.stalledCount,automaticRestarts:M.automaticRestarts,lastUpdatedAt:Date.now()})},250),ye=()=>{Y(),(String(j.state)==="suspended"||String(j.state)==="interrupted")&&G()},de=()=>{document.visibilityState==="visible"&&G()},Z=()=>{G()};return j.addEventListener("statechange",ye),document.addEventListener("visibilitychange",de),window.addEventListener("pageshow",Z),window.addEventListener("pointerdown",Z),window.addEventListener("keydown",Z),m("connecting"),w(""),Y(),k.addEventListener("open",()=>{T||(D=performance.now(),M.lastPacketAt=D,M.lastAcceptedAt=0,M.lastCaptureStatusAt=0,M.lastPcmAtEpochMs=0,M.captureAlive=!1,M.helperAlive=!1,M.silentForMs=0,m("open"),k.send(JSON.stringify({type:"subscribe",deviceIds:[n]})),G())}),k.addEventListener("message",z=>{if(typeof z.data=="string")return;const se=z.data instanceof ArrayBuffer?z.data:null;if(!se||se.byteLength<5)return;const W=performance.now();M.lastPacketAt=W,(async()=>{try{const le=new DataView(se).getUint32(0,!1);if(le<=0||le+4>se.byteLength){K();return}const ce=new Uint8Array(se,4,le),Q=JSON.parse(Rp.decode(ce)),be=se.slice(4+le),he=String(Q.frameKind||Q.kind||"").toLowerCase();if(Q.type==="remote.audio.status"||he==="audio-status"){if(M.lastCaptureStatusAt=W,M.captureAlive=Q.captureAlive===!0,M.helperAlive=Q.helperAlive===!0,M.captureRestartCount=Math.max(0,Number(Q.restartCount||0)||0),M.lastPcmAtEpochMs=Math.max(0,Number(Q.lastPcmAtEpochMs||0)||0),M.silentForMs=Math.max(0,Number(Q.silentForMs||0)||0),M.captureAgeMs=M.lastPcmAtEpochMs>0?Math.max(0,Date.now()-M.lastPcmAtEpochMs):M.silentForMs,M.captureAlive&&M.helperAlive){if($=0,q=0,!F){w("");const ee=String(j.state)==="running",Se=M.lastAcceptedAt>0&&performance.now()-M.lastAcceptedAt<=tf;m(ee?Se?"playing":"silent":"suspended")}}else F||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||be.byteLength),payload:be};if(!fe.deviceId||T)return;if(performance.now()-W>Uy){K();return}if(M.pendingDecodes>=W1){K();return}M.pendingDecodes+=1;try{const ee=U1(fe.mimeType)?Q1(j,fe,be):await j.decodeAudioData(be.slice(0));if(M.localProcessingAgeMs=Math.max(0,performance.now()-W),T)return;if(M.localProcessingAgeMs>Uy){K();return}if(fe.frameSeq>0&&fe.frameSeq<=M.lastFrameSeq){K();return}if(M.activeStreamId&&fe.streamId!==M.activeStreamId&&fe.frameSeq<=M.lastFrameSeq){K();return}fe.streamId&&fe.streamId!==M.activeStreamId&&(M.activeStreamId=fe.streamId,M.lastFrameSeq=0,L());const Se=j.currentTime;Math.max(0,c.current-Se)>G1&&(L(),M.resyncs+=1);const Fe=j.createBufferSource();Fe.buffer=ee,Fe.connect(j.destination),N.add(Fe),Fe.onended=()=>{N.delete(Fe),Fe.onended=null};const ne=Math.max(j.currentTime+V1,c.current);Fe.start(ne),c.current=ne+ee.duration,M.browserAgeMs=qy(fe.receivedAt),M.captureAgeMs=qy(fe.capturedAt),M.lastAcceptedAt=performance.now(),M.framesReceived+=1,M.lastFrameSeq=fe.frameSeq,$=0,q=0,g(fe),G();const Pe=String(j.state)==="running";Pe&&w(""),m(Pe?"playing":"suspended")}finally{M.pendingDecodes=Math.max(0,M.pendingDecodes-1)}}catch(O){T||(m("error"),w(O instanceof Error?O.message:String(O)))}})()}),k.addEventListener("error",()=>{T||(m("error"),w("Remote audio WebSocket error."))}),k.addEventListener("close",()=>{T||m("closed")}),()=>{T=!0,window.clearInterval(H),j.removeEventListener("statechange",ye),document.removeEventListener("visibilitychange",de),window.removeEventListener("pageshow",Z),window.removeEventListener("pointerdown",Z),window.removeEventListener("keydown",Z),L(!1),k.close(),j.close().catch(()=>{}),l.current===j&&(l.current=null)}},[n,a,i]),{state:d,lastFrame:h,stats:y,error:b}}const Z1=3;function Gy(n,a,i){const l=Math.max(1,Number(i)||1),c=Math.max(0,Math.min(l,Number(n)-Number(a))),d=Math.min(l/2,Z1);return c<=d?0:c>=l-d?1:c/l}function J1(n,a,i){return{normalizedX:Gy(n,i.left,i.width),normalizedY:Gy(a,i.top,i.height)}}const _f=Object.freeze({shiftKey:Object.freeze(["ShiftLeft","ShiftRight"]),ctrlKey:Object.freeze(["ControlLeft","ControlRight"]),altKey:Object.freeze(["AltLeft","AltRight"]),metaKey:Object.freeze(["MetaLeft","MetaRight"])}),ek=Object.freeze({shiftKey:"ShiftLeft",ctrlKey:"ControlLeft",altKey:"AltLeft",metaKey:"MetaLeft"}),cp=64;function yc(n,a=80){return String(n||"").replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,a)}function Wx(n={}){const a=yc(n.key),i=Number.isFinite(Number(n.location))?Math.max(0,Math.min(3,Math.trunc(Number(n.location)))):0;return a?`Key:${i}:${a}`.slice(0,80):""}function Vy(n){for(const[a,i]of Object.entries(_f))if(i.includes(n))return a;return""}function Ru(n,a){return _f[a].some(i=>n.has(i))}function Wy(n,a,i={}){for(const l of Object.keys(_f)){const c=i[l]===!0,d=_f[l];if(c){!Ru(n,l)&&n.size<cp&&n.add(ek[l]);continue}for(const m of d)a.has(m)||n.delete(m)}}function up(n){return{shiftKey:Ru(n,"shiftKey"),ctrlKey:Ru(n,"ctrlKey"),altKey:Ru(n,"altKey"),metaKey:Ru(n,"metaKey")}}function tk(n={},a={}){return{shiftKey:n.shiftKey===!0||a.shiftKey===!0,ctrlKey:n.ctrlKey===!0||a.ctrlKey===!0,altKey:n.altKey===!0||a.altKey===!0,metaKey:n.metaKey===!0||a.metaKey===!0}}function nk(n,a,i){const l=yc(n.code)||Wx(n),c=yc(n.key),d=Number(n.keyCode??n.which),m=Number(n.location);return{type:a,key:c,code:l,keyCode:Number.isFinite(d)?Math.max(0,Math.min(65535,Math.trunc(d))):0,location:Number.isFinite(m)?Math.max(0,Math.min(255,Math.trunc(m))):0,text:c.length===1?c:"",repeat:a==="keydown"&&n.repeat===!0,pressedCodes:[...i],...up(i)}}function ak(){const n=new Set,a=new Set;return{event(i={},l=""){if(l!=="keydown"&&l!=="keyup")return null;const c=yc(i.code)||Wx(i);if(!c)return null;const d=Vy(c),m=n.has(c);return d?(l==="keydown"?n.size<cp&&n.add(c):a.has(c)||n.delete(c),Wy(n,a,i)):(Wy(n,a,i),l==="keydown"?n.size<cp&&n.add(c):n.delete(c)),l==="keydown"&&m&&i.repeat!==!0?null:nk(i,l,n)},modifier(i,l){const c=yc(i),d=Vy(c);if(!d)return null;const m=a.has(c);return l===m?null:(l?(a.add(c),n.add(c)):(a.delete(c),n.delete(c)),{type:l?"keydown":"keyup",key:d==="metaKey"?"Meta":d==="ctrlKey"?"Control":d==="altKey"?"Alt":"Shift",code:c,keyCode:0,location:c.endsWith("Right")?2:1,text:"",repeat:!1,pressedCodes:[...n],...up(n)})},reset(i="keyboard-owner-reset",l=!1){const c=n.size>0;return n.clear(),a.clear(),!c&&!l?null:{type:"keyboard.reset",reason:yc(i,120)||"keyboard-owner-reset",pressedCodes:[],shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1,repeat:!1}},snapshot(){return{pressedCodes:[...n],latchedCodes:[...a],...up(n)}}}}function kc(n){const a=Number(n);return Number.isSafeInteger(a)&&a>0?a:0}function Zn(n){return String(n||"").trim()}function af(n,a,i={}){return{deviceId:Zn(n),transitionGeneration:kc(a),sessionId:Zn(i.sessionId),streamId:Zn(i.streamId),commandId:Zn(i.commandId),captureGeneration:kc(i.captureGeneration),monitorIndex:Math.max(0,Math.floor(Number(i.monitorIndex)||0))}}function gs(n,a){return!!n&&!!a&&Zn(n.deviceId)===Zn(a.deviceId)&&kc(n.transitionGeneration)===kc(a.transitionGeneration)}function Yy(n,a){const i=Promise.resolve(n).catch(()=>{}).then(a);return{result:i,tail:i.then(()=>{},()=>{})}}function sf(n,a,i){const l=Zn(n);return!l||!a||Zn(a.deviceId)!==l?!1:!i||Zn(i.deviceId)!==l}function Ky(n,a){if(!n||!a)return!1;const i=kc(a.captureGeneration),l=Zn(a.commandId),c=Zn(a.sessionId),d=Zn(a.streamId),m=Number(n.monitorIndex);return!i||!l||!c||!d||!Number.isInteger(m)||m<0?!1:Zn(n.deviceId)===Zn(a.deviceId)&&Zn(n.sessionId)===c&&Zn(n.streamId)===d&&Zn(n.commandId)===l&&kc(n.captureGeneration)===i&&Zn(n.streamPurpose).toLowerCase()==="control"&&m===a.monitorIndex}const bs=Object.freeze({automaticDirectH264:!0,interactiveDirectFps:30,directFullFpsDeviceLimit:6,directMinAdaptiveFps:8,controlWallReuseMaxFps:30,scalableAtlasMinInputFps:8,scalableAtlasMaxInputFps:20,scalableAtlasAggregateInputFps:120,atlasOutputFps:20,maxDirectFramesPerSecond:180,directDecodeAcceleration:"prefer-hardware",directLatencyMode:"interactive"});function sk(n,a){const i=Math.max(0,Math.floor(Number(a)||0));return n===!0&&i>0}function Mu({mode4Enabled:n,directMode4WallEnabled:a,isMac:i}){return"direct"}function rk({mode4Enabled:n,directMode4WallEnabled:a,adaptiveFps:i,directDeviceCount:l,adaptive:c=!0}){const d=Math.max(1,Math.floor(Number(i)||1));if(!c)return d;const m=Math.max(1,Math.floor(Number(l)||1));return m<=bs.directFullFpsDeviceLimit?d:Math.max(bs.directMinAdaptiveFps,Math.min(d,Math.floor(bs.maxDirectFramesPerSecond/m)))}function ik({deviceCount:n,targetFps:a,adaptive:i=!0}){const l=Math.max(1,Math.floor(Number(n)||1)),c=Math.max(1,Math.min(bs.scalableAtlasMaxInputFps,Math.floor(Number(a)||bs.scalableAtlasMaxInputFps)));if(!i)return c;const d=Math.max(bs.scalableAtlasMinInputFps,Math.min(bs.scalableAtlasMaxInputFps,Math.floor(bs.scalableAtlasAggregateInputFps/l)));return Math.min(c,d)}function lk(n,a){return{acceleration:bs.directDecodeAcceleration,latencyMode:bs.directLatencyMode}}const lo={revision:0,settings:{security:{accessMode:"trusted-only"},control:{allowKeyboardMouse:!0},filesAudio:{allowFileTransfer:!0,allowRemoteAudio:!0,rollingBufferEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0}}},ok=[{id:"connection",label:"Connection",icon:$f},{id:"remote-access",label:"Remote Access",icon:Vn},{id:"capture-audio",label:"Capture & Audio",icon:Kh},{id:"agent",label:"Agent",icon:yl}];function jf(n,a){return n?.settings?.[a]||lo.settings[a]||{}}function Qy(n,a){return{...n,settings:{...n.settings,[a.section]:{...jf(n,a.section),[a.key]:a.value}}}}function Mh(n){return{revision:Number(n.revision||0),updatedAt:n.updatedAt,settings:n.settings}}function fc({icon:n,title:a,description:i,children:l,recommended:c=!1}){return r.jsxs("div",{className:"product-setting-row",children:[r.jsx("div",{className:"product-setting-control",children:l}),n&&r.jsx("span",{className:"product-setting-icon",children:r.jsx(n,{size:17})}),r.jsxs("div",{className:"product-setting-copy",children:[r.jsx("strong",{children:a}),c&&r.jsx("em",{children:"Recommended"}),r.jsx("small",{children:i})]})]})}function rf({checked:n,onChange:a,label:i}){return r.jsxs("label",{className:"product-switch",children:[r.jsx("input",{"aria-label":i,type:"checkbox",checked:n,onChange:l=>a(l.target.checked)}),r.jsx("span",{})]})}function Xy({value:n,onChange:a,options:i,label:l}){return r.jsx("select",{"aria-label":l,value:String(n),onChange:c=>a(c.target.value),children:i.map(([c,d])=>r.jsx("option",{value:c,children:d},c))})}function ck({hubUrl:n="",runtimeRole:a="hub",runtimeDeviceId:i="",sessionAccessToken:l="",initialTab:c="connection",pin:d,agent:m,captureGallery:h}){const[g,y]=u.useState(c),[x,b]=u.useState(null),[w,A]=u.useState("loading"),[j,k]=u.useState(""),[N,M]=u.useState("idle"),[T,D]=u.useState(""),F=u.useRef(null),$=u.useRef(null),q=u.useRef([]),L=u.useRef(Promise.resolve()),Y=u.useRef(0),G=u.useRef(0);u.useEffect(()=>{const ce=++G.current;let Q=!0;return q.current=[],$.current=null,F.current=null,L.current=Promise.resolve(),A("loading"),Ve("/api/settings",void 0,n).then(be=>{if(!Q||ce!==G.current)return;const he=Mh(be);$.current=he,F.current=he,b(he),A("saved")}).catch(be=>{!Q||ce!==G.current||(k(be instanceof Error?be.message:String(be)),$.current=lo,F.current=lo,b(lo),A("failed"))}),()=>{Q=!1}},[n]);const P=async(ce,Q,be)=>{const he={id:++Y.current,section:ce,key:Q,value:be},fe=G.current;q.current.push(he);const ee=Qy(F.current||$.current||lo,he);F.current=ee,b(ee),A("saving"),k(""),L.current=L.current.then(async()=>{if(fe!==G.current)return;let Se=null,Ne=null;for(let Pe=0;Pe<2&&!Se;Pe+=1){const mt=$.current||lo;try{const J=await Ve("/api/settings",{method:"PATCH",body:JSON.stringify({revision:mt.revision,[he.section]:{[he.key]:he.value}})},n);Se=Mh(J)}catch(J){if(Ne=J,Pe!==0||!String(J instanceof Error?J.message:J).startsWith("409 "))break;try{const ke=await Ve("/api/settings",void 0,n);if(fe!==G.current)return;$.current=Mh(ke)}catch(ke){Ne=ke;break}}}if(fe!==G.current)return;q.current=q.current.filter(Pe=>Pe.id!==he.id),Se&&($.current=Se);const Fe=$.current||lo,ne=q.current.reduce(Qy,Fe);F.current=ne,b(ne),Se?(k(""),A(q.current.length>0?"saving":"saved")):(A(q.current.length>0?"saving":"failed"),k(Ne instanceof Error?Ne.message:String(Ne||"Settings could not be saved.")))}),await L.current},K=(ce,Q)=>be=>{P(ce,Q,be)},H=async()=>{if(a!=="hub"||!i||!l){M("failed"),D("Sign in to this Hub before changing its runtime role.");return}M("changing"),D("");try{const ce=await Ve("/api/runtime/status",void 0,n);await Ve("/api/runtime/role",{method:"POST",headers:{Authorization:`Bearer ${l}`},body:JSON.stringify({role:"client"})},n),M("accepted"),await Sx({baseUrl:n,targetRole:"client",previousRuntimePid:Number(ce.runtimePid||0),allowedStates:["running","waiting-auth"]}),IC(5179)}catch(ce){M("failed"),D(ce instanceof Error?ce.message:String(ce))}},ye=jf(x,"security"),de=jf(x,"control"),Z=jf(x,"filesAudio"),z=`settings-panel-${g}`,se=r.jsxs("div",{className:"settings-tab-content product-settings-content",children:[d,r.jsxs("section",{className:"settings-section-card runtime-role-settings",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Runtime role"}),r.jsx("h3",{children:"Use this computer as a Client"})]}),r.jsx(mx,{size:20})]}),r.jsx("p",{className:"settings-help",children:"Stop hosting from this computer and reconnect it to the selected Hub."}),N==="accepted"?r.jsx("p",{className:"settings-help runtime-role-success",children:"LiveDesk is restarting as Client."}):T?r.jsx("p",{className:"settings-help runtime-role-error",role:"alert",children:T}):null,r.jsx("button",{className:"settings-reset",onClick:()=>{H()},disabled:N==="changing"||a!=="hub",type:"button",children:N==="changing"?"Switching role...":"Switch this computer to Client"})]})]}),W=r.jsxs("div",{className:"settings-tab-content product-settings-content",children:[r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Remote access"}),r.jsx("h3",{children:"Who may connect?"})]}),r.jsx(Ti,{size:20})]}),r.jsx(fc,{icon:Vn,title:"Access mode",description:"Choose the default permission boundary for remote sessions.",recommended:!0,children:r.jsx(Xy,{value:String(ye.accessMode),onChange:K("security","accessMode"),label:"Access mode",options:[["trusted-only","Trusted devices only"],["block-remote-access","Block remote access"]]})})]}),r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Session permissions"}),r.jsx("h3",{children:"What may remote users do?"})]}),r.jsx(Ta,{size:20})]}),r.jsx(fc,{icon:Ta,title:"Keyboard and mouse control",description:"Allow Control to send keyboard and pointer input.",recommended:!0,children:r.jsx(rf,{checked:!!de.allowKeyboardMouse,onChange:K("control","allowKeyboardMouse"),label:"Keyboard and mouse control"})}),r.jsx(fc,{icon:Kh,title:"File transfer",description:"Allow files to be delivered to connected computers.",children:r.jsx(rf,{checked:!!Z.allowFileTransfer,onChange:K("filesAudio","allowFileTransfer"),label:"File transfer"})}),r.jsx(fc,{icon:ho,title:"Remote audio",description:"Allow sound capture from connected computers.",children:r.jsx(rf,{checked:!!Z.allowRemoteAudio,onChange:K("filesAudio","allowRemoteAudio"),label:"Remote audio"})})]})]}),O=r.jsxs("div",{className:"settings-tab-content product-settings-content",children:[r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Capture"}),r.jsx("h3",{children:"Recording defaults"})]}),r.jsx(Kh,{size:20})]}),r.jsx(fc,{icon:ho,title:"Keep a Last 30s buffer",description:"Keep recent video in memory until you explicitly save it.",children:r.jsx(rf,{checked:!!Z.rollingBufferEnabled,onChange:K("filesAudio","rollingBufferEnabled"),label:"Keep a Last 30s buffer"})}),r.jsx(fc,{icon:ho,title:"Timelapse interval",description:"Choose how often a timelapse frame is captured.",children:r.jsx(Xy,{value:Number(Z.timelapseIntervalSeconds),onChange:ce=>K("filesAudio","timelapseIntervalSeconds")(Number(ce)),label:"Timelapse interval",options:[["5","5 seconds"],["10","10 seconds"],["30","30 seconds"],["60","60 seconds"]]})})]}),h]}),le=g==="connection"?se:g==="remote-access"?W:g==="capture-audio"?O:m;return r.jsxs("section",{className:"settings-page",children:[r.jsx("div",{className:"settings-page-tabs",role:"tablist","aria-label":"LiveDesk settings",children:ok.map(({id:ce,label:Q,icon:be})=>r.jsxs("button",{className:g===ce?"active":"",id:`settings-tab-${ce}`,role:"tab","aria-selected":g===ce,"aria-controls":`settings-panel-${ce}`,tabIndex:g===ce?0:-1,onClick:()=>y(ce),type:"button",children:[r.jsx(be,{size:16}),Q]},ce))}),w==="saving"&&r.jsx("div",{className:"product-save-state",role:"status",children:"Saving settings..."}),j&&r.jsx("div",{className:"agent-settings-alert error",role:"alert",children:j}),r.jsx("section",{className:"settings-page-panel",id:z,role:"tabpanel","aria-labelledby":`settings-tab-${g}`,tabIndex:0,children:le})]})}function uk({children:n}){return r.jsx("div",{className:"settings-tab-content",children:n})}const dp={enabled:!1,provider:"codex",codexModelId:"",codexReasoningEffort:"medium",codexTaskTimeoutMs:6e5,codexMaxToolCalls:20,codexWorkingDirectory:"",codexResumeSessions:!0,codexShowDetailedEvents:!0,deterministicParserFirst:!0,generateSummary:!0,fallbackSummary:!0,includeRawDeviceDetails:!1,baseUrl:"https://opencode.ai/zen/go/v1",defaultModelId:"deepseek-v4-flash"};function Zy(n){return{...dp,...n||{}}}async function dk(n,a,i){let l=null;for(let c=0;c<2;c+=1){const d=await Ve("/api/settings",{signal:i},a);if(d.settings.agent?.enabled===n)return;try{await Ve("/api/settings",{method:"PATCH",signal:i,body:JSON.stringify({revision:d.revision,agent:{enabled:n}})},a);return}catch(m){if(l=m,c!==0||!String(m instanceof Error?m.message:m).startsWith("409 "))throw m}}throw l}function fk({hubUrl:n}){const[a,i]=u.useState(dp),[l,c]=u.useState(null),[d,m]=u.useState(""),[h,g]=u.useState(""),[y,x]=u.useState(""),[b,w]=u.useState(""),A=u.useRef(0),j=u.useRef(null);u.useEffect(()=>{let G=!0;j.current?.abort();const P=new AbortController;j.current=P;const K=++A.current;return c(null),i(dp),m(""),g(""),w(""),x(""),Ve("/api/settings/agent",{signal:P.signal},n).then(H=>{!G||P.signal.aborted||K!==A.current||(c(H.settings),i(Zy(H.settings)))}).catch(H=>{G&&!P.signal.aborted&&K===A.current&&w(H instanceof Error?H.message:String(H))}),()=>{G=!1,P.abort(),j.current===P&&(j.current=null)}},[n]);const k=(G,P)=>i(K=>({...K,[G]:P})),N=G=>{c(G),i(Zy(G))},M=()=>({generation:A.current,controller:j.current}),T=G=>G.generation===A.current&&G.controller!==null&&G.controller===j.current&&!G.controller.signal.aborted,D=async()=>{if(!l){w("Agent settings are not available yet.");return}const G=M();if(T(G)){g("save"),w(""),x("");try{if(await dk(a.enabled,n,G.controller.signal),!T(G))return;const{enabled:P,...K}=a,H={...K};d.trim()&&(H.apiKey=d.trim());const ye=await Ve("/api/settings/agent",{method:"PUT",signal:G.controller.signal,body:JSON.stringify(H)},n);if(!T(G))return;N(ye.settings),m(""),x("Agent settings saved.")}catch(P){T(G)&&w(P instanceof Error?P.message:String(P))}finally{T(G)&&g("")}}},F=async()=>{const G=M();if(T(G)){g("reset"),w("");try{const P=await Ve("/api/settings/agent/reset",{method:"POST",signal:G.controller.signal,body:JSON.stringify({})},n);if(!T(G))return;N(P.settings),x("Codex defaults restored.")}catch(P){T(G)&&w(P instanceof Error?P.message:String(P))}finally{T(G)&&g("")}}},$=async()=>{const G=M();if(T(G)){g("test"),w(""),x("");try{const P=await Ve("/api/settings/agent/test",{method:"POST",signal:G.controller.signal,body:JSON.stringify({})},n);if(!T(G))return;const K=await Ve("/api/settings/agent",{signal:G.controller.signal},n);if(!T(G))return;N(K.settings),x(`Codex connection verified with ${P.connection?.modelName||"the configured model"}${P.connection?.latencyMs?` in ${P.connection.latencyMs} ms.`:"."}`)}catch(P){T(G)&&w(P instanceof Error?P.message:String(P))}finally{T(G)&&g("")}}},q=async()=>{const G=M();if(T(G)){g("clear-key"),w("");try{const P=await Ve("/api/settings/agent/api-key",{method:"DELETE",signal:G.controller.signal},n);if(!T(G))return;N(P.settings),m(""),x("The optional OpenCode Go key was removed.")}catch(P){T(G)&&w(P instanceof Error?P.message:String(P))}finally{T(G)&&g("")}}},L=l?.codexInstallation==="installed"&&l.codexAuth==="signed-in",Y=l!==null;return r.jsxs("div",{className:"settings-tab-content agent-settings-content",children:[r.jsx("section",{className:"settings-section-card agent-enable-card",children:r.jsxs("label",{className:"settings-toggle agent-enable-toggle",children:[r.jsx("input",{type:"checkbox",checked:a.enabled,onChange:G=>k("enabled",G.target.checked),disabled:!Y||h!==""}),r.jsx("span",{children:"Enable Agent AI"})]})}),b&&r.jsx("div",{className:"agent-settings-alert error",role:"alert",children:b}),y&&r.jsx("div",{className:"agent-settings-alert success",role:"status",children:y}),r.jsxs("div",{className:"settings-section-grid",children:[r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Provider"}),r.jsx("h3",{children:"Choose the AI service"})]}),r.jsx(Vn,{size:20})]}),r.jsxs("label",{className:"settings-field",children:[r.jsx("span",{children:"Agent provider"}),r.jsxs("select",{value:a.provider,onChange:G=>k("provider",G.target.value),children:[r.jsx("option",{value:"codex",children:"Codex SDK"}),r.jsx("option",{value:"opencode-go",children:"OpenCode Go"})]})]}),a.provider==="codex"&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"agent-connection-row",children:[r.jsx("span",{className:`agent-connection-dot ${L?"connected":l?.codexAuth==="not-signed-in"?"unavailable":""}`}),r.jsx("span",{children:l?.codexInstallation==="not-installed"?"Codex SDK not installed":l?.codexAuth==="signed-in"?"Codex CLI signed in":l?.codexAuth==="not-signed-in"?"Codex CLI sign-in required":"Codex status not tested"}),r.jsxs("button",{className:"settings-reset",onClick:()=>{$()},disabled:h!=="",type:"button",children:[r.jsx(g0,{size:15})," ",h==="test"?"Testing":"Test connection"]})]}),r.jsxs("p",{className:"settings-help",children:[r.jsx(v0,{size:12})," Authentication uses the installed Codex CLI."]})]})]}),a.provider==="codex"?r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Codex"}),r.jsx("h3",{children:"Model and reasoning"})]}),r.jsx(y0,{size:20})]}),r.jsxs("label",{className:"settings-field",children:[r.jsx("span",{children:"Model"}),r.jsx("input",{value:a.codexModelId,onChange:G=>k("codexModelId",G.target.value),placeholder:"Codex default"})]}),r.jsxs("label",{className:"settings-field",children:[r.jsx("span",{children:"Reasoning effort"}),r.jsxs("select",{value:a.codexReasoningEffort,onChange:G=>k("codexReasoningEffort",G.target.value),children:[r.jsx("option",{value:"minimal",children:"Minimal"}),r.jsx("option",{value:"low",children:"Low"}),r.jsx("option",{value:"medium",children:"Medium"}),r.jsx("option",{value:"high",children:"High"}),r.jsx("option",{value:"xhigh",children:"Extra high"})]})]})]}):r.jsxs("section",{className:"settings-section-card agent-legacy-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"OpenCode Go"}),r.jsx("h3",{children:"Connection"})]}),r.jsx(fx,{size:20})]}),r.jsxs("label",{className:"settings-field",children:[r.jsx("span",{children:"Base URL"}),r.jsx("input",{value:a.baseUrl,onChange:G=>k("baseUrl",G.target.value)})]}),r.jsxs("label",{className:"settings-field",children:[r.jsx("span",{children:"API key"}),r.jsx("input",{type:"password",value:d,onChange:G=>m(G.target.value),placeholder:l?.hasApiKey?l.apiKeyPreview:"Stored only in the Hub",autoComplete:"new-password"})]}),r.jsxs("button",{className:"settings-reset",onClick:()=>{q()},disabled:h!==""||!l?.hasApiKey,type:"button",children:[r.jsx(Sp,{size:15})," Clear key"]})]})]}),r.jsxs("div",{className:"settings-action-row agent-settings-actions",children:[r.jsxs("button",{className:"settings-reset",onClick:()=>{F()},disabled:h!=="",type:"button",children:[r.jsx(Cp,{size:15})," Reset defaults"]}),r.jsxs("button",{className:"text-button primary",onClick:()=>{D()},disabled:!Y||h!=="",type:"button",children:[r.jsx(b0,{size:15})," ",h==="save"?"Saving":"Save Agent settings"]})]})]})}new Date().valueOf();function Or(n){const[a,i]=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,i(n)}},[n]),[a,i]}function Ep(n,a){return typeof n=="function"?typeof a=="object"?n(a):n():n}function jc(n,a="data-id"){let i=n;for(!i.tagName&&n.target&&(i=n.target);i;){if(i.getAttribute&&i.getAttribute(a))return i;i=i.parentNode}return null}function mk(n,a="data-id"){const i=jc(n,a);return i?i.getAttribute(a):null}function Vu(n,a="data-id"){const i=jc(n,a);return i?qf(i,a):null}function qf(n,a="data-id"){const i=n.getAttribute(a);return i?hk(i):null}function Jn(n){return typeof n=="string"?":"+n:n}function hk(n){if(n.startsWith(":"))return n.substring(1);const a=n*1;return isNaN(a)?n:a}function pk(){return{detect:()=>!0,addEvent:function(n,a,i){return n.addEventListener(a,i),()=>n.removeEventListener(a,i)},addGlobalEvent:function(n,a){return document.addEventListener(n,a),()=>document.removeEventListener(n,a)},getTopNode:function(){return window.document.body}}}var ls=pk();function Dp(n){Object.assign(ls,n)}function Jy(n,a,i){function l(c){const d=jc(c);if(!d)return;const m=qf(d);if(typeof a=="function")return a(m,c);let h,g=c.target;for(;g!=d;){if(h=g.dataset?g.dataset.action:null,h&&a[h]){a[h](m,c);return}g=g.parentNode}a[i]&&a[i](m,c)}ls.addEvent(n,i,l)}function Ac(n,a){Jy(n,a,"click"),a.dblclick&&Jy(n,a.dblclick,"dblclick")}function gk(n,a){for(let i=n.length-1;i>=0;i--)if(n[i]===a){n.splice(i,1);break}}function vk(n,a,i){for(let l=0;l<Ri.length;l++){if(l===i)continue;const c=Ri[l],d=c.props.parent?.();if(d&&n.contains(d)&&c.node.contains(a))return!0}return!1}var Yx=new Date,If=!1,lf=[],Ri=[],eb=n=>{const a=n.target;if(If||!a.isConnected){If=!1;return}for(let i=Ri.length-1;i>=0;i--){const{node:l,date:c,props:d}=Ri[i];if(!(c>Yx)&&!l.contains(a)&&l!==a&&(vk(l,a,i)||(d.callback&&d.callback(n),d.modal||n.defaultPrevented)))break}},yk=n=>{Yx=new Date,If=!0;for(let a=Ri.length-1;a>=0;a--){const{node:i}=Ri[a];if(!i.contains(n.target)&&i!==n.target){If=!1;break}}};function Hr(n,a){lf.length||(lf=[ls.addGlobalEvent("click",eb,n),ls.addGlobalEvent("contextmenu",eb,n),ls.addGlobalEvent("mousedown",yk,n)]),typeof a!="object"&&(a={callback:a});const i={node:n,date:new Date,props:a};return Ri.push(i),{destroy(){gk(Ri,i),Ri.length||(lf.forEach(l=>l()),lf=[])}}}var of=n=>n.indexOf("bottom")!==-1,cf=n=>n.indexOf("left")!==-1,uf=n=>n.indexOf("right")!==-1,Nh=n=>n.indexOf("top")!==-1,tb=n=>n.indexOf("fit")!==-1,Nu=n=>n.indexOf("overlap")!==-1,bk=n=>n.split("-").every(a=>["center","fit"].indexOf(a)>-1),xk=n=>{const a=n.match(/(start|center|end)/);return a?a[0]:null};function wk(n,a){let i=0;const l=ls.getTopNode(n);for(;n&&n!==l;){const c=getComputedStyle(n).position;if((c==="absolute"||c==="relative"||c==="fixed")&&(i=parseInt(getComputedStyle(n).zIndex)||0),n=n.parentNode,n===a)break}return i}var In,ka,Tu,ma;function Kx(n,a,i="bottom",l=0,c=0){if(!n)return null;In=l,ka=c,Tu="auto";let d=0,m=0,h=i;const g=Qx(n),y=Nu(i)?ls.getTopNode(n):g;if(!g)return null;const x=g.getBoundingClientRect(),b=n.getBoundingClientRect(),w=y.getBoundingClientRect(),A=window.getComputedStyle(y),j={left:0,top:0,bottom:0,right:0};for(const F in j){const $=`border-${F}-width`;j[F]=parseFloat(A.getPropertyValue($))}if(a){const F=wk(a,g);d=Math.max(F+1,20)}if(a){if(ma=a.getBoundingClientRect(),tb(i)&&(Tu=ma.width+"px"),i!=="point")if(bk(i))tb(i)?In=0:(In=w.width/2,m=1),ka=(w.height-b.height)/2;else{const F=Nu(i)?0:1;In=uf(i)?ma.right+F:ma.left-F,ka=of(i)?ma.bottom+1:ma.top;const $=xk(i);$&&(uf(i)||cf(i)?$==="center"?ka-=(b.height-ma.height)/2:$==="end"&&(ka-=b.height-ma.height):(of(i)||Nh(i))&&($==="center"?In-=(b.width-ma.width)/2:$==="end"&&(In-=b.width-ma.width),Nu(i)||(In+=1)))}}else ma={left:l,right:l,top:c,bottom:c};const k=(cf(i)||uf(i))&&(of(i)||Nh(i));cf(i)&&(m=2);const N=In-b.width-w.left;a&&cf(i)&&!k&&N<0&&(In=ma.right,m=0,h=h.replace("left","right"));const M=In+b.width*(1-m/2)-w.right;if(M>0)if(!uf(i))In=w.right-j.right-b.width;else{const F=ma.left-w.x-b.width;a&&!k&&F>=0?(In=ma.left-b.width,h=h.replace("right","left")):In-=M+j.right}m&&(In=Math.round(In-b.width*m/2));const T=N<0||M>0||!k;Nh(i)&&(ka=ma.top-b.height,a&&ka<w.y&&T&&(ka=ma.bottom,h=h.replace("top","bottom")));const D=ka+b.height-w.bottom;return D>0&&(a&&of(i)&&T?(ka-=b.height+ma.height+1,h=h.replace("bottom","top")):ka-=D+j.bottom),In-=x.left+j.left,ka-=x.top+j.top,In=(Nu(i)?In:Math.max(In,0))+y.scrollLeft,ka=(Nu(i)?ka:Math.max(ka,0))+y.scrollTop,Tu=Tu||"auto",{at:h,x:In,y:ka,z:d,width:Tu}}function Qx(n){const a=ls.getTopNode(n);for(n&&(n=n.parentElement);n;){const i=getComputedStyle(n).position;if(n===a||i==="relative"||i==="absolute"||i==="fixed")return n;n=n.parentNode}return null}function Sk(n){const a=[];let i=n;const l=ls.getTopNode(n);for(;i&&i!==l&&!i.getAttribute("data-wx-portal-root");)getComputedStyle(i).position==="absolute"&&a.push(i),i=i.parentNode;return a}var nb=new Date().valueOf();function Lp(){return nb+=1,nb}function Aa(n){return n<10?"0"+n:n.toString()}function Ck(n){const a=Aa(n);return a.length==2?"0"+a:a}function Xx(n){const a=Math.floor(n/11)*11;return{start:a,end:a+11}}function Th(n){const a=(n.getDay()+6)%7,i=new Date(n.valueOf());i.setDate(n.getDate()+(3-a)),i.setHours(0,0,0,0);const l=new Date(i.getFullYear(),0,1),c=Math.round((i.getTime()-l.getTime())/864e5);return 1+Math.floor(c/7)}var ab=["",""];function kk(n,a,i){switch(n){case"%d":return Aa(a.getDate());case"%m":return Aa(a.getMonth()+1);case"%j":return a.getDate();case"%n":return a.getMonth()+1;case"%y":return Aa(a.getFullYear()%100);case"%Y":return a.getFullYear();case"%D":return i.dayShort[a.getDay()];case"%l":return i.dayFull[a.getDay()];case"%M":return i.monthShort[a.getMonth()];case"%F":return i.monthFull[a.getMonth()];case"%h":return Aa((a.getHours()+11)%12+1);case"%g":return(a.getHours()+11)%12+1;case"%G":return a.getHours();case"%H":return Aa(a.getHours());case"%i":return Aa(a.getMinutes());case"%a":return((a.getHours()>11?i.pm:i.am)||ab)[0];case"%A":return((a.getHours()>11?i.pm:i.am)||ab)[1];case"%s":return Aa(a.getSeconds());case"%S":return Ck(a.getMilliseconds());case"%W":return Aa(Th(a));case"%w":{const l=i.weekStart??1;if(l===1)return Aa(Th(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)),Aa(Th(m))}case"%c":{let l=a.getFullYear()+"";return l+="-"+Aa(a.getMonth()+1),l+="-"+Aa(a.getDate()),l+="T",l+=Aa(a.getHours()),l+=":"+Aa(a.getMinutes()),l+=":"+Aa(a.getSeconds()),l}case"%Q":return Math.floor(a.getMonth()/3)+1;default:return n}}var jk=/%[a-zA-Z]/g;function bc(n,a){return typeof n=="function"?n:function(i){return i?(i.getMonth||(i=new Date(i)),n.replace(jk,l=>kk(l,i,a))):""}}function sb(n){return n&&typeof n=="object"&&!Array.isArray(n)}function fp(n,a){for(const i in a){const l=a[i];sb(n[i])&&sb(l)?n[i]=fp({...n[i]},a[i]):n[i]=a[i]}return n}function Yu(n){return{getGroup(a){const i=n[a];return l=>i&&i[l]||l},getRaw(){return n},extend(a,i){if(!a)return this;let l;return i?l=fp({...a},n):l=fp({...n},a),Yu(l)}}}var Ak=bx();const Mk="en-US",Nk={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},Tk={ok:"OK",cancel:"Cancel",select:"Select","No data":"No data","Rows per page":"Rows per page","Total pages":"Total pages"},Rk={timeFormat:"%H:%i",dateFormat:"%m/%d/%Y",monthYearFormat:"%F %Y",yearFormat:"%Y"},Zx={core:Tk,calendar:Nk,formats:Rk,lang:Mk},_p=u.createContext(""),Jx=u.createContext({}),gr=u.createContext(null),ew=u.createContext(null),ta=Object.freeze(Object.defineProperty({__proto__:null,fieldId:ew,helpers:Jx,i18n:gr,theme:_p},Symbol.toStringTag,{value:"Module"}));function tw(n){const a=u.useContext(ew),[i]=u.useState(()=>n||a||Lp());return i}function Fu({type:n="",css:a="",icon:i="",disabled:l=!1,title:c="",tooltip:d,text:m="",children:h,onClick:g}){const y=u.useMemo(()=>{let b=n?n.split(" ").filter(w=>w!=="").map(w=>"wx-"+w).join(" "):"";return a+(a?" ":"")+b},[n,a]),x=b=>{g&&g(b)};return r.jsxs("button",{title:c,className:`wx-2ZWgb4 wx-button ${y} ${i&&!h?"wx-icon":""}`,disabled:l,onClick:x,"data-tooltip-text":d,children:[i&&r.jsx("i",{className:"wx-2ZWgb4 "+i}),h||m||" "]})}function Ek({id:n,label:a="",inputValue:i="",value:l=!1,onChange:c,disabled:d=!1,css:m=""}){const h=tw(n),[g,y]=Or(l),x=({target:b})=>{const w=b.checked;y(w),c&&c({value:w,inputValue:i})};return r.jsxs("div",{className:`wx-2IvefP wx-checkbox ${m}`,children:[r.jsx("input",{type:"checkbox",id:h,disabled:d,className:"wx-2IvefP wx-check",checked:g,value:i,onChange:x}),r.jsxs("label",{htmlFor:h,className:"wx-2IvefP wx-label",children:[r.jsx("span",{className:"wx-2IvefP wx-before"}),a&&r.jsx("span",{className:"wx-2IvefP wx-after",children:a})]})]})}function Ip({theme:n="",target:a,children:i}){const l=u.useRef(null),c=u.useRef(null),[d,m]=u.useState(null);l.current||(l.current=document.createElement("div"));const h=u.useContext(_p);return u.useEffect(()=>{m(a||Dk(c.current)||ls.getTopNode(c.current))},[c.current]),r.jsxs(r.Fragment,{children:[r.jsx("span",{ref:c,style:{display:"none"}}),c.current&&d?Ak.createPortal(r.jsx("div",{className:`wx-3ZWsT0 wx-${n||h}-theme`,children:i}),d):null]})}function Dk(n){const a=ls.getTopNode(n);for(;n&&n!==a&&!n.getAttribute("data-wx-portal-root");)n=n.parentNode;return n}function Lk({left:n=0,top:a=0,at:i="bottom",parent:l=null,width:c="auto",css:d="",onCancel:m,children:h,trackScroll:g=!1}){const[y,x]=u.useState(0),[b,w]=u.useState(0),[A,j]=u.useState("auto"),[k,N]=u.useState(!1),M=u.useRef(null),T=u.useRef(null),D=u.useRef(m);u.useEffect(()=>{D.current=m},[m]);function F(q){return l&&(c+"").indexOf("%")>-1?c.replace(/(\d+)%/,(L,Y)=>(Y=Y*l.offsetWidth/100+"px",c.replace(L,Y))):c&&c!=="auto"?c:q}const $=u.useCallback(()=>{if(!M.current)return;const q=Kx(M.current,l,i,n,a);q&&(x(q.x),w(q.y),j(F(q.width)))},[M,l,i,n,a,c]);return u.useLayoutEffect(()=>{const q=Y=>{D.current&&Y.target!==T.current&&M.current&&!M.current.contains(Y.target)&&D.current(Y)};let L;return requestAnimationFrame(()=>{$(),N(!0),g&&M.current&&(T.current=Qx(M.current),T.current&&T.current.addEventListener("scroll",q,!0)),l&&(L=new ResizeObserver($),L.observe(l))}),()=>{g&&T.current&&T.current.removeEventListener("scroll",q,!0),L?.disconnect()}},[]),u.useLayoutEffect(()=>{$()},[l,i,n,a]),u.useEffect(()=>{const q=L=>{D.current&&D.current(L)};if(M.current)return Hr(M.current,{callback:q,parent:()=>l}).destroy},[l]),r.jsx("div",{ref:M,className:["wx-37M6Fj","wx-popup",d].filter(Boolean).join(" "),style:{position:"absolute",visibility:k?"visible":"hidden",top:b+"px",left:y+"px",width:A},children:h})}function _k({position:n="bottom",align:a="start",autoFit:i=!0,onCancel:l=null,width:c="100%",css:d="",children:m}){const h=u.useRef(null),[g,y]=u.useState(n),[x,b]=u.useState(a),w=u.useRef(l);return u.useEffect(()=>{w.current=l},[l]),u.useEffect(()=>{if(i){const A=h.current;if(A){const j=A.getBoundingClientRect(),k=document.body.getBoundingClientRect();j.right>=k.right&&b("end"),j.bottom>=k.bottom&&y("top")}}},[]),u.useEffect(()=>{if(h.current){const A=j=>{w.current&&w.current(j)};return Hr(h.current,A).destroy}},[]),r.jsx("div",{ref:h,className:["wx-dropdown",`wx-${g}-${x}`,d||"","wx-aaaVytZW"].filter(Boolean).join(" "),style:{width:c},children:m})}function zp({position:n="bottom",align:a="start",autoFit:i=!0,inline:l=!1,onCancel:c,width:d="100%",children:m,...h}){const[g,y]=u.useState(void 0),x=u.useRef(null),b=u.useMemo(()=>`${n}-${a}`,[n,a]);return u.useLayoutEffect(()=>{x.current&&y(x.current.parentNode)},[]),r.jsxs(r.Fragment,{children:[g&&(l?r.jsx(_k,{onCancel:c,position:n,align:a,autoFit:i,width:d,...h,children:m}):r.jsx(Ip,{children:r.jsx(Lk,{parent:g,at:b,onCancel:c,width:d,...h,children:m})})),r.jsx("span",{ref:x,className:"wx-portal-node wx-32GZ52"})]})}function Gf(){return Yu(Zx)}function Ik(){let n=null,a=!1,i=!1,l,c,d,m;const h=(b,w,A,j,k)=>{l=b,c=w,d=A,m=j,i=k},g=b=>{n=b,a=n!==null,d(n)},y=(b,w)=>{if(!i&&b!==null&&l){const A=l.querySelectorAll(".wx-list > .wx-item")[b];A&&(A.scrollIntoView({block:"nearest"}),w&&w.preventDefault())}},x=(b,w)=>{const A=b===null?null:Math.max(0,Math.min(n+b,c.length-1));A!==n&&(g(A),l?y(A,w):requestAnimationFrame(()=>y(A,w)))};return{move:b=>{const w=Vu(b),A=c.findIndex(j=>j.id===w);A!==n&&g(A)},keydown:(b,w)=>{switch(b.code){case"Enter":a?m():g(0);break;case"Space":a||g(0);break;case"Escape":d(n=null);break;case"Tab":d(n=null);break;case"ArrowDown":x(a?1:w||0,b);break;case"ArrowUp":x(a?-1:w||0,b);break}},init:h,navigate:x}}const rb=10,zk=u.memo(function({data:n,checkboxes:a,itemTemplate:i,value:l}){return r.jsxs(r.Fragment,{children:[a&&r.jsx(Ek,{id:n.id,css:"wx-list-checkbox",value:l&&l.includes(n.id)}),i?Ep(i,{option:n}):n.label]})});function ib({visibleItems:n,visibleRange:a,navIndex:i,checkboxes:l,itemTemplate:c,value:d,measureRefCallback:m}){return n.map((h,g)=>{const y=a.start+g;return r.jsx("div",{ref:g===0?m:void 0,className:`wx-233fr7 wx-item ${y===i?"wx-focus":""}`,"data-id":h.id,children:r.jsx(zk,{data:h,checkboxes:l,itemTemplate:c,value:d})},h.id)})}function Vf({items:n=[],children:a,onSelect:i,onReady:l,virtualized:c=!1,checkboxes:d,multiselect:m,value:h,...g}){const y=u.useRef(),x=u.useRef(!1),b=u.useRef(Ik()),[w,A]=u.useState(null),j=u.useRef(w),[k,N]=u.useState(0),[M,T]=u.useState(24),D=u.useRef(!1),F=(u.useContext(gr)||Gf()).getGroup("core"),$=u.useRef(n);u.useEffect(()=>{$.current=n},[n]);const q=u.useRef(h);u.useEffect(()=>{q.current=h},[h]);const L=u.useRef(0);u.useEffect(()=>{L.current=M},[M]);const Y=u.useCallback(Q=>{Q&&Q.stopPropagation();const be=$.current,he=q.current,fe=j.current;let ee;const Se=be[fe]?.id;m?he&&he.includes(Se)?ee=he.filter(Ne=>Ne!==Se):ee=[...he||[],Se]:ee=Se,i&&i({id:ee})},[m,i]),G=u.useRef(Y);u.useEffect(()=>{G.current=Y},[Y]);const P=u.useCallback(Q=>{if(y.current){let be=Q*L.current-y.current.clientHeight+L.current;N(be),y.current.scrollTop=be}},[L.current]),K=u.useCallback(Q=>{y.current=Q,c&&(Q&&!x.current&&j.current!==null&&requestAnimationFrame(()=>{y.current&&(P(j.current),x.current=!0)}),Q||(x.current=!1))},[P]),H=u.useCallback(Q=>{if(!Q||D.current)return;const be=Q.getBoundingClientRect().height;be&&(T(be),L.current=be,D.current=!0)},[]);u.useEffect(()=>{b.current.init(y.current,n,Q=>{A(Q),j.current=Q},Q=>G.current(Q),c)},[n,y.current,c]),u.useEffect(()=>{const Q=(he,fe)=>{b.current.navigate(he,fe),P(j.current)},be=(he,fe)=>{const ee=j.current,Se=$.current;if(ee!==0&&ee!==Se.length-1&&(he.key==="ArrowDown"||he.key==="ArrowUp")&&he.preventDefault(),b.current.keydown(he,fe),y.current){const Ne=y.current.scrollTop<=j.current*L.current,Fe=y.current.scrollTop+y.current.clientHeight>=j.current*L.current+L.current;Ne?Fe||P(j.current):(y.current.scrollTop=j.current*L.current,N(y.current.scrollTop))}};l&&l({navigate:c?Q:b.current.navigate,keydown:c?be:b.current.keydown,move:b.current.move})},[]);const ye=u.useRef(0),de=u.useRef(n);de.current!==n&&(de.current=n,ye.current+=1);const Z=u.useCallback(()=>{b.current.navigate(null)},[b]),z=u.useCallback(Q=>{c&&N(Q.target.scrollTop)},[c]),se=u.useMemo(()=>Math.ceil((y.current?.clientHeight||0)/M),[M,k]),W=u.useMemo(()=>{if(!c)return{start:0,end:n.length};if(!n.length)return{start:0,end:0};const Q=Math.floor(k/M),be=Q+se;return{start:Math.max(0,Q-rb),end:Math.min(n.length,be+rb)}},[c,n,k,M,se]),O=u.useMemo(()=>{if(!c)return n;const{start:Q,end:be}=W;return n.slice(Q,be).map(he=>({...he}))},[c,n,W]),le=W.start*M,ce=n.length*M;return u.useEffect(()=>{c&&N(0)},[n,c]),u.useEffect(()=>{w===null&&(x.current=!1)},[w]),w===null?null:r.jsx(zp,{onCancel:Z,...g,children:r.jsx("div",{className:"wx-233fr7 wx-list",ref:K,onClick:Y,onMouseMove:b.current.move,onScroll:z,children:n.length?c?r.jsx("div",{className:"wx-233fr7 wx-list-wrapper",style:{height:`${ce}px`},children:r.jsx("div",{className:"wx-233fr7 wx-list-content",style:{transform:`translateY(${le}px)`},children:r.jsx(ib,{visibleRange:W,visibleItems:O,navIndex:w,measureRefCallback:H,checkboxes:d,itemTemplate:a,value:h})})}):r.jsx(ib,{visibleRange:W,visibleItems:O,navIndex:w,measureRefCallback:H,checkboxes:d,itemTemplate:a,value:h}):r.jsx("div",{className:"wx-233fr7 wx-no-data",children:F("No data")})})},ye.current)}function Op({value:n="",id:a,readonly:i=!1,focus:l=!1,select:c=!1,type:d="text",placeholder:m="",disabled:h=!1,error:g=!1,title:y="",tooltip:x,css:b="",icon:w="",clear:A=!1,onChange:j}){const k=tw(a),[N,M]=Or(n),T=u.useRef(null),D=u.useMemo(()=>w&&b.indexOf("wx-icon-left")===-1?"wx-icon-right "+b:b,[w,b]),F=u.useMemo(()=>w&&b.indexOf("wx-icon-left")!==-1,[w,b]);u.useEffect(()=>{const G=setTimeout(()=>{l&&T.current&&T.current.focus(),c&&T.current&&T.current.select()},1);return()=>clearTimeout(G)},[l,c]);const $=u.useCallback(G=>{const P=G.target.value;M(P),j&&j({value:P,input:!0})},[j]),q=u.useCallback(G=>j&&j({value:G.target.value}),[j]);function L(G){G.stopPropagation(),M(""),j&&j({value:""})}let Y=d;return d!=="password"&&d!=="number"&&(Y="text"),u.useEffect(()=>{const G=q,P=T.current;return P.addEventListener("change",G),()=>{P&&P.removeEventListener("change",G)}},[q]),r.jsxs("div",{className:`wx-hQ64J4 wx-text ${D} ${g?"wx-error":""} ${h?"wx-disabled":""} ${A?"wx-clear":""}`,"data-tooltip-text":x,children:[r.jsx("input",{className:"wx-hQ64J4 wx-input",ref:T,id:k,readOnly:i,disabled:h,placeholder:m,type:Y,title:y,value:N,onInput:$}),A&&!h&&N?r.jsxs(r.Fragment,{children:[r.jsx("i",{className:"wx-hQ64J4 wx-icon wxi-close",onClick:L}),F&&r.jsx("i",{className:`wx-hQ64J4 wx-icon ${w}`})]}):w?r.jsx("i",{className:`wx-hQ64J4 wx-icon ${w}`}):null]})}function Ok({date:n,type:a,part:i,onShift:l}){const{calendar:c,formats:d}=u.useContext(gr).getRaw(),m=n.getFullYear(),h=u.useMemo(()=>{switch(a){case"month":return bc(d.monthYearFormat,c)(n);case"year":return bc(d.yearFormat,c)(n);case"duodecade":{const{start:y,end:x}=Xx(m),b=bc(d.yearFormat,c);return`${b(new Date(y,0,1))} - ${b(new Date(x,11,31))}`}default:return""}},[n,a,m,c,d]);function g(){l&&l({diff:0,type:a})}return r.jsxs("div",{className:"wx-8HQVQV wx-header",children:[i!=="right"?r.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-left",onClick:()=>l&&l({diff:-1,type:a})}):r.jsx("span",{className:"wx-8HQVQV wx-spacer"}),r.jsx("span",{className:"wx-8HQVQV wx-label",onClick:g,children:h}),i!=="left"?r.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-right",onClick:()=>l&&l({diff:1,type:a})}):r.jsx("span",{className:"wx-8HQVQV wx-spacer"})]})}function Hp({onClick:n,children:a}){return r.jsx("button",{className:"wx-3s8W4d wx-button",onClick:n,children:a})}function Hk({value:n,current:a,part:i="",markers:l=null,css:c="",onCancel:d,onChange:m}){const h=(u.useContext(gr)||Gf()).getRaw().calendar,g=(h.weekStart||7)%7,y=h.dayShort.slice(g).concat(h.dayShort.slice(0,g)),x=($,q,L)=>new Date($.getFullYear(),$.getMonth()+(q||0),$.getDate()+(L||0));let b=i!=="normal";function w($){const q=$.getDay();return q===0||q===6}function A(){const $=x(a,0,1-a.getDate());return $.setDate($.getDate()-($.getDay()-(g-7))%7),$}function j(){const $=x(a,1,-a.getDate());return $.setDate($.getDate()+(6-$.getDay()+g)%7),$}const k=u.useRef(0);function N($,q){q.timeStamp!==k.current&&(k.current=q.timeStamp,q.stopPropagation(),m&&m(new Date($)),d&&d())}const M=u.useMemo(()=>i=="normal"?[n?x(n).valueOf():0]:n?[n.start?x(n.start).valueOf():0,n.end?x(n.end).valueOf():0]:[0,0],[i,n]),T=u.useMemo(()=>{const $=A(),q=j(),L=a.getMonth();let Y=[];for(let G=$;G<=q;G.setDate(G.getDate()+1)){const P={day:G.getDate(),in:G.getMonth()===L,date:G.valueOf()};let K="";if(K+=P.in?"":" wx-inactive",K+=M.indexOf(P.date)>-1?" wx-selected":"",b){const H=P.date==M[0],ye=P.date==M[1];H&&!ye?K+=" wx-left":ye&&!H&&(K+=" wx-right"),P.date>M[0]&&P.date<M[1]&&(K+=" wx-inrange")}if(K+=w(G)?" wx-weekend":"",l){const H=l(G);H&&(K+=" "+H)}Y.push({...P,css:K})}return Y},[a,M,b,l]),D=u.useRef(null);let F=u.useRef({});return F.current.click=N,u.useEffect(()=>{Ac(D.current,F.current)},[]),r.jsxs("div",{className:`wx-398RBS wx-month ${c}`,children:[r.jsx("div",{className:"wx-398RBS wx-weekdays",children:y.map($=>r.jsx("div",{className:"wx-398RBS wx-weekday",children:$},$))}),r.jsx("div",{className:"wx-398RBS wx-days",ref:D,children:T.map($=>r.jsx("div",{className:`wx-398RBS wx-day ${$.css} ${$.in?"":"wx-out"}`,"data-id":$.date,children:$.day},$.date))})]})}function Fk({value:n,current:a,part:i,onCancel:l,onChange:c,onShift:d}){const m=u.useRef(new Date),[h,g]=Or(n||m.current),[y,x]=Or(a||m.current),b=u.useContext(gr).getRaw().calendar,w=b.monthShort||[],A=u.useMemo(()=>y.getMonth(),[y]),j=u.useCallback((M,T)=>{if(M!=null){T.stopPropagation();const D=new Date(y);D.setMonth(M),x(D),d&&d({current:D})}i==="normal"&&g(new Date(y)),l&&l()},[y,i,d,l]),k=u.useCallback(()=>{const M=new Date(nw(h,i)||y);M.setMonth(y.getMonth()),M.setFullYear(y.getFullYear()),c&&c(M)},[h,y,i,c]),N=u.useCallback(M=>{const T=M.target.closest("[data-id]");if(T){const D=parseInt(T.getAttribute("data-id"),10);j(D,M)}},[j]);return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-34U8T8 wx-months",onClick:N,children:w.map((M,T)=>r.jsx("div",{className:"wx-34U8T8 wx-month"+(A===T?" wx-current":""),"data-id":T,children:M},T))}),r.jsx("div",{className:"wx-34U8T8 wx-buttons",children:r.jsx(Hp,{onClick:k,children:b.done})})]})}const Rh="wx-1XEF33",$k=({value:n,current:a,onCancel:i,onChange:l,onShift:c,part:d})=>{const m=u.useContext(gr).getRaw().calendar,[h,g]=Or(a),[y,x]=Or(n),b=u.useMemo(()=>h.getFullYear(),[h]),w=u.useMemo(()=>{const{start:M,end:T}=Xx(b),D=[];for(let F=M;F<=T;++F)D.push(F);return D},[b]),A={click:j};function j(M,T){if(M){T.stopPropagation();const D=new Date(h);D.setFullYear(M),g(D),c&&c({current:D})}d==="normal"&&x(new Date(h)),i&&i()}function k(){const M=new Date(nw(y,d)||h);M.setFullYear(h.getFullYear()),l&&l(M)}const N=u.useRef(null);return u.useEffect(()=>{N.current&&Ac(N.current,A)},[]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:Rh+" wx-years",ref:N,children:w.map((M,T)=>r.jsx("div",{className:Rh+` wx-year ${b==M?"wx-current":""} ${T===0?"wx-prev-decade":""} ${T===11?"wx-next-decade":""}`,"data-id":M,children:M},T))}),r.jsx("div",{className:Rh+" wx-buttons",children:r.jsx(Hp,{onClick:k,children:m.done})})]})},lb={month:{component:Hk,next:Pk,prev:Bk},year:{component:Fk,next:qk,prev:Uk},duodecade:{component:$k,next:Vk,prev:Gk}};function Bk(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 Uk(n){return n=new Date(n),n.setFullYear(n.getFullYear()-1),n}function qk(n){return n=new Date(n),n.setFullYear(n.getFullYear()+1),n}function Gk(n){return n=new Date(n),n.setFullYear(n.getFullYear()-10),n}function Vk(n){return n=new Date(n),n.setFullYear(n.getFullYear()+10),n}function nw(n,a){let i;if(a==="normal")i=n;else{const{start:l,end:c}=n;a==="left"?i=l:a=="right"?i=c:i=l&&c}return i}const Wk=["clear","today"];function Yk(n){if(n==="done")return-1;if(n==="clear")return null;if(n==="today")return new Date}function Kk({value:n,current:a,onCurrentChange:i,part:l="normal",markers:c=null,buttons:d,css:m="",onShift:h,onChange:g}){const y=u.useContext(gr).getGroup("calendar"),[x,b]=u.useState("month"),w=Array.isArray(d)?d:d?Wk:[],A=(T,D)=>{T.preventDefault(),g&&g({value:D})},j=()=>{x==="duodecade"?b("year"):x==="year"&&b("month")},k=T=>{const{diff:D,current:F}=T;if(D===0){x==="month"?b("year"):x==="year"&&b("duodecade");return}if(D){const $=lb[x];i(D>0?$.next(a):$.prev(a))}else F&&i(F);h&&h()},N=T=>{b("month"),g&&g({select:!0,value:T})},M=u.useMemo(()=>lb[x].component,[x]);return r.jsx("div",{className:`wx-2Gr4AS wx-calendar ${l!=="normal"&&l!=="both"?"wx-part":""} ${m}`,children:r.jsxs("div",{className:"wx-2Gr4AS wx-wrap",children:[r.jsx(Ok,{date:a,part:l,type:x,onShift:k}),r.jsxs("div",{children:[r.jsx(M,{value:n,current:a,onCurrentChange:i,part:l,markers:c,onCancel:j,onChange:N,onShift:k}),x==="month"&&w.length>0&&r.jsx("div",{className:"wx-2Gr4AS wx-buttons",children:w.map(T=>r.jsx("div",{className:"wx-2Gr4AS wx-button-item",children:r.jsx(Hp,{onClick:D=>A(D,Yk(T)),children:y(T)})},T))})]})]})})}function Fp(n){let{words:a=null,optional:i=!1,children:l}=n,c=u.useContext(gr);const d=u.useMemo(()=>{let m=c;return(!m||!m.extend)&&(m=Yu(Zx)),a!==null&&(m=m.extend(a,i)),m},[a,i,c]);return r.jsx(gr.Provider,{value:d,children:l})}function ob(n,a,i,l){if(!n||l){const c=a?new Date(a):new Date;c.setDate(1),i(c)}else if(n.getDate()!==1){const c=new Date(n);c.setDate(1),i(c)}}const Qk=["clear","today"];function aw({value:n,current:a,markers:i=null,buttons:l=Qk,css:c="",onChange:d}){const[m,h]=Or(n),[g,y]=Or(a);u.useEffect(()=>{ob(g,m,y,!1)},[m,g]);const x=u.useCallback(w=>{const A=w.value;A?(h(new Date(A)),ob(g,new Date(A),y,!0)):h(null),d&&d({value:A?new Date(A):null})},[d,g]),b=u.useCallback(w=>{y(w)},[y]);return g?r.jsx(Fp,{children:r.jsx(Kk,{value:m,current:g,markers:i,buttons:l,css:c,onChange:x,onCurrentChange:b})}):null}function Xk(n){return n||(n={}),n.width||(n.width="unset"),n}const Zk=["clear","today"];function Jk({value:n,id:a,disabled:i=!1,error:l=!1,placeholder:c="",format:d="",buttons:m=Zk,css:h="",title:g="",tooltip:y,editable:x=!1,clear:b=!1,onChange:w,dropdown:A={}}){const{calendar:j,formats:k}=(u.useContext(gr)||Gf()).getRaw(),N=d||k?.dateFormat;let M=typeof N=="function"?N:bc(N,j);const[T,D]=u.useState(n),[F,$]=u.useState(!1);u.useEffect(()=>{D(n)},[n]);function q(){$(!1)}function L(P){const K=P===T||P&&T&&P.valueOf()===T.valueOf()||!P&&!T;D(P),K||w&&w({value:P}),setTimeout(q,1)}const Y=u.useMemo(()=>T?M(T):"",[T,M]);function G({value:P,input:K}){if(!x&&!b||K)return;let H=typeof x=="function"?x(P):P?new Date(P):null;H=isNaN(H)?T||null:H||null,L(H)}return u.useEffect(()=>{const P=q;return window.addEventListener("scroll",P),()=>window.removeEventListener("scroll",P)},[]),r.jsxs("div",{className:"wx-1lKOFG wx-datepicker",onClick:()=>$(!0),children:[r.jsx(Op,{css:`wx-date-input ${h}`,title:g,tooltip:y,value:Y,id:a,readonly:!x,disabled:i,error:l,placeholder:c,onInput:q,onChange:G,icon:"wxi-calendar",clear:b}),F&&!i&&r.jsx(zp,{onCancel:q,...Xk(A),children:r.jsx(aw,{buttons:m,value:T,onChange:P=>L(P.value)})})]})}function ej({value:n="",options:a=[],textOptions:i=null,placeholder:l="",disabled:c=!1,error:d=!1,title:m="",tooltip:h,textField:g="label",clear:y=!1,css:x="",children:b,onChange:w,dropdown:A={}}){const j=u.useRef(null),k=u.useRef(null);let[N,M]=Or(n);function T(L){j.current=L.navigate,k.current=L.keydown}const D=u.useMemo(()=>N||N===0?(i||a).find(L=>L.id===N):null,[N,i,a]),F=u.useCallback(({id:L})=>{(L||L===0)&&(M(L),j.current(null),w&&w({value:L}))},[M,w]),$=u.useCallback(L=>{L.stopPropagation(),M(""),w&&w({value:""})},[M,w]),q=u.useCallback(()=>a.findIndex(L=>L.id===N),[a,N]);return r.jsxs("div",{className:`wx-2YgblL wx-richselect ${x} ${d?"wx-2YgblL wx-error":""} ${c?"wx-2YgblL wx-disabled":""} ${b?"":"wx-2YgblL wx-nowrap"}`,title:m,onClick:()=>j.current(q()),onKeyDown:L=>k.current(L,q()),tabIndex:0,"data-tooltip-text":h,children:[r.jsx("div",{className:"wx-2YgblL wx-label",children:D?b?b(D):D[g]:l?r.jsx("span",{className:"wx-2YgblL wx-placeholder",children:l}):" "}),y&&!c&&N?r.jsx("i",{className:"wx-2YgblL wx-icon wxi-close",onClick:$}):r.jsx("i",{className:"wx-2YgblL wx-icon wxi-angle-down"}),!c&&r.jsx(Vf,{items:a,onReady:T,onSelect:F,...A,children:({option:L})=>b?b(L):L[g]})]})}const tj=({options:n=[],value:a="",css:i="",children:l,onChange:c})=>{const[d,m]=u.useState(a),h=g=>{m(g),c&&c({value:g})};return u.useEffect(()=>{m(a)},[a]),r.jsx("div",{className:`wx-0hMO7P wx-segmented ${i}`,children:n.map(g=>r.jsx("button",{className:`wx-0hMO7P wx-segment ${g.css} ${g.id===d?"wx-selected":""}`,title:g.title,onClick:()=>h(g.id),"data-tooltip-text":g.tooltip,children:l?Ep(l,{option:g}):r.jsxs(r.Fragment,{children:[g.icon&&r.jsx("i",{className:`wx-0hMO7P wx-icon ${g.icon} ${g.label?"":"wx-only"}`}),g.label&&r.jsx("span",{className:"wx-0hMO7P wx-label",children:g.label})]})},g.id))})};function nj({notice:n={}}){function a(){n.remove&&n.remove()}return r.jsxs("div",{className:`wx-11sNg5 wx-notice wx-${n.type?n.type:""}`,role:"status","aria-live":"polite",children:[r.jsx("div",{className:"wx-11sNg5 wx-text",children:n.text}),r.jsx("div",{className:"wx-11sNg5 wx-button",children:r.jsx("i",{className:"wx-11sNg5 wxi-close",onClick:a})})]})}function aj({data:n=[]}){return r.jsx("div",{className:"wx-3nwoO9 wx-notices",children:n.map(a=>r.jsx(nj,{notice:a},a.id))})}function mp({title:n="",buttons:a=["cancel","ok"],header:i,children:l,footer:c,css:d="",onConfirm:m,onCancel:h}){const g=(u.useContext(gr)||Gf()).getGroup("core"),y=u.useRef(null);u.useEffect(()=>{y.current?.focus()},[]);function x(w){switch(w.code){case"Enter":{const A=w.target.tagName;if(A==="TEXTAREA"||A==="BUTTON")return;m&&m({event:w});break}case"Escape":h&&h({event:w});break}}function b(w,A){const j={event:w,button:A};A==="cancel"?h&&h(j):m&&m(j)}return r.jsx("div",{className:`wx-1FxkZa wx-modal ${d}`,ref:y,tabIndex:0,onKeyDown:x,children:r.jsxs("div",{className:"wx-1FxkZa wx-window",children:[i||(n?r.jsx("div",{className:"wx-1FxkZa wx-header",children:n}):null),r.jsx("div",{children:l}),c||a&&r.jsx("div",{className:"wx-1FxkZa wx-buttons",children:a.map(w=>r.jsx("div",{className:"wx-1FxkZa wx-button",children:r.jsx(Fu,{type:`block ${w==="ok"?"primary":"secondary"}`,onClick:A=>b(A,w),children:g(w)})},w))})]})})}function sj({children:n},a){const[i,l]=u.useState(null),[c,d]=u.useState([]);return u.useImperativeHandle(a,()=>({showModal:m=>{const h={...m};return l(h),new Promise((g,y)=>{h.resolve=x=>{l(null),g(x)},h.reject=x=>{l(null),y(x)}})},showNotice:m=>{m={...m},m.id=m.id||Lp(),m.remove=()=>d(h=>h.filter(g=>g.id!==m.id)),m.expire!=-1&&setTimeout(m.remove,m.expire||5100),d(h=>[...h,m])}}),[]),r.jsxs(r.Fragment,{children:[n,i&&r.jsx(mp,{title:i.title,buttons:i.buttons,onConfirm:i.resolve,onCancel:i.reject,children:i.message}),r.jsx(aj,{data:c})]})}const rj=u.forwardRef(sj);function ij(n){let{children:a}=n,i=u.useRef();const l=u.useMemo(()=>({showNotice:c=>i.current.showNotice(c),showModal:c=>i.current.showModal(c)}),[]);return r.jsx(Jx.Provider,{value:l,children:r.jsx(rj,{ref:i,children:a})})}const lj=({value:n=!1,type:a="",icon:i="",disabled:l=!1,iconActive:c="",onClick:d,title:m="",tooltip:h,css:g="",text:y="",textActive:x="",children:b,active:w,onChange:A})=>{const[j,k]=Or(n),N=u.useMemo(()=>(j?"pressed":"")+(a?" "+a:""),[j,a]),M=u.useCallback(T=>{let D=!j;d&&d(T),T.defaultPrevented||(k(D),A&&A({value:D}))},[j,d,A]);return j&&w?r.jsx(Fu,{title:m,tooltip:h,text:j&&x||y,css:g,type:N,icon:j&&c||i,onClick:M,disabled:l,children:Ep(w,{value:j})}):b?r.jsx(Fu,{title:m,tooltip:h,text:j&&x||y,css:g,type:N,icon:j&&c||i,onClick:M,disabled:l,children:b}):r.jsx(Fu,{title:m,tooltip:h,text:j&&x||y,css:g,type:N,icon:j&&c||i,onClick:M,disabled:l})};function oj(){return r.jsx(r.Fragment,{})}function cb(n){const{fonts:a=!0,children:i}=n;return r.jsx(_p.Provider,{value:"willow",children:r.jsxs(r.Fragment,{children:[i&&i&&r.jsx("div",{className:"wx-theme wx-willow-theme",children:i}),a&&r.jsxs(r.Fragment,{children:[r.jsx("link",{rel:"preconnect",href:"https://cdn.svar.dev",crossOrigin:"true"}),r.jsx(oj,{}),r.jsx("link",{rel:"stylesheet",href:"https://cdn.svar.dev/fonts/wxi/wx-icons.css"})]})]})})}Dp(ls);const $p={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 sw=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 cj=class{constructor(n){const a={id:0,$level:0,data:[],parent:null},i=new Map;i.set(0,a),this._pool=i,n&&n.length&&this.parse(n,0)}parse(n,a){const i=this._pool;for(let c=0;c<n.length;c++){const d=n[c];d.parent=d.parent||a,d.data=null,i.set(d.id,d)}for(let c=0;c<n.length;c++){const d=n[c],m=i.get(d.parent);m&&(m.data||(m.data=[]),m.data.push(d))}const l=i.get(a);this.setLevel(l,l.$level+1,!1)}add(n,a){const i=this._pool.get(n.parent||0);n.$level=i.$level+1,this._pool.set(n.id,n),i.data?a===-1?i.data=[...i.data,n]:ub(i,a,n):i.data=[n]}addAfter(n,a){if(!a)return this.add(n,-1);const i=this.byId(a),l=this.byId(i.parent),c=df(l,i.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 i=this._pool.get(a.parent);i.data=i.data.filter(l=>l.id!=n),this._clearBranch(i)}_remove(n){n.data&&n.data.forEach(a=>this._remove(a)),this._pool.delete(n.id)}update(n,a){let i=this._pool.get(n);const l=this._pool.get(i.parent),c=df(l,i.id);i={...i,...a},l&&c>=0&&(l.data[c]=i,l.data=[...l.data]),this._pool.set(i.id,i)}move(n,a,i){const l=this._pool.get(n),c=a==="child",d=this._pool.get(i),m=d.$level+(c?1:0);if(!l||!d)return;const h=this._pool.get(l.parent),g=c?d:this._pool.get(d.parent);g.data||(g.data=[]);const y=df(h,l.id);uj(h,y);const x=c?g.data.length:df(g,d.id)+(a==="after"?1:0);if(ub(g,x,l),h.id===g.id&&y===x)return null;l.parent=g.id,l.$level!==m&&(l.$level=m,this.setLevel(l,m+1,!0)),this.update(l.id,l),this._clearBranch(h)}_clearBranch(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&&rw(a,n),n}byId(n){return this._pool.get(n)}getBranch(n){return this._pool.get(n).data}forEach(n){this._pool.forEach((a,i)=>{i!==0&&n(a)})}eachChild(n,a){const i=this.byId(a);!i||!i.data||i.data.forEach((l,c)=>{n(this.byId(l.id),c),this.eachChild(n,l.id)})}setLevel(n,a,i){n.data&&(n.data=n.data.map(l=>(i&&(l={...l},this._pool.set(l.id,l)),l.$level=a,l.data&&this.setLevel(l,a+1,i),l)))}};function rw(n,a){n.forEach(i=>{a.push(i),i.open===!0&&rw(i.data,a)})}function uj(n,a){const i=[...n.data];i.splice(a,1),n.data=i}function ub(n,a,i){const l=[...n.data];l.splice(a,0,i),n.data=l}function df(n,a){return n?.data.findIndex(i=>i.id===a)}var iw=2,dj=class{constructor(a){a&&(this._writable=a.writable,this._async=a.async),this._values={},this._state={}}setState(a,i=0){const l={};return this._wrapProperties(a,this._state,this._values,"",l,i),l}getState(){return this._values}getReactive(){return this._state}_wrapProperties(a,i,l,c,d,m){for(const h in a){const g=i[h],y=l[h],x=a[h];if(g&&(y===x&&typeof x!="object"||x instanceof Date&&y instanceof Date&&y.getTime()===x.getTime()))continue;const b=c+(c?".":"")+h;g?(g.__parse(x,b,d,m)&&(l[h]=x),m&iw?d[b]=g.__trigger:g.__trigger()):(x&&x.__reactive?i[h]=this._wrapNested(x,x,b,d):i[h]=this._wrapWritable(x),l[h]=x),d[b]=d[b]||null}}_wrapNested(a,i,l,c){const d=this._wrapWritable(a);return this._wrapProperties(a,d,i,l,c,0),d.__parse=(m,h,g,y)=>(this._wrapProperties(m,d,i,h,g,y),!1),d}_wrapWritable(a){const i=[],l=function(){for(let c=0;c<i.length;c++)i[c](a)};return{subscribe:c=>(i.push(c),this._async?setTimeout(c,1,a):c(a),()=>{const d=i.indexOf(c);d>=0&&i.splice(d,1)}),__trigger:()=>{i.length&&(this._async?setTimeout(l,1):l())},__parse:function(c){return a=c,!0}}}};function db(n,a){return Object.defineProperty(n,"__reactive",{value:!0,enumerable:!1,writable:!1}),n}var fj=class{constructor(a,i,l,c){typeof a=="function"?this._setter=a:this._setter=a.setState.bind(a),this._routes=i,this._parsers=l,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(d=>{d.in.forEach(m=>{const h=this._triggers.get(m)||[];h.push(d),this._triggers.set(m,h)}),d.out.forEach(m=>{const h=this._sources.get(m)||{};d.in.forEach(g=>h[g]=!0),this._sources.set(m,h)})}),this._routes.forEach(d=>{d.length=Math.max(...d.in.map(m=>lw(m,this._sources,1)))}),this._bus=c}init(a){const i={};for(const l in a)if(this._prev[l]!==a[l]){const c=this._parsers[l];i[l]=c?c(a[l]):a[l]}this._prev=this._prev?{...this._prev,...a}:{...a},this.setState(i),this._bus&&this._bus.exec("init-state",i)}setStateAsync(a){const i=this._setter(a,iw);return this._async?Object.assign(this._async.signals,i):this._async={signals:i,timer:setTimeout(this._applyState.bind(this),1)},i}_applyState(){const a=this._async;if(a){this._async=null,this._triggerUpdates(a.signals,[]);for(const i in a.signals){const l=a.signals[i];l&&l()}}}setState(a,i=[]){const l=this._setter(a);return this._triggerUpdates(l,i),l}_triggerUpdates(a,i){const l=Object.keys(a),c=!i.length;i=i||[];for(let d=0;d<l.length;d++){const m=l[d],h=this._triggers.get(m);h&&h.forEach(g=>{i.indexOf(g)==-1&&i.push(g)})}c&&this._execNext(i)}_execNext(a){for(;a.length;){a.sort((l,c)=>l.length<c.length?1:-1);const i=a[a.length-1];a.splice(a.length-1),i.exec(a)}}};function lw(n,a,i){const l=a.get(n);if(!l)return i;const c=Object.keys(l).map(d=>lw(d,a,i+1));return Math.max(...c)}var mj=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(a,i,l){let c=this._handlers[a];c?l&&l.intercept?c.unshift(i):c.push(i):c=this._handlers[a]=[i],l&&l.tag&&this._tag.set(i,l.tag)}intercept(a,i,l){this.on(a,i,{...l,intercept:!0})}detach(a){for(const i in this._handlers){const l=this._handlers[i];for(let c=l.length-1;c>=0;c--)this._tag.get(l[c])===a&&l.splice(c,1)}}async exec(a,i){const l=this._handlers[a];if(l)for(let c=0;c<l.length;c++){const d=l[c](i);if(d===!1||d&&d.then&&await d===!1)return}return this._nextHandler&&await this._nextHandler.exec(a,i),i}setNext(a){return this._nextHandler=a}};const mc=1024;function Wu(n){return n<mc?`${n} B`:n<mc**2?`${(n/mc).toFixed(1)} KB`:n<mc**3?`${(n/mc**2).toFixed(1)} MB`:`${(n/mc**3).toFixed(1)} GB`}function fb(n,a){a||(a={key:"name",order:"asc"});const i=n.filter(m=>m.type==="folder"),l=n.filter(m=>m.type!=="folder"),c=i.sort(mb(a)),d=l.sort(mb(a));return[...c,...d]}function hj(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 pj(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 mb({key:n,order:a}){const i=a==="asc"?hj:pj;return(l,c)=>i(l[n],c[n])}function Bp(n,a){const i=n==="/"?1:n.split("/").length;return i>=a.length?null:a[i].id}function gj(n){return n.length>1?n[n.length-2].id:null}let vj=class extends cj{constructor(a){const i={id:"/",name:"My files",open:!0,$level:1,parent:0,ext:"",type:"folder"};super([i]),this.parse(a,"/")}parse(a,i,l){!a||!a.length||(a.forEach(c=>this.parseId(c,l?i:void 0)),super.parse(a,i))}parseId(a,i){if(a.parent===0)return;const l=a.id,c=l.lastIndexOf("/");if(a.parent=i??(c===0?"/":l.slice(0,c)),a.name=l.slice(c+1),a.type=a.type||"file",a.type!=="folder"){const d=a.name.lastIndexOf("."),m=d!==-1?a.name.slice(d+1):"";a.ext=m!=="new"?m?.toLocaleLowerCase():""}}getParents(a){const i=[];let l=this.byId(a);if(!l)return i;for(;l.id!==0;)i.push(l),l=this.byId(l.parent);return i.reverse()}findFiles(a,i="/"){const l=[],c=a.toLocaleLowerCase();return this.eachChild(d=>{d.name.toLowerCase().indexOf(c)!==-1&&l.push(d)},i),l}add(a,i){const l=this.byId(a.parent||"/"),c=a.data?[...a.data]:null;a.data=null,super.add(a,i??l.data?l.data.length:0),c&&c.forEach(d=>this.add(d))}renameFiles(a,i,l){const c=this.byId(a),d=this.normalizeFile(c,i),m=[];return d.data?.forEach(h=>m.push(this.renameFiles(h.id,d.id,l))),m.length&&(d.data=m),l[a]=d.id,d}copyFiles(a,i,l){const c={};return a.forEach(d=>{const m=this.renameFiles(d,i,c);this.add(m),l&&this.remove(d),c[d]=m.id}),c}moveFiles(a,i){if(this.byId(a[0]).parent!==i)return this.copyFiles(a,i,!0)}serialize(a="/"){const i=[],l=this.byId(a);return l?(l.data?.forEach(c=>{const{id:d,date:m,type:h,size:g,lazy:y}=c,x={id:d,date:m,type:h??"file"};y&&(x.lazy=y),g&&(x.size=g),i.push(x);const b=this.serialize(d);b.length&&i.push(...b)}),i):null}normalizeFile(a,i){const l=a.name,c=l.lastIndexOf("."),d=c!==-1?l.slice(c+1):"",m=d?`.${d}`:"";let h=c!==-1?l.slice(0,c):l,g=i+(i==="/"?"":"/")+h;for(;this.byId(g+m);){const y=".new";g+=y,h+=y}return{...a,id:g+m,name:h+m,parent:i,ext:d.toLocaleLowerCase()}}},yj=class extends dj{in;_router;constructor(a){super({writable:a,async:!1});const i=[];for(let d=0;d<2;d++)i.push({in:["data",`panels.${d}.path`],out:[`panels.${d}._crumbs`],exec:m=>{const{data:h,panels:g}=this.getState(),y=[];y[d]={_crumbs:h.getParents(g[d].path)},this.setState({panels:y},m)}}),i.push({in:["data",`panels.${d}.path`,`panels.${d}._sorts`,"search"],out:[`panels.${d}._files`],exec:m=>{const{data:h,panels:g,search:y}=this.getState();let x;y?x=h.findFiles(y,g[d].path):x=h.byId(g[d].path)?.data||[];const{path:b,_sorts:w}=g[d];x=fb(x,w[b]);const A=[];A[d]={_files:x},this.setState({panels:A},m)}}),i.push({in:["data",`panels.${d}.selected`,`panels.${d}._sorts`],out:[`panels.${d}._selected`],exec:m=>{const{data:h,panels:g}=this.getState(),y=[];g[d].selected.forEach(j=>{const k=h.byId(j);k&&y.push(k)});const{path:x,_sorts:b}=g[d],w=fb(y,b[x]),A=[];A[d]={_selected:w},this.setState({panels:A},m)}});this._router=new fj(super.setState.bind(this),i,{data:d=>new vj(d)});const l=this.in=new mj;l.on("select-file",({id:d,toggle:m,range:h,panel:g,type:y})=>{const{panels:x,activePanel:b}=this.getState();typeof g>"u"&&(g=b),d||(m=h=!1);let w=[...x[g].selected];if(m){const j=w.indexOf(d);j===-1?w.push(d):w.splice(j,1)}else if(h&&x[g]._lastSelected){const j=x[g]._files;let k=j.findIndex(T=>T.id==x[g]._lastSelected),N=j.findIndex(T=>T.id==d);N<k&&([k,N]=[N,k]);const M=j.slice(k,N+1).map(T=>T.id);w=[...new Set([...w,...M])]}else w=d?[d]:[];const A=[];A[g]={selected:w,_lastSelected:d,_selectNavigation:y==="navigation"},this.setState({panels:A})}),l.on("set-path",({id:d,panel:m,selected:h})=>{const{data:g,activePanel:y}=this.getState(),x=g.byId(d);if(x){const b=[];typeof m>"u"&&(m=y),b[m]={path:d},this.setState({panels:b}),l.exec("select-file",{panel:m}),h&&h.forEach(w=>l.exec("select-file",{id:w,panel:m,toggle:!0})),x.lazy&&l.exec("request-data",{id:d})}}),l.on("provide-data",({id:d,data:m})=>{const{mode:h,data:g}=this.getState(),y=g.byId(d);y&&(y.lazy||(y.data=[]),y.lazy=!1,g.parse(m,d,h==="search"),this.setState({data:g}))}),l.on("open-tree-folder",({id:d,mode:m})=>{const{data:h}=this.getState();h.update(d,{open:m}),this.setState({data:h})}),l.on("show-preview",({mode:d})=>{this.setState({preview:d})}),l.on("rename-file",d=>{const{id:m,name:h}=d,{data:g,panels:y}=this.getState(),x=g.byId(m);if(x.name!==h){x.name=h;const b=g.normalizeFile(x,x.parent);d.newId=b.id,b.data=null,g.add(b);let w={[m]:b.id};x.data?.forEach(j=>w={...g.moveFiles([j.id],b.id),...w});const A=y.map(j=>({selected:j.selected,_crumbs:j._crumbs,_lastSelected:j._lastSelected,_sorts:j._sorts}));g.remove(m),this._updatePanels(A,w),this.setState({data:g,panels:A})}}),l.on("create-file",d=>{const{file:m,parent:h}=d,{data:g}=this.getState(),y=g.normalizeFile(m,h);y.type=m.type||"file",d.newId=y.id,g.add(y),this.setState({data:g}),l.exec("select-file",{id:y.id})}),l.on("delete-files",({ids:d})=>{const{data:m,panels:h}=this.getState(),g=h.map(y=>({selected:y.selected,_crumbs:y._crumbs,_lastSelected:y._lastSelected,_sorts:y._sorts}));d.forEach(y=>m.remove(y)),this._updatePanels(g,{}),this.setState({data:m,panels:g})}),l.on("copy-files",d=>{const{ids:m,target:h}=d;if(this._isPlacedIntoSelf(m,h)){console.error("You cannot copy a folder into itself"),d.skipProvider=!0;return}const{data:g,panels:y,activePanel:x}=this.getState(),b=g.copyFiles(m,h);d.newIds=m.map(w=>b[w]),this.setState({data:g}),y[x].path==h&&(l.exec("select-file",{}),m.forEach(w=>{l.exec("select-file",{id:b[w],toggle:!0})}))}),l.on("move-files",d=>{const{ids:m,target:h}=d;if(this._isPlacedIntoSelf(m,h)){console.error("You cannot move a folder into itself"),d.skipProvider=!0;return}const{data:g,panels:y,activePanel:x}=this.getState(),b=g.moveFiles(m,h);if(b){d.newIds=m.map(A=>b[A]);const w=y.map(A=>({selected:A.selected,_crumbs:A._crumbs,_lastSelected:A._lastSelected,_sorts:A._sorts}));this._updatePanels(w,b,!0),this.setState({data:g,panels:w}),y[x].path==h&&(l.exec("select-file",{}),m.forEach(A=>{l.exec("select-file",{id:b[A],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:h}=this.getState();c||(c={panels:m,mode:h,search:""}),this.setState({mode:"search",search:d})}),l.on("set-mode",({mode:d})=>{const{activePanel:m}=this.getState(),h=[];h[m]={_selectNavigation:!1};const g={mode:d,search:"",panels:h};c=null,this.setState(g)}),l.on("set-active-panel",({panel:d})=>{this.setState({activePanel:d})}),l.on("sort-files",({key:d,order:m,panel:h,path:g})=>{const{activePanel:y,panels:x}=this.getState();h=h??y,g=g??x[h].path;const b=[];b[h]={_sorts:{...x[h]._sorts,[g]:{key:d,order:m}}},this.setState({panels:b})}),this.initOnce()}initOnce(){const a=[];for(let l=0;l<2;l++)a[l]=db({_crumbs:[],_files:[],_selected:[],_sorts:{},path:"/",selected:[],...a[l]});const i={panels:db(a),data:[],search:""};this._router.init(i)}init(a){const i={...a};this._router.init(i)}setState(a,i){return this._router.setState(a,i)}getFile(a){const{data:i}=this.getState();return i.byId(a)||null}serialize(a){const{data:i}=this.getState();return i.serialize(a)}_updatePanels(a,i,l){const{data:c}=this.getState();a.forEach(d=>{const m=[];d.selected.forEach(y=>{c.byId(y)?m.push(y):!l&&i[y]&&m.push(i[y])}),d.selected=m,c.byId(d._lastSelected)||(d._lastSelected=l?null:i[d._lastSelected]||null);const h={};Object.keys(d._sorts).forEach(y=>{c.byId(y)?h[y]=d._sorts[y]:i[y]&&!l&&(h[i[y]]=d._sorts[y])}),d._sorts=h;const g=d._crumbs[d._crumbs.length-1];g?.id!=="/"&&(i[g.id]?d.path=i[g.id]:c.byId(g.id)||(d.path="/"))})}_isPlacedIntoSelf(a,i){return a.some(l=>l===i||this.getState().data.getParents(i).some(c=>c.id===l))}};function bj(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 xj(n,a="data-id"){let i=n;for(!i.tagName&&n.target&&(i=n.target);i;){if(i.getAttribute&&i.getAttribute(a))return i;i=i.parentNode}return null}function wj(n,a="data-id"){const i=xj(n,a);return i?i.getAttribute(a):null}new Date().valueOf();function Sj(n,a){const{api:i}=a;function l(d,m){const h=a.getPanel(),g=h.selected,y=m.ctrlKey||m.metaKey,x=m.shiftKey;let b;const w=g?.[0]?i.getFile(g[0]):null;g?.length?g.length>1?b=a.menuOptions("multiselect"):b=a.menuOptions(w.type,w):b=a.menuOptions("body");const A=`${y?"ctrl+":""}${x?"shift+":""}${d}`,j=b?b.find(N=>N.hotkey?.toLowerCase()===A):!1,k=a.performAction;if(j)switch(A){case"ctrl+c":k("copy");break;case"ctrl+x":k("move");break;case"ctrl+v":k("paste",w);break;case"delete":k("delete");break;case"ctrl+r":m.preventDefault(),k("rename",w);break;case"ctrl+d":m.preventDefault(),k("download",w);break;default:j.handler?.({context:w})}switch(d){case"enter":{if(y||x)break;const{_crumbs:N,_selectNavigation:M}=h;if(M){const T=gj(N);if(T){const D=Bp(T,N);i.exec("set-path",{id:T,selected:[D]})}}else if(g.length===1){const T=i.getFile(g[0]);T&&i.exec(T.type==="folder"?"set-path":"open-file",{id:T.id})}break}case"arrowup":case"arrowleft":{const{_files:N,_selected:M,path:T,_selectNavigation:D}=h;let F;if(M.length){const $=M.at(0).id,q=N.findIndex(L=>L.id===$);if(q!==-1){const L=q-1;N[L]?F=N[L].id:T!=="/"&&!(y||x)&&i.exec("select-file",{type:"navigation"})}}else{if(D)break;if(T!=="/"){i.exec("select-file",{type:"navigation"});break}F=N.at(0)?.id}F&&i.exec("select-file",{id:F,toggle:y,range:x});break}case"arrowdown":case"arrowright":{const{_files:N,_selected:M,path:T,_selectNavigation:D}=h;let F;if(M.length){const $=M.at(-1).id,q=N.findIndex(L=>L.id===$);if(q!==-1){const L=q+1;N[L]&&(F=N[L].id)}}else{if(T!=="/"&&!D){i.exec("select-file",{type:"navigation"});break}F=N.at(0)?.id}F&&i.exec("select-file",{id:F,toggle:y,range:x});break}}}function c(d){const m=d.code.replace("Key","").toLowerCase();l(m,d),m=="tab"&&setTimeout(()=>{const h=document.activeElement;h.className.indexOf("table")!=-1&&i.exec("set-active-panel",{panel:+wj(h,"data-panel")})})}return n.addEventListener("keydown",c),{destroy:()=>{n.removeEventListener("keydown",c)}}}function Cj(n,a="data-id"){let i=n;for(!i.tagName&&n.target&&(i=n.target);i;){if(i.getAttribute&&i.getAttribute(a))return i;i=i.parentNode}return null}function kj(n,a="data-id"){const i=n.getAttribute(a);return i?jj(i):null}function jj(n){if(n.startsWith(":"))return n.substring(1);const a=n*1;return isNaN(a)?n:a}function Aj(){return{detect:()=>!0,addEvent:function(n,a,i){return n.addEventListener(a,i),()=>n.removeEventListener(a,i)},addGlobalEvent:function(n,a){return document.addEventListener(n,a),()=>document.removeEventListener(n,a)},getTopNode:function(){return window.document.body}}}var Mj=Aj();new Date().valueOf();function ow(n){const[a,i]=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,i(n)}},[n]),[a,i]}function Nj(n,a,i){const[l,c]=u.useState(()=>a);return n||console.warn(`Writable ${i} is not defined`),u.useEffect(()=>n?n.subscribe(m=>{c(()=>m)}):void 0,[n]),l}function vt(n,a){const i=n.getState(),l=n.getReactiveState();return Nj(l[a],i[a],a)}function Tj(n,a){const i=u.useRef(a);i.current=a;const[l,c]=u.useState(1);return u.useEffect(()=>n.subscribe(m=>{i.current=m,c(h=>h+1)}),[n]),[i.current,l]}function Us(n,a){const i=n.getState(),l=n.getReactiveState();return Tj(l[a],i[a])}function cw(n){const a={};return n.split(";").forEach(i=>{const[l,c]=i.split(":");if(c){let d=l.trim();d.indexOf("-")&&(d=d.replace(/-([a-z])/g,(m,h)=>h.toUpperCase())),a[d]=c.trim()}}),a}function uw(n){let a=n,i=[];return{subscribe:h=>{i.push(h),h(a)},unsubscribe:h=>{i=i.filter(g=>g!==h)},set:h=>{a=h,i.forEach(g=>g(a))},update:h=>{a=h(a),i.forEach(g=>g(a))}}}function hb(n,a,i){function l(c){const d=Cj(c);if(!d)return;const m=kj(d);if(typeof a=="function")return a(m,c);let h,g=c.target;for(;g!=d;){if(h=g.dataset?g.dataset.action:null,h&&a[h]){a[h](m,c);return}g=g.parentNode}a[i]&&a[i](m,c)}return Mj.addEvent(n,i,l)}function Rj(n,a){const i=[hb(n,a,"click")];return a.dblclick&&i.push(hb(n,a.dblclick,"dblclick")),()=>{i.forEach(l=>l())}}function dw(n,a){return n.map((i,l)=>{const c=a(i,l);return i.data&&i.data.length&&(c.data=dw(i.data,a)),c}).filter(Boolean)}function fw(n,a){const i=[];return n.forEach(l=>{if(l.data){const c=fw(l.data,a);c.length&&i.push({...l,data:c})}else a(l)&&i.push(l)}),i}function Ej(n){return dw(n,(a,i)=>{const l={...a,id:a.id||Lp()};return l.type&&(l.comp=l.type),l.comp==="separator"&&n[i-1]?.comp==="separator"?null:l})}const mw={};function Dj(n){return mw[n]||n}function Lj(n,a){mw[n]=a}function _j({onClick:n,onShow:a,option:i}){const l=u.useRef(null),c=u.useCallback(()=>{a(i.data?i.id:!1,l.current)},[a,i]),d=u.useCallback(h=>{if(i.data){h.stopPropagation(),a(i.id,l.current);return}n(h)},[n,a,i]),m=u.useMemo(()=>i&&i.comp?Dj(i.comp):null,[i]);return r.jsxs("div",{ref:l,className:`wx-cDCz9rZQ wx-option ${i.css||""} ${i.disabled?"wx-disabled":""}`,"data-id":Jn(i.id),onMouseEnter:c,onClick:d,children:[i.icon?r.jsx("i",{className:`wx-cDCz9rZQ wx-icon ${i.icon}`}):null,i.comp?m?r.jsx(m,{item:i,option:i}):null:r.jsxs("span",{className:"wx-cDCz9rZQ wx-value",children:[" ",i.text," "]}),i.subtext?r.jsx("span",{className:"wx-cDCz9rZQ wx-subtext",children:i.subtext}):null,i.data?r.jsx("i",{className:"wx-cDCz9rZQ wx-sub-icon wxi-angle-right"}):null]})}function Pp({options:n,left:a=0,top:i=0,at:l="bottom",parent:c=null,mount:d=null,context:m=null,css:h="",onClick:g,onCancel:y}){const[x,b]=u.useState(-1e4),[w,A]=u.useState(-1e4),[j,k]=u.useState(20),[N,M]=u.useState(),T=u.useRef(null),[D,F]=u.useState(!1),[$,q]=u.useState(null),L=u.useCallback(()=>{const de=Kx(T.current,c,l,a,i);de&&(b(de.x),A(de.y),M(de.width));let Z=de?.z??20;const z=c?Sk(c):[];let se=0;for(const W of z){const O=parseInt(getComputedStyle(W).zIndex,10);O>se&&(se=O)}se>=Z&&(Z=se+1),k(Z)},[c,l,a,i]);u.useEffect(()=>{d&&d(L)},[]);const Y=u.useCallback(()=>{F(!1)},[]),G=u.useCallback((de,Z)=>{F(de),q(Z)},[]),P=u.useMemo(()=>Ej(n),[n]);u.useEffect(()=>{L()},[c,L]);const K=u.useRef(g),H=u.useRef(y),ye=u.useRef(c);return u.useEffect(()=>{K.current=g},[g]),u.useEffect(()=>{H.current=y},[y]),u.useEffect(()=>{ye.current=c},[c]),u.useEffect(()=>{if(!T.current)return;function de(Z){H.current?H.current(Z):K.current&&K.current({action:null,option:null})}return Hr(T.current,{callback:de,modal:!0,parent:()=>ye.current}).destroy},[]),r.jsx("div",{ref:T,"data-wx-menu":"true",className:`wx-XMmAGqVx wx-menu ${h}`,style:{position:"absolute",top:w+"px",left:x+"px",width:N,zIndex:j},onMouseLeave:Y,children:P.map(de=>r.jsxs(u.Fragment,{children:[de.comp==="separator"?r.jsx("div",{className:"wx-XMmAGqVx wx-separator"}):r.jsx(_j,{option:de,onShow:G,onClick:Z=>{if(!de.data&&!Z.defaultPrevented){const z={context:m,action:de,option:de,event:Z};de.handler&&de.handler(z),g&&g(z),Z.stopPropagation()}}}),de.data&&D===de.id?r.jsx(Pp,{css:h,options:de.data,at:"right-overlap",parent:$,context:m,onClick:g,onCancel:y}):null]},de.id))})}const hw=u.forwardRef(function(n,a){const{options:i,at:l="bottom",resolver:c=null,dataKey:d="contextId",filter:m=null,css:h="",children:g,onClick:y}=n,[x,b]=u.useState(null),[w,A]=u.useState(null),[j,k]=u.useState(0),[N,M]=u.useState(0),T=u.useRef(null),D=u.useMemo(()=>`data-${d.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,[d]),F=u.useMemo(()=>x!==null&&m?fw(i,Y=>m(Y,x)):i,[x,m,i]);function $(Y){A(null),y&&y(Y)}function q(Y){if(T.current===Y){T.current=null;return}A(null),y&&y({action:null,option:null})}const L=u.useCallback((Y,G)=>{if(!Y){A(null);return}if(Y.defaultPrevented)return;const P=Y.target;if(P&&P.dataset&&P.dataset.menuIgnore)return;if(w&&w===P){A(null),Y.preventDefault();return}k(Y.clientX+1),M(Y.clientY+1);let K=typeof G<"u"?G:Vu(P,D);c&&(K=c(K,Y),!K)||(b(K),A(P),T.current=Y.nativeEvent||Y,Y.preventDefault())},[w,D,c]);return u.useImperativeHandle(a,()=>({show:L}),[L]),r.jsxs(r.Fragment,{children:[g?r.jsx("span",{onClick:L,"data-menu-ignore":"true",children:typeof g=="function"?g():g}):null,w?r.jsx(Ip,{children:r.jsx(Pp,{css:h,at:l,top:N,left:j,parent:w,context:x,onClick:$,onCancel:q,options:F},w)}):null]})}),Ij=u.forwardRef(function(n,a){const{options:i,at:l="bottom",css:c="",children:d,onClick:m}=n,[h,g]=u.useState(null),y=u.useRef(null);function x(j){g(null),m&&m(j)}function b(j){if(y.current===j){y.current=null;return}g(null),m&&m({action:null,option:null})}const w=u.useCallback(j=>{g(j.target),y.current=j.nativeEvent||j,j.preventDefault()},[]);u.useImperativeHandle(a,()=>({show:w}),[w]);function A(j){let k=j.target;for(;!k.dataset.menuIgnore;)g(k),k=k.parentNode}return r.jsxs(r.Fragment,{children:[r.jsx("span",{onClick:A,"data-menu-ignore":"true",children:d}),h?r.jsx(Ip,{children:r.jsx(Pp,{css:c,at:l,parent:h,options:i,onClick:x,onCancel:b})}):null]})}),zj=u.forwardRef(function(n,a){const{options:i,at:l="bottom",resolver:c=null,dataKey:d="contextId",filter:m=null,css:h="",children:g,onClick:y}=n,x=u.useRef(null),b=u.useCallback((w,A)=>{x.current.show(w,A)},[]);return u.useImperativeHandle(a,()=>({show:b}),[b]),r.jsxs(r.Fragment,{children:[g?r.jsx("span",{onContextMenu:b,"data-menu-ignore":"true",children:g}):null,r.jsx(hw,{css:h,at:l,options:i,resolver:c,dataKey:d,filter:m,ref:x,onClick:y})]})}),Oj={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 Hj=class{constructor(a,i,l,c,d){this.setFiles=a,this.setReady=i,this.setSignal=l,this.setDrag=c,d&&d.length&&this.setFiles(d)}open(a){this.setSignal(["click",a||{}])}getState(){let a="server";const i=this.files;for(let l=0;l<i.length;l++){if(i[l].status==="client")return"client";i[l].status==="error"&&(a="error")}return a}droparea(a,i){i=i||{};const l=()=>{i.dragEnter&&i.dragEnter(),this.setDrag(!0)},c=()=>{i.dragLeave&&i.dragLeave(),this.setDrag(!1)},d=h=>{h.preventDefault()},m=h=>{h.preventDefault(),this.setDrag(!1),this.setSignal(["drop",i,h]),i.dragLeave&&i.dragLeave(),i.drop&&i.drop()};return a.addEventListener("dragenter",l),a.addEventListener("dragleave",c),a.addEventListener("dragover",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,i){const l=this.files.findIndex(d=>d.id===a);if(l===-1)return;const c=[...this.files];return c[l]={...c[l],...i},this.files=c,this.setFiles(this.files),this.files[l]}deleteFile(a){this.files=this.files.filter(i=>i.id!==a),this.setFiles(this.files)}addFile(a,i){i?this.files=[...this.files,a]:this.files=[a],this.setFiles(this.files)}deleteAll(){this.files=[],this.setFiles(this.files)}};function pw(n){const[a,i]=u.useState([]),[l,c]=u.useState(Promise.resolve(null)),[d,m]=u.useState(null),[h,g]=u.useState(!1),y=u.useRef();return y.current||(y.current=new Hj(i,c,m,g,n)),y.current.files=a,y.current.ready=l,y.current.signal=d,y.current.drag=h,y.current}function Fj(n,a){{if(n){const i=n.getGroup(a);if(i)return i}return Yu(Oj).getGroup(a)}}const $j=()=>Math.random().toString(36).substr(2,9),Bj=({data:n,accept:a="",multiple:i=!0,folder:l=!1,uploadURL:c="",apiOnly:d=!1,disabled:m=!1,children:h,onChange:g,onUpload:y})=>{const x=u.useRef(null),b=u.useRef(null),[w,A]=u.useState({}),j=pw(),k=n||j,N=u.useContext(ta.i18n),M=Fj(N,"uploader");u.useEffect(()=>{x.current&&l&&(x.current.webkitdirectory=!0)},[l]),u.useEffect(()=>{if(!d&&b.current&&!m)return k.droparea(b.current)},[d,m,b]);const T=P=>{const K=new FormData;return K.append("upload",P.file),fetch(c,{method:"POST",body:K}).then(H=>H.json()).then(H=>({id:P.id,...H}),()=>({id:P.id,status:"error"})).catch(H=>(console.log(H),{id:P.id,status:"error"}))},D=(P,K)=>{const H=k.updateFile(P,K),ye={...H,status:k.getState()};H&&H.uploaded&&H.uploaded(ye),y&&y(ye),H.temp&&k.deleteFile(H.id)},F=P=>{if(!P)return;const K=typeof c=="function"?c(P):T(P);k.setReady(K.then(H=>{H.status=H.status||"server",D(P.id,H)}).catch(H=>{D(P.id,{status:"error",error:H})}))},$=(P,K)=>{const H={...K||w,id:$j(),status:"client",name:P.name,file:P};H.selected&&H.selected(H),g&&g(H),k.addFile(H,i),F(H),x.current&&(x.current.value="")},q=(P,K,H)=>{P.isFile?P.file(ye=>{$(ye,H)}):P.isDirectory&&P.createReader().readEntries(ye=>{ye.forEach(de=>{q(de,K+de.name+"/",H)})})},L=P=>{Array.from(P.target.files).forEach(K=>$(K))},Y=(P,K)=>{Array.from(P.dataTransfer.items).forEach(H=>{const ye=H.webkitGetAsEntry();ye&&q(ye,"",K)})},G=()=>{x.current&&x.current.click()};return u.useEffect(()=>{if(k.signal){const[P,K,H]=k.signal;A(K),P==="click"?G():P==="drop"&&Y(H,K),k.setSignal(null)}},[k.signal]),d?r.jsxs(r.Fragment,{children:[r.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:x,onChange:L,accept:a,multiple:i,disabled:m}),h]}):r.jsxs("div",{className:`wx-at1A8tb8 wx-label ${k.drag?"wx-active":""} ${m?"wx-disabled":""}`,ref:b,children:[r.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:x,onChange:L,accept:a,multiple:i,disabled:m}),h||r.jsx("div",{className:"wx-at1A8tb8 wx-dropzone",children:r.jsxs("span",{children:[M("Drop files here or")," ",r.jsx("span",{className:"wx-at1A8tb8 wx-action",onClick:G,children:M("select files")})]})})]})};new Date().valueOf();function Pj(n,a){if(Object.keys(n).length!==Object.keys(a).length)return!1;for(const i in a){const l=n[i],c=a[i];if(!Wf(l,c))return!1}return!0}function Wf(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 i=n.length-1;i>=0;i--)if(!Wf(n[i],a[i]))return!1;return!0}else return Pj(n,a);return n===a}function hp(n){if(typeof n!="object"||n===null)return n;if(n instanceof Date)return new Date(n);if(n instanceof Array)return n.map(hp);const a={};for(const i in n)a[i]=hp(n[i]);return a}var gw=2,Uj=class{constructor(n){n&&(this._writable=n.writable,this._async=n.async),this._values={},this._state={}}setState(n,a=0){const i={};return this._wrapProperties(n,this._state,this._values,"",i,a),i}getState(){return this._values}getReactive(){return this._state}_wrapProperties(n,a,i,l,c,d){for(const m in n){const h=a[m],g=i[m],y=n[m];if(h&&(g===y&&typeof y!="object"||y instanceof Date&&g instanceof Date&&g.getTime()===y.getTime()))continue;const x=l+(l?".":"")+m;h?(h.__parse(y,x,c,d)&&(i[m]=y),d&gw?c[x]=h.__trigger:h.__trigger()):(y&&y.__reactive?a[m]=this._wrapNested(y,y,x,c):a[m]=this._wrapWritable(y),i[m]=y),c[x]=c[x]||null}}_wrapNested(n,a,i,l){const c=this._wrapWritable(n);return this._wrapProperties(n,c,a,i,l,0),c.__parse=(d,m,h,g)=>(this._wrapProperties(d,c,a,m,h,g),!1),c}_wrapWritable(n){const a=[],i=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(i,1):i())},__parse:function(l){return n=l,!0}}}},qj=class{constructor(n,a,i,l){typeof n=="function"?this._setter=n:this._setter=n.setState.bind(n),this._routes=a,this._parsers=i,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(h=>m[h]=!0),this._sources.set(d,m)})}),this._routes.forEach(c=>{c.length=Math.max(...c.in.map(d=>vw(d,this._sources,1)))}),this._bus=l}init(n){const a={};for(const i in n)if(this._prev[i]!==n[i]){const l=this._parsers[i];a[i]=l?l(n[i]):n[i]}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,gw);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 i=n.signals[a];i&&i()}}}setState(n,a=[]){const i=this._setter(n);return this._triggerUpdates(i,a),i}_triggerUpdates(n,a){const i=Object.keys(n),l=!a.length;a=a||[];for(let c=0;c<i.length;c++){const d=i[c],m=this._triggers.get(d);m&&m.forEach(h=>{a.indexOf(h)==-1&&a.push(h)})}l&&this._execNext(a)}_execNext(n){for(;n.length;){n.sort((i,l)=>i.length<l.length?1:-1);const a=n[n.length-1];n.splice(n.length-1),a.exec(n)}}};function vw(n,a,i){const l=a.get(n);if(!l)return i;const c=Object.keys(l).map(d=>vw(d,a,i+1));return Math.max(...c)}var Gj=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(n,a,i){let l=this._handlers[n];l?i&&i.intercept?l.unshift(a):l.push(a):l=this._handlers[n]=[a],i&&i.tag&&this._tag.set(a,i.tag)}intercept(n,a,i){this.on(n,a,{...i,intercept:!0})}detach(n){for(const a in this._handlers){const i=this._handlers[a];for(let l=i.length-1;l>=0;l--)this._tag.get(i[l])===n&&i.splice(l,1)}}async exec(n,a){const i=this._handlers[n];if(i)for(let l=0;l<i.length;l++){const c=i[l](a);if(c===!1||c&&c.then&&await c===!1)return}return this._nextHandler&&await this._nextHandler.exec(n,a),a}setNext(n){return this._nextHandler=n}};function Vj(n){return a=>a[n]}function Wj(n){return(a,i)=>a[n]=i}function xl(n,a){return(a.getter||Vj(a.id))(n)}function Eh(n,a,i){return(a.setter||Wj(a.id))(n,i)}function Yj(n,a){const i=document.createElement("a");i.href=URL.createObjectURL(n),i.download=a,document.body.appendChild(i),i.click(),document.body.removeChild(i)}function bl(n,a){let i=xl(n,a)??"";return a.template?i=a.template(i,n,a):a.optionsMap&&(Array.isArray(i)?i=i.map(l=>a.optionsMap.get(l)).join(", "):i=a.optionsMap.get(i)),typeof i>"u"?"":i+""}function Kj(n,a){const i=/\n|"|;|,/;let l="";const c=a.rows||`
13
+ `,d=a.cols||" ",m=n._columns,h=n.flatData;a.header!==!1&&m[0].header&&(l=pb("header",m,l,d,c));for(let g=0;g<h.length;g++){const y=[];for(let x=0;x<m.length;x++){let b=bl(h[g],m[x]);i.test(b)&&(b='"'+b.replace(/"/g,'""')+'"'),y.push(b)}l+=(l?c:"")+y.join(d)}return a.footer!==!1&&m[0].footer&&(l=pb("footer",m,l,d,c)),l}function pb(n,a,i,l,c){const d=/\n|"|;|,/;for(let m=0;m<a[0][n].length;m++){const h=[];for(let g=0;g<a.length;g++){let y=(a[g][n][m].text||"")+"";d.test(y)&&(y='"'+y.replace(/"/g,'""')+'"'),h.push(y)}i+=(i?c:"")+h.join(l)}return i}const Qj="portrait",Xj=100,Zj="a4",Jj={a3:{width:11.7,height:16.5},a4:{width:8.27,height:11.7},letter:{width:8.5,height:11}};function eA(n,a){const i=[];let l=[],c=0;const d=n.filter(h=>!h.hidden),m=tA(a);return d.forEach((h,g)=>{c+h.width<=m?(c+=h.width,l.push(h)):(l.length&&i.push(l),l=[h],c=h.width),g===d.length-1&&l.length&&i.push(l)}),i}function gb(n,a,i){const l=[];return n.forEach((c,d)=>{const m=c[a];for(let h=0;h<i.length;h++){l[h]||(l[h]=[]);const g={...m[h]};if(l[h][d]!==null){if(!d&&!g.rowspan&&!g.colspan){let y=1,x=n[d+y][a][h],b=g.width;for(;!x.rowspan&&!x.colspan;)y++,x=n[d+y][a][h],b+=x.width;g.colspan=y,g.width=b,g.height=i[h]}if(l[h].push(g),!g.collapsed&&g.colspan>1){let y=g.colspan-1;if(g.colspan+d>n.length){const x=g.colspan-(g.colspan+d-n.length);g.colspan=x,g.width=n.slice(d,d+y+1).reduce((b,w)=>b+w.width,0),x>1&&(y=x-1)}for(let x=0;x<y;x++)l[h].push(null)}if(g.rowspan>1){const y=g.rowspan;for(let x=1;x<y;x++)l[h+x]||(l[h+x]=[]),l[h+x].push(null)}}}if(c.collapsed)for(let h=0;h<l.length;h++){const g=l[h],y=g[d];if(y&&y.collapsed){if(g[d]=null,!h)break}else{const x=y||g.findLast(b=>b?.colspan>=1);x&&(x.colspan=x.colspan-1,x.width=x.width-c.width)}}}),l.map(c=>c.filter(d=>d&&d.colspan!==0))}function tA(n){const{mode:a,ppi:i,paper:l}=n,{width:c,height:d}=Jj[l];return nA(a==="portrait"?c:d,i)}function nA(n,a){return n*a}function aA(n={}){const{mode:a,ppi:i,paper:l}=n;return{mode:a||Qj,ppi:i||Xj,paper:l||Zj}}function yw(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 sA(n,a,i){let l=n[i.id];if(i.filter.type==="richselect"&&l){const c=i.filter.config?.options||a.find(({id:d})=>d==i.id).options;c&&(l=c.find(({id:d})=>d==l).label)}return l??""}const vb=["resize-column","hide-column","update-cell"],rA=["delete-row","update-row","update-cell"],iA=["move-item"],lA=["resize-column","move-item"];class oA{undo=[];redo=[];progress={};in;getState;setState;_previousValues={};constructor(a,i,l){this.in=a,this.getState=i,this.setState=l,this.setHandlers(),this.resetStateHistory()}getHandlers(){return{"add-row":{handler:a=>({action:"delete-row",data:{id:a.id},source:{action:"add-row",data:a}})},"delete-row":{handler:a=>{const{id:i}=a,{data:l}=this.getPrev(),c=l.findIndex(d=>d.id===i);return{action:"add-row",data:{id:i,row:l[c],before:c<l.length-1?l[c+1].id:void 0},source:{action:"delete-row",data:a}}}},"update-cell":{handler:a=>{const{id:i,column:l}=a,c=this.getRow(i),d=this.getColumn(l),m=xl(c,d);return Wf(m,a.value)?null:{action:"update-cell",data:{id:i,column:l,value:m},source:{action:"update-cell",data:a}}}},"update-row":{handler:a=>{const{id:i,row:l}=a,c=this.getRow(i);for(const d in l)Object.keys(c).includes(d)||(c[d]=void 0);return{action:"update-row",data:{id:i,row:c},source:{action:"update-row",data:a}}}},"copy-row":{handler:a=>{const{id:i}=a,{data:l}=this.getState(),c=l.findIndex(m=>m.id===i),d=l[c];return{action:"delete-row",data:{id:i},source:{action:"add-row",data:{id:i,row:d,before:c<l.length-1?l[c+1].id:void 0}}}}},"resize-column":{handler:a=>{const{id:i,width:l}=a,c=this.getColumn(i),{_sizes:d}=this.getState();return{action:"resize-column",data:{id:i,width:c.width??d.columnWidth},source:{action:"resize-column",data:{id:i,width:l}}}}},"hide-column":{handler:a=>{const{id:i}=a,l=this.getColumn(i);return{action:"hide-column",data:{id:i,mode:l.hidden},source:{action:"hide-column",data:a}}}},"collapse-column":{handler:a=>{const{id:i,row:l,mode:c}=a;return{action:"collapse-column",data:{id:i,row:l,mode:typeof c=="boolean"?!c:c},source:{action:"collapse-column",data:a}}}},"move-item":{handler:a=>{const{id:i,target:l,mode:c}=a,{flatData:d}=this.getPrev(),m=d.findIndex(h=>h.id===i);return{action:"move-item",data:{id:i,target:d[m+(m?-1:1)].id,mode:m?"after":"before"},source:{action:"move-item",data:{id:i,target:l,mode:c}}}}},"open-row":{handler:a=>{const{id:i,nested:l}=a;return{action:"close-row",data:{id:i,nested:l},source:{action:"open-row",data:a}}}},"close-row":{handler:a=>{const{id:i,nested:l}=a;return{action:"open-row",data:{id:i,nested:l},source:{action:"close-row",data:a}}}}}}resetHistory(){this.undo=[],this.redo=[],this.progress={},this.resetStateHistory()}getPrev(){return this._previousValues}setHandlers(){const a=this.getHandlers();for(const i in a)this.in.intercept(i,l=>{if(!(l.eventSource==="undo"||l.eventSource==="redo"||l.skipUndo)){if(lA.includes(i)){(l.inProgress&&!this.progress[i]||typeof l.inProgress!="boolean")&&(iA.includes(i)&&this.setPrev("flatData"),vb.includes(i)&&this.setPrev("columns")),this.progress[i]=l.inProgress;return}rA.includes(i)&&this.setPrev("data"),vb.includes(i)&&this.setPrev("columns")}}),this.in.on(i,l=>{if(l.eventSource==="undo"||l.eventSource==="redo"||l.skipUndo||l.inProgress)return;const c=a[i].handler(l);c&&this.addToHistory(c)})}setPrev(a){this._previousValues[a]=hp(this.getState()[a])}addToHistory(a){this.undo.push(a),this.redo=[],this.setStateHistory()}handleUndo(){if(!this.undo.length)return;const a=this.undo.pop();this.redo.push({...a.source,source:a}),this.in.exec(a.action,{...a.data,eventSource:"undo"}),this.setStateHistory()}handleRedo(){if(!this.redo.length)return;const a=this.redo.pop();this.undo.push({...a.source,source:a}),this.in.exec(a.action,{...a.data,eventSource:"redo"}),this.setStateHistory()}resetStateHistory(){this.setState({history:{undo:0,redo:0}})}setStateHistory(){this.setState({history:{undo:this.undo.length,redo:this.redo.length}})}getRow(a){const{data:i}=this.getPrev();return this.getState().tree?this.getTreeRow(i,a):i.find(l=>l.id===a)}getTreeRow(a,i){for(let l=0;l<a.length;l++){if(a[l].id===i)return a[l];if(a[l].data){const c=this.getTreeRow(a[l].data,i);if(c)return c}}return null}getColumn(a){const{columns:i}=this.getPrev();return i.find(l=>l.id===a)}}function bw(n,a){return typeof n>"u"||n===null?-1:typeof a>"u"||a===null?1:n===a?0:n>a?1:-1}function cA(n,a){return-bw(n,a)}function uA(n,a){if(typeof a.sort=="function")return function(l,c){const d=a.sort(l,c);return n==="asc"?d:-d};const i=n==="asc"?bw:cA;return function(l,c){return i(xl(l,a),xl(c,a))}}function dA(n,a){if(!n||!n.length)return;const i=n.map(l=>{const c=a.find(d=>d.id==l.key);return uA(l.order,c)});return n.length===1?i[0]:function(l,c){for(let d=0;d<i.length;d++){const m=i[d](l,c);if(m!==0)return m}return 0}}const ff=28,fA=20;function mA(){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 zf(n,a,i,l,c){const d=document.createElement("div"),m=document.createElement("div"),h=document.body;c=c?`${c}px`:"auto";let g,y;m.className=a,d.classList.add(`wx-${i}-theme`),d.style.cssText=`height:auto;position:absolute;top:0px;left:100px;overflow:hidden;width=${c};white-space:nowrap;`,d.appendChild(m),h.appendChild(d),typeof n!="object"&&(n=[n]);for(let x=0;x<n.length;x++){m.innerText=n[x]+"";const b=d.getBoundingClientRect(),w=Math.ceil(b.width)+(l&&l.length?l[x]:0),A=Math.ceil(b.height);g=Math.max(g||0,w),y=Math.max(y||0,A)}return d.remove(),{width:g,height:y}}function yb(n,a,i,l,c){const d=[];for(let m=0;m<n.length;m++){const h=n[m][a],g=h.length;for(let y=0;y<g;y++){const{text:x,vertical:b,collapsed:w,rowspan:A,css:j}=h[y];if(!x){d[y]=Math.max(d[y]||0,l);continue}let k=0;if(b&&!w){let N=`wx-measure-cell-${a}`;if(N+=j?` ${j}`:"",k=zf(x,N,c).width,(A>1||!h[y+1])&&i>y+1){const M=A||i-y,T=d.slice(y,y+M).reduce((D,F)=>D+F,0);if(T<k){const D=Math.ceil((k-T)/M);for(let F=y;F<y+M;F++)d[F]=(d[F]||l)+D}continue}}d[y]=Math.max(d[y]||l,k)}}return d}function hA(n,a,i){const l=[],c=[];let d="wx-measure-cell-body";d+=n.css?` ${n.css}`:"";for(let m=0;m<a.length;m++){const h=a[m],g=bl(h,n);g&&(l.push(g),n.treetoggle?c.push(a[m].$level*ff+(a[m].$count?ff:0)+(n.draggable?ff:0)):n.draggable&&c.push(ff))}return zf(l,d,i,c).width}function pA(n,a){const i="wx-measure-cell-header",l=n.sort?fA:0;let c=n.header;if(typeof c=="string")return zf(c,i,a).width+l;let d;Array.isArray(c)||(c=[c]);for(let m=0;m<c.length;m++){const h=c[m],g=typeof h=="string"?h:h.text,y=i+(typeof h=="string"?"":` ${h.css}`);let x=zf(g,y,a).width;m===c.length-1&&(x+=l),d=Math.max(d||0,x)}return d}const gA={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&&yA(n,a):!0,multiselect:(n,a)=>!a||a?.length===0?!0:Array.isArray(n)?n?.some(i=>a.includes(i)):n&&a.includes(n)};function xw(n){return gA[n]}function vA(n,a){const i=[];for(const l in n){const c=a.find(g=>g.id==l),{config:d,type:m}=c.header.find(g=>g.filter).filter,h=n[l];i.push(g=>{const y=xl(g,c);return d?.handler?d.handler(y,h):xw(m)(y,h)})}return l=>{for(let c=0;c<i.length;c++)if(!i[c](l))return!1;return!0}}function yA(n,a){return n.getFullYear()===a.getFullYear()&&n.getMonth()===a.getMonth()&&n.getDate()===a.getDate()}let bA=class extends Uj{in;_router;_branches;_xlsxWorker;_historyManager;constructor(a){super({writable:a,async:!1});const i={rowHeight:37,columnWidth:160,headerHeight:36,footerHeight:36};this._router=new qj(super.setState.bind(this),[{in:["columns","sizes","_skin"],out:["_columns","_sizes"],exec:c=>{const{columns:d,sizes:m,_skin:h}=this.getState(),g=this.copyColumns(d),y=g.reduce((w,A)=>Math.max(A.header.length,w),0),x=g.reduce((w,A)=>Math.max(A.footer.length,w),0);g.forEach(this.setCollapsibleColumns);const b=this.normalizeSizes(g,m,y,x,h);for(let w=0;w<g.length;w++)this.normalizeColumns(g,w,"header",y,b),this.normalizeColumns(g,w,"footer",x,b);this.setState({_columns:g,_sizes:b},c)}},{in:["data","tree","_filterIds"],out:["flatData","_rowHeightFromData"],exec:c=>{const{data:d,tree:m,dynamic:h,_filterIds:g}=this.getState(),y=g&&new Set(g),x=m?this.flattenRows(d,[],g):y?d.filter(w=>y.has(w.id)):d,b=!h&&x.some(w=>w.rowHeight);this.setState({flatData:x,_rowHeightFromData:b},c)}}],{sizes:c=>({...i,...c})});const l=this.in=new Gj;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 h=this.getRow(c),g=d?this.getColumn(d):this.getNextEditor(h);if(g?.editor){let y=g.editor;if(typeof y=="function"&&(y=y(h,g)),!y)return;m={column:g.id,id:c,value:xl(h,g)??"",renderedValue:bl(h,g),type:y.type||y},typeof y=="object"&&y.config&&(m.config=y.config,y.config.options&&(m.options=y.config.options)),g.options&&!m.options&&(m.options=g.options),this.setState({editor:m})}}),l.on("editor",({value:c})=>{let d=this.getState().editor;if(d){d={...d},d.value=c;const m=this.getColumn(d.column),h={...this.getRow(d.id)};Eh(h,m,c),d.renderedValue=bl(h,m),this.setState({editor:d})}}),l.on("add-row",c=>{const d=this.getState();let{data:m}=d;const{select:h,_filterIds:g}=d,{row:y,before:x,after:b,select:w}=c;if(c.id=y.id=c.id||y.id||mf(),x||b){const j=x||b,k=m.findIndex(N=>N.id===j);m=[...m],m.splice(k+(b?1:0),0,c.row)}else m=[...m,c.row];const A={data:m};g&&(A._filterIds=[...g,c.id]),this.setState(A),!(typeof w=="boolean"&&!w)&&(w||h)&&l.exec("select-row",{id:y.id,show:!0})}),l.on("delete-row",c=>{const{data:d,selectedRows:m,focusCell:h,editor:g}=this.getState(),{id:y}=c,x={data:d.filter(b=>b.id!==y)};this.isSelected(y)&&(x.selectedRows=m.filter(b=>b!==y)),g?.id===y&&(x.editor=null),this.setState(x),h?.row===y&&this.in.exec("focus-cell",{eventSource:"delete-row"})}),l.on("update-cell",c=>{const d=this.getState();let{data:m}=d;m=[...m];const{tree:h}=d,{id:g,column:y,value:x}=c,b=this.getColumn(y);if(h){const w={...this._branches[g]};Eh(w,b,x);const A=this.updateTreeRow(w);w.$parent===0&&(m=A)}else{const w=m.findIndex(j=>j.id===g),A={...m[w]};Eh(A,b,x),m[w]=A}this.setState({data:m})}),l.on("update-row",c=>{let{data:d}=this.getState();const{id:m,row:h}=c,g=d.findIndex(y=>y.id===m);d=[...d],d[g]={...d[g],...h},this.setState({data:d})}),l.on("select-row",({id:c,toggle:d,range:m,mode:h,show:g,column:y})=>{const x=this.getState(),{focusCell:b}=x;let{selectedRows:w}=x;if(w.length||(m=d=!1),m){const{data:A}=this.getState();let j=A.findIndex(N=>N.id===w[w.length-1]),k=A.findIndex(N=>N.id===c);j>k&&([j,k]=[k,j]),A.slice(j,k+1).forEach(N=>{this.isSelected(N.id)||w.push(N.id)})}else if(d&&this.isSelected(c)){if(h===!0)return;w=w.filter(A=>A!==c)}else if(d){if(h===!1)return;w.push(c)}else w=[c];this.setState({selectedRows:[...w]}),b?.row!==c&&this.in.exec("focus-cell",{eventSource:"select-row"}),g&&this.in.exec("scroll",{row:c,column:y})}),this.in.on("focus-cell",c=>{const{row:d,column:m,eventSource:h}=c,{_columns:g,split:y}=this.getState();d&&m?(this.setState({focusCell:{row:d,column:m}}),h!=="click"&&((!y.left||g.findIndex(x=>x.id===c.column)>=y.left)&&(!y.right||g.findIndex(x=>x.id===c.column)<g.length-y.right)?this.in.exec("scroll",{row:d,column:m}):this.in.exec("scroll",{row:d}))):this.setState({focusCell:null})}),l.on("resize-column",c=>{const{id:d,auto:m,maxRows:h,inProgress:g}=c;if(g===!1)return;let y=c.width||0;const x=[...this.getState().columns],b=this.getColumn(d);if(m){if(m==="data"||m===!0){const{flatData:w,_skin:A}=this.getState();let j=w.length;h&&(j=Math.min(h,j));const k=w.slice(0,j);y=hA(b,k,A)}if(m==="header"||m===!0){const{_skin:w}=this.getState();y=Math.max(pA(b,w),y)}}b.width=Math.max(17,y),delete b.flexgrow,this.setState({columns:x})}),l.on("hide-column",c=>{const{id:d,mode:m}=c,h=[...this.getState().columns],g=this.getColumn(d),y=h.reduce((x,b)=>x+(b.hidden?0:1),0);!m||y>1?(g.hidden=!g.hidden,this.setState({columns:h})):c.skipUndo=!0}),l.on("sort-rows",c=>{const{key:d,add:m,sort:h}=c,g=this.getState(),{columns:y,data:x,tree:b}=g;if(h){const T=[...x];T.sort(h),this.setState({data:T});return}const{order:w="asc"}=c;let A=g.sortMarks;const j=Object.keys(A),k=j.length;!m||!k||k===1&&A[d]?A={[d]:{order:w}}:(k===1&&(A[j[0]]={...A[j[0]],index:0}),A={...A,[d]:{order:w,index:typeof m=="number"?m:A[d]?.index??k}});const N=Object.keys(A).sort((T,D)=>A[T].index-A[D].index).map(T=>({key:T,order:A[T].order}));this.setState({sortMarks:A});const M=dA(N,y);if(M){const T=[...x];b?this.sortTree(T,M):T.sort(M),this.setState({data:T})}}),l.on("filter-rows",c=>{const{value:d,key:m,filter:h}=c;if(!Object.keys(c).length){this.setState({filterValues:{},_filterIds:null});return}const g=this.getState(),{data:y,tree:x,_columns:b}=g;let w=g.filterValues;const A={};m&&(w={...w,[m]:d},A.filterValues=w);const j=h??vA(w,b);let k=[];x?k=this.filterTree(y,j,k):y.forEach(N=>{j(N)&&k.push(N.id)}),A._filterIds=k,this.setState(A)}),l.on("collapse-column",c=>{const{id:d,row:m,mode:h}=c,g=[...this.getState().columns],y=this.getColumn(d).header,x=Array.isArray(y)?y[m]:y;typeof x=="object"&&(x.collapsed=h??!x.collapsed,this.setState({columns:g}))}),l.on("move-item",c=>{const{id:d,inProgress:m}=c;let{target:h,mode:g="after"}=c;const{data:y,flatData:x,tree:b}=this.getState(),w=x.findIndex(k=>k.id===d);let A;if(g==="up"||g==="down"){if(g==="up"){if(w===0)return;A=w-1,g="before"}else if(g==="down"){if(w===x.length-1)return;A=w+1,g="after"}h=x[A]&&x[A].id}else A=x.findIndex(k=>k.id===h);if(w===-1||A===-1||m===!1)return;let j;b||(j=this.moveItem(d,h,y,g)),this.setState({data:b?this.normalizeTreeRows(j):j})}),l.on("copy-row",c=>{const{id:d,target:m,mode:h="after"}=c,g=this.getState(),{flatData:y,_filterIds:x}=g;let{data:b}=g;const w=this.getRow(d);if(!w)return;const A={...w,id:mf()};c.id=A.id;const j=y.findIndex(N=>N.id===m);if(j===-1)return;b.splice(j+(h==="after"?1:0),0,A),b=[...b];const k={data:b};x&&(k._filterIds=[...x,A.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 h=c.format||"csv",g=`${c.fileName||"data"}.${h}`;if(h==="csv"){const y=Kj(this.getState(),c.csv||{});c.download!==!1?Yj(new Blob(["\uFEFF"+y],{type:"text/csv"}),g):c.result=y,d(!0)}else m()})),l.on("hotkey",({key:c,event:d,isInput:m})=>{switch(c){case"arrowup":{const{flatData:h,focusCell:g,select:y}=this.getState();if(d.preventDefault(),m)return;const x=g?g.column:this._getFirstVisibleColumn()?.id,b=g?this.getPrevRow(g.row)?.id:h[h.length-1]?.id;x&&b&&(this.in.exec("focus-cell",{row:b,column:x,eventSource:"key"}),y&&this.in.exec("select-row",{id:b}));break}case"arrowdown":{const{flatData:h,focusCell:g,select:y}=this.getState();if(d.preventDefault(),m)return;const x=g?g.column:this._getFirstVisibleColumn()?.id,b=g?this.getNextRow(g.row)?.id:h[0]?.id;x&&b&&(this.in.exec("focus-cell",{row:b,column:x,eventSource:"key"}),y&&this.in.exec("select-row",{id:b}));break}case"arrowright":{const{focusCell:h}=this.getState();if(m)return;if(d.preventDefault(),h){const g=this.getNextColumn(h.column,!0)?.id;g&&this.in.exec("focus-cell",{row:h.row,column:g,eventSource:"key"})}break}case"arrowleft":{const{focusCell:h}=this.getState();if(m)return;if(d.preventDefault(),h){const g=this.getPrevColumn(h.column,!0)?.id;g&&this.in.exec("focus-cell",{row:h.row,column:g,eventSource:"key"})}break}case"tab":{const{editor:h,focusCell:g,select:y}=this.getState();if(h){d.preventDefault();const x=h.column;let b=h.id,w=this.getNextEditor(this.getRow(b),this.getColumn(x));if(!w){const A=this.getNextRow(b);A&&(b=A.id,w=this.getNextEditor(A))}w&&(this.in.exec("open-editor",{id:b,column:w.id}),this.in.exec("focus-cell",{row:b,column:w.id,eventSource:"key"}),y&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}else g&&this.in.exec("focus-cell",{eventSource:"key"});break}case"shift+tab":{const{editor:h,focusCell:g,select:y}=this.getState();if(h){d.preventDefault();const x=h.column;let b=h.id,w=this.getPrevEditor(this.getRow(b),this.getColumn(x));if(!w){const A=this.getPrevRow(b);A&&(b=A.id,w=this.getPrevEditor(A))}w&&(this.in.exec("open-editor",{id:b,column:w.id}),this.in.exec("focus-cell",{row:b,column:w.id,eventSource:"key"}),y&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}else g&&this.in.exec("focus-cell",{eventSource:"key"});break}case"escape":{const{editor:h}=this.getState();h&&(this.in.exec("close-editor",{ignore:h.type!="multiselect"}),this.in.exec("focus-cell",{row:h.id,column:h.column,eventSource:"key"}));break}case"f2":{const{editor:h,focusCell:g}=this.getState();!h&&g&&this.in.exec("open-editor",{id:g.row,column:g.column});break}case"enter":{const{focusCell:h,tree:g}=this.getState();if(!m&&g&&h&&this.getColumn(h.column).treetoggle){const y=this.getRow(h.row);if(!y.data)return;this.in.exec(y.open?"close-row":"open-row",{id:h.row,nested:!0})}break}case"home":{const{editor:h,focusCell:g}=this.getState();if(!h&&g){d.preventDefault();const y=this._getFirstVisibleColumn()?.id;this.in.exec("focus-cell",{row:g.row,column:y,eventSource:"key"})}break}case"ctrl+home":{const{editor:h,focusCell:g,flatData:y,select:x}=this.getState();if(!h&&g){d.preventDefault();const b=y[0]?.id,w=this._getFirstVisibleColumn()?.id;b&&w&&(this.in.exec("focus-cell",{row:b,column:w,eventSource:"key"}),x&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}break}case"end":{const{editor:h,focusCell:g}=this.getState();if(!h&&g){d.preventDefault();const y=this._getLastVisibleColumn()?.id,x=g.row;this.in.exec("focus-cell",{row:x,column:y,eventSource:"key"})}break}case"ctrl+end":{const{editor:h,focusCell:g,flatData:y,select:x}=this.getState();if(!h&&g){d.preventDefault();const b=y.at(-1).id,w=this._getLastVisibleColumn()?.id;b&&w&&(this.in.exec("focus-cell",{row:b,column:w,eventSource:"key"}),x&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}break}case"ctrl+z":{this.in.exec("undo",{});break}case"ctrl+y":{this.in.exec("redo",{});break}}}),l.on("scroll",c=>{const{_columns:d,split:m,_sizes:h,flatData:g,dynamic:y,_rowHeightFromData:x}=this.getState();let b=-1,w=-1,A=0,j=0;if(c.column){b=0;const k=d.findIndex(N=>N.id===c.column);A=d[k].width;for(let N=m.left??0;N<k;N++){const M=d[N];M.hidden||(b+=M.width)}}if(c.row&&!y){const k=g.findIndex(N=>N.id===c.row);k>=0&&(x?(w=g.slice(0,k).reduce((N,M)=>N+(M.rowHeight||h.rowHeight),0),j=g[k].rowHeight):w=h.rowHeight*k)}this.setState({scroll:{top:w,left:b,width:A,height:j||h.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=aA(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 i=window.URL.createObjectURL(new Blob([`importScripts('${a}');`],{type:"text/javascript"}));this._xlsxWorker=new Promise(l=>{const c=new Worker(i);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=mA()),a.columns&&a.columns.forEach(i=>{i.options&&(i.optionsMap=new Map(i.options.map(l=>[l.id,l.label])))}),Wf(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 oA(this.in,this.getState.bind(this),this.setState.bind(this))),this._router.init({...a})}setState(a,i){return this._router.setState(a,i)}setStateAsync(a){this._router.setStateAsync(a)}getRow(a){const{tree:i}=this.getState();return i?this._branches[a]:this.getState().data.find(l=>l.id===a)}getRowIndex(a,i){return i||(i=this.getState().flatData),i.findIndex(l=>l.id===a)}getNextRow(a){const i=this.getState().flatData,l=this.getRowIndex(a,i);return i[l+1]}getPrevRow(a){const i=this.getState().flatData,l=this.getRowIndex(a,i);return i[l-1]}getColumn(a){return this.getState().columns.find(i=>i.id===a)}getNextColumn(a,i){const l=this.getState()._columns,c=l.findIndex(d=>d.id===a);return i?this._getFirstVisibleColumn(c+1):l[c+1]}getPrevColumn(a,i){const l=this.getState()._columns,c=l.findIndex(d=>d.id===a);return i?this._getLastVisibleColumn(c-1):l[c-1]}_getFirstVisibleColumn(a){const i=this.getState()._columns;let l=a??0;for(;l<i.length&&(i[l]?.hidden||i[l]?.collapsed);)l++;return i[l]}_getLastVisibleColumn(a){const i=this.getState()._columns;let l=a??i.length-1;for(;l<i.length&&(i[l]?.hidden||i[l]?.collapsed);)l--;return i[l]}isCellEditable(a,i){const{editor:l,hidden:c}=i;return!l||c?!1:typeof l=="function"?l(a,i):!0}getNextEditor(a,i){let l=this.getState().columns;if(i){const c=l.findIndex(d=>d.id===i.id);l=l.slice(c+1)}return l.find(c=>this.isCellEditable(a,c))}getPrevEditor(a,i){let l=this.getState().columns;if(i){const c=l.findLastIndex(d=>d.id===i.id);l=l.slice(0,c)}return l.findLast(c=>this.isCellEditable(a,c))}toggleBranch(a,i,l){let c=this._branches[a],{data:d}=this.getState();if(d=[...d],a!==0){c={...c,open:i};const m=this.updateTreeRow(c);c.$parent===0&&(d=m)}l&&c.data?.length&&c.data.forEach(m=>{const h=this.toggleKids(m,i,l);a===0&&(d=h)}),this.setState({data:d})}toggleKids(a,i,l){a={...a,open:i};const c=this.updateTreeRow(a);return l&&a.data?.length&&a.data.forEach(d=>{this.toggleKids(d,i,l)}),c}updateTreeRow(a){const i=a.id;this._branches[i]=a;const l=this._branches[a.$parent],c=l.data.findIndex(d=>d.id===i);return l.data=[...l.data],l.data[c]=a,l.data}isSelected(a){return this.getState().selectedRows.indexOf(a)!==-1}findAndRemove(a,i){for(let l=0;l<a.length;l++){if(a[l].id===i)return a.splice(l,1)[0];if(a[l].data){const c=[...a[l].data],d=this.findAndRemove(c,i);if(d)return a[l]={...a[l],data:c},d}}return null}insertItem(a,i,l,c){for(let d=0;d<a.length;d++){if(a[d].id===i){const m=a[d],h=c==="before"?d:d+1;if(m.data){if(c==="before"){const g=d>0?a[d-1]:null;return g?.data&&g.open?a[d-1]={...g,data:[...g.data,l]}:a.splice(h,0,l),!0}else if(m.open)return a[d]={...m,data:[l,...m.data]},!0}return a.splice(h,0,l),!0}if(a[d].data&&(a[d]={...a[d],data:[...a[d].data]},this.insertItem(a[d].data,i,l,c)))return!0}return!1}moveItem(a,i,l,c){const d=[...l],m=this.findAndRemove(d,a);return this.insertItem(d,i,m,c),d}copyColumns(a){const i=[];for(let l=0;l<a.length;l++){const c={...a[l]};this.copyHeaderFooter(c,"header"),this.copyHeaderFooter(c,"footer"),i[l]=c}return i}copyHeaderFooter(a,i){let l=a[i];l=Array.isArray(l)?[...l]:[l],l.forEach((c,d)=>{l[d]=typeof c=="string"?{text:c}:{...c}}),a[i]=l}setCollapsibleColumns(a,i,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 g=c.length-d;c=c.slice(0,d+1),c[d].rowspan=g}const h=m.colspan;if(h){const g=c[d+1];let y=1;g&&g.colspan&&!g.collapsed&&(y=g.colspan);for(let x=y;x<h;x++){const b=l[i+x];b&&(b.hidden=!0)}}}}}normalizeColumns(a,i,l,c,d){const m=a[i];m.width||(m.width=m.flexgrow?17:d.columnWidth),m._colindex=i+1;const h=m[l],g=d[`${l}RowHeights`];for(let y=0;y<c;y++){const x=h[y];x.id=m.id,y===h.length-1&&(x.rowspan=x.rowspan?Math.min(x.rowspan,c-y):c-y);for(let b=1;b<x.rowspan;b++){h.splice(y+b,0,{_hidden:!0});for(let w=1;w<x.colspan;w++)a[i+w][l].splice(y+b,0,{})}if(x.rowspan){const b=(x.rowspan===c?g:g.slice(y,x.rowspan+y)).reduce((w,A)=>w+A,0);x.height=b,y+x.rowspan!=c&&x.height--}if(x.colspan){let b=m.width,w=m.flexgrow||0;const A=x.colspan;for(let j=1;j<A;j++){const k=a[i+j];k&&(k.hidden?x.colspan-=1:k.flexgrow?w+=k.flexgrow:b+=k.width||d.columnWidth),w?x.flexgrow=w:x.width=b}}else x.width=m.width,x.flexgrow=m.flexgrow;l==="header"&&x.filter&&typeof x.filter=="string"&&(x.filter={type:x.filter})}h.length>c&&(h.length=c),m[l]=h}normalizeRows(a){for(let i=0;i<a.length;i++)a[i].id||(a[i].id=mf());return a}normalizeTreeRows(a,i,l){return!i&&!l&&(this._branches={0:{data:a}}),a.forEach(c=>{c.id||(c.id=mf()),c.$level=i||0,c.$parent=l||0,this._branches[c.id]=c,c.data&&(c.data.length?(c.$count=c.data.length,this.normalizeTreeRows(c.data,c.$level+1,c.id)):(delete c.data,delete c.$count,delete c.open))}),a}sortTree(a,i){a.sort(i),a.forEach(l=>{l.data&&this.sortTree(l.data,i)})}filterTree(a,i,l){return a.forEach(c=>{i(c)&&l.push(c.id),c.data&&this.filterTree(c.data,i,l)}),l}flattenRows(a,i,l){const c=i;return a.forEach(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:i}=this.getState(),l=[];for(const c in a){const d=i.find(y=>y.id==c),{config:m,type:h}=d.header.find(y=>y.filter).filter,g=a[c];l.push(y=>{const x=xl(y,d);return m?.handler?m.handler(x,g):xw(h)(x,g)})}return c=>{for(let d=0;d<l.length;d++)if(!l[d](c))return!1;return!0}}searchRows(a,i){a=a.trim().toLowerCase();const l={};if(!a)return l;const{flatData:c,columns:d}=this.getState(),m=i?d.filter(h=>i[h.id]):d;return c.forEach(h=>{const g={};m.forEach(y=>{const x=bl(h,y);String(x).toLowerCase().includes(a)&&(g[y.id]=!0)}),Object.keys(g).length&&(l[h.id]=g)}),l}normalizeSizes(a,i,l,c,d){const m=yb(a,"header",l,i.headerHeight,d),h=yb(a,"footer",c,i.footerHeight,d),g=m.reduce((x,b)=>x+b,0),y=h.reduce((x,b)=>x+b,0);return{...i,headerRowHeights:m,footerRowHeights:h,headerHeight:g,footerHeight:y}}},xA=new Date().valueOf();function mf(){return"temp://"+xA++}function wA(n,a="data-id"){let i=n;for(!i.tagName&&n.target&&(i=n.target);i;){if(i.getAttribute&&i.getAttribute(a))return i;i=i.parentNode}return null}new Date().valueOf();var SA=class{constructor(){this.store=new Map}configure(n,a){this.node=a;for(const i in n)if(n[i]){const l=i.toLowerCase().replace(/[ ]/g,""),c=n[i];this.store.set(l,c)}}},xc=[],CA={subscribe:n=>{kA();const a=new SA;return xc.push(a),n(a),()=>{const i=xc.findIndex(l=>l===a);i>=0&&xc.splice(i,1)}}},bb=!1;function kA(){bb||(bb=!0,document.addEventListener("keydown",n=>{if(xc.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 i=n.code.replace("Key","").toLocaleLowerCase();n.key===" "&&(i="space"),a.push(i);const l=a.join("+");for(let c=xc.length-1;c>=0;c--){const d=xc[c],m=d.store.get(l)||d.store.get(i);m&&d.node.contains(n.target)&&m(n,{key:l,evKey:i})}}}))}const jA={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 AA(n,{keys:a,exec:i}){if(!a)return;function l(m){const h=m.target;return h.tagName==="INPUT"||h.tagName==="TEXTAREA"||wA(h,"data-header-id")?.classList.contains("wx-filter")||!!h.closest(".wx-cell.wx-editor")}const c={};for(const m in a){const h=a[m];typeof h<"u"&&(typeof h=="function"?c[m]=h:h&&(c[m]=g=>{const y=l(g);i({key:m,event:g,isInput:y})}))}const d=CA.subscribe(m=>{m.configure(c,n)});return{destroy:()=>{d()}}}function MA(n,a){let i=null;a.scroll.subscribe(l=>{if(!l||l===i)return;i=l;const{left:c,top:d,height:m,width:h}=l,g=a.getHeight(),y=a.getWidth(),x=a.getScrollMargin();if(d>=0){const b=n.scrollTop;d<b?n.scrollTop=d:d+m>b+g&&(n.scrollTop=d-g+m)}if(c>=0){const b=n.scrollLeft;c<b?n.scrollLeft=c:c+h>b+y-x&&(n.scrollLeft=c-y+h+x)}}),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 xs=u.createContext(null);function NA(n,a){const i=new ResizeObserver(l=>{requestAnimationFrame(()=>a(l[0].contentRect))});return i.observe(n.parentNode),{destroy(){i.disconnect()}}}const xb=5,TA=700;function Af(n){const a=n.getBoundingClientRect(),i=document.body,l=a.top+i.scrollTop-i.clientTop||0,c=a.left+i.scrollLeft-i.clientLeft||0;return{y:Math.round(l),x:Math.round(c),width:n.offsetWidth,height:n.offsetHeight}}function pp(n,a){const i=Af(a);return{x:n.clientX-i.x,y:n.clientY-i.y}}function RA(n,a){const i=a.current;let l=null,c,d,m=!1,h=!1;const g=document.createElement("DIV");g.className="wx-drag-zone",g.setAttribute("tabindex",-1);function y(){clearTimeout(c),c=null}function x(L){const Y=jc(L);Y&&(l={container:g,sourceNode:L.target,from:qf(Y),pos:pp(L,n)},d=l.pos,b(L))}function b(L){if(!l)return;const Y=l.pos=pp(L,n);if(!m){if(!h&&!L?.target?.getAttribute("draggable-data")&&Math.abs(d.x-Y.x)<xb&&Math.abs(d.y-Y.y)<xb)return;if($(L)===!1)return q()}if(h){const G=window.scrollX||document.documentElement.scrollLeft||document.body.scrollLeft,P=window.scrollY||document.documentElement.scrollTop||document.body.scrollTop;l.targetNode=document.elementFromPoint(L.pageX-G,L.pageY-P)}else l.targetNode=L.target;i.move&&i.move(L,l),g.style.left=-(l.offset?l.offset.x:0)+"px",g.style.top=l.pos.y+(l.offset?l.offset.y:0)+"px"}function w(L){g.parentNode&&g.parentNode.removeChild(g),g.innerHTML="",m&&i.end&&i.end(L,l),l=d=null,q()}function A(L){i.getReorder&&!i.getReorder()||L.button===0&&(F(L),window.addEventListener("mousemove",j),window.addEventListener("mouseup",k),x(L))}function j(L){b(L)}function k(L){w(L)}function N(L){if(i.getReorder&&!i.getReorder())return;c=setTimeout(()=>{h=!0,x(L.touches[0])},TA),F(L);function Y(){c&&y(),L.target.removeEventListener("touchmove",M),L.target.removeEventListener("touchend",Y),w(L)}L.target.addEventListener("touchmove",M),L.target.addEventListener("touchend",Y),n.addEventListener("contextmenu",T)}function M(L){m?(L.preventDefault(),b(L.touches[0])):c&&y()}function T(L){if(m||c)return L.preventDefault(),!1}function D(L){L.preventDefault()}function F(L){if(!i.getDraggableInfo)return;const{hasDraggable:Y}=i.getDraggableInfo();(!Y||L.target.getAttribute("draggable-data"))&&(document.body.style.userSelect="none",document.body.style.webkitUserSelect="none")}function $(L){if(m=!0,i.start){if(i.start(L,l)===!1)return!1;n.appendChild(g),document.body.style.cursor="move"}}function q(L){m=h=!1,document.body.style.cursor="",document.body.style.userSelect="",document.body.style.webkitUserSelect="",window.removeEventListener("mousemove",j),window.removeEventListener("mouseup",k),L&&(n.removeEventListener("mousedown",A),n.removeEventListener("touchstart",N),n.removeEventListener("dragstart",D))}return n.addEventListener("mousedown",A),n.addEventListener("touchstart",N),n.addEventListener("dragstart",D),{destroy(){q(!0)}}}const EA=.004;function DA(){return{dirX:0,dirY:0,scrollSpeedFactor:1}}function LA(n,a,i,l){const{node:c,left:d,top:m,bottom:h,sense:g,xScroll:y,yScroll:x}=l,b=pp(n,c);i.scrollState||(i.scrollState=DA());let w=0,A=0;b.x<d+g?w=-1:b.x>a.width-g&&(w=1),b.y<m+Math.round(g/2)?A=-1:b.y>a.height-h-Math.round(g/2)&&(A=1),(i.scrollState.dirX!==w||i.scrollState.dirY!==A)&&(ww(i),i.scrollState.dirX=w,i.scrollState.dirY=A),(y&&i.scrollState.dirX!==0||x&&i.scrollState.dirY!==0)&&_A(i,l,{x:i.scrollState.dirX,y:i.scrollState.dirY})}function _A(n,a,i){n.autoScrollTimer||(n.autoScrollTimer=setTimeout(()=>{n.activeAutoScroll=setInterval(IA,15,n,a,i)},250))}function ww(n){n.scrollSpeedFactor=1,n.autoScrollTimer&&(n.autoScrollTimer=clearTimeout(n.autoScrollTimer),n.activeAutoScroll=clearInterval(n.activeAutoScroll))}function IA(n,a,i){const{x:l,y:c}=i;n.scrollSpeedFactor+=EA,l!==0&&OA(n,a,l),c!==0&&zA(n,a,c)}function zA(n,a,i){const l=a.node.scrollTop;Sw(l+Math.round(a.sense/3)*n.scrollSpeedFactor*i,"scrollTop",a)}function OA(n,a,i){const l=a.node.scrollLeft;Sw(l+Math.round(a.sense/3)*n.scrollSpeedFactor*i,"scrollLeft",a)}function Sw(n,a,i){i.node[a]=n}function Yf(n,a,i,l,c,d){const m={};return n&&(m.width=`${n}px`,m.minWidth=`${n}px`),a&&(m.flexGrow=a),d&&(m.height=`${d}px`),i&&(m.position="sticky",i.left&&(m.left=`${l}px`),i.right&&(m.right=`${c}px`)),m}function Cw(n,a,i){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+=i?i(n)+" ":"",l}function HA(n){const{row:a,column:i,cellStyle:l=null,columnStyle:c=null,children:d,focusable:m}=n,h=u.useContext(xs),g=vt(h,"focusCell"),y=vt(h,"search"),x=vt(h,"reorder"),b=u.useMemo(()=>y?.rows[a.id]&&y.rows[a.id][i.id],[y,a.id,i.id]),w=u.useMemo(()=>Yf(i.width,i.flexgrow,i.fixed,i.left,i.right),[i.width,i.flexgrow,i.fixed,i.left,i.right]);function A($,q){let L="wx-cell";return L+=i.fixed?" "+(i.fixed===-1?"wx-shadow":"wx-fixed"):"",L+=$?" "+$(i):"",L+=q?" "+q(a,i):"",L+=i.treetoggle?" wx-tree-cell":"",L}const j=u.useMemo(()=>A(c,l),[c,l,i,a]),k=u.useMemo(()=>typeof i.draggable=="function"?i.draggable(a,i)!==!1:i.draggable,[i,a]),N=u.useRef(null);u.useEffect(()=>{N.current&&m&&g?.row===a.id&&g?.column===i.id&&N.current.focus()},[g,m,a.id,i.id]);const M=u.useCallback(()=>{m&&!g&&h.exec("focus-cell",{row:a.id,column:i.id,eventSource:"focus"})},[h,m,g,a.id,i.id]);function T($){const q=new RegExp(`(${y.value.trim()})`,"gi");return String($).split(q).map(L=>({text:L,highlight:q.test(L)}))}const D=u.useMemo(()=>{const $=i.fixed&&i.fixed.left===-1||i.fixed.right===-1,q=i.fixed&&i.fixed.right;return[j,$?"wx-shadow":"",q?"wx-fixed-right":""].filter(Boolean).join(" ")},[j,i]),F=i.cell;return r.jsxs("div",{className:"wx-TSCaXsGV "+D,ref:N,onFocus:M,style:w,"data-row-id":Jn(a.id),"data-col-id":Jn(i.id),tabIndex:m?"0":"-1",role:"gridcell","aria-colindex":i._colindex,"aria-readonly":i.editor?void 0:!0,children:[x&&i.draggable?k?r.jsx("i",{"draggable-data":"true",className:"wx-TSCaXsGV wx-draggable wxi-drag"}):r.jsx("i",{className:"wx-TSCaXsGV wx-draggable-stub"}):null,i.treetoggle?r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{marginLeft:`${a.$level*28}px`}}),a.$count?r.jsx("i",{"data-action":"toggle-row",className:`wx-TSCaXsGV wx-table-tree-toggle wxi-menu-${a.open!==!1?"down":"right"}`}):null]}):null,F?r.jsx(F,{api:h,row:a,column:i,onAction:({action:$,data:q})=>h.exec($,q)}):d?d():b?r.jsx("span",{children:T(bl(a,i)).map(({highlight:$,text:q},L)=>$?r.jsx("mark",{className:"wx-TSCaXsGV wx-search",children:q},L):r.jsx("span",{children:q},L))}):bl(a,i)]})}function wb(n,a){let i,l;function c(h){i=h.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(h){l=h.clientX-i,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:i,filterValue:l}){function c({value:d}){i({value:d,key:a.id})}return r.jsx(Op,{...n.config??{},value:l,onChange:c})}function $A({filter:n,column:a,action:i,filterValue:l}){const c=u.useContext(xs),d=vt(c,"flatData"),m=u.useMemo(()=>n?.config?.options||a?.options||g(),[n,a,d]),h=u.useMemo(()=>n?.config?.template,[n]);function g(){const b=[];return d.forEach(w=>{const A=xl(w,a);b.includes(A)||b.push(A)}),b.map(w=>({id:w,label:w}))}function y({value:b}){i({value:b,key:a.id})}function x(b){b.key!=="Tab"&&b.preventDefault()}return r.jsx("div",{style:{width:"100%"},onKeyDown:x,children:r.jsx(ej,{placeholder:"",clear:!0,...n?.config??{},options:m,value:l,onChange:y,children:b=>h?h(b):b.label})})}function BA({filter:n,column:a,action:i,filterValue:l}){function c({value:d}){i({value:d,key:a.id})}return r.jsx("div",{className:"wx-aaaK5VYO",style:{width:"100%"},children:r.jsx(Jk,{placeholder:"",clear:!0,...n?.config??{},value:l,onChange:c})})}function kw(n){const{value:a,options:i=[],placeholder:l="",clear:c=!1,text:d=null,template:m=null,cell:h=null,dropdown:g={},autoOpen:y=!1,onChange:x,onAction:b}=n,[w,A]=ow(a||[]),j=u.useMemo(()=>(w||[]).map(P=>i.find(K=>K.id===P)).filter(Boolean),[w,i]),k=u.useRef(null),N=u.useRef(null),[M,T]=u.useState(null),D=()=>{const P=w||[];if(!P.length)return 0;const K=i.find(H=>P.includes(H.id));return K?i.indexOf(K):0};function F(P){N.current=P.navigate,T(()=>P.keydown),y&&P.navigate(D())}u.useEffect(()=>{y&&(k.current?.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges())},[]);function $({id:P}){A(P),x&&x({value:P})}function q(P){P.stopPropagation(),A([]),x&&x({value:[]})}function L(){N.current?.(D())}function Y(){N.current?.(null)}function G(P){M?.(P,D())}return r.jsxs("div",{ref:k,className:"wx-multiselect wx-aadNNOwy",onClick:L,onKeyDown:G,tabIndex:0,children:[r.jsx("div",{className:"wx-label wx-aadNNOwy",children:m?m(j):h?r.jsx(h,{data:j,onAction:b}):d?r.jsx("span",{className:"wx-text wx-aadNNOwy",children:d}):j.length?r.jsx("span",{className:"wx-text wx-aadNNOwy",children:j.map(P=>P.label).join(", ")}):l?r.jsx("span",{className:"wx-placeholder wx-aadNNOwy",children:l}):" "}),c&&w?.length?r.jsx("i",{className:"wx-icon wxi-close wx-aadNNOwy",onClick:q}):r.jsx("i",{className:"wx-icon wxi-angle-down wx-aadNNOwy"}),r.jsx(Vf,{items:i,onReady:F,onSelect:$,multiselect:!0,checkboxes:!0,value:w||[],onCancel:Y,...g,children:({option:P})=>r.jsx("div",{className:"wx-option wx-aadNNOwy",children:m?m(P):h?r.jsx(h,{data:P,onAction:b}):P.label})})]})}function PA({filter:n,column:a,action:i,filterValue:l}){const c=u.useContext(ta.i18n)?.getGroup("grid")||Yu($p).getGroup("grid"),d=u.useMemo(()=>({clear:!0,...n?.config||{}}),[n]),m=u.useMemo(()=>d.options||a.options,[d,a]),h=u.useMemo(()=>{const x=l?.length;return x?x<3?l.map(b=>a.optionsMap.get(b)).join(", "):x+" "+c("selected"):""},[l,a,c]);function g({value:x}){i({value:x,key:a.id})}function y(x){x.key!=="Tab"&&x.preventDefault()}return r.jsx("div",{style:{width:"100%"},onKeyDown:y,children:r.jsx(kw,{placeholder:"",...d,options:m,value:l||[],text:h,onChange:g})})}const UA={text:FA,richselect:$A,datepicker:BA,multiselect:PA};function qA({filter:n,column:a}){const i=u.useContext(xs),l=vt(i,"filterValues");function c(m){i.exec("filter-rows",m)}const d=u.useMemo(()=>UA[n.type],[n.type]);return r.jsx(d,{filter:n,column:a,action:c,filterValue:l[a.id]})}function GA(n){const{cell:a,column:i,row:l,lastRow:c,sortRow:d,columnStyle:m,bodyHeight:h,hasSplit:g}=n,y=u.useContext(xs),x=vt(y,"sortMarks"),b=u.useMemo(()=>x?x[i.id]:void 0,[x,i.id]),w=u.useRef(),A=u.useCallback(de=>{w.current=a.flexgrow?de.parentNode.clientWidth:a.width},[a.flexgrow,a.width]),j=u.useCallback((de,Z)=>{y.exec("resize-column",{id:a.id,width:Math.max(1,(w.current||0)+de),inProgress:Z})},[y,a.id]),k=u.useCallback(de=>j(de,!0),[j]),N=u.useCallback(de=>j(de,!1),[j]),M=u.useCallback(de=>{if(!i.sort||a.filter)return;let Z=b?.order;Z&&(Z=Z==="asc"?"desc":"asc"),y.exec("sort-rows",{key:a.id,add:de.ctrlKey||de.metaKey,order:Z})},[y,a.id,a.filter,i.sort,b?.order]),T=u.useCallback(de=>{de&&de.stopPropagation(),y.exec("collapse-column",{id:a.id,row:l})},[y,a.id,l]),D=u.useCallback(de=>{de.key==="Enter"&&T()},[T]),F=u.useCallback(de=>{de.key==="Enter"&&!a.filter&&M(de)},[M,a.filter]),$=u.useMemo(()=>a.collapsed&&i.collapsed,[a.collapsed,i.collapsed]),q=u.useMemo(()=>$&&!g&&a.collapsible!=="header",[$,g,a.collapsible]),L=u.useMemo(()=>q?{top:-h/2,position:"absolute"}:{},[q,h]),Y=u.useMemo(()=>Yf(a.width,a.flexgrow,i.fixed,i.left,a.right??i.right,a.height+($&&q?h:0)),[a.width,a.flexgrow,i.fixed,i.left,a.right,i.right,a.height,$,q,h]),G=u.useMemo(()=>Cw(i,a,m),[i,a,m]),P=u.useCallback(()=>Object.fromEntries(Object.entries(a).filter(([de])=>de!=="cell")),[a]),K=`wx-cell ${G} ${a.css||""} wx-collapsed`,H=["wx-cell",G,a.css||"",a.filter?"wx-filter":"",i.fixed&&i.fixed.right?"wx-fixed-right":""].filter(Boolean).join(" "),ye=u.useRef(null);return u.useEffect(()=>{const de=ye.current;if(!de)return;const Z=wb(de,{down:A,move:k,up:N});return()=>{typeof Z=="function"&&Z()}},[A,k,N,wb]),$?r.jsx("div",{className:"wx-RsQD74qC "+K,style:Y,role:"button","aria-label":`Expand column ${a.text||""}`,"aria-expanded":!a.collapsed,tabIndex:0,onKeyDown:D,onClick:T,"data-header-id":Jn(i.id),children:r.jsx("div",{className:"wx-RsQD74qC wx-text",style:L,children:a.text||""})}):r.jsxs("div",{className:"wx-RsQD74qC "+H,style:Y,onClick:M,"data-header-id":Jn(i.id),tabIndex:!a._hidden&&i.sort&&!a.filter?0:void 0,role:"columnheader","aria-colindex":i._colindex,"aria-colspan":a.colspan>1?a.colspan:void 0,"aria-rowspan":a.rowspan>1?a.rowspan:void 0,"aria-sort":!b?.order||a.filter?"none":b?.order==="asc"?"ascending":"descending",onKeyDown:F,children:[a.collapsible?r.jsx("div",{className:"wx-RsQD74qC wx-collapse",role:"button","aria-label":a.collapsed?"Expand column":"Collapse column","aria-expanded":!a.collapsed,tabIndex:0,onKeyDown:D,onClick:T,children:r.jsx("i",{className:`wx-RsQD74qC wxi-angle-${a.collapsed?"down":"right"}`})}):null,a.cell?(()=>{const de=a.cell;return r.jsx(de,{api:y,cell:P(),column:i,row:l,onAction:({action:Z,data:z})=>y.exec(Z,z)})})():a.filter?r.jsx(qA,{filter:a.filter,column:i}):r.jsx("div",{className:"wx-RsQD74qC wx-text",children:a.text||""}),i.resize&&c&&!a._hidden?r.jsx("div",{className:"wx-RsQD74qC wx-grip",role:"presentation","aria-label":"Resize column",ref:ye,onClick:de=>de.stopPropagation(),children:r.jsx("div",{})}):null,d?r.jsx("div",{className:"wx-RsQD74qC wx-sort",children:b?r.jsxs(r.Fragment,{children:[typeof b.index<"u"?r.jsx("div",{className:"wx-RsQD74qC wx-order",children:b.index+1}):null,r.jsx("i",{className:`wx-RsQD74qC wxi-arrow-${b.order==="asc"?"up":"down"}`})]}):null}):null]})}function VA({cell:n,column:a,row:i,columnStyle:l}){const c=u.useContext(xs),d=u.useMemo(()=>Yf(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(()=>Cw(a,n,l),[a,n,l]),h=u.useCallback(()=>Object.fromEntries(Object.entries(n||{}).filter(([y])=>y!=="cell")),[n]),g=`wx-6Sdi3Dfd wx-cell ${m||""} ${n?.css||""}`+(a?.fixed&&a?.fixed.right?" wx-fixed-right":"");return r.jsx("div",{className:g,style:d,children:!a?.collapsed&&!n?.collapsed?n?.cell?kp.createElement(n.cell,{api:c,cell:h(),column:a,row:i,onAction:({action:y,data:x})=>c.exec(y,x)}):r.jsx("div",{className:"wx-6Sdi3Dfd wx-text",children:n?.text||""}):null})}function Sb({deltaLeft:n,contentWidth:a,columns:i,type:l="header",columnStyle:c,bodyHeight:d}){const m=u.useContext(xs),h=vt(m,"_sizes"),g=vt(m,"split"),y=u.useMemo(()=>h?.[`${l}RowHeights`],[h,l]),x=u.useMemo(()=>{let k=[];if(i&&i.length){const N=i[0][l].length;for(let M=0;M<N;M++){let T=0;k.push([]),i.forEach((D,F)=>{const $={...D[l][M]};T||k[M].push($),$.colspan>1?T=$.colspan-1:T&&T--})}}return k},[i,l]),b=u.useMemo(()=>g?.left||g?.right,[g]);function w(k){return i.find(N=>N.id===k)}function A(k,N){let M=N;return k.rowspan&&(M+=k.rowspan-1),M===x.length-1}function j(k,N,M){if(!M.sort)return!1;for(let T=x.length-1;T>=0;T--){const D=M.header[T];if(!D.filter&&!D._hidden)return N===T}return A(k,N)}return r.jsx("div",{className:`wx-sAsPVaUK wx-${l}`,style:{paddingLeft:`${n}px`,width:`${a}px`},role:"rowgroup",children:x.map((k,N)=>r.jsx("div",{className:l==="header"?"wx-sAsPVaUK wx-h-row":"wx-sAsPVaUK wx-f-row",style:{height:`${y?.[N]}px`,display:"flex"},role:"row",children:k.map(M=>{const T=w(M.id);return l==="header"?r.jsx(GA,{cell:M,columnStyle:c,column:T,row:N,lastRow:A(M,N),bodyHeight:d,sortRow:j(M,N,T),hasSplit:b},M.id):r.jsx(VA,{cell:M,columnStyle:c,column:w(M.id),row:N},M.id)})},N))})}function WA({overlay:n}){const a=u.useContext(xs);function i(c){return typeof c=="function"}const l=n;return r.jsx("div",{className:"wx-1ty666CQ wx-overlay",children:i(n)?r.jsx(l,{onAction:({action:c,data:d})=>a.exec(c,d)}):n})}function YA(n){const{editor:a,onSave:i,onApply:l}=n,[c,d]=u.useState(a?.value||""),{type:m="text"}=u.useMemo(()=>a?.config||{},[a]),h=u.useRef(null);u.useEffect(()=>{h.current&&h.current.focus()},[]),u.useEffect(()=>{if(!h.current)return;const x=Hr(h.current,()=>i(!0));return()=>x.destroy()},[i]);function g(){h.current&&(d(h.current.value),l(h.current.value))}function y({key:x}){x==="Enter"&&i()}return r.jsx("input",{className:"wx-e7Ao5ejY wx-text",onInput:g,onKeyDown:y,ref:h,type:m,value:c})}function KA({editor:n,onAction:a,onSave:i,onApply:l,onCancel:c}){const[d,m]=u.useState(n?.value),[h,g]=u.useState(n?.renderedValue),[y,x]=u.useState(n?.options||[]),b=u.useMemo(()=>n?.config?.template,[n]),w=u.useMemo(()=>n?.config?.cell,[n]),A=u.useMemo(()=>n?.config?.dropdown||{},[n]),j=u.useMemo(()=>({trackScroll:!0,...A}),[A]),k=u.useMemo(()=>(y||[]).findIndex(L=>L.id===d),[y,d]),N=u.useRef(null),M=u.useRef(null),T=u.useCallback(L=>{N.current=L.navigate,M.current=L.keydown,N.current(k)},[k,N]),D=u.useCallback(L=>{const Y=L?.target?.value??"";g(Y);const G=Y?(n?.options||[]).filter(P=>(P.label||"").toLowerCase().includes(Y.toLowerCase())):n?.options||[];x(G),G.length?N.current(-1/0):N.current(null)},[n]),F=u.useRef(null);u.useEffect(()=>{F.current&&F.current.focus()},[]);const $=u.useRef(i);u.useEffect(()=>{$.current=i},[i]),u.useEffect(()=>{if(!F.current)return;const L=Hr(F.current,()=>$.current(!0));return()=>L.destroy()},[]),u.useEffect(()=>{m(n?.value),g(n?.renderedValue),x(n?.options||[])},[n]);const q=u.useCallback(({id:L})=>{l(L),i()},[l,i]);return r.jsxs(r.Fragment,{children:[r.jsx("input",{className:"wx-0UYfSd1x wx-input",ref:F,value:h??"",onChange:D,onKeyDown:L=>M.current?M.current(L,k):void 0}),r.jsx(Vf,{items:y,onReady:T,onSelect:q,...j,onCancel:c,children:({option:L})=>b?b(L):w?r.jsx(w,{data:L,onAction:a}):L.label})]})}function QA({editor:n,onAction:a,onSave:i,onApply:l,onCancel:c}){const[d]=u.useState(()=>n.value||new Date),{template:m,cell:h,dropdown:g={}}=n?.config||{},y=u.useMemo(()=>({trackScroll:!0,width:"auto",...g}),[g]);function x({value:j}){l(j),i()}const b=u.useRef(null),[w,A]=u.useState(null);return u.useEffect(()=>{b.current&&b.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),u.useEffect(()=>{if(!w)return;const j=Hr(w,()=>i(!0));return()=>j.destroy()},[w,i]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-lNWNYUb6 wx-value",ref:b,tabIndex:0,onClick:c,onKeyDown:j=>j.preventDefault(),children:m?m(d):h?r.jsx(h,{data:n.value,onAction:a}):r.jsx("span",{className:"wx-lNWNYUb6 wx-text",children:n.renderedValue})}),r.jsx(zp,{...y,onCancel:c,children:r.jsx("div",{ref:A,className:"wx-lNWNYUb6",children:r.jsx(aw,{value:d,onChange:x,buttons:n.config?.buttons})})})]})}function XA(n){const{editor:a}=n,i=n.onAction??n.onaction,l=n.onSave??n.onsave,c=n.onApply??n.onapply,d=n.onCancel??n.oncancel,m=a.config||{},{dropdown:h={}}=m,g=u.useMemo(()=>({trackScroll:!0,...h}),[h]),[y]=u.useState(a.options.find(D=>D.id===a.value)),[x]=u.useState(a.value),[b]=u.useState(a.options),w=u.useMemo(()=>b.findIndex(D=>D.id===x),[b,x]);function A({id:D}){c(D),l()}let j;const[k,N]=u.useState();function M(D){j=D.navigate,N(()=>D.keydown),j(w)}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 D=Hr(T.current,()=>l(!0));return()=>D.destroy()},[l]),r.jsxs(r.Fragment,{children:[r.jsx("div",{ref:T,className:"wx-ywGRk611 wx-value",tabIndex:0,onClick:d,onKeyDown:D=>{k(D,w),D.preventDefault()},children:m.template?m.template(y):m.cell?(()=>{const D=m.cell;return r.jsx(D,{data:y,onAction:i})})():r.jsx("span",{className:"wx-ywGRk611 wx-text",children:a.renderedValue})}),r.jsx(Vf,{items:b,onReady:M,onSelect:A,...g,onCancel:d,children:({option:D})=>m.template?m.template(D):m.cell?(()=>{const F=m.cell;return r.jsx(F,{data:D,onAction:i})})():D.label})]})}function ZA(n){const{editor:a,onAction:i,onSave:l,onApply:c}=n,d=a?.config||{},m=a?.options??[],h=a?.value||[],g=a?.renderedValue,y=u.useMemo(()=>({trackScroll:!0,...d.dropdown||{}}),[d]);function x({value:w}){c(w)}const b=u.useRef(null);return u.useEffect(()=>{if(!b.current)return;const w=Hr(b.current,()=>l(!0));return()=>w.destroy()},[l]),r.jsx("div",{ref:b,className:"wx-value wx-aacZ4gNU",onClick:()=>l(!0),children:r.jsx(kw,{value:h,options:m,text:g,template:d.template,cell:d.cell,clear:d.clear,dropdown:y,autoOpen:!0,onChange:x,onAction:i})})}const JA={text:YA,combo:KA,datepicker:QA,richselect:XA,multiselect:ZA};function eM({column:n,row:a}){const i=u.useContext(xs),l=vt(i,"editor"),c=u.useCallback((j,k)=>{i.exec("close-editor",{ignore:j}),k&&i.exec("focus-cell",{...k,eventSource:"click"})},[i]),d=u.useCallback(j=>{const k=j?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]),h=u.useCallback(j=>{i.exec("editor",{value:j})},[i]),g=u.useCallback(j=>{j.key==="Enter"&&l&&(n.editor.type==="multiselect"?h(l.value):m())},[l,n.editor,m,h]),y=u.useMemo(()=>Yf(n.width,n.flexgrow,n.fixed,n.left,n.right),[n.width,n.flexgrow,n.fixed,n.left,n.right]),x=u.useMemo(()=>{let j=n.editor;if(typeof j=="function"&&(j=j(a,n)),!j)return null;let k=typeof j=="string"?j:j.type;return JA[k]},[n,a]),b=u.useRef(null);u.useEffect(()=>{b.current&&typeof y=="string"&&b.current.setAttribute("style",y)},[y]);const w=typeof a.$parent<"u"?"gridcell":"cell",A=typeof a.$parent<"u"?!n.editor:void 0;return r.jsx("div",{className:"wx-8l724t2g wx-cell wx-editor",ref:b,style:typeof y=="object"&&y!==null?y:void 0,role:w,"aria-readonly":A,tabIndex:-1,onClick:j=>j.stopPropagation(),onDoubleClick:j=>j.stopPropagation(),onKeyDown:g,children:x?r.jsx(x,{editor:l,onSave:d,onApply:h,onCancel:m,onAction:({action:j,data:k})=>i.exec(j,k)}):null})}function Cb(n){const{columns:a,type:i,columnStyle:l}=n,c=u.useContext(xs),{filterValues:d,_columns:m,_sizes:h}=c.getState();function g(y){return l?" "+l(y):""}return r.jsx(r.Fragment,{children:a.map((y,x)=>r.jsx("tr",{children:y.map(b=>{const w=m.find(k=>k.id===b.id),A=`wx-print-cell-${i}${g(w)}${b.filter?" wx-print-cell-filter":""}${b.vertical?" wx-vertical":""}`,j=b.cell;return r.jsx("th",{style:cw(yw(b,h.columnWidth)),className:"wx-Gy81xq2u "+A,rowSpan:b.rowspan,colSpan:b.colspan,children:j?r.jsx(j,{api:c,cell:Object.fromEntries(Object.entries(b).filter(([k])=>k!=="cell")),column:w,row:x}):b.filter?r.jsx("div",{className:"wx-Gy81xq2u wx-print-filter",children:sA(d,m,b)}):r.jsx("div",{className:"wx-Gy81xq2u wx-text",children:b.text??""})},b.id)})},x))})}function tM(n){const{columns:a,rowStyle:i,columnStyle:l,cellStyle:c,header:d,footer:m,reorder:h}=n,g=u.useContext(xs),{flatData:y,_sizes:x}=g.getState(),b=d&&gb(a,"header",x.headerRowHeights),w=m&&gb(a,"footer",x.footerRowHeights);function A(k,N){let M="";return M+=l?" "+l(N):"",M+=c?" "+c(k,N):"",M}function j(k,N){return typeof N.draggable=="function"?N.draggable(k,N)!==!1:N.draggable}return r.jsxs("table",{className:`wx-8NTMLH0z wx-print-grid ${a.some(k=>k.flexgrow)?"wx-flex-columns":""}`,children:[d?r.jsx("thead",{children:r.jsx(Cb,{columns:b,type:"header",columnStyle:l})}):null,r.jsx("tbody",{children:y.map((k,N)=>r.jsx("tr",{className:"wx-8NTMLH0z wx-row"+(i?" "+i(k):""),style:{height:`${k.rowHeight||x.rowHeight}px`},children:a.map(M=>M.collapsed?null:r.jsxs("td",{className:`wx-8NTMLH0z wx-print-cell wx-cell ${A(k,M)}`,style:cw(yw(M,x.columnWidth)),children:[h&&M.draggable?r.jsx("span",{className:"wx-8NTMLH0z wx-print-draggable",children:j(k,M)?r.jsx("i",{className:"wx-8NTMLH0z wxi-drag"}):null}):null,M.treetoggle?r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{marginLeft:k.$level*28+"px"}}),k.$count?r.jsx("i",{className:`wx-8NTMLH0z wx-print-grid-tree-toggle wxi-menu-${k.open!==!1?"down":"right"}`}):null]}):null,M.cell?(()=>{const T=M.cell;return r.jsx(T,{api:g,row:k,column:M})})():r.jsx("span",{children:bl(k,M)})]},M.id))},N))}),m?r.jsx("tfoot",{children:r.jsx(Cb,{columns:w,type:"footer",columnStyle:l})}):null]})}function nM(n){const{config:a,...i}=n,l=u.useContext(xs),{_skin:c,_columns:d}=l.getState(),m=u.useMemo(()=>eA(d,a),[]),h=u.useRef(null);return u.useEffect(()=>{const g=document.body;g.classList.add("wx-print");const y=h.current;if(!y)return;const x=y.cloneNode(!0);g.appendChild(x);const b=`@media print { @page { size: ${a.paper} ${a.mode}; }`,w=document.createElement("style");w.setAttribute("type","text/css"),w.setAttribute("media","print"),document.getElementsByTagName("head")[0].appendChild(w),w.appendChild(document.createTextNode(b)),window.print(),w.remove(),g.classList.remove("wx-print"),x.remove()},[]),r.jsx("div",{className:`wx-4zwCKA7C wx-${c}-theme wx-print-container`,ref:h,children:m.map((g,y)=>r.jsx("div",{className:"wx-4zwCKA7C wx-print-grid-wrapper",children:r.jsx(tM,{columns:g,...i})},y))})}function aM(n){const{header:a,footer:i,overlay:l,multiselect:c,onreorder:d,rowStyle:m,columnStyle:h,cellStyle:g,autoRowHeight:y,resize:x,clientWidth:b,clientHeight:w,responsiveLevel:A,hotkeys:j}=n,k=u.useContext(xs),N=vt(k,"dynamic"),M=vt(k,"_columns"),T=vt(k,"flatData"),D=vt(k,"split"),F=vt(k,"_sizes"),[$,q]=Us(k,"selectedRows"),L=vt(k,"select"),Y=vt(k,"editor"),G=vt(k,"scrollLeft"),P=vt(k,"scrollTop"),K=vt(k,"tree"),H=vt(k,"focusCell"),ye=vt(k,"_print"),de=vt(k,"undo"),Z=vt(k,"reorder"),z=vt(k,"_rowHeightFromData"),[se,W]=u.useState(0);u.useEffect(()=>{W(pn())},[]);const[O,le]=u.useState(0),ce=u.useMemo(()=>(M||[]).some(re=>!re.hidden&&re.flexgrow),[M]),Q=u.useMemo(()=>F?.rowHeight||0,[F]),be=u.useRef(null),[he,fe]=u.useState(null),[ee,Se]=u.useState(null),Ne=u.useMemo(()=>{let re=[],Te=0;return D&&D.left&&(re=(M||[]).slice(0,D.left).filter(Ue=>!Ue.hidden).map(Ue=>({...Ue})),re.forEach(Ue=>{Ue.fixed={left:1,leftSize:D.left},Ue.left=Te,Te+=Ue.width}),re.length&&(re[re.length-1].fixed.left=-1)),{columns:re,width:Te}},[D,M]),Fe=u.useMemo(()=>{let re=[],Te=0;if(D&&D.right){re=(M||[]).slice(D.right*-1).filter(Ue=>!Ue.hidden).map(Ue=>({...Ue}));for(let Ue=re.length-1;Ue>=0;Ue--){const yt=re[Ue];yt.fixed={right:1},yt.right=Te,Te+=yt.width}re.length&&(re[0].fixed={right:-1})}return{columns:re,width:Te}},[D,M]),ne=u.useMemo(()=>{const re=(M||[]).slice(D?.left||0,(M||[]).length-(D?.right??0)).filter(Te=>!Te.hidden);return re.forEach(Te=>{Te.fixed=0}),re},[M,D]),Pe=u.useMemo(()=>(M||[]).reduce((re,Te)=>(Te.hidden||(re+=Te.width),re),0),[M]),mt=1;function J(re,Te,Ue){let yt=Te,qt=re;if(ne.length){let Yt=ne.length;for(let st=re;st>=0;st--)ne[st][Ue].forEach(Mt=>{Mt.colspan>1&&st>re-Mt.colspan&&st<Yt&&(Yt=st)});if(Yt!==ne.length&&Yt<re){for(let st=Yt;st<re;st++)yt-=ne[st].width;qt=Yt}}return{index:qt,delta:yt}}const ke=u.useMemo(()=>{let re,Te,Ue;const yt=G||0,qt=(G||0)+(b||0);let Yt=0,st=0,Mt=0,sa=0;ne.forEach((Cn,Tn)=>{yt>Mt&&(Yt=Tn,sa=Mt),Mt=Mt+Cn.width,qt>Mt&&(st=Tn+mt)});const On={header:0,footer:0};for(let Cn=st;Cn>=Yt;Cn--)["header","footer"].forEach(Tn=>{ne[Cn]&&ne[Cn][Tn].forEach(go=>{const Nt=go.colspan;if(Nt&&Nt>1){const ga=Nt-(st-Cn+1);ga>0&&(On[Tn]=Math.max(On[Tn],ga))}})});const gn=J(Yt,sa,"header"),nn=J(Yt,sa,"footer"),We=gn.delta,At=gn.index,Vs=nn.delta,zt=nn.index;return ce&&Pe>(b||0)?re=Te=Ue=[...Ne.columns,...ne,...Fe.columns]:(re=[...Ne.columns,...ne.slice(Yt,st+1),...Fe.columns],Te=[...Ne.columns,...ne.slice(At,st+On.header+1),...Fe.columns],Ue=[...Ne.columns,...ne.slice(zt,st+On.footer+1),...Fe.columns]),{data:re||[],header:Te||[],footer:Ue||[],d:sa,df:Vs,dh:We}},[ne,Ne,Fe,G,b,ce,Pe]),Le=u.useMemo(()=>a&&F?.headerHeight||0,[a,F]),Be=u.useMemo(()=>i&&F?.footerHeight||0,[i,F]),_e=u.useMemo(()=>b&&w?Pe>=b:!1,[b,w,Pe]),[Qe,Ye]=u.useState(!1),Ze=u.useMemo(()=>(w||0)-Le-Be-(_e?se:0),[w,Le,Be,_e,se]),ut=u.useMemo(()=>Math.ceil((Ze||0)/(Q||1))+1,[Ze,Q]),U=u.useRef([]),[ve,je]=u.useState(0),[$e,dt]=u.useState(void 0),it=u.useMemo(()=>{let re=0,Te=0;const Ue=2,yt=P||0;if(y){let st=yt;for(;st>0;)st-=U.current[re]||Q,re++;Te=yt-st;for(let Mt=Math.max(0,re-Ue-1);Mt<re;Mt++)Te-=U.current[re-Mt]||Q;re=Math.max(0,re-Ue)}else{if(z){let st=0,Mt=0;for(let nn=0;nn<(T||[]).length;nn++){const We=T[nn].rowHeight||Q;if(Mt+We>yt){st=nn;break}Mt+=We}re=Math.max(0,st-Ue);for(let nn=0;nn<re;nn++)Te+=T[nn].rowHeight||Q;let sa=0,On=0;for(let nn=st+1;nn<(T||[]).length;nn++){const We=T[nn].rowHeight||Q;if(sa++,On+We>Ze)break;On+=We}const gn=Math.min(N?N.rowCount:(T||[]).length,st+sa+Ue);return{d:Te,start:re,end:gn}}re=Math.floor(yt/(Q||1)),re=Math.max(0,re-Ue),Te=re*(Q||0)}const qt=N?N.rowCount:(T||[]).length,Yt=Math.min(qt,re+(ut||0)+Ue);return{d:Te,start:re,end:Yt}},[y,z,P,Q,N,T,ut,Ze]),pt=u.useMemo(()=>{const re=N?N.rowCount:(T||[]).length;if(y)return ve+it.d+(re-($e||0))*(Q||0);if(!z)return re*(Q||0);let Te=0;for(let Ue=0;Ue<re;Ue++)Te+=T[Ue]?.rowHeight||Q;return Te},[N,T,Q,y,z,ve,it.d,$e]),ct=u.useRef({});ct.current={clientWidth:b,clientHeight:w,fullHeight:pt,headerHeight:Le,footerHeight:Be,fullWidth:Pe,SCROLLSIZE:se};const kt=u.useCallback(()=>{const re=ct.current;Ye(re.clientWidth&&re.clientHeight?re.fullHeight+re.headerHeight+re.footerHeight>=re.clientHeight-(re.fullWidth>=re.clientWidth?re.SCROLLSIZE:0):!1)},[]);u.useEffect(()=>{const re=requestAnimationFrame(kt);return()=>window.cancelAnimationFrame(re)},[O,kt]),u.useEffect(()=>{kt()},[w,kt]);const pe=u.useMemo(()=>ce&&Pe<=(b||0)?(b||0)-0-(Qe?se:0):Pe,[ce,Pe,b,Qe,se,_e]),De=u.useMemo(()=>ce&&Pe<=(b||0)?b||0:pe<(b||0)?Pe+(Qe?se:0):-1,[ce,Pe,b,pe,Qe,se]),Oe=u.useRef({});u.useEffect(()=>{if(N&&(Oe.current.start!==it.start||Oe.current.end!==it.end)){const{start:re,end:Te}=it;Oe.current={start:re,end:Te},k&&k.exec&&k.exec("request-data",{row:{start:re,end:Te}})}},[N,it,k]);const Ae=u.useMemo(()=>N?T||[]:(T||[]).slice(it.start,it.end),[N,T,it]),ft=u.useMemo(()=>($||[]).filter(re=>(Ae||[]).some(Te=>Te.id===re)),[q,Ae]),xt=u.useMemo(()=>it.start,[it.start]),Ie=u.useRef({top:P,left:G});Ie.current={top:P,left:G};const na=u.useCallback(re=>{const Te=re.target.scrollTop,Ue=re.target.scrollLeft,yt=Ie.current;(Te!==yt.top||Ue!==yt.left)&&k.exec("scroll-to",{top:Te,left:Ue})},[k]),wn=u.useCallback(re=>{re.shiftKey&&re.preventDefault(),be.current&&be.current.focus&&be.current.focus()},[]),at=u.useCallback(()=>!!(M||[]).find(re=>!!re.draggable),[M]),Ot=u.useRef(null),aa=u.useRef(null),pa=u.useRef({dblclick:(re,Te)=>{const Ue={id:re,column:Vu(Te,"data-col-id")};k.exec("open-editor",Ue)},click:(re,Te)=>{if(Te.target.closest("input")||Ot.current)return;const Ue=Vu(Te,"data-col-id");if(H?.id!==re&&k.exec("focus-cell",{row:re,column:Ue,eventSource:"click"}),L===!1)return;const yt=c&&(Te.ctrlKey||Te.metaKey),qt=c&&Te.shiftKey;(yt||$.length>1||!$.includes(re))&&k.exec("select-row",{id:re,toggle:yt,range:qt})},"toggle-row":re=>{const Te=k.getRow(re);k.exec(Te.open!==!1?"close-row":"open-row",{id:re})},"ignore-click":()=>!1}),He=u.useMemo(()=>({top:Le,bottom:Be,left:Ne.width,xScroll:_e,yScroll:Qe,sense:y&&ee?ee.offsetHeight:Math.max(F?.rowHeight||0,40),node:be.current&&be.current.firstElementChild}),[Le,Be,Ne.width,_e,Qe,y,ee,F]);function Sn(re,Te){const{container:Ue,sourceNode:yt,from:qt}=Te;if(at()&&!yt.getAttribute("draggable-data"))return!1;fe(qt),K&&k.getRow(qt).open&&k.exec("close-row",{id:qt,nested:!0});const Yt=jc(yt),st=Yt.cloneNode(!0);st.classList.remove("wx-selected"),st.querySelectorAll("[tabindex]").forEach(gn=>gn.setAttribute("tabindex","-1")),Ue.appendChild(st),Se(st);const Mt=(G||0)-ke.d,sa=Qe?se:0;Ue.style.width=Math.min((b||0)-sa,ce&&Pe<=(b||0)?pe:pe-sa)+Mt+"px";const On=Af(Yt);Te.offset={x:Mt,y:-Math.round(On.height/2)},aa.current||(aa.current=re.clientY)}function zn(re,Te){const{from:Ue}=Te,yt=Te.pos,qt=Af(be.current);yt.x=qt.x;const Yt=He.top;if(yt.y<Yt)yt.y=Yt;else{const st=qt.height-(_e&&se>0?se:Math.round(He.sense/2))-He.bottom;yt.y>st&&(yt.y=st)}if(be.current.contains(Te.targetNode)){const st=jc(Te.targetNode),Mt=st&&qf(st);if(Mt&&Mt!==Ue){Te.to=Mt;const sa=y?ee?.offsetHeight:F?.rowHeight;if(ee&&((P||0)===0||yt.y>Yt+sa-1)){const On=st.getBoundingClientRect(),gn=Af(ee).y,nn=On.y,We=gn>nn?-1:1,At=We===1?"after":"before",Vs=k.getState().flatData,zt=Math.abs(Vs.findIndex(Tn=>Tn.id===Ue)-Vs.findIndex(Tn=>Tn.id===Mt)),Cn=zt!==1?At==="before"?"after":"before":At;if(zt===1&&(We===-1&&re.clientY>aa.current||We===1&&re.clientY<aa.current))return;aa.current=re.clientY,k.exec("move-item",{id:Ue,target:Mt,mode:Cn,inProgress:!0})}}d&&d({event:re,context:Te})}LA(re,qt,Te,He)}function ws(re,Te){const{from:Ue,to:yt}=Te;k.exec("move-item",{id:Ue,target:yt,inProgress:!1}),Ot.current=setTimeout(()=>{Ot.current=0},1),fe(null),Se(null),aa.current=null,ww(Te)}function pn(){const re=document.createElement("div");re.style.cssText="position:absolute;left:-1000px;width:100px;padding:0px;margin:0px;min-height:100px;overflow-y:scroll;",document.body.appendChild(re);const Te=re.offsetWidth-re.clientWidth;return document.body.removeChild(re),Te}const qs=u.useMemo(()=>De>0?{width:`${De}px`}:void 0,[De]),Wn=u.useRef(null);function Gs(){Promise.resolve().then(()=>{let re=0,Te=xt;const Ue=Wn.current;Ue&&(Array.from(Ue.children).forEach((yt,qt)=>{U.current[xt+qt]=yt.offsetHeight,re+=yt.offsetHeight,Te++}),je(re),dt(Te))})}u.useEffect(()=>{Ae&&y&&Gs()},[Ae,y,xt]);let[B,Ke]=u.useState();u.useEffect(()=>{if(H&&(!L||!ft.length||ft.includes(H.row)))Ke({...H});else if(Ae.length&&ke.data.length){if(!B||ft.length&&!ft.includes(B.row)||Ae.findIndex(re=>re.id===B.row)===-1||ke.data.findIndex(re=>re.id===B.column&&!re.collapsed)===-1){const re=ft[0]||Ae[0].id,Te=ke.data.findIndex(Ue=>!Ue.collapsed);Ke(Te!==-1?{row:re,column:ke.data[Te].id}:null)}}else Ke(null)},[H]);const ht=u.useRef(null);u.useEffect(()=>{const re=be.current;if(!re)return;const Te=NA(re,x);return()=>{typeof Te=="function"&&Te()}},[x]);const fn=u.useRef({});Object.assign(fn.current,{start:Sn,move:zn,end:ws,getReorder:()=>Z,getDraggableInfo:()=>({hasDraggable:at()})}),u.useEffect(()=>{const re=be.current;return re?RA(re,fn).destroy:void 0},[Z,be.current]),u.useEffect(()=>{const re=be.current;return re?AA(re,{keys:j!==!1&&{...jA,"ctrl+z":de,"ctrl+y":de,...j},exec:Te=>k.exec("hotkey",Te)}).destroy:void 0},[k,de,j]);const Fa=u.useRef({scroll:k.getReactiveState().scroll,scrollLeft:k.getReactiveState().scrollLeft,scrollTop:k.getReactiveState().scrollTop});Fa.current.getWidth=()=>(b||0)-(Qe?se:0),Fa.current.getHeight=()=>Ze,Fa.current.getScrollMargin=()=>Ne.width+Fe.width,u.useEffect(()=>{MA(ht.current,Fa.current)},[]);const Di=u.useRef(null);u.useEffect(()=>{const re=Di.current;if(!re)return;const Te=[];Te.push(Hr(re,()=>H&&k.exec("focus-cell",{eventSource:"click"})).destroy),Te.push(Rj(re,pa.current)),le(re.clientHeight);const Ue=new ResizeObserver(()=>{le(re.clientHeight)});return Ue.observe(re),Te.push(()=>Ue.disconnect()),()=>Te.forEach(yt=>yt())},[]);const Ss=`wx-grid ${A?`wx-responsive-${A}`:""}`;return u.useEffect(()=>{H&&(Ae.some(re=>re.id===H.row)&&ke.data.some(re=>re.id===H.column&&!re.collapsed)||k.exec("focus-cell",{eventSource:"destroy"}))},[H,Ae,ke.data,k]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-4VuBwK2D "+Ss,style:{"--header-height":`${Le}px`,"--footer-height":`${Be}px`,"--split-left-width":`${Ne.width}px`,"--split-right-width":`${Fe.width}px`},children:r.jsx("div",{ref:be,className:"wx-4VuBwK2D wx-table-box",style:qs,role:K?"treegrid":"grid","aria-colcount":ke.data.length,"aria-rowcount":Ae.length,"aria-multiselectable":K&&c?!0:void 0,tabIndex:-1,children:r.jsxs("div",{ref:ht,className:"wx-4VuBwK2D wx-scroll",style:{overflowX:_e?"scroll":"hidden",overflowY:Qe?"scroll":"hidden"},onScroll:na,children:[a?r.jsx("div",{className:"wx-4VuBwK2D wx-header-wrapper",children:r.jsx(Sb,{contentWidth:pe,deltaLeft:ke.dh,columns:ke.header,columnStyle:h,bodyHeight:Ze-+i})}):null,r.jsxs("div",{ref:Di,className:"wx-4VuBwK2D wx-body",style:{width:`${pe}px`,height:`${pt}px`},onMouseDown:re=>wn(re),children:[l?r.jsx(WA,{overlay:l}):null,r.jsx("div",{ref:Wn,className:"wx-4VuBwK2D wx-data",style:{paddingTop:`${it.d}px`,paddingLeft:`${ke.d}px`},children:Ae.map((re,Te)=>{const Ue=$.indexOf(re.id)!==-1,yt=he===re.id,qt="wx-row"+(y?" wx-autoheight":"")+(m?" "+m(re):"")+(Ue?" wx-selected":"")+(yt?" wx-inactive":""),Yt=y?{minHeight:`${re.rowHeight||Q}px`}:{height:`${re.rowHeight||Q}px`};return r.jsx("div",{className:"wx-4VuBwK2D "+qt,"data-id":Jn(re.id),"data-context-id":Jn(re.id),style:Yt,role:"row","aria-rowindex":Te,"aria-expanded":re.open,"aria-level":K?re.$level+1:void 0,"aria-selected":K?Ue:void 0,tabIndex:-1,children:ke.data.map(st=>st.collapsed?r.jsx("div",{className:"wx-4VuBwK2D wx-cell wx-collapsed"},st.id):Y?.id===re.id&&Y.column===st.id?r.jsx(eM,{row:re,column:st},st.id):r.jsx(HA,{row:re,column:st,columnStyle:h,cellStyle:g,reorder:Z,focusable:B?.row===re.id&&B?.column===st.id},st.id))},re.id)})})]}),i&&(T||[]).length?r.jsx(Sb,{type:"footer",contentWidth:pe,deltaLeft:ke.df,columns:ke.footer,columnStyle:h}):null]})})}),ye?r.jsx(nM,{config:ye,rowStyle:m,columnStyle:h,cellStyle:g,header:a,footer:i,reorder:Z}):null]})}const sM=n=>n.split("-").map(a=>a?a.charAt(0).toUpperCase()+a.slice(1):"").join(""),rM=u.forwardRef(function({data:n=[],columns:a=[],rowStyle:i=null,columnStyle:l=null,cellStyle:c=null,selectedRows:d,select:m=!0,multiselect:h=!1,header:g=!0,footer:y=!1,dynamic:x=null,overlay:b=null,reorder:w=!1,onReorder:A=null,autoRowHeight:j=!1,sizes:k,split:N,tree:M=!1,autoConfig:T=!1,init:D=null,responsive:F=null,sortMarks:$,undo:q=!1,hotkeys:L=null,filterValues:Y,...G},P){const K=u.useRef();K.current=G;const H=u.useMemo(()=>new bA(uw),[]),ye=u.useMemo(()=>H.in,[H]),de=u.useRef(null);de.current===null&&(de.current=new sw((Fe,ne)=>{const Pe="on"+sM(Fe);K.current&&K.current[Pe]&&K.current[Pe](ne)}),ye.setNext(de.current));const Z=u.useMemo(()=>({getState:H.getState.bind(H),getReactiveState:H.getReactive.bind(H),getStores:()=>({data:H}),exec:ye.exec,setNext:Fe=>(de.current=de.current.setNext(Fe),de.current),intercept:ye.intercept.bind(ye),on:ye.on.bind(ye),detach:ye.detach.bind(ye),getRow:H.getRow.bind(H),getColumn:H.getColumn.bind(H)}),[H,ye]),[z,se]=u.useState(0),[W,O]=u.useState(0),[le,ce]=u.useState(null),[Q,be]=u.useState(null),he=u.useMemo(()=>{if(T&&!a.length&&n.length){const Fe=n[0],ne=[];for(let Pe in Fe)if(Pe!=="id"&&Pe[0]!=="$"){let mt={id:Pe,header:Pe[0].toUpperCase()+Pe.slice(1)};typeof T=="object"&&(mt={...mt,...T}),ne.push(mt)}return ne}return(Q&&Q.columns)??a},[T,a,n,Q]),fe=u.useMemo(()=>(Q&&Q.sizes)??k,[Q,k]),ee=u.useCallback(Fe=>{if(se(Fe.width),O(Fe.height),F){const ne=Object.keys(F).map(Number).sort((Pe,mt)=>Pe-mt).find(Pe=>Fe.width<=Pe)??null;ne!==le&&(be(F[ne]),ce(ne))}},[F,le]),Se=u.useContext(ta.theme),Ne=u.useRef(0);return u.useEffect(()=>{if(!Ne.current)D&&D(Z);else{const Fe=H.getState();H.init({data:n,columns:he,split:N||Fe.split,sizes:fe||Fe.sizes,selectedRows:d||Fe.selectedRows,dynamic:x,tree:M,sortMarks:$||Fe.sortMarks,filterValues:Y||Fe.filterValues,undo:q,reorder:w,_skin:Se,_select:m})}Ne.current++},[H,n,he,N,fe,d,x,M,$,Y,q,w,Se,m,D,Z]),Ne.current===0&&H.init({data:n,columns:he,split:N||{left:0},sizes:fe||{},selectedRows:d||[],dynamic:x,tree:M,sortMarks:$||{},filterValues:Y||{},undo:q,reorder:w,_skin:Se,select:m}),u.useImperativeHandle(P,()=>({...Z}),[Z]),r.jsx(xs.Provider,{value:Z,children:r.jsx(Fp,{words:$p,optional:!0,children:r.jsx(aM,{header:g,footer:y,overlay:b,rowStyle:i,columnStyle:l,cellStyle:c,onReorder:A,multiselect:h,autoRowHeight:j,clientWidth:z,clientHeight:W,responsiveLevel:le,resize:ee,hotkeys:L})})})});Dp(ls);const ea=u.createContext(null),Up=u.createContext(null),qp=u.createContext(null);function iM({children:n}){const a=u.useContext(ta.i18n),i=u.useMemo(()=>a.getGroup("filemanager"),[a]),l=u.useContext(ea),[c]=Us(l,"panels"),d=vt(l,"activePanel"),m=c[d].path,[h,g]=u.useState(null),[y,x]=u.useState(null),[b,w]=u.useState(""),[A,j]=u.useState(""),[k,N]=u.useState(!1);function M(){const $=b.trim();if(!$){N(!0);return}h.add?l.exec("create-file",{file:{...h.item,name:$},parent:m}):A!==$&&l.exec("rename-file",{id:h.item.id,name:$}),T()}function T(){g(null),N(null),j(""),w("")}function D(){l.exec("delete-files",{ids:y.selected}),x(null)}const F=u.useMemo(()=>({showPrompt($){const q=$.item.name||($.item.type==="folder"?i("New folder"):`${i("New file")}.txt`);j(q),w(q),g({...$})},showConfirm($){x({...$})}}),[i]);return r.jsxs(Up.Provider,{value:F,children:[r.jsx(ij,{children:n}),h?r.jsx(mp,{title:i(`Enter ${h.item.type} name`),onConfirm:M,onCancel:T,children:r.jsx(Op,{error:k,select:!0,focus:!0,value:b,onChange:({value:$})=>w($)})}):null,y?r.jsx(mp,{title:i("Are you sure you want to delete these items:"),onConfirm:D,onCancel:()=>x(null),children:y.selected?r.jsx("ul",{className:"wx-gq7BMzEP wx-list",children:y.selected.map(($,q)=>r.jsx("li",{children:$},q))}):null}):null]})}let kb={"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 lM(n){const a=n.lastIndexOf("."),i=a>0&&a<n.length-1?Math.min(10,n.length-a):Math.min(5,n.length),l=n.slice(0,-i),c=n.slice(-i);return[l,c]}function oM({item:n}){const a=u.useContext(ea),i=u.useContext(ta.i18n).getGroup("filemanager"),l=u.useContext(ea).templates,[c]=Us(a,"panels"),d=vt(a,"activePanel"),m=vt(a,"mode"),h=c[d].selected,g=u.useMemo(()=>l.preview(n,214,163),[l,n]),y=u.useMemo(()=>l.icon(n,"big"),[l,n]),[x,b]=u.useMemo(()=>lM(n.name),[n.name]);return r.jsx(r.Fragment,{children:n.id==="/wx-filemanager-parent-link"?m!=="search"?r.jsx("div",{className:"wx-GAOa4kDV wx-back-item",children:r.jsxs("div",{className:`wx-GAOa4kDV wx-back ${n.navigation?"wx-selected":""}`,"data-id":Jn("/wx-filemanager-parent-link"),children:[r.jsx("i",{className:"wx-GAOa4kDV wxi-arrow-left"}),r.jsx("span",{children:i("Back to parent folder")})]})}):null:r.jsxs("div",{className:`wx-GAOa4kDV wx-item ${h?.length&&h.indexOf(n.id)>=0?"wx-selected":""}`,"data-id":Jn(n.id),children:[g?r.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-preview",children:r.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:i("A miniature file preview"),src:g})}):y?r.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-icon",children:r.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:"",src:y})}):r.jsx("div",{className:"wx-GAOa4kDV wx-preview",children:r.jsx("i",{className:`wx-GAOa4kDV wxi-${n.type}`})}),n.type==="folder"?r.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[r.jsxs("div",{className:"wx-GAOa4kDV wx-folder-name",children:[r.jsx("span",{className:"wx-GAOa4kDV wx-type",children:i("Folder")}),r.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[r.jsx("span",{children:x}),r.jsx("span",{children:b})]})]}),r.jsx("div",{"data-action-id":Jn(n.id),className:"wx-GAOa4kDV wx-more",children:r.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]}):r.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[r.jsx("div",{className:"wx-GAOa4kDV wx-file-name",children:r.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[r.jsx("span",{children:x}),r.jsx("span",{children:b})]})}),r.jsx("div",{"data-action-id":Jn(n.id),className:"wx-GAOa4kDV wx-more",children:r.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]})]})})}function jw(){const n=u.useContext(ea),a=u.useContext(ta.i18n),i=u.useMemo(()=>a.getGroup("filemanager"),[a]),[l]=Us(n,"panels"),c=vt(n,"activePanel"),d=vt(n,"mode"),m=l[c]._files,h=l[c].selected,g=l[c].path,y=l[c]._crumbs,x=l[c]._selectNavigation,b=u.useCallback((T,D)=>{const F=D&&(D.ctrlKey||D.metaKey),$=D&&D.shiftKey;if(T==="/wx-filemanager-parent-link"){if(h.length&&(F||$))return;n.exec("select-file",{type:"navigation"});return}let q=T==="body"&&D?null:T;const L=D.target.className.indexOf("wx-more")!==-1||D.target.className.indexOf("wxi-dots-v")!==-1;setTimeout(()=>{n.exec("select-file",{id:q,toggle:F&&!L,range:$&&!L,panel:c})},1)},[n,h,c]),w=u.useCallback(()=>{y.length>1&&n.exec("set-path",{id:y[y.length-2].id,panel:c,selected:[y[y.length-1].id]})},[n,y,c]),A=u.useCallback(T=>{if(T==="/wx-filemanager-parent-link")return w();d==="search"&&n.exec("filter-files",{text:""});const D=m.find(F=>F.id===T);D&&(D.type=="folder"?n.exec("set-path",{id:D.id,panel:c}):n.exec("open-file",{id:D.id}))},[n,w,d,m,c]),j=u.useCallback((T,D)=>{(!h?.length||!h.filter(F=>F?.id===T).length>0)&&b(T,D)},[h,b]),k=u.useMemo(()=>g!=="/"?[{id:"/wx-filemanager-parent-link",name:i("Back to parent folder"),navigation:x},...m]:m,[g,i,x,m]),N=u.useRef(null),M=u.useRef();return u.useEffect(()=>{N.current&&(M.current?(M.current.click=b,M.current._dblclick=A,M.current.context=j):(M.current={click:b,dblclick:T=>M.current._dblclick(T),_dblclick:A,context:j},Ac(N.current,M.current)))},[b,A,j]),d=="search"&&!k.length?r.jsx("div",{className:"wx-iyjASZCY wx-not-found",children:r.jsx("div",{className:"wx-iyjASZCY wx-not-found-text",children:i("Looks like nothing is here")})}):r.jsx("div",{tabIndex:0,className:"wx-iyjASZCY "+("wx-cards"+(g!=="/"&&d!=="search"?" wx-has-back-link":"")),"data-id":Jn("body"),ref:N,children:k.map(T=>r.jsx(oM,{item:T},T.id))})}function po({name:n="",spin:a=!1,onClick:i}){return r.jsx("i",{"data-menu-ignore":"true",className:`wx-uwcvNSAG wx-icon wxi-${n} ${a?"wx-spin":""} ${i?"wx-clickable":""}`,onClick:()=>{i&&i()}})}function cM(){const n=u.useContext(ta.i18n).getGroup("filemanager"),a=u.useContext(ea),i=vt(a,"activePanel"),[l]=Us(a,"panels"),c=u.useMemo(()=>l[i]._crumbs,[l,i]);function d(){a.exec("filter-files",{text:""})}return r.jsxs("div",{className:"wx-GDJvtROw wx-search",children:[r.jsxs("div",{className:"wx-GDJvtROw wx-toolbar",children:[r.jsx("div",{className:"wx-GDJvtROw wx-back-icon",children:r.jsx(po,{name:"angle-left",onClick:d})}),r.jsxs("div",{className:"wx-GDJvtROw wx-text",children:[n("Search results in")," ",Array.isArray(c)&&c.map((m,h)=>r.jsxs(u.Fragment,{children:[h?"/":null,m.id=="/"?n(m.name):m.name]},h))]})]}),r.jsx(jw,{})]})}function Dh({narrowMode:n,extraInfo:a}){const i=u.useContext(ea),{preview:l,icon:c}=i.templates,d=u.useContext(ta.i18n),m=u.useMemo(()=>d.getGroup("filemanager"),[d]),h=u.useMemo(()=>bc("%D, %d %F %Y, %H:%i",d.getRaw().calendar),[d]),[g,y]=Us(i,"panels"),x=vt(i,"activePanel"),b=vt(i,"preview"),w=vt(i,"search"),A=u.useMemo(()=>{const L=g&&x!=null&&g[x]?._selected?.length||0;return w&&!L},[w,y,x]),j=u.useMemo(()=>{const L=g&&x!=null?g[x]:null;return L?A?L._files:L._selected:[]},[A,y,x]),k=u.useCallback((L,Y)=>(L?`${L} ${m(L>1?"folders":"folder")} `:"")+(Y?`${Y} ${m(Y>1?"files":"file")}`:""),[m]),N=u.useCallback(()=>{i.exec("show-preview",{mode:!b})},[i,b]),M=u.useCallback(L=>L.type==="folder"?m("Folder"):L.ext||m("Unknown file"),[m]),T=u.useMemo(()=>{let L,Y,G,P,K,H,ye,de;if(j.length===1&&!A){Y=j[0],L=Y.name;const Z=l(Y,400,500);Z?(G=Z,P=""):(P=c(Y,"big"),G=""),K=Y.type!=="folder"}else{if(Y=K=null,L="",j.length){let Z=0,z=0,se=0,W=[],O;j.forEach(ce=>{typeof ce.size>"u"&&(O=!0,Z=void 0),O||(Z+=ce.size),W.push(M(ce)),ce.type==="folder"?z++:se++});const le=new Set(W);H=le.size>1?m("multiple"):[...le][0],ye=k(z,se),de=Z,A||(L=m("Multiple files"))}P=c({type:A?"search":j.length?"multiple":"none"},"big"),G=""}return{name:L,item:Y,previewSrc:G,iconSrc:P,showDownloadIcon:K,type:H,totalCount:ye,totalSize:de}},[j,A,l,c,m,M,k]),D=u.useCallback(()=>{i.exec("download-file",{id:j[0].id})},[i,j]),F=u.useCallback(async L=>{if(!a||!L)return null;try{return await a(L)}catch(Y){return console.log(Y),null}},[a]),[$,q]=u.useState(null);return u.useEffect(()=>{let L=!1;return q(null),Promise.resolve(F(T.item)).then(Y=>{L||q(Y)}).catch(()=>{L||q(null)}),()=>{L=!0}},[F,T.item]),r.jsx("div",{className:"wx-O0BTtRrH wx-wrapper",children:j&&j.length?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"wx-O0BTtRrH wx-preview",children:[r.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[r.jsx("div",{className:"wx-O0BTtRrH wx-name",children:T.name}),r.jsxs("div",{className:"wx-O0BTtRrH wx-icons",children:[T.showDownloadIcon?r.jsx(po,{name:"download",onClick:D}):null,n?r.jsx(po,{name:"close",onClick:N}):null]})]}),T.previewSrc?r.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:r.jsx("img",{src:T.previewSrc,alt:m("A miniature file preview")})}):T.iconSrc?r.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:r.jsx("img",{src:T.iconSrc,alt:m("A miniature file preview")})}):r.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:T.item?r.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${T.item.type}`}):r.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${A?"search":"file-multiple-outline"}`})})]}),r.jsxs("div",{className:"wx-O0BTtRrH wx-info-panel",children:[r.jsx("div",{className:"wx-O0BTtRrH wx-title",children:m(A?"Found":"Information")}),r.jsxs("div",{className:"wx-O0BTtRrH wx-list",children:[T.item?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Type")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:M(T.item)}),typeof T.item.size<"u"?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Size")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:Wu(T.item.size)})]}):null,r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Date")}),r.jsxs("span",{className:"wx-O0BTtRrH wx-value",children:[h(T.item.date)," "]})]}):r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Count")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:T.totalCount}),r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Type")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:T.type}),typeof T.totalSize<"u"?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Size")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:Wu(T.totalSize)})]}):null]}),$?Object.entries($).map(([L,Y])=>r.jsxs(kp.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:L}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:Y})]},L)):null]})]})]}):r.jsxs("div",{className:"wx-O0BTtRrH wx-no-info-panel",children:[r.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[r.jsx("div",{className:"wx-O0BTtRrH wx-name",children:T.name}),r.jsx("div",{className:"wx-O0BTtRrH wx-icons",children:n?r.jsx(po,{name:"close",onClick:N}):null})]}),r.jsx("div",{className:"wx-O0BTtRrH wx-no-info-wrapper",children:r.jsxs("div",{className:"wx-O0BTtRrH wx-no-info",children:[T.previewSrc?r.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:r.jsx("img",{src:T.previewSrc,alt:m("A miniature file preview")})}):T.iconSrc?r.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:r.jsx("img",{src:T.iconSrc,alt:m("A miniature file preview")})}):r.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:r.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${A?"search":"message-question-outline"}`})}),r.jsx("span",{className:"wx-O0BTtRrH wx-text",children:A?"":m("Select file or folder to view details")})]})})]})})}function Aw({panel:n}){const a=u.useContext(ea),i=u.useContext(ta.i18n),l=u.useMemo(()=>i.getGroup("filemanager"),[i]),[c,d]=Us(a,"panels"),m=u.useMemo(()=>c[n]._files,[d,n]),h=u.useMemo(()=>c[n]._crumbs||[],[d,n]);function g(j){const k=Bp(j,h);a.exec("set-path",{id:j,panel:n,...k&&{selected:[k]}})}const[y,x]=u.useState(null);u.useEffect(()=>{m&&x(null)},[m]);function b(){x(!0),a.exec("request-data",{id:h[h.length-1].id}),setTimeout(()=>{x(null)},5e3)}const w=u.useRef(null),A=u.useRef();return u.useEffect(()=>{A.current?A.current.click=g:(A.current={click:g},Ac(w.current,A.current))},[g]),r.jsxs("div",{className:"wx-SNY5LTYx wx-breadcrumbs","data-menu-ignore":"true",ref:w,children:[r.jsx("div",{className:"wx-SNY5LTYx wx-refresh-icon",children:r.jsx(po,{name:"refresh",spin:!!y,onClick:b})}),h.map((j,k)=>r.jsxs(kp.Fragment,{children:[k?r.jsx(po,{name:"angle-right"}):null,r.jsx("div",{className:"wx-SNY5LTYx wx-item","data-id":Jn(j.id),"data-menu-ignore":"true",children:j.id=="/"?l(j.name):j.name})]},k))]})}function uM({row:n}){const a=u.useContext(ta.i18n),[i]=u.useState(()=>a.getGroup("filemanager")),l=u.useContext(ea).templates,[c]=u.useState(()=>l.icon(n,"small"));return r.jsx("div",{className:"wx-qgAqG6sL wx-name-cell",children:n.id==="/wx-filemanager-parent-link"?r.jsxs(r.Fragment,{children:[r.jsx("i",{className:"wx-qgAqG6sL wxi-arrow-left"}),r.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",i("Back to parent folder")]})]}):r.jsxs(r.Fragment,{children:[c?r.jsx("img",{className:"wx-qgAqG6sL wx-icon",alt:"",src:c,height:"24px",width:"24px"}):r.jsx("i",{className:`wx-qgAqG6sL wxi-${n.type}`}),r.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",n.name," "]})]})})}function Mw({children:n}){const a=u.useContext(ea),i=vt(a,"activePanel"),l=u.useContext(qp),c=u.useRef(null);let d=u.useRef({});return d.current.drop=()=>{const m=c.current,h=mk(m,"data-panel");h&&h!=i&&a.exec("set-active-panel",{panel:h*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)},[]),r.jsx("div",{className:"wx-LT9X7tb7 wx-upload-area",ref:c,children:n})}function gp({panel:n,active:a=!1,onClick:i,onContextMenu:l}){const c=u.useContext(ea),d=u.useContext(ta.i18n),m=u.useMemo(()=>d.getGroup("filemanager"),[d]),h=u.useMemo(()=>bc("%d %M %Y",d.getRaw().calendar),[d]),[g]=Us(c,"panels"),y=g[n].selected,x=g[n].path,b=g[n]._crumbs,w=g[n]._sorts,A=g[n]._selectNavigation,j=g[n]._files,k=u.useMemo(()=>[{id:"name",header:m("Name"),flexgrow:3,sort:!0,resize:!0,cell:uM},{id:"size",header:m("Size"),width:100,sort:!0,resize:!0,template:H=>typeof H=="number"?Wu(H):""},{id:"date",header:m("Date"),width:120,sort:!0,resize:!0,template:H=>H?h(H):""}],[m,h]),N=u.useRef(null),M=u.useRef(null),T=u.useMemo(()=>A?["/wx-filemanager-parent-link"]:[...y],[A,y]);function D(H,ye){if(ye&&ye.target&&ye.target.className&&ye.target.className.indexOf("wx-grip")!==-1)return;const de=ye&&(ye.ctrlKey||ye.metaKey),Z=ye&&ye.shiftKey;if(H==="/wx-filemanager-parent-link"){if(y.length&&(de||Z))return;c.exec("select-file",{type:"navigation"});return}let z=H==="body"&&ye?null:H;!N.current&&!M.current?c.exec("select-file",{id:z,toggle:de,range:Z,panel:n}):(N.current=null,M.current=null)}function F(){b.length>1&&c.exec("set-path",{id:b[b.length-2].id,panel:n,selected:[b[b.length-1].id]})}function $(H){if(H==="/wx-filemanager-parent-link")return F();const ye=j.find(de=>de.id===H);ye&&(ye.type==="folder"?c.exec("set-path",{id:ye.id,panel:n}):c.exec("open-file",{id:ye.id}))}function q(H){const ye=H.key,de=w[x];let Z=de?"asc":"desc";de&&de.key===ye&&(Z=de.order==="asc"?"desc":"asc"),c.exec("sort-files",{key:ye,order:Z,panel:n,path:x})}function L(H){H.intercept("sort-rows",ye=>(N.current=!0,q(ye),!1)),H.intercept("select-row",()=>!1),H.on("resize-column",()=>M.current=!0),H.intercept("hotkey",()=>!1)}const Y=u.useMemo(()=>x!=="/"?[{id:"/wx-filemanager-parent-link",name:m("Back to parent folder")},...j]:j,[x,j,m]),G=u.useMemo(()=>{if(Y&&w&&w[x]){const{key:H,order:ye}=w[x];return{[H]:{order:ye}}}},[Y,w,x]),P=u.useRef(null),K=u.useRef();return u.useEffect(()=>{K.current?(K.current.click=D,K.current._dblclick=$):(K.current={click:D,dblclick:H=>K.current._dblclick(H),_dblclick:$},Ac(P.current,K.current))},[D,$]),r.jsxs("div",{onClick:i,onContextMenu:l,className:"wx-SSaVhET7 wx-wrapper",children:[r.jsx(Aw,{panel:n}),r.jsx("div",{"data-id":Jn("body"),className:`wx-SSaVhET7 wx-list ${a?"wx-active":""}`,ref:P,children:r.jsx(Mw,{children:r.jsx(rM,{init:L,data:Y,columns:k,selectedRows:T,columnStyle:()=>"wx-SSaVhET7 wx-each-cell",sizes:{rowHeight:42,headerHeight:42},sortMarks:G})})})]})}function dM(){const n=u.useContext(ea),a=vt(n,"activePanel");function i(l){n.exec("set-active-panel",{panel:l})}return r.jsxs("div",{className:"wx-L55BfJa2 wx-panels","data-id":Jn("body"),children:[r.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":0,children:r.jsx(gp,{panel:0,active:a==0,onClick:()=>i(0),onContextMenu:()=>i(0)})}),r.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":1,children:r.jsx(gp,{panel:1,active:a==1,onClick:()=>i(1),onContextMenu:()=>i(1)})})]})}function Nw({folderIcon:n=!1,folder:a={}}){const i=u.useContext(ea),[l,c]=Us(i,"panels"),d=vt(i,"activePanel"),m=u.useMemo(()=>l[d].path,[c,d]),h=u.useContext(ta.i18n),g=u.useMemo(()=>h.getGroup("filemanager"),[h]),y=u.useMemo(()=>!!a.data?.find(A=>A.type==="folder"),[a]),x=u.useMemo(()=>a.id=="/"?g(a.name):a.name,[a,g]),b=u.useMemo(()=>a.$level>1?(a.$level-1)*20:0,[a]),w=a.open;return r.jsxs(r.Fragment,{children:[r.jsxs("li",{"data-id":Jn(a.id),className:`wx-NYfhvGIt wx-folder${m===a.id?" wx-selected":""}`,style:{paddingLeft:`${b}px`},children:[y?r.jsx("i",{className:`wx-NYfhvGIt wx-toggle wxi-${w?"angle-down":"angle-right"}`,"data-action":"toggle"}):r.jsx("span",{className:"wx-NYfhvGIt wx-toggle-placeholder"}),r.jsx("i",{className:"wx-NYfhvGIt "+(n||"wxi-folder")}),r.jsxs("span",{className:"wx-NYfhvGIt wx-name",children:[" ",x," "]})]}),w&&a.data&&a.data.length&&y?r.jsx(r.Fragment,{children:a.data.map(A=>A.type==="folder"?r.jsx(Nw,{folder:A},A.id):null)}):null]})}function fM(){const n=u.useContext(ea),[a,i]=Us(n,"data"),[l,c]=Us(n,"panels"),d=vt(n,"activePanel"),m=u.useMemo(()=>l[d]._crumbs,[c,d]),h=u.useCallback(A=>{n.exec("open-tree-folder",{id:A,mode:!a.byId(A).open})},[n,i]),g=u.useCallback(A=>{const j=Bp(A,m);n.exec("set-path",{id:A,panel:d,...j&&{selected:[j]}})},[n,m,d]),[y,x]=u.useState([]);u.useEffect(()=>{x(a.byId(0).data)},[i]);const b=u.useRef(null),w=u.useRef();return u.useEffect(()=>{w.current?(w.current.click=g,w.current.toggle=h):(w.current={click:g,toggle:h},Ac(b.current,w.current))},[g,h]),r.jsx("ul",{ref:b,className:"wx-LyHJ6R6A",children:y.map(A=>A.type==="folder"?r.jsx(Nw,{folder:A},A.id):null)})}function mM(){const n=u.useContext(ea),a=u.useContext(ta.i18n),i=u.useMemo(()=>a.getGroup("filemanager"),[a]),l=vt(n,"drive"),c=l?l.used:"",d=l?l.total:"";return c&&d?r.jsxs("div",{className:"wx-DetSyKGG wx-drive",children:[r.jsx("progress",{value:c,max:d,className:"wx-DetSyKGG wx-progress"}),r.jsxs("p",{children:[Wu(c)," ",i("of")," ",Wu(d)," ",i("used")]})]}):null}function hM({option:n}){const a=u.useContext(ta.i18n).getGroup("filemanager"),i=u.useContext(qp),l=u.useCallback(()=>{i.open({})},[i]);return r.jsx("div",{className:"wx-9XiKcxq5 wx-upload-button",onClick:l,children:r.jsx("span",{children:a(n.text)})})}function pM({readonly:n,menuOptions:a}){const i=u.useContext(ta.i18n).getGroup("filemanager"),{showPrompt:l}=u.useContext(Up);u.useEffect(()=>{Lj("upload",hM)},[]);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=i(m.text),m)),[a,i]);return r.jsxs("div",{className:"wx-FlucfALM wx-wrapper",children:[!n&&r.jsx("div",{className:"wx-FlucfALM wx-button",children:r.jsx(Ij,{options:d,at:"bottom-fit",onClick:c,children:r.jsx(Fu,{type:"primary block",children:i("Add New")})})}),r.jsx("div",{className:"wx-FlucfALM wx-tree",children:r.jsx(fM,{})}),r.jsx(mM,{})]})}function gM({value:n="",onSearch:a}){const[i,l]=ow(n),c=u.useContext(ta.i18n).getGroup("filemanager"),d=u.useRef(null),m=u.useMemo(()=>i!==""?"wxi-close":"wxi-search",[i]);function h(y){const x=y.target.value;l(x),a&&a({value:x})}function g(){l(""),d.current&&d.current.focus(),a&&a({value:""})}return r.jsxs("div",{className:"wx-lUZMtgT1 wx-search-input",children:[r.jsx("i",{className:`wx-lUZMtgT1 wx-icon ${m}`,onClick:g}),r.jsx("input",{type:"text",className:"wx-lUZMtgT1 wx-text",ref:d,value:i,onInput:h,placeholder:c("Search")})]})}function vM({narrowMode:n=!1,onShowTree:a}){const i=u.useContext(ea),l=u.useContext(ta.i18n).getGroup("filemanager"),c=vt(i,"mode"),d=vt(i,"preview"),m=vt(i,"search"),h=[{icon:"wxi-view-sequential",id:"table"},{icon:"wxi-view-grid",id:"cards"},{icon:"wxi-view-column",id:"panels"}];function g({value:b}){i.exec("set-mode",{mode:b})}function y(b){b.preventDefault(),i.exec("show-preview",{mode:!d})}function x(b){i.exec("filter-files",{text:b.value})}return r.jsxs("div",{className:"wx-5PZQQztG wx-toolbar",children:[r.jsxs("div",{className:"wx-5PZQQztG wx-left "+(n?"wx-left-narrow":""),children:[n?c==="panels"||c==="search"?null:r.jsx("div",{className:"wx-5PZQQztG wx-sidebar-icon","data-id":Jn("toggle-tree"),children:r.jsx(po,{onClick:()=>a&&a(),name:"subtask"})}):r.jsx("div",{className:"wx-5PZQQztG wx-name",children:l("Files")}),r.jsx(gM,{onSearch:x,value:m})]}),r.jsxs("div",{className:"wx-5PZQQztG wx-right",children:[n?null:r.jsx("div",{className:"wx-5PZQQztG wx-preview-icon",children:r.jsx(lj,{onClick:y,value:d,children:r.jsx("i",{className:"wx-5PZQQztG wxi-eye"})})}),r.jsx("div",{className:"wx-5PZQQztG wx-modes",children:r.jsx(tj,{value:c,options:h,onChange:g})})]})]})}function yM(){const n=u.useContext(ea),a=vt(n,"activePanel");return r.jsxs("div",{className:"wx-NwohNJzN wx-wrapper",children:[r.jsx(Aw,{panel:a}),r.jsx(Mw,{children:r.jsx(jw,{})})]})}function bM({readonly:n=!1,menuOptions:a,extraInfo:i}){const l=u.useRef(null),c=u.useRef(null),[d,m]=u.useState(void 0),[h,g]=u.useState(void 0),[y,x]=u.useState(!1),b=pw(),w=u.useContext(ea),{showPrompt:A,showConfirm:j}=u.useContext(Up),k=u.useContext(ta.i18n),N=u.useMemo(()=>k.getGroup("filemanager"),[k]),M=vt(w,"mode"),T=vt(w,"preview"),D=vt(w,"activePanel"),[F,$]=Us(w,"panels"),q=u.useMemo(()=>(F&&D!=null?F[D]:null)?.selected??[],[$,D]),L=u.useMemo(()=>(F&&D!=null?F[D]:null)?.path,[$,D]),[Y,G]=u.useState([]);u.useEffect(()=>{const le=l.current;if(!le)return;const ce=new ResizeObserver(Q=>{const be=Q[0]?.borderBoxSize?.[0]?.inlineSize;typeof be=="number"&&g(be<768)});return ce.observe(le),()=>{ce.disconnect()}},[]);const P=u.useCallback(()=>{x(le=>!le)},[]),K=u.useCallback(le=>{h&&Vu(le)!=="toggle-tree"&&x(!1)},[h]);u.useEffect(()=>{const le=c.current;if(le)return Hr(le,K).destroy},[K]),u.useEffect(()=>{const le=c.current;if(!le)return;const ce=new ResizeObserver(()=>{le&&m(le.clientWidth)});return ce.observe(le),le&&m(le.clientWidth),()=>{ce.disconnect()}},[]);const H=u.useMemo(()=>({icon:"wxi-eye",text:"Preview",id:"preview"}),[]),ye=u.useCallback(le=>{let ce=h?[H]:[];return le==="file"&&(ce=[...ce,...a().filter(Q=>Q.id==="download")]),ce},[h,H,a]),de=u.useRef(null),Z=u.useCallback((le,ce,Q)=>{const be=Q?[ce.id]:q;switch(le){case"download":w.exec("download-file",{id:ce.id});break;case"copy":case"move":de.current={action:le,ids:be};break;case"paste":de.current&&w.exec(de.current.action==="copy"?"copy-files":"move-files",{ids:de.current.ids,target:ce?.type==="folder"?ce.id:L});break;case"rename":A({item:ce});break;case"delete":j({selected:be});break;case"preview":w.exec("show-preview",{mode:!T});break}},[w,q,L,A,j,T]),z=u.useCallback(()=>F?.[D],[F,D]);u.useEffect(()=>{const le=l.current;if(!le)return;const ce=Sj(le,{api:w,menuOptions:n?ye:a,performAction:Z,getPanel:z});return()=>{typeof ce=="function"?ce():ce&&typeof ce.destroy=="function"&&ce.destroy()}},[w,n,ye,a,Z,z]);const se=u.useCallback((le,ce)=>{const Q=le?w.getFile(le):null,be=ce.target.closest(".tree-item.folder");let he;if(n)he=ye(Q?.type);else{switch(le){case"body":he=a(le);break;default:if(Q)if(!be&&q.length>1)he=h?[H,...a("multiselect")]:a("multiselect");else if(le==="/")he=a("folder",Q).filter(fe=>fe.id==="paste");else{const fe=a(Q.type,Q);fe&&(he=h?[H,...fe]:fe)}}M==="search"&&(he=he?.filter(fe=>fe.id!=="paste"))}if(Q?.id&&(!q.length||!q.some(fe=>fe===Q.id))&&!be&&w.exec("select-file",{id:Q.id}),he?.length)return he.forEach(fe=>{be&&(fe.hotkey=""),fe.text&&(fe.text=N(fe.text)),fe.hotkey&&(fe.subtext=fe.hotkey)}),G(he),Q||{}},[w,n,ye,a,q,h,H,M,N]),W=u.useCallback(le=>{const{action:ce,context:Q}=le;ce&&Z(ce.id,Q,!ce.hotkey)},[Z]);async function O(le){await Promise.resolve();const{name:ce,size:Q}=le.file;w.exec("create-file",{file:{name:ce,size:Q,date:new Date,file:le.file},parent:L})}return r.jsx("div",{className:"wx-RJbNonjJ wx-filemanager wx-flex",ref:l,"data-menu-ignore":"false",children:h&&T?r.jsx("div",{className:"wx-RJbNonjJ wx-info-narrow",children:r.jsx(Dh,{narrowMode:h,extraInfo:i})}):r.jsxs(r.Fragment,{children:[r.jsx(vM,{narrowMode:h,onShowTree:P}),r.jsx(zj,{dataKey:"id",at:"point",options:Y,resolver:se,onClick:W,children:r.jsxs(hw,{dataKey:"actionId",options:Y,resolver:se,onClick:W,children:[r.jsx(Bj,{data:b,apiOnly:!0,uploadURL:O}),r.jsx(qp.Provider,{value:b,children:r.jsx("div",{className:"wx-RJbNonjJ wx-content-wrapper wx-flex",children:M!=="panels"&&M!=="search"?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-RJbNonjJ "+["wx-sidebar",h?"wx-sidebar-narrow":"",y?"wx-sidebar-visible":""].filter(Boolean).join(" "),ref:c,children:r.jsx(pM,{readonly:n,menuOptions:a})}),r.jsxs("div",{className:"wx-RJbNonjJ wx-content",style:{width:`calc(100% - ${d||0}px - 10px)`},children:[r.jsx("div",{className:`wx-RJbNonjJ wx-content-item${T?"":"-fit"}`,"data-id":Jn("body"),children:M==="table"?r.jsx(gp,{panel:D}):r.jsx(yM,{})}),T?r.jsx("div",{className:"wx-RJbNonjJ wx-info",children:r.jsx(Dh,{extraInfo:i})}):null]})]}):r.jsxs(r.Fragment,{children:[r.jsx("div",{className:`wx-RJbNonjJ wx-content-item${T?"":"-fit"}`,children:M==="panels"?r.jsx(dM,{}):r.jsx(cM,{})}),T?r.jsx("div",{className:"wx-RJbNonjJ wx-info",children:r.jsx(Dh,{extraInfo:i})}):null]})})})]})})]})})}const xM=n=>n.split("-").map(a=>a?a.charAt(0).toUpperCase()+a.slice(1):"").join("");function wM(n,a){const{type:i,ext:l}=n;if(i==="folder")return!1;let c;return i&&i!=="file"&&kb[i]?c=i:l?c=kb[l]?l:"file":c="unknown",`https://cdn.svar.dev/icons/filemanager/vivid/${a}/${c}.svg`}const SM=u.forwardRef(function(n,a){const{data:i=[],mode:l="cards",drive:c=null,preview:d=!1,panels:m=null,activePanel:h=0,readonly:g=!1,menuOptions:y=bj,extraInfo:x=null,init:b=null,icons:w=wM,previews:A=null,...j}=n,k=u.useRef();k.current=j;const N=u.useMemo(()=>new yj(uw),[]),M=u.useMemo(()=>N.in,[N]),T=u.useRef(null);T.current===null&&(T.current=new sw(($,q)=>{const L="on"+xM($);k.current&&k.current[L]&&k.current[L](q)}),M.setNext(T.current));const D=u.useMemo(()=>({getState:N.getState.bind(N),getReactiveState:N.getReactive.bind(N),getStores:()=>({data:N}),exec:M.exec,setNext:$=>(T.current=T.current.setNext($),T.current),intercept:M.intercept.bind(M),on:M.on.bind(M),detach:M.detach.bind(M),getFile:N.getFile.bind(N),serialize:N.serialize.bind(N),templates:{preview:A||(()=>null),icon:w==="simple"?(()=>null):w}}),[N,M]),F=u.useRef(0);return u.useEffect(()=>{if(!F.current)b&&b(D);else{const $=N.getState();N.init({data:i,mode:l,drive:c,preview:d,panels:m||$.panels||[],activePanel:h})}F.current++},[N,i,l,c,d,m,h,b,D]),F.current===0&&N.init({data:i,mode:l,drive:c,preview:d,panels:m||[],activePanel:h}),u.useImperativeHandle(a,()=>({...D}),[D]),r.jsx(ea.Provider,{value:D,children:r.jsx(Fp,{words:$p,optional:!0,children:r.jsx(iM,{children:r.jsx(bM,{readonly:g,menuOptions:y,extraInfo:x})})})})});function CM({fonts:n=!0,children:a}){return a?r.jsx(cb,{fonts:n,children:a}):r.jsx(cb,{fonts:n})}Dp(ls);function Gp(n,a){if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`Invalid Hub ${a} response.`);return n}function Ku(n,a,i){const l=Gp(n,i);if(!Array.isArray(l[a]))throw new Error(`Invalid Hub ${i} response: ${a} must be an array.`);return l[a]}function kM(n,a,i){const l=Gp(n,i);if(!l[a]||typeof l[a]!="object"||Array.isArray(l[a]))throw new Error(`Invalid Hub ${i} response: ${a} must be an object.`);return l[a]}async function jM(n,a=!1){return Ku(await Ve(`/api/remote/filesystem/roots${a?"?refresh=1":""}`,void 0,n),"roots","filesystem roots")}async function Lh(n,a){const i=await Ve(`/api/remote/filesystem/entries?id=${encodeURIComponent(n)}`,void 0,a);return{folder:kM(i,"folder","filesystem entries"),entries:Ku(i,"entries","filesystem entries")}}async function AM(n,a){return Ve("/api/remote/filesystem/selection/scan",{method:"POST",body:JSON.stringify({itemIds:n})},a)}async function MM(n,a,i,l){return Ve("/api/remote/files/from-hub",{method:"POST",body:JSON.stringify({itemIds:n,deviceIds:a,remoteDirectory:i})},l)}async function NM(n,a=!1){const i=await Ve(`/api/remote/files/jobs?active=${a?"1":"0"}`,void 0,n);return{jobs:Ku(i,"jobs","file transfer jobs")}}async function TM(n,a){return Ve(`/api/remote/files/jobs/${encodeURIComponent(n)}`,void 0,a)}async function RM(n,a){return Ve(`/api/remote/files/jobs/${encodeURIComponent(n)}/cancel`,{method:"POST"},a)}async function jb(n){return Ku(await Ve("/api/remote/filesystem/shared-folders",void 0,n),"folders","shared folders")}async function EM(n,a){return Ve("/api/remote/filesystem/shared-folders",{method:"POST",body:JSON.stringify({sourceId:n})},a)}async function DM(n,a,i){return Ve(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)},i)}async function LM(n,a){return Ve(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}`,{method:"DELETE"},a)}async function _M(n,a,i,l){const c=await Ve(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}/sync`,{method:"POST",body:JSON.stringify({deviceIds:a,remoteDirectory:i})},l),d=Gp(c,"shared folder sync");return{ok:d.ok===!0,jobs:Ku(c,"jobs","shared folder sync"),files:Number(d.files||0),totalBytes:Number(d.totalBytes||0)}}function IM(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 Ab(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let i=n,l=0;for(;i>=1024&&l<a.length-1;)i/=1024,l+=1;return`${i.toFixed(l===0||i>=100?0:1)} ${a[l]}`}function Mf(n){return n.driveType==="network"?"network":n.driveType==="removable"?"removable":"local"}function zM(n){const a=n.filter(i=>Mf(i)==="local");return a.find(i=>/\bC:/i.test(`${i.name} ${i.displayPath||""}`))||a[0]||n[0]||null}function OM({hubUrl:n,roots:a,loading:i,error:l,onRefreshRoots:c,onImportFiles:d,onImportFolder:m,onSelectionChange:h,onShareItem:g,onAddSyncFolder:y,onNotice:x}){const b=u.useRef(null),w=u.useRef("/"),A=u.useRef(0),j=u.useRef([]),k=u.useRef(new Map),[N,M]=u.useState(null),[T,D]=u.useState([]),[F,$]=u.useState([]),[q,L]=u.useState(0),[Y,G]=u.useState(null),[P,K]=u.useState(!1),[H,ye]=u.useState(""),[de,Z]=u.useState(new Set),z=a.find(J=>J.id===N)||null,se=T[T.length-1]||null,W=z?se?.svarPath||`/${z.name}`:null,O=W;u.useEffect(()=>{j.current=T,w.current=O||"/"},[O,T]);const le=u.useMemo(()=>(k.current.clear(),!z||!O||T.length===0?[]:(T.forEach(J=>k.current.set(J.svarPath,J.hubId)),[...T.map((J,ke)=>({id:J.svarPath,parent:ke===0?"/":T[ke-1].svarPath,type:"folder",name:J.name,date:J.modifiedAt?new Date(J.modifiedAt):void 0,lazy:!1})),...F.map(J=>{const ke=`${O}/${J.name}`;return k.current.set(ke,J.id),{id:ke,parent:O,name:J.name,type:J.type==="file"?"file":"folder",...J.type==="file"?{size:J.size}:{},date:J.modifiedAt?new Date(J.modifiedAt):void 0,lazy:J.type!=="file"&&J.hasChildren===!0,displayPath:J.displayPath,locked:J.locked,driveType:J.driveType,totalBytes:J.totalBytes,freeBytes:J.freeBytes}})])),[z,F,O,T]),ce=J=>k.current.get(String(J))||String(J),Q=J=>IM({...J,id:ce(String(J.id)),parent:ce(String(J.parent))}),be=async(J,ke)=>{const Le=J[J.length-1];if(!Le)return;const Be=++A.current;K(!0),ye("");try{const _e=await Lh(Le.hubId,n);if(Be!==A.current)return;if(!Array.isArray(_e.entries))throw new Error("Invalid Hub filesystem entries response.");const Qe={...Le,displayPath:_e.folder.displayPath||Le.displayPath,modifiedAt:_e.folder.modifiedAt||Le.modifiedAt},Ye=[...J.slice(0,-1),Qe];j.current=Ye,D(Ye),$(_e.entries),L(Ze=>Ze+1)}catch(_e){if(Be!==A.current)return;console.error("[LiveDesk FS] folder navigation failed",{folderId:Le.hubId,error:_e}),ye(_e instanceof Error?`${ke}: ${_e.message}`:`${ke}: Unable to read this folder.`)}finally{Be===A.current&&K(!1)}},he=async J=>{const ke={svarPath:`/${J.name}`,hubId:J.id,name:J.name,displayPath:J.displayPath,modifiedAt:J.modifiedAt},Le=++A.current;M(J.id),j.current=[ke],D([ke]),w.current=ke.svarPath,$([]),ye(""),K(!0),G(J.id),Z(Be=>{const _e=new Set(Be);return _e.delete(J.id),_e});try{const Be=await Lh(J.id,n);if(Le!==A.current)return;if(!Array.isArray(Be.entries))throw new Error("Invalid Hub filesystem entries response.");const _e={...ke,displayPath:Be.folder.displayPath||ke.displayPath,modifiedAt:Be.folder.modifiedAt||ke.modifiedAt};j.current=[_e],D([_e]),$(Be.entries),L(Qe=>Qe+1)}catch(Be){if(Le!==A.current)return;console.error("[LiveDesk FS] getEntries failed",{rootId:J.id,error:Be}),Z(_e=>new Set(_e).add(J.id)),ye(Be instanceof Error?`${J.name}: ${Be.message}`:`${J.name}: Unable to read this drive.`),x(Be instanceof Error?`${J.name}: ${Be.message}`:`${J.name}: Unable to read this drive.`)}finally{Le===A.current&&(G(null),K(!1))}},fe=J=>{const ke=j.current;J<0||J>=ke.length||J===ke.length-1||be(ke.slice(0,J+1),ke[J].name)},ee=(J,ke)=>{if(J.type!=="folder")return;const Le=j.current,Be=Le.findIndex(Qe=>Qe.svarPath===ke);if(Be<0)return;const _e={svarPath:`${ke}/${J.name}`,hubId:J.id,name:J.name,displayPath:J.displayPath,modifiedAt:J.modifiedAt};be([...Le.slice(0,Be+1),_e],J.name)},Se=()=>fe(j.current.length-2),Ne=J=>{if(J.key!=="Enter"&&J.code!=="Enter"&&J.code!=="NumpadEnter"||J.target?.closest('button, input, textarea, [contenteditable="true"]'))return;const Le=b.current;if(!Le)return;const Be=Le.getState().panels?.flatMap(Qe=>Qe.selected||[])||[];if(Be.length!==1)return;const _e=Le.getFile(String(Be[0]));_e?.type==="folder"&&(J.preventDefault(),J.stopPropagation(),ee(Q(_e),String(_e.parent||w.current)))};u.useEffect(()=>{const J=a.find(ke=>ke.id===N)||zM(a);if(Z(ke=>new Set([...ke].filter(Le=>a.some(Be=>Be.id===Le)))),!J){M(null),j.current=[],D([]),$([]);return}he(J)},[a]);const Fe=J=>{b.current=J,J.on("request-data",async({id:ke})=>{const Le=String(ke),Be=ce(Le);try{const _e=await Lh(Be,n);if(!Array.isArray(_e.entries))throw new Error("Invalid Hub filesystem entries response.");const Qe=_e.entries.map(Ye=>{const Ze=`${Le}/${Ye.name}`;return k.current.set(Ze,Ye.id),{id:Ze,parent:Le,name:Ye.name,type:Ye.type==="file"?"file":"folder",...Ye.type==="file"?{size:Ye.size}:{},date:Ye.modifiedAt?new Date(Ye.modifiedAt):void 0,lazy:Ye.type!=="file"&&Ye.hasChildren===!0,displayPath:Ye.displayPath,locked:Ye.locked,driveType:Ye.driveType,totalBytes:Ye.totalBytes,freeBytes:Ye.freeBytes}});await J.exec("provide-data",{id:Le,data:Qe})}catch(_e){console.error("[LiveDesk FS] nested getEntries failed",{id:Be,error:_e}),x(_e instanceof Error?_e.message:"Unable to read this folder.")}}),J.intercept("set-path",({id:ke})=>{const Le=String(ke),Be=j.current.findIndex(Qe=>Qe.svarPath===Le);if(Be>=0)return fe(Be),!1;const _e=J.getFile(Le);if(_e?.type==="folder")return ee(Q(_e),String(_e.parent||w.current)),!1}),J.intercept("open-file",()=>!1),J.on("select-file",()=>{window.setTimeout(()=>{const Be=(J.getState().panels?.flatMap(_e=>_e.selected||[])||[]).map(_e=>J.getFile(_e)).filter(Boolean).map(_e=>Q(_e));h(Be.map(_e=>_e.id),Be)},0)})},ne=(J,ke)=>{const Le=ke?Q(ke):null,Be=()=>{const _e=Le?.type==="file"?String(ke?.parent||w.current):String(ke?.id||w.current);b.current?.exec("request-data",{id:_e})};return J==="body"?[{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Be},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>x("Select a file or folder to view its properties.")}]:J==="multiselect"?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>{(b.current?.getState().panels?.flatMap(Qe=>Qe.selected||[])||[]).forEach(Qe=>{const Ye=b.current?.getFile(Qe);Ye&&g(Q(Ye))})}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Be}]:Le?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>g(Le)},...Le.type==="folder"?[{id:"sync",text:"Add folder to Sync",icon:"mdi mdi-folder-sync-outline",handler:()=>y(Le)}]:[],{id:"copy-path",text:"Copy path",icon:"mdi mdi-content-copy",handler:()=>{Cf(Le.displayPath||Le.name)}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Be},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>x(`${Le.name}
14
+ ${Le.displayPath||""}`)}]:[]},Pe=async()=>{try{await c()}catch(J){x(J instanceof Error?J.message:"Unable to refresh Hub drives.")}},mt=[{id:"local",label:"Local drives",icon:co,roots:a.filter(J=>Mf(J)==="local")},{id:"removable",label:"Removable drives",icon:x0,roots:a.filter(J=>Mf(J)==="removable")},{id:"network",label:"Network drives",icon:jp,roots:a.filter(J=>Mf(J)==="network")}];return r.jsxs("section",{className:"hub-file-explorer-panel","aria-label":"Hub file explorer",children:[r.jsxs("div",{className:"hub-file-explorer-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Hub file explorer"}),r.jsxs("strong",{children:[r.jsx(co,{size:16})," Browse files on this Hub"]})]}),r.jsxs("div",{className:"hub-file-explorer-heading-actions",children:[r.jsx("button",{className:"icon-button",onClick:d,title:"Import files from this browser",type:"button",children:r.jsx(hx,{size:16})}),r.jsx("button",{className:"icon-button",onClick:m,title:"Import folder from this browser",type:"button",children:r.jsx(w0,{size:16})}),r.jsx("button",{className:"icon-button",onClick:()=>{Pe()},title:"Refresh drives",type:"button",children:r.jsx(Sc,{size:16})})]})]}),i?r.jsxs("div",{className:"hub-file-explorer-state",children:[r.jsx(co,{size:24}),r.jsx("strong",{children:"Connecting to LiveDesk Hub file system..."})]}):l?r.jsxs("div",{className:"hub-file-explorer-state error",role:"alert",children:[r.jsx(Ti,{size:24}),r.jsx("strong",{children:l})]}):r.jsxs("div",{className:"hub-file-explorer-content",children:[r.jsxs("aside",{className:"hub-file-explorer-drive-sidebar","aria-label":"Hub drives",children:[r.jsxs("div",{className:"hub-drive-sidebar-title",children:[r.jsx(co,{size:15}),r.jsx("strong",{children:"This PC"})]}),mt.map(J=>J.roots.length>0&&r.jsxs("section",{className:"hub-drive-group",children:[r.jsxs("h3",{children:[r.jsx(J.icon,{size:13}),J.label]}),r.jsx("div",{className:"hub-drive-list",children:J.roots.map(ke=>{const Le=J.icon,Be=de.has(ke.id)||ke.locked===!0;return r.jsxs("button",{className:`hub-drive-item ${N===ke.id?"active":""} ${Be?"unavailable":""}`,onClick:()=>{he(ke)},"aria-pressed":N===ke.id,type:"button",children:[r.jsx("span",{className:"hub-drive-item-icon",children:r.jsx(Le,{size:16})}),r.jsxs("span",{className:"hub-drive-item-copy",children:[r.jsx("strong",{children:ke.name}),r.jsx("small",{children:ke.displayPath||ke.name}),r.jsxs("em",{children:[Ab(ke.freeBytes||0)," free / ",Ab(ke.totalBytes||0)]})]}),Y===ke.id?r.jsx(Lr,{className:"hub-drive-item-status spin",size:15}):Be?r.jsx(hy,{className:"hub-drive-item-status",size:15}):null]},ke.id)})})]},J.id)),a.length===0&&r.jsxs("div",{className:"hub-drive-sidebar-empty",children:[r.jsx(Ti,{size:17}),r.jsx("span",{children:"No drives available."})]})]}),r.jsxs("div",{className:"hub-file-explorer-browser",children:[r.jsxs("div",{className:"hub-file-explorer-navigation",children:[r.jsx("nav",{className:"hub-file-explorer-breadcrumbs","aria-label":"Current Hub folder",children:T.map((J,ke)=>r.jsxs("span",{className:"hub-file-explorer-breadcrumb-item",children:[ke>0&&r.jsx(Ap,{size:13,"aria-hidden":"true"}),r.jsx("button",{className:`hub-file-explorer-breadcrumb ${ke===T.length-1?"current":""}`,onClick:()=>fe(ke),"aria-current":ke===T.length-1?"location":void 0,type:"button",children:J.name})]},J.svarPath))}),r.jsxs("div",{className:"hub-file-explorer-navigation-actions",children:[P&&r.jsx(Lr,{className:"hub-file-explorer-loading-icon spin",size:15,"aria-label":"Loading folder"}),r.jsx("button",{className:"icon-button",onClick:Se,disabled:T.length<=1||P,title:"Back to parent folder",type:"button",children:r.jsx(lx,{size:16})})]})]}),H&&r.jsxs("div",{className:"hub-file-explorer-folder-error",role:"alert",children:[r.jsx(hy,{size:15}),r.jsx("span",{children:H})]}),r.jsx("div",{className:"hub-file-explorer-svar",onKeyDownCapture:Ne,children:r.jsx(CM,{fonts:!1,children:r.jsx(SM,{data:le,panels:W?[{path:W,selected:[]}]:void 0,readonly:!0,mode:"table",preview:!1,init:Fe,icons:"simple",menuOptions:ne},`${z?.id||"no-root"}:${q}`)})})]})]})]})}class HM extends u.Component{state={error:null};static getDerivedStateFromError(a){return{error:a}}componentDidCatch(a,i){console.error("[LiveDesk] Share Files runtime error",a,i.componentStack)}render(){return this.state.error?r.jsxs("section",{className:"file-share-error-boundary",role:"alert",children:[r.jsx(Bf,{size:24}),r.jsx("strong",{children:"Share Files could not be opened."}),r.jsx("span",{children:this.state.error.message||"An unexpected file explorer error occurred."}),r.jsxs("button",{className:"text-button",onClick:this.props.onRetry,type:"button",children:[r.jsx(Sc,{size:15})," Retry"]})]}):this.props.children}}function FM(n){return n.deviceName||n.hostname||n.deviceId}function $M({devices:n,mode:a,selectedIds:i,onModeChange:l,onToggle:c}){const d=new Set(i);return r.jsxs("section",{className:"distribution-targets",children:[r.jsxs("div",{className:"file-share-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Target"}),r.jsx("strong",{children:a==="all"?`${n.length} connected`:`${i.length} selected`})]}),r.jsxs("div",{className:"file-share-tabs compact","aria-label":"File transfer targets",children:[r.jsxs("button",{className:a==="all"?"active":"",onClick:()=>l("all"),type:"button",children:[r.jsx(Pu,{size:14})," All connected"]}),r.jsxs("button",{className:a==="selected"?"active":"",onClick:()=>l("selected"),type:"button",children:[r.jsx(Ta,{size:14})," Selected"]})]})]}),r.jsx("div",{className:"file-share-device-list","aria-label":"Connected Client targets",children:n.length===0?r.jsx("div",{className:"file-share-empty-inline",children:"No connected Clients."}):n.map(m=>{const h=a==="all"||d.has(m.deviceId);return r.jsxs("label",{className:`file-share-device-option ${h?"selected":""}`,children:[r.jsx("input",{type:"checkbox",checked:h,disabled:a==="all",onChange:()=>c(m.deviceId)}),r.jsx(Ta,{size:20,"aria-hidden":"true"}),r.jsxs("span",{children:[r.jsx("strong",{children:FM(m)}),r.jsxs("small",{children:["Slot ",m.slotNumber?String(m.slotNumber).padStart(3,"0"):"-"," / ",m.platform||"unknown OS"]})]}),r.jsx(Xn,{size:17,"aria-hidden":"true"})]},m.deviceId)})})]})}function BM(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let i=n,l=0;for(;i>=1024&&l<a.length-1;)i/=1024,l+=1;return`${i.toFixed(l===0||i>=100?0:1)} ${a[l]}`}function PM({folders:n,loading:a,busy:i,canSync:l,onSyncAll:c,onSync:d,onToggleAuto:m,onRemove:h,onAdd:g}){return r.jsxs("section",{className:"file-share-sync-panel",children:[r.jsxs("div",{className:"file-share-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Hub folders"}),r.jsx("strong",{children:"Continuous sync"})]}),r.jsxs("button",{className:"text-button compact",onClick:c,disabled:i||!l||n.length===0,type:"button",children:[r.jsx(Sf,{size:15})," ",i?"Syncing":"Sync all"]})]}),a?r.jsx("div",{className:"file-share-empty-state",children:"Loading Hub sync folders..."}):n.length===0?r.jsxs("button",{className:"file-share-empty-state interactive",onClick:g,type:"button",children:[r.jsx(Sf,{size:28}),r.jsx("strong",{children:"Add a selected Hub folder"}),r.jsx("span",{children:"Hub keeps the manifest and can sync while this browser is closed."})]}):r.jsx("div",{className:"file-share-sync-list",children:n.map(y=>r.jsxs("article",{className:`file-share-sync-row state-${y.status}`,children:[r.jsx("div",{className:"file-share-sync-icon",children:r.jsx(Sf,{size:19})}),r.jsxs("div",{className:"file-share-sync-info",children:[r.jsx("strong",{children:y.name}),r.jsx("span",{children:y.displayPath}),r.jsxs("small",{children:[y.fileCount," files / ",BM(y.totalBytes)," · ",y.lastSyncedAt?`Last sync ${Cx(y.lastSyncedAt)} ago`:y.message||"Not synced yet"]})]}),r.jsxs("label",{className:"file-share-auto-sync",children:[r.jsx("input",{type:"checkbox",checked:y.autoSync,onChange:()=>m(y)}),r.jsx("span",{children:"Auto"})]}),r.jsxs("button",{className:"text-button compact",onClick:()=>d(y),disabled:i||!l||y.status==="syncing",type:"button",children:[r.jsx(Sc,{size:14})," Sync now"]}),r.jsx("button",{className:"icon-button",onClick:()=>h(y),title:"Remove sync folder",type:"button",children:r.jsx(Sp,{size:15})})]},y.id))})]})}function UM(n){const i=(n.targetMode==="all"?n.devices.map(l=>l.deviceId):n.selectedTargetIds).length>0;return r.jsxs("aside",{className:"file-share-distribution-panel",children:[r.jsxs("div",{className:"file-share-distribution-head",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Distribution"}),r.jsx("strong",{children:"Hub → Clients"})]}),r.jsx(Bu,{size:18})]}),r.jsxs("div",{className:"file-share-tabs",role:"tablist","aria-label":"Distribution mode",children:[r.jsx("button",{className:n.tab==="send"?"active":"",onClick:()=>n.onTabChange("send"),role:"tab","aria-selected":n.tab==="send",type:"button",children:"Send"}),r.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"?r.jsxs(r.Fragment,{children:[r.jsx($M,{devices:n.devices,mode:n.targetMode,selectedIds:n.selectedTargetIds,onModeChange:n.onTargetModeChange,onToggle:n.onTargetToggle}),r.jsxs("label",{className:"file-share-destination",children:[r.jsx("span",{children:"Destination folder"}),r.jsxs("div",{children:[r.jsx(gc,{size:15}),r.jsx("input",{value:n.remoteDirectory,onChange:l=>n.onRemoteDirectoryChange(l.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),r.jsx("small",{children:"Blank uses Desktop/LiveDeskFiles."})]}),r.jsxs("div",{className:"file-share-selection-summary",children:[r.jsx("span",{children:"Selected"}),r.jsx("strong",{children:n.selectedSummary})]}),r.jsxs("button",{className:"file-share-share-button",onClick:n.onShare,disabled:!n.canShare,type:"button",children:[r.jsx(Bu,{size:17})," Share selected"]}),r.jsxs("button",{className:"file-share-secondary-button",onClick:n.onAddSync,disabled:!n.canAddSync,type:"button",children:[r.jsx(gc,{size:16})," Add selected folder to Sync"]})]}):r.jsx(PM,{folders:n.folders,loading:n.foldersLoading,busy:n.syncBusy,canSync:i,onSyncAll:n.onSyncAll,onSync:n.onSync,onToggleAuto:n.onToggleAuto,onRemove:n.onRemove,onAdd:n.onAddFolder})]})}function qM(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let i=n,l=0;for(;i>=1024&&l<a.length-1;)i/=1024,l+=1;return`${i.toFixed(l===0||i>=100?0:1)} ${a[l]}`}function Mb(n){if(n.state==="completed")return 100;const a=n.totalBytes>0?Math.round(n.sentBytes/n.totalBytes*100):n.totalFiles>0?Math.round(n.completedFiles/n.totalFiles*100):0;return Math.max(0,Math.min(vp(n.state)?100:99,a))}function Nb(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} Client${n.targetCount===1?"":"s"}`:n.state==="partially-failed"?`${n.failedTargets.length} Client${n.failedTargets.length===1?"":"s"} failed`:n.state==="cancelled"?"Transfer cancelled":n.error||"Transfer failed"}function vp(n){return["completed","partially-failed","failed","cancelled"].includes(n)}function GM({hubUrl:n,devices:a,localFeatureAccess:i,upgradeNotice:l,remoteDirectory:c,onRemoteDirectoryChange:d,targetMode:m,selectedTargetIds:h,onTargetModeChange:g,onTargetToggle:y,filePickerRef:x,folderPickerRef:b,onBrowserFileImport:w,onBrowserFolderImport:A,onNotice:j,onTransferChange:k}){const N=Array.isArray(a)?a:[],[M,T]=u.useState([]),[D,F]=u.useState(!0),[$,q]=u.useState(""),[L,Y]=u.useState([]),[G,P]=u.useState([]),[K,H]=u.useState(null),[ye,de]=u.useState(!1),[Z,z]=u.useState([]),[se,W]=u.useState(!0),[O,le]=u.useState(!1),[ce,Q]=u.useState("send"),[be,he]=u.useState([]),fe=u.useRef(new Set),ee=u.useRef(!1),Se=u.useMemo(()=>m==="all"?N.map(U=>U.deviceId):h.filter(U=>N.some(ve=>ve.deviceId===U)),[N,h,m]),Ne=be.find(U=>!vp(U.state)),Fe=G.length===1&&G[0].type==="folder"?G[0]:null,ne=G.length===0?"Select files or folders from the Hub explorer.":ye?"Calculating selection size...":K?`${K.files} files, ${K.folders} folders · ${qM(K.totalBytes)}`:`${G.length} item${G.length===1?"":"s"} selected`,Pe=U=>{k({id:U.jobId,state:U.state,progress:Mb(U),message:Nb(U)})},mt=u.useCallback(async()=>{const U=await jM(n,!0);return T(U),q(""),U},[n]),J=async()=>{if(!ee.current){ee.current=!0;try{const ve=(await NM(n,!0)).jobs||[],je=await Promise.all([...fe.current].map(async it=>{try{return await TM(it,n)}catch{return null}})),$e=[...ve,...je.filter(Boolean)],dt=[...new Map($e.map(it=>[it.jobId,it])).values()];he(dt),dt.forEach(Pe),dt.filter(it=>vp(it.state)).forEach(it=>fe.current.delete(it.jobId))}catch{}finally{ee.current=!1}}};u.useEffect(()=>{let U=!0;F(!0),q(""),Promise.all([mt(),jb(n).then(je=>{U&&z(je)})]).catch(je=>{U&&(q(je instanceof Error?"Hub file system is unavailable. Make sure LiveDesk Hub is running on this computer.":"Hub file system is unavailable."),j(je instanceof Error?je.message:"Hub file system is unavailable."))}).finally(()=>{U&&(F(!1),W(!1))}),J();const ve=window.setInterval(()=>{J()},800);return()=>{U=!1,window.clearInterval(ve)}},[n,mt]),u.useEffect(()=>{if(L.length===0){H(null);return}let U=!1;return de(!0),AM(L,n).then(ve=>{U||H(ve)}).catch(ve=>{U||j(ve instanceof Error?ve.message:"Unable to calculate selected size.")}).finally(()=>{U||de(!1)}),()=>{U=!0}},[n,L.join("|")]);const ke=(U,ve)=>{Y(U),P(ve)},Le=U=>{U.forEach(ve=>fe.current.add(ve.jobId)),he(ve=>[...new Map([...ve,...U].map(je=>[je.jobId,je])).values()]),U.forEach(Pe)},Be=async()=>{if(!i){j(l);return}if(L.length===0){j("Select files or folders from the Hub explorer.");return}if(Se.length===0){j("Choose at least one connected Client.");return}if(Ne){j("A Hub transfer is already running.");return}try{const U=await MM(L,Se,c.trim(),n);fe.current.add(U.jobId),j("Hub transfer queued."),await J()}catch(U){j(U instanceof Error?U.message:"Unable to start Hub transfer.")}},_e=async U=>{const ve=U||Fe;if(!ve||ve.type!=="folder"){j("Select one folder to add it to Sync.");return}try{const je=await EM(ve.id,n);z($e=>[...$e.filter(dt=>dt.id!==je.folder.id),je.folder]),Q("sync"),j(`${ve.name} is ready for Hub sync.`)}catch(je){j(je instanceof Error?je.message:"Unable to add the Hub folder to Sync.")}},Qe=async U=>{if(Se.length===0){j("Choose at least one connected Client.");return}le(!0),z(ve=>ve.map(je=>je.id===U.id?{...je,status:"syncing"}:je));try{const ve=await _M(U.id,Se,c.trim(),n);Le(ve.jobs||[]),j(ve.jobs?.length?"Hub sync queued.":"No changed files to sync.");const je=await jb(n);z(je)}catch(ve){j(ve instanceof Error?ve.message:"Unable to sync the Hub folder."),z(je=>je.map($e=>$e.id===U.id?{...$e,status:"error",message:"Sync failed"}:$e))}finally{le(!1)}},Ye=async()=>{le(!0);try{for(const U of Z)await Qe(U)}finally{le(!1)}},Ze=async U=>{try{const ve=await DM(U.id,{autoSync:!U.autoSync},n);z(je=>je.map($e=>$e.id===U.id?ve.folder:$e))}catch(ve){j(ve instanceof Error?ve.message:"Unable to update auto sync.")}},ut=async U=>{try{await LM(U.id,n),z(ve=>ve.filter(je=>je.id!==U.id))}catch(ve){j(ve instanceof Error?ve.message:"Unable to remove the sync folder.")}};return r.jsxs("section",{className:"livedesk-file-explorer",children:[r.jsx("input",{ref:x,className:"hidden-file-input",type:"file",multiple:!0,onChange:U=>{U.currentTarget.files&&w(U.currentTarget.files),U.currentTarget.value=""}}),r.jsx("input",{ref:b,className:"hidden-file-input",type:"file",multiple:!0,webkitdirectory:"",directory:"",onChange:U=>{U.currentTarget.files&&A(U.currentTarget.files),U.currentTarget.value=""}}),r.jsx("div",{className:"file-share-workspace",children:r.jsxs(HM,{onRetry:()=>window.location.reload(),children:[r.jsx(OM,{hubUrl:n,roots:M,loading:D,error:$,onRefreshRoots:mt,onImportFiles:()=>x.current?.click(),onImportFolder:()=>b.current?.click(),onSelectionChange:ke,onShareItem:U=>{Y([U.id]),P([U]),Q("send")},onAddSyncFolder:U=>{Y([U.id]),P([U]),_e(U)},onNotice:j}),r.jsx(UM,{devices:N,targetMode:m,selectedTargetIds:h,onTargetModeChange:g,onTargetToggle:y,remoteDirectory:c,onRemoteDirectoryChange:d,selectedEntries:G,selectedSummary:ne,canShare:i&&!Ne&&L.length>0&&Se.length>0&&!ye,onShare:()=>{Be()},canAddSync:!!Fe,onAddSync:()=>{_e()},tab:ce,onTabChange:Q,folders:Z,foldersLoading:se,syncBusy:O,onSyncAll:()=>{Ye()},onSync:U=>{Qe(U)},onToggleAuto:U=>{Ze(U)},onRemove:U=>{ut(U)},onAddFolder:()=>{_e()}})]})}),Ne&&r.jsx("footer",{className:"file-share-workspace-footer",children:r.jsxs("span",{children:[Nb(Ne)," · ",Mb(Ne),"% ",r.jsx("button",{className:"icon-button",onClick:()=>{RM(Ne.jobId,n).then(U=>{he(ve=>ve.map(je=>je.jobId===U.jobId?U:je)),Pe(U)})},title:"Cancel transfer",type:"button",children:r.jsx(Na,{size:14})})]})})]})}const VM=u.forwardRef(function({value:a,onChange:i,onSubmit:l,onOpenSuggestedTasks:c,suggestedOpen:d=!1,suggestedTaskCount:m,disabled:h=!1,placeholder:g="Ask LiveDesk to work across your machines...",compact:y=!1},x){return r.jsxs("form",{className:"agents-composer",onSubmit:b=>{b.preventDefault(),l()},children:[r.jsx("button",{className:`agents-suggested-trigger ${d?"active":""}`,type:"button","aria-label":m===void 0?"Open Suggested tasks":`Open Suggested tasks (${m} available)`,"aria-expanded":d,onClick:c,disabled:h,children:r.jsx(S0,{size:17})}),r.jsx("textarea",{ref:x,value:a,onChange:b=>i(b.target.value.slice(0,4e3)),placeholder:g,"aria-label":"Ask LiveDesk",rows:y?1:2,disabled:h}),r.jsxs("button",{className:"agents-run-button",type:"submit",disabled:h||!a.trim(),children:[h?r.jsx(Lr,{className:"spin",size:16}):r.jsx(Bu,{size:16}),h?"Running":"Run"]})]})}),WM=["read","processControl","serviceControl","applicationControl","fileRead","fileWrite","fileDelete","shell","script","softwareInstall","network","systemPower","systemConfiguration","userAccount"];function Of(n){return n.deviceName?.trim()||n.hostname?.trim()||n.deviceId}function Hf(n){return n.connected!==!0?!1:n.synthetic===!0?!0:!n.channels||n.channels.control===!0}function YM(n){return n==="running"||n==="completed"||n==="failed"||n==="cancelled"?n:"queued"}function KM(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 QM(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:null}function vs(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function hf(n){const a=vs(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 XM(n){const a=vs(n);return a===null?"":`${Math.round((a<=1?a:a/100)*100)}%`}function ZM(n){return!n||/^(?:[\w .-]+ )?collected(?:\.)?$/i.test(n.trim())?"":n.trim()}function Ff(n,a){if(a.error)return a.error;const i=QM(a.data),l=ZM(a.result||"");if(!i)return l||a.stage||a.status;if(n==="system.health"){const c=typeof i.machine=="string"?i.machine:"",d=hf(i.freeMemoryBytes),m=hf(i.totalMemoryBytes),h=vs(i.totalMemoryBytes)&&vs(i.freeMemoryBytes)!==null?`${Math.round(vs(i.freeMemoryBytes)/vs(i.totalMemoryBytes)*100)}% RAM free`:"";return[c,d&&m?`RAM ${d}/${m}`:"",h,typeof i.platform=="string"?i.platform:""].filter(Boolean).join(" · ")||l||a.status}if(n==="disk.status"){const c=typeof i.root=="string"?i.root:"",d=hf(i.freeBytes),m=vs(i.totalBytes)&&vs(i.freeBytes)!==null?`${Math.round(vs(i.freeBytes)/vs(i.totalBytes)*100)}% free`:"";return[c,d&&`${d} free`,m].filter(Boolean).join(" · ")||l||a.status}if(n==="gpu.status"){const c=typeof i.name=="string"&&i.name?i.name:"No GPU provider",d=XM(i.usageRatio),m=vs(i.temperatureC)!==null?`${Math.round(vs(i.temperatureC))}°C`:"",h=hf(i.freeMemoryBytes);return[c,d&&`GPU ${d}`,m,h&&`${h} free`].filter(Boolean).join(" · ")||l||a.status}if(n==="process.list"){const c=vs(i.count);return c!==null?`${c} matching process${c===1?"":"es"}`:l||a.status}if(n==="network.status"){const c=Array.isArray(i.adapters)?i.adapters.length:null;return c!==null?`${c} active adapter${c===1?"":"s"}`:l||a.status}return l||a.stage||a.status}function Tb(n,a){const i=Ff(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||""} ${i}`)}function JM({state:n,operation:a}){const i=n.status==="completed"?Ir:n.status==="failed"||n.status==="cancelled"?Na:n.status==="running"?Lr:px,l=n.status==="running"?n.stage||"Working":n.status==="completed"?a?Ff(a,n):n.result||"Completed":n.status==="failed"?n.error||"Failed":n.status==="cancelled"?"Cancelled":"Queued";return r.jsxs("div",{className:`agent-target-row status-${n.status}`,"data-agent-target-id":n.deviceId,children:[r.jsx("span",{className:"agent-target-status","aria-hidden":"true",children:r.jsx(i,{size:15})}),r.jsx("strong",{children:n.deviceName}),r.jsx("span",{className:"agent-target-state",children:n.status[0].toUpperCase()+n.status.slice(1)}),r.jsx("small",{children:l})]})}function eN({operation:n,states:a,status:i,onCancel:l,onRetry:c,busy:d=!1}){const m=["running","queued"].includes(i),[h,g]=u.useState(!1),[y,x]=u.useState("all"),b=u.useMemo(()=>({total:a.length,completed:a.filter(D=>D.status==="completed").length,failed:a.filter(D=>D.status==="failed").length,running:a.filter(D=>D.status==="running").length,queued:a.filter(D=>D.status==="queued").length,cancelled:a.filter(D=>D.status==="cancelled").length}),[a]),w=a.filter(D=>Tb(n,D)),A=w.filter(D=>D.status==="completed").length,j=b.failed>0,k=w.length>0,N=a.filter(D=>y==="issues"?Tb(n,D):y==="running"?D.status==="running"||D.status==="queued":y==="completed"?D.status==="completed":y==="failed"?D.status==="failed":!0),M=k&&!m||i==="completed-with-failures"?"Completed with issues":i[0]?.toUpperCase()+i.slice(1),T=a.filter(D=>D.status==="completed").map(D=>Ff(n,D)).filter(Boolean).filter((D,F,$)=>$.indexOf(D)===F).slice(0,2);return r.jsxs("section",{className:"agent-task-block","aria-label":"Task execution",children:[r.jsxs("div",{className:"agent-task-head",children:[r.jsxs("div",{children:[r.jsx("span",{children:"LiveDesk Agent"}),r.jsx("strong",{children:KM(n)})]}),r.jsx("span",{className:`agent-task-status status-${k?"completed-with-failures":i}`,children:M})]}),r.jsxs("div",{className:"agent-task-summary","aria-label":"Task summary",children:[r.jsxs("strong",{children:[b.total," targets"]}),r.jsxs("span",{className:"summary-completed",children:[b.completed," completed"]}),b.running>0&&r.jsxs("span",{className:"summary-running",children:[b.running," running"]}),b.queued>0&&r.jsxs("span",{children:[b.queued," queued"]}),j&&r.jsxs("span",{className:"summary-failed",children:[b.failed," failed"]}),A>0&&r.jsxs("span",{className:"summary-cancelled",children:[A," warning"]}),b.cancelled>0&&r.jsxs("span",{className:"summary-cancelled",children:[b.cancelled," cancelled"]})]}),T.length>0&&r.jsxs("div",{className:"agent-task-result-preview",title:T.join(" · "),children:[r.jsx("span",{children:"Result"}),T.join(" · ")]}),r.jsx("div",{className:"agent-target-chips","aria-label":"Target status overview",children:a.map((D,F)=>{const $=D.status==="completed"?"✓":D.status==="failed"?"×":D.status==="cancelled"?"!":D.status==="running"?"…":"·";return r.jsxs("span",{className:`agent-target-chip status-${D.status}`,title:`${D.deviceName}: ${Ff(n,D)}`,"aria-label":`${F+1}. ${D.deviceName}: ${D.status}`,children:[r.jsx("b",{children:String(F+1).padStart(2,"0")}),r.jsx("span",{children:$})]},D.deviceId)})}),a.length>0&&r.jsx("div",{className:"agent-task-details-toggle",children:r.jsxs("button",{type:"button",onClick:()=>g(D=>!D),"aria-expanded":h,children:[h?r.jsx(C0,{size:14}):r.jsx(gx,{size:14}),h?"Hide details":"Show details"]})}),h&&r.jsxs("div",{className:"agent-task-details",children:[r.jsx("div",{className:"agent-task-filters",role:"tablist","aria-label":"Task result filter",children:["all","issues","running","completed","failed"].map(D=>r.jsx("button",{className:y===D?"active":"",onClick:()=>x(D),role:"tab","aria-selected":y===D,type:"button",children:D==="all"?"All":D==="issues"?"Issues only":D[0].toUpperCase()+D.slice(1)},D))}),r.jsx("div",{className:"agent-task-rows",children:N.length>0?N.map(D=>r.jsx(JM,{operation:n,state:D},D.deviceId)):r.jsx("small",{className:"agent-task-no-results",children:"No targets match this filter."})})]}),(m||j)&&r.jsxs("div",{className:"agent-task-actions",children:[m&&l&&r.jsxs("button",{onClick:l,disabled:d,type:"button",children:[r.jsx(k0,{size:14})," Cancel"]}),!m&&j&&c&&r.jsxs("button",{onClick:c,disabled:d,type:"button",children:[r.jsx(Cp,{size:14})," Retry failed"]})]})]})}function tN(n){try{return JSON.stringify(n,null,2).slice(0,6e3)}catch{return"{}"}}function nN({approval:n,busy:a=!1,onApprove:i,onReject:l}){return r.jsxs("article",{className:"agent-approval-card","aria-label":"Agent approval required",children:[r.jsxs("div",{className:"agent-approval-head",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Approval required"}),r.jsx("strong",{children:n.toolName})]}),r.jsx("span",{className:`agent-approval-risk risk-${n.risk}`,children:n.risk})]}),r.jsx("p",{children:n.description}),r.jsx("pre",{children:tN(n.arguments)}),r.jsxs("small",{children:["Permission: ",n.permissionMode," · Scope: selected devices only · Expires in 5 minutes"]}),r.jsxs("div",{className:"agent-approval-actions",children:[r.jsxs("button",{className:"reject",disabled:a,onClick:l,type:"button",children:[r.jsx(Na,{size:14})," Reject"]}),r.jsxs("button",{disabled:a,onClick:()=>i("once"),type:"button",children:[r.jsx(Ir,{size:14})," Once"]}),r.jsx("button",{disabled:a,onClick:()=>i("same-action-this-run"),type:"button",children:"Allow same action"}),r.jsx("button",{disabled:a,onClick:()=>i("category-this-run"),type:"button",children:"Allow category"})]}),r.jsxs("div",{className:"agent-approval-scope",children:[r.jsx(Bf,{size:13})," Approval is bound to this run, tool, arguments, selected devices, and policy hash."]})]})}function aN(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 sN({items:n,onCancel:a,onRetry:i,busyBatchId:l,approvals:c,onApprove:d,onReject:m,busyApprovalId:h,progress:g,emptyTitle:y="Ask LiveDesk to work across your machines.",emptyBody:x="Start with a read-only request such as “모든 PC에서 ComfyUI가 실행 중인지 확인해줘”."}){const b=u.useRef(null),w=u.useRef(!0),A=u.useRef(""),j=n[n.length-1];return u.useLayoutEffect(()=>{const k=b.current;k&&(j?.type==="user"&&j.id!==A.current&&(w.current=!0),A.current=j?.id||"",w.current&&(k.scrollTop=k.scrollHeight))},[c,n,j?.id,j?.type,g?.message,g?.stage]),r.jsxs("section",{className:"agents-conversation","aria-live":"polite",ref:b,onScroll:k=>{const N=k.currentTarget;w.current=N.scrollHeight-N.scrollTop-N.clientHeight<72},children:[c.filter(k=>k.status==="pending").map(k=>r.jsx(nN,{approval:k,busy:h===k.approvalId,onApprove:N=>d(k,N),onReject:()=>m(k)},k.approvalId)),n.length===0&&r.jsxs("div",{className:"agents-empty-conversation",children:[r.jsx("strong",{children:y}),r.jsx("span",{children:x})]}),n.map(k=>{if(k.type==="task"){const N=k;return r.jsx(eN,{operation:N.operation,states:N.states,status:N.status,onCancel:()=>a(N.batchId,N.agentRunId),onRetry:()=>i(N.batchId),busy:l===N.batchId},N.id)}return r.jsxs("article",{className:`agents-message ${k.type}`,children:[r.jsx("span",{children:k.type==="user"?"You":"LiveDesk Agent"}),r.jsx("p",{children:k.text})]},k.id)}),g&&r.jsxs("article",{className:"agents-message agent agents-progress-message",role:"status",children:[r.jsxs("span",{children:[r.jsx(Lr,{"aria-hidden":"true",size:15}),aN(g.stage)]}),r.jsx("p",{children:g.message})]})]})}const Rb=["Recommended","Health & capacity","Processes & services","AI workloads","Files & configuration","Software & automation","Network & connectivity","Power & maintenance","Troubleshooting & recovery"],An=["windows","macos","linux"],gl={"system.health":{label:"system health",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:An},"gpu.status":{label:"GPU status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:An},"disk.status":{label:"disk status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:An},"process.list":{label:"process inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:An},"service.status":{label:"service inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:An},"diagnostics.collect":{label:"diagnostics collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:An},"process.control":{label:"process control",permissionCategory:"processControl",readOnly:!1,risk:"high",supportedPlatforms:An},"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:An},"application.close":{label:"application close",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:An},"file.read":{label:"file reading",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:An},"file.write":{label:"file writing",permissionCategory:"fileWrite",readOnly:!1,risk:"high",supportedPlatforms:An},"file.delete":{label:"file deletion",permissionCategory:"fileDelete",readOnly:!1,risk:"critical",supportedPlatforms:An},"file.list":{label:"directory listing",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:An},"command.run":{label:"command execution",permissionCategory:"shell",readOnly:!1,risk:"critical",supportedPlatforms:An},"script.run":{label:"script execution",permissionCategory:"script",readOnly:!1,risk:"high",supportedPlatforms:An},"software.install":{label:"software installation",permissionCategory:"softwareInstall",readOnly:!1,risk:"high",supportedPlatforms:An},"network.status":{label:"network inspection",permissionCategory:"network",readOnly:!0,risk:"low",supportedPlatforms:An},"system.power":{label:"power control",permissionCategory:"systemPower",readOnly:!1,risk:"critical",supportedPlatforms:An},"system.configure":{label:"system configuration",permissionCategory:"systemConfiguration",readOnly:!1,risk:"critical",supportedPlatforms:An},"logs.collect":{label:"log collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:An}};new Set(Object.keys(gl));const rN={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","문제해결","복구","장애"]},Eb=["low","medium","high","critical"];function iN(n){return n.reduce((a,i)=>{const l=gl[i].risk;return Eb.indexOf(l)>Eb.indexOf(a)?l:a},"low")}function lN(n){return An.filter(a=>n.every(i=>gl[i].supportedPlatforms.includes(a)))}function Ge(n,a,i,l,c,d,m={}){const h=m.description||l,g=c.flatMap(x=>x.split(".")),y=[...new Set([...rN[a],...d,...g])];return{id:n,category:a,title:i,prompt:l,description:h,requiredOperations:c,risk:m.risk||iN(c),targetSupport:m.targetSupport||"single-or-multiple",supportedPlatforms:m.supportedPlatforms||lN(c),keywords:y,recommended:m.recommended??!1,enabled:!0}}const Tw=[Ge("recommended-fleet-health","Recommended","Summarize current target health","Summarize system health, GPU, and disk capacity for the current target Clients.",["system.health","gpu.status","disk.status"],["summary","overview"],{recommended:!0}),Ge("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}),Ge("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}),Ge("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}),Ge("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}),Ge("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}),Ge("recommended-recover-ai","Recommended","Recover stopped AI workers","Find stopped AI workers and relaunch the registered worker application or service on the target Client.",["process.list","application.launch","service.control"],["recover","start","ai worker"],{targetSupport:"single",recommended:!0}),Ge("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}),Ge("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","높은 사용량"]),Ge("health-uptime","Health & capacity","Review Client uptime","Show uptime, boot time, and current system health for the target Clients.",["system.health"],["uptime","boot","가동시간"]),Ge("health-gpu-temperature","Health & capacity","Check GPU temperature","Check GPU temperature and thermal warnings on the current targets.",["gpu.status"],["thermal","temperature","발열"]),Ge("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"]),Ge("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","디스크"]),Ge("health-gpu-compare","Health & capacity","Compare GPU capacity","Compare GPU model, memory, temperature, and utilization across the current targets.",["gpu.status"],["compare","graphics","capacity"]),Ge("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","경고"]),Ge("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"]),Ge("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","실행 중"]),Ge("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"]),Ge("process-stop-named","Processes & services","Stop a named process","Stop process named [process name] on the target Client after checking its current state.",["process.list","process.control"],["stop","terminate","종료"],{targetSupport:"single"}),Ge("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"}),Ge("process-launch-app","Processes & services","Launch a registered application","Launch the registered application [application] on the target Client with [arguments].",["application.launch"],["launch","open","실행"],{targetSupport:"single"}),Ge("process-close-app","Processes & services","Close an application","Close application [application] on the target Client and report whether it exited cleanly.",["application.close","process.list"],["close","exit","앱 종료"],{targetSupport:"single"}),Ge("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","서비스 상태"]),Ge("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"}),Ge("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"]),Ge("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"}),Ge("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"}),Ge("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"]),Ge("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"]),Ge("ai-worker-logs","AI workloads","Collect AI worker logs","Collect recent logs and relevant log files for the AI worker on the target Client.",["logs.collect","file.list","file.read"],["logs","diagnostics","worker"],{targetSupport:"single"}),Ge("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"]),Ge("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"}),Ge("files-list-directory","Files & configuration","List a directory","List files and folders under [path] on the target Client.",["file.list"],["directory","folder","list","목록"],{targetSupport:"single"}),Ge("files-read-config","Files & configuration","Read a configuration file","Read the relevant settings from configuration file [path] on the target Client.",["file.read"],["config","settings","read","구성"]),Ge("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"]),Ge("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"}),Ge("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"}),Ge("files-compare-config","Files & configuration","Compare configuration files","Read configuration file [path] on the target Client and compare it with [reference path].",["file.read"],["compare","diff","configuration"]),Ge("files-set-environment","Files & configuration","Set an environment variable","Set environment variable [name] to [value] for the target Client and verify the resulting configuration.",["system.configure","file.read"],["environment","variable","env","환경변수"],{targetSupport:"single"}),Ge("files-archive-diagnostics","Files & configuration","Write a diagnostic manifest","Collect selected diagnostics and write a manifest file to [path] on the target Client.",["diagnostics.collect","file.write"],["manifest","export","diagnostic file"],{targetSupport:"single"}),Ge("software-winget-install","Software & automation","Install software with winget","Install package [package name] with winget on the Windows target Client, then verify it.",["software.install","process.list"],["winget","windows","install","설치"],{targetSupport:"single",supportedPlatforms:["windows"]}),Ge("software-apt-install","Software & automation","Install software with apt","Install package [package name] with apt on the Linux target Client, then verify it.",["software.install","process.list"],["apt","linux","package","설치"],{targetSupport:"single",supportedPlatforms:["linux"]}),Ge("software-brew-install","Software & automation","Install software with Homebrew","Install package [package name] with brew on the macOS target Client, then verify it.",["software.install","process.list"],["brew","homebrew","macos","설치"],{targetSupport:"single",supportedPlatforms:["macos"]}),Ge("software-npm-install","Software & automation","Install an npm package","Install npm package [package name] on the target Client and verify the installed version.",["software.install","command.run"],["npm","node","package"],{targetSupport:"single"}),Ge("software-run-script","Software & automation","Run a registered script","Run the registered script [script path] on the target Client and report its result.",["script.run"],["script","automation","registered"],{targetSupport:"single"}),Ge("software-run-command","Software & automation","Run a command on one target","Run command [command] on the target Client and return its exit status and output.",["command.run"],["command","shell","terminal"],{targetSupport:"single"}),Ge("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"]),Ge("software-toolchain-setup","Software & automation","Set up a toolchain","Install the requested package [package name], configure [change], and verify the toolchain on the target Client.",["software.install","system.configure","process.list"],["toolchain","setup","developer"],{targetSupport:"single"}),Ge("network-adapter-status","Network & connectivity","Check network adapters","Show adapter state, address, and link information for the current targets.",["network.status"],["adapter","ethernet","wifi","네트워크 상태"]),Ge("network-disconnected","Network & connectivity","Find disconnected targets","Find current targets with disconnected or degraded network adapters.",["network.status"],["disconnected","offline","연결 끊김"]),Ge("network-link-speed","Network & connectivity","Check link speed","Report network link speed and duplex information for the current targets.",["network.status"],["speed","bandwidth","duplex"]),Ge("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"]),Ge("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"]),Ge("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"]),Ge("network-compare","Network & connectivity","Compare target connectivity","Compare adapter state, addresses, and link speed across the current targets.",["network.status"],["compare","inventory","connectivity"]),Ge("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"]),Ge("power-lock","Power & maintenance","Lock the Client","Lock the target Client and report the resulting power action status.",["system.power"],["lock","security","잠금"],{targetSupport:"single",risk:"critical"}),Ge("power-logoff","Power & maintenance","Log off the Client","Log off the target Client after warning that interactive sessions will close.",["system.power"],["logoff","session","로그오프"],{targetSupport:"single",risk:"critical"}),Ge("power-sleep","Power & maintenance","Put the Client to sleep","Put the target Client to sleep after confirming the requested delay of [delay].",["system.power"],["sleep","suspend","절전"],{targetSupport:"single",risk:"critical"}),Ge("power-restart","Power & maintenance","Restart the Client","Restart the target Client after confirming that active work may be interrupted.",["system.power"],["restart","reboot","재부팅"],{targetSupport:"single",risk:"critical"}),Ge("power-shutdown","Power & maintenance","Shut down the Client","Shut down the target Client after confirming that active work may be interrupted.",["system.power"],["shutdown","power off","종료"],{targetSupport:"single",risk:"critical"}),Ge("power-maintenance-restart","Power & maintenance","Restart after maintenance","Check the target Client, restart it after maintenance, and verify that it returns online.",["system.health","system.power","network.status"],["maintenance","reboot","verify"],{targetSupport:"single",risk:"critical"}),Ge("power-timezone","Power & maintenance","Set the Client timezone","Set the target Client timezone to [timezone] and verify the resulting system configuration.",["system.configure"],["timezone","clock","시간대"],{targetSupport:"single",risk:"critical"}),Ge("power-persistent-environment","Power & maintenance","Persist an environment variable","Persist environment variable [name] with value [value] for the target Client and verify it.",["system.configure"],["environment","persistent","환경변수"],{targetSupport:"single",risk:"critical"}),Ge("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"}),Ge("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"}),Ge("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"}),Ge("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"}),Ge("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"}),Ge("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"}),Ge("recovery-network-instability","Troubleshooting & recovery","Recover network instability","Collect network diagnostics, inspect network services, and report the safest recovery action for the target Client.",["network.status","service.status","diagnostics.collect"],["network","unstable","네트워크 복구"],{targetSupport:"single"}),Ge("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","장애 보고서"])],_h={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 oN(n,a){return n==="safe-auto"?_h:n==="full-access"?{..._h,processControl:"allow",serviceControl:"allow",applicationControl:"allow",fileDelete:"allow",shell:"allow",script:"allow",softwareInstall:"allow",systemPower:"allow",systemConfiguration:"allow"}:n==="custom"&&a?a:{..._h,processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileWrite:"ask",network:"ask"}}function cN(n,a,i){const l=oN(a,i),c=n.requiredOperations.map(d=>l[gl[d].permissionCategory]);if(c.includes("deny")){const d=n.requiredOperations.find(m=>l[gl[m].permissionCategory]==="deny");return{state:"blocked",label:"Blocked",reason:`This task requires ${gl[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 Client."}:n.requiredOperations.every(d=>gl[d].readOnly)?{state:"read-only",label:"Read only"}:a==="full-access"?{state:"full-access",label:"Full Access"}:{state:"auto",label:"Auto allowed"}}function uN(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 dN(n,a,i){const l=new Set(i);return n.filter(c=>c.connected&&(a==="all"||a==="auto"||l.has(c.deviceId)))}function fN(n,a){const i=uN(n.platform);if(!i||!a.supportedPlatforms.includes(i))return!1;const l=n.capabilities?.agentTools;return!Array.isArray(l)||l.length===0?a.requiredOperations.every(c=>gl[c].readOnly):a.requiredOperations.every(c=>l.includes(c))}function Rw(n,a,i,l,c,d){const m=cN(n,c,d),h=dN(a,i,l),g=h.map(A=>A.deviceId),y={...m,available:!1,availableDeviceIds:[],unsupportedDeviceIds:g,risk:n.risk,supportedPlatforms:n.supportedPlatforms};if(h.length===0)return{...y,reason:"Select at least one connected Client."};if(n.targetSupport==="single"&&h.length!==1)return{...y,reason:"This task supports one Client at a time."};if(m.state==="blocked")return y;const x=h.filter(A=>fN(A,n)),b=x.map(A=>A.deviceId),w=g.filter(A=>!b.includes(A));return x.length===0?{...y,unsupportedDeviceIds:w,reason:"No current target supports the required platform and client capabilities."}:{...y,available:!0,availableDeviceIds:b,unsupportedDeviceIds:w}}function mN(n,a,i,l,c,d){return n.filter(m=>m.enabled&&Rw(m,a,i,l,c,d).available).length}const Ih="livedesk.agentPromptRecent",zh="livedesk.agentPromptFavorites",hN={Recommended:yl,"Health & capacity":ho,"Processes & services":N0,"AI workloads":Yh,"Files & configuration":M0,"Software & automation":mx,"Network & connectivity":jp,"Power & maintenance":Vn,"Troubleshooting & recovery":A0};function Db(n){if(typeof window>"u")return[];try{const a=JSON.parse(window.localStorage.getItem(n)||"[]");return Array.isArray(a)?a.filter(i=>typeof i=="string"):[]}catch{return[]}}function pf(n,a){try{window.localStorage.setItem(n,JSON.stringify(a))}catch{}}function Oh(n){return n==="all"?"All tasks":n==="recent"?"Recent":n==="favorites"?"Favorites":n==="read-only"?"Read only":n==="auto"?"Auto allowed":n==="approval"?"Approval required":n==="full-access"?"Full Access":n==="available"?"Available":n==="unavailable"?"Unavailable":n}function pN(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 gN(n,a,i){if(!i.trim())return!0;const l=i.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 vN(n){return`permission-${n}`}function yN(n){return n==="low"?"Low risk":n==="medium"?"Medium risk":n==="high"?"High risk":"Critical risk"}function bN(n){return n==="windows"?"Windows":n==="macos"?"macOS":"Linux"}function xN({devices:n,targetMode:a,selectedIds:i,permissionMode:l,customCategories:c,onSelectPrompt:d,onClose:m}){const[h,g]=u.useState(""),[y,x]=u.useState("all"),[b,w]=u.useState(()=>Db(Ih)),[A,j]=u.useState(()=>Db(zh)),[k,N]=u.useState(0),[M,T]=u.useState(""),D=u.useRef(null),F=u.useRef(null),$=u.useMemo(()=>Tw.filter(Z=>Z.enabled),[]),q=u.useMemo(()=>new Map($.map(Z=>[Z.id,Rw(Z,n,a,i,l,c)])),[c,n,l,i,a,$]),L=u.useMemo(()=>[...q.values()].filter(Z=>Z.available).length,[q]),Y=u.useMemo(()=>n.filter(Z=>Z.connected&&(a==="all"||a==="auto"||i.includes(Z.deviceId))).length,[n,i,a]),G=u.useMemo(()=>{const Z=$.filter(z=>gN(z,q.get(z.id),h));return y==="recent"?b.map(z=>Z.find(se=>se.id===z)).filter(z=>!!z):y==="favorites"?A.map(z=>Z.find(se=>se.id===z)).filter(z=>!!z):y==="all"?Z:Z.filter(z=>{const se=q.get(z.id);return y==="read-only"?se.state==="read-only":y==="auto"?se.state==="auto":y==="approval"?se.state==="approval":y==="full-access"?se.state==="full-access":y==="available"?se.available:y==="unavailable"?!se.available:z.category===y})},[q,A,y,b,h,$]),P=u.useMemo(()=>y!=="all"?[{category:Oh(y),templates:G}]:Rb.map(Z=>({category:Z,templates:G.filter(z=>z.category===Z)})).filter(Z=>Z.templates.length>0),[y,G]);u.useEffect(()=>{N(Z=>Math.min(Z,Math.max(0,G.length-1)))},[G.length]),u.useEffect(()=>{pf(Ih,b)},[b]),u.useEffect(()=>{pf(zh,A)},[A]),u.useEffect(()=>{F.current?.focus();const Z=se=>{se.target instanceof Node&&!D.current?.contains(se.target)&&m()},z=se=>{se.key==="Escape"&&(se.preventDefault(),m())};return document.addEventListener("pointerdown",Z),document.addEventListener("keydown",z),()=>{document.removeEventListener("pointerdown",Z),document.removeEventListener("keydown",z)}},[m]);const K=Z=>{const z=q.get(Z.id);if(!z.available){T(z.reason||"This task is not available for the current targets and permission policy.");return}const se=[Z.id,...b.filter(W=>W!==Z.id)].slice(0,10);w(se),pf(Ih,se),d(Z.prompt),m()},H=Z=>{j(z=>{const se=z.includes(Z)?z.filter(W=>W!==Z):[Z,...z];return pf(zh,se),se})},ye=Z=>{Z.key==="ArrowDown"?(Z.preventDefault(),N(z=>Math.min(z+1,Math.max(0,G.length-1)))):Z.key==="ArrowUp"?(Z.preventDefault(),N(z=>Math.max(z-1,0))):Z.key==="Enter"&&G[k]&&(Z.preventDefault(),K(G[k]))};let de=-1;return r.jsxs("section",{className:"agents-suggested-tasks",ref:D,"aria-label":"Suggested tasks",children:[r.jsxs("header",{className:"agents-suggested-header",children:[r.jsxs("div",{children:[r.jsxs("span",{className:"agents-suggested-title",children:[r.jsx(yl,{size:15})," Suggested tasks"]}),r.jsxs("small",{children:[L," available · ",$.length," total. Choose a task, edit it, then run it."]})]}),r.jsx("button",{className:"agents-suggested-close",type:"button","aria-label":"Close suggested tasks",onClick:m,children:r.jsx(Na,{size:16})})]}),r.jsxs("label",{className:"agents-suggested-search",children:[r.jsx(j0,{size:15,"aria-hidden":"true"}),r.jsx("input",{ref:F,value:h,onChange:Z=>g(Z.target.value),onKeyDown:ye,placeholder:"Search tasks...","aria-label":"Search suggested tasks"})]}),r.jsx("div",{className:"agents-suggested-filters","aria-label":"Task categories and availability filters",children:["all","recent","favorites","read-only","auto","approval","full-access","available","unavailable",...Rb].map(Z=>{const z=Z==="recent"?dx:Z==="favorites"?Qh:Z==="all"?yl:Z==="available"?Xn:Z==="unavailable"?vx:Z==="read-only"||Z==="auto"||Z==="approval"||Z==="full-access"?Vn:hN[Z];return r.jsxs("button",{className:y===Z?"active":"",type:"button",title:Oh(Z),"aria-label":Oh(Z),"aria-pressed":y===Z,onClick:()=>{x(Z),N(0),T("")},children:[r.jsx(z,{size:12})," ",pN(Z)]},Z)})}),M&&r.jsx("div",{className:"agents-suggested-notice",role:"status",children:M}),r.jsxs("div",{className:"agents-suggested-list",role:"listbox","aria-label":"Suggested tasks",children:[P.map(Z=>r.jsxs("div",{className:"agents-suggested-group",children:[r.jsx("strong",{children:Z.category}),Z.templates.map(z=>{de+=1;const se=de===k,W=A.includes(z.id),O=q.get(z.id),le=O.availableDeviceIds.length+O.unsupportedDeviceIds.length||Y,ce=O.available?`Available on ${O.availableDeviceIds.length} of ${le} target${le===1?"":"s"}`:`Unavailable: ${O.reason||"not supported by the current targets"}`;return r.jsxs("div",{className:`agents-suggested-item ${se?"active":""} ${O.available?"":"unavailable"}`,children:[r.jsxs("button",{className:"agents-suggested-prompt",type:"button",role:"option","aria-selected":se,"aria-disabled":!O.available,onClick:()=>K(z),children:[r.jsx("span",{children:z.title}),r.jsx("small",{className:"agents-suggested-description",children:z.description}),r.jsxs("span",{className:"agents-suggested-meta",children:[r.jsx("em",{children:z.category}),r.jsx("em",{className:vN(O.state),children:O.label}),r.jsx("em",{className:`risk-${z.risk}`,children:yN(z.risk)}),r.jsx("em",{children:z.supportedPlatforms.map(bN).join(" · ")}),r.jsx("em",{className:O.available?"availability-ok":"availability-unavailable",children:ce}),O.available&&O.unsupportedDeviceIds.length>0&&r.jsxs("em",{className:"availability-warning",children:["Unsupported on ",O.unsupportedDeviceIds.length]})]})]}),r.jsx("button",{className:`agents-suggested-favorite ${W?"favorite":""}`,type:"button","aria-label":W?`Remove ${z.title} from favorites`:`Add ${z.title} to favorites`,"aria-pressed":W,onClick:()=>H(z.id),children:r.jsx(Qh,{size:14,fill:W?"currentColor":"none"})})]},z.id)})]},Z.category)),G.length===0&&r.jsx("p",{className:"agents-suggested-empty",children:"No tasks match this search or current filter."})]})]})}function wN({devices:n,mode:a,selectedIds:i,onModeChange:l,onToggle:c,permissionMode:d,onPermissionModeChange:m}){const h=n.filter(Hf),g=i.filter(y=>h.some(x=>x.deviceId===y)).length;return r.jsxs("section",{className:"agents-target-picker","aria-label":"Agent targets",children:[r.jsxs("div",{className:"agents-target-toolbar",children:[r.jsx("span",{className:"agents-section-label",children:"Targets"}),r.jsxs("div",{className:"agents-target-modes",children:[r.jsxs("button",{className:a==="all"?"active":"",onClick:()=>l("all"),type:"button",children:[r.jsx(Pu,{size:14})," All connected ",r.jsx("small",{children:h.length})]}),r.jsxs("button",{className:a==="selected"?"active":"",onClick:()=>l("selected"),type:"button",children:[r.jsx(Ir,{size:14})," Selected ",g]}),r.jsxs("button",{className:a==="auto"?"active":"",onClick:()=>l("auto"),type:"button",children:[r.jsx(yl,{size:14})," Auto"]}),r.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[r.jsx(Pu,{size:14})," Group ",r.jsx("small",{children:"Soon"})]})]}),r.jsxs("label",{className:`agents-permission-picker permission-${d}`,children:[r.jsx(Bf,{size:14}),r.jsx("span",{children:"Permission"}),r.jsxs("select",{value:d,onChange:y=>m(y.target.value),"aria-label":"Agent permission mode",children:[r.jsx("option",{value:"ask",children:"Ask"}),r.jsx("option",{value:"safe-auto",children:"Safe Auto"}),r.jsx("option",{value:"full-access",children:"Full Access"}),r.jsx("option",{value:"custom",children:"Custom"})]}),r.jsx(gx,{size:13,"aria-hidden":"true"})]})]}),r.jsx("div",{className:"agents-target-list",children:n.length===0?r.jsx("span",{className:"agents-target-empty",children:"No Clients discovered."}):n.map(y=>{const x=Hf(y),b=a==="all"||a==="auto"?x:i.includes(y.deviceId);return r.jsxs("label",{className:`agents-target-option ${b?"selected":""} ${x?"":"offline"}`,children:[r.jsx("input",{type:"checkbox",checked:b,disabled:!x||a!=="selected",onChange:()=>c(y.deviceId)}),r.jsx("span",{className:"agents-target-icon",children:r.jsx(Ta,{size:15})}),r.jsxs("span",{children:[r.jsx("strong",{children:Of(y)}),r.jsx("small",{children:x?"Ready":y.connected?"Agent reconnecting":"Offline"})]}),b&&r.jsx(Ir,{className:"agents-target-check",size:15,"aria-hidden":"true"})]},y.deviceId)})})]})}async function SN(n,a){return Ve("/api/settings/agent/plan",{method:"POST",body:JSON.stringify({instruction:a})},n)}async function CN(n,a){return Ve("/api/settings/agent/run",{method:"POST",body:JSON.stringify(a)},n)}async function kN(n,a){return Ve(`/api/settings/agent/runs/${encodeURIComponent(a)}`,void 0,n)}async function jN(n,a){return Ve(`/api/settings/agent/runs/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})},n)}async function AN(n){return Ve("/api/settings/agent/runs/cancel-all",{method:"POST",body:JSON.stringify({})},n)}async function MN(n,a,i,l){return Ve(`/api/settings/agent/runs/${encodeURIComponent(a)}/approvals/${encodeURIComponent(i)}/approve`,{method:"POST",body:JSON.stringify({scope:l})},n)}async function NN(n,a,i,l="User rejected this action."){return Ve(`/api/settings/agent/runs/${encodeURIComponent(a)}/approvals/${encodeURIComponent(i)}/reject`,{method:"POST",body:JSON.stringify({reason:l})},n)}async function TN(n,a,i){return Ve(`/api/settings/agent/policies/${encodeURIComponent(a)}`,{method:"PUT",body:JSON.stringify({categories:i})},n)}async function RN(n,a){return Ve("/api/settings/agent/summary",{method:"POST",body:JSON.stringify(a)},n)}async function EN(n,a){return Ve("/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 DN(n,a){return Ve(`/api/remote/tasks/${encodeURIComponent(a)}`,void 0,n)}async function LN(n,a){return Ve(`/api/remote/tasks/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})},n)}async function _N(n,a){return Ve(`/api/remote/tasks/${encodeURIComponent(a)}/retry`,{method:"POST",body:JSON.stringify({failedOnly:!0})},n)}function no(n){return`${n}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function gf(n,a){const i=new Map(a.map(l=>[l.deviceId,Of(l)]));return n.results.map(l=>({deviceId:l.deviceId,deviceName:l.deviceName||i.get(l.deviceId)||l.deviceId,status:YM(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 IN(n,a){const i=new Map(a.map(l=>[l.deviceId,l]));return n.map(l=>{const c=i.get(l.deviceId);return!c||c.sequence<=l.sequence?l:c})}function zN(n,a){const i=a.filter(d=>d.status==="completed"),l=a.filter(d=>d.status==="failed");if(n.operation==="process.list"){const m=`${i.filter(h=>{const g=h.result||"";return!/not running|no process/i.test(g)&&/running|online|found/i.test(g)}).length}대에서 요청한 프로세스가 실행 중입니다.`;return l.length>0?`${m}
15
15
  ${l.map(h=>`${h.deviceName}는 ${h.error||"응답하지 않았습니다."}`).join(`
16
- `)}`:m}return l.length>0?`${i.length}대 완료, ${l.length}대 실패했습니다.`:`${i.length}대 작업이 완료되었습니다.`}const ON={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 HN(n){return n==="safe-auto"?"Safe Auto":n==="full-access"?"Full Access":n==="custom"?"Custom":"Ask"}function FN(n){return n.replace(/([A-Z])/g," $1").replace(/^./,a=>a.toUpperCase())}function $N(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 Client is reconnecting. Wait until its Agent status is Ready and try again.":/codex-auth-required/i.test(a)?"Codex sign-in is required on the Hub. Open Settings > Agent and test the Codex connection.":a}function Lb({hubUrl:n,devices:a,launchRequest:i,variant:l="page",selectedDeviceIds:c=[]}){const d=l==="dock",[m,h]=u.useState(d?c.length>0?"selected":"auto":"all"),[g,y]=u.useState(c),[x,b]=u.useState("auto"),[w,A]=u.useState(""),[j,k]=u.useState([]),[N,M]=u.useState(""),[T,D]=u.useState(""),[F,$]=u.useState(""),[G,L]=u.useState("safe-auto"),[Q]=u.useState("custom-default"),[q,P]=u.useState(ON),[Y,H]=u.useState([]),[ye,de]=u.useState(""),[Z,z]=u.useState(!1),[se,W]=u.useState(null),[O,le]=u.useState(!1),[ce,K]=u.useState(""),[be,he]=u.useState(!1),[fe,ee]=u.useState(null),we=u.useRef(null),Me=u.useRef(new Set),He=u.useRef(new Set),ne=u.useRef(new Set),qe=u.useMemo(()=>a.filter(Hf).map(pe=>pe.deviceId),[a]),mt=u.useMemo(()=>mN(Tw,a,m,g,G,q),[q,a,G,g,m]);u.useEffect(()=>{d&&y(c)},[d,c]),u.useEffect(()=>{i?.deviceId&&(h("selected"),y([i.deviceId]),A(i.instruction),he(!1),window.requestAnimationFrame(()=>{we.current?.focus(),we.current?.setSelectionRange(i.instruction.length,i.instruction.length)}))},[i]);const J=u.useCallback(pe=>{const De=gf(pe,a);if(k($e=>$e.map(je=>je.type==="task"&&je.batchId===pe.batchId?{...je,states:IN(je.states,De),status:pe.status}:je)),!["running","queued"].includes(pe.status)&&!Me.current.has(pe.batchId)){Me.current.add(pe.batchId);const $e=no("agent-summary");k(je=>[...je,{type:"agent",id:$e,text:zN(pe,De)}]),pe.operation&&RN(n,{instruction:pe.instructionPreview,operation:pe.operation,total:De.length,completed:De.filter(je=>je.status==="completed").length,failed:De.filter(je=>je.status==="failed").length,results:De.map(je=>({deviceName:je.deviceName,status:je.status,result:je.result,error:je.error}))}).then(je=>{!je.ok||!je.summary||k(ct=>ct.map(bt=>bt.type==="agent"&&bt.id===$e?{...bt,text:je.summary}:bt))}).catch(()=>{}),M(je=>je===pe.batchId?"":je)}},[a,n]),Ce=u.useCallback(async pe=>{const De=await DN(n,pe);return J(De),De},[n,J]),Le=u.useCallback((pe,De)=>{ne.current.has(pe.batchId)||(ne.current.add(pe.batchId),k($e=>[...$e,{type:"task",id:no("task"),batchId:pe.batchId,agentRunId:De,operation:pe.operation||"diagnostics.collect",instruction:pe.instructionPreview,states:gf(pe,a),status:pe.status}])),J(pe)},[a,J]),Fe=u.useCallback(async pe=>{const De=await kN(n,pe);for(const je of De.taskBatches||[])Le(je,pe);H(De.approvals||[]);const $e=["running","queued","waiting-approval"].includes(De.status);if(ee($e?{runId:pe,stage:De.stage||De.status,message:De.progressMessage||(De.status==="waiting-approval"?"Review the requested action to continue.":"Codex is preparing the answer.")}:je=>je?.runId===pe?null:je),!$e&&!He.current.has(pe)){He.current.add(pe);const je=[De.error,De.errorMessage].filter(Boolean).join(" — "),ct=De.finalResponse?.trim()||(De.status==="cancelled"?"Codex 작업을 취소했습니다.":je?`Codex 작업이 완료되지 않았습니다: ${je}`:"Codex 작업이 완료되었습니다.");k(bt=>[...bt,{type:De.status==="failed"?"error":"agent",id:no("agent-run-result"),text:ct}])}return De},[Le,n]);u.useEffect(()=>{if(!N)return;let pe=!0;const De=async()=>{try{const je=await Ce(N);pe&&!["running","queued"].includes(je.status)&&M("")}catch(je){pe&&K(je instanceof Error?je.message:String(je))}};De();const $e=window.setInterval(()=>{De()},800);return()=>{pe=!1,window.clearInterval($e)}},[N,Ce]),u.useEffect(()=>{if(!T)return;let pe=!0;const De=async()=>{try{const je=await Fe(T);pe&&!["running","queued","waiting-approval"].includes(je.status)&&(D(""),le(!1))}catch(je){pe&&K(je instanceof Error?je.message:String(je))}};De();const $e=window.setInterval(()=>{De()},800);return()=>{pe=!1,window.clearInterval($e)}},[T,Fe]);const _e=async(pe="",De,$e=!1)=>{const je=(pe||w).trim();if(!je||N||T)return;let ct=null;const bt=De||(m==="all"||m==="auto"?qe:g.filter(nt=>qe.includes(nt)));if(bt.length===0){K("Select at least one connected Client.");return}if(G==="full-access"&&!O&&!$e){W({instruction:je,targetIds:bt});return}if(k(nt=>[...nt,{type:"user",id:no("user"),text:je}]),A(""),he(!1),K(""),bt.length===0){k(nt=>[...nt,{type:"error",id:no("no-targets"),text:"연결된 대상 장비를 하나 이상 선택해 주세요."}]);return}const aa=x==="ask"?`Read-only request. Inspect and answer without changing Client state.
16
+ `)}`:m}return l.length>0?`${i.length}대 완료, ${l.length}대 실패했습니다.`:`${i.length}대 작업이 완료되었습니다.`}const ON={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 HN(n){return n==="safe-auto"?"Safe Auto":n==="full-access"?"Full Access":n==="custom"?"Custom":"Ask"}function FN(n){return n.replace(/([A-Z])/g," $1").replace(/^./,a=>a.toUpperCase())}function $N(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 Client is reconnecting. Wait until its Agent status is Ready and try again.":/codex-auth-required/i.test(a)?"Codex sign-in is required on the Hub. Open Settings > Agent and test the Codex connection.":a}function Lb({hubUrl:n,devices:a,launchRequest:i,variant:l="page",selectedDeviceIds:c=[]}){const d=l==="dock",[m,h]=u.useState(d?c.length>0?"selected":"auto":"all"),[g,y]=u.useState(c),[x,b]=u.useState("auto"),[w,A]=u.useState(""),[j,k]=u.useState([]),[N,M]=u.useState(""),[T,D]=u.useState(""),[F,$]=u.useState(""),[q,L]=u.useState("safe-auto"),[Y]=u.useState("custom-default"),[G,P]=u.useState(ON),[K,H]=u.useState([]),[ye,de]=u.useState(""),[Z,z]=u.useState(!1),[se,W]=u.useState(null),[O,le]=u.useState(!1),[ce,Q]=u.useState(""),[be,he]=u.useState(!1),[fe,ee]=u.useState(null),Se=u.useRef(null),Ne=u.useRef(new Set),Fe=u.useRef(new Set),ne=u.useRef(new Set),Pe=u.useMemo(()=>a.filter(Hf).map(pe=>pe.deviceId),[a]),mt=u.useMemo(()=>mN(Tw,a,m,g,q,G),[G,a,q,g,m]);u.useEffect(()=>{d&&y(c)},[d,c]),u.useEffect(()=>{i?.deviceId&&(h("selected"),y([i.deviceId]),A(i.instruction),he(!1),window.requestAnimationFrame(()=>{Se.current?.focus(),Se.current?.setSelectionRange(i.instruction.length,i.instruction.length)}))},[i]);const J=u.useCallback(pe=>{const De=gf(pe,a);if(k(Oe=>Oe.map(Ae=>Ae.type==="task"&&Ae.batchId===pe.batchId?{...Ae,states:IN(Ae.states,De),status:pe.status}:Ae)),!["running","queued"].includes(pe.status)&&!Ne.current.has(pe.batchId)){Ne.current.add(pe.batchId);const Oe=no("agent-summary");k(Ae=>[...Ae,{type:"agent",id:Oe,text:zN(pe,De)}]),pe.operation&&RN(n,{instruction:pe.instructionPreview,operation:pe.operation,total:De.length,completed:De.filter(Ae=>Ae.status==="completed").length,failed:De.filter(Ae=>Ae.status==="failed").length,results:De.map(Ae=>({deviceName:Ae.deviceName,status:Ae.status,result:Ae.result,error:Ae.error}))}).then(Ae=>{!Ae.ok||!Ae.summary||k(ft=>ft.map(xt=>xt.type==="agent"&&xt.id===Oe?{...xt,text:Ae.summary}:xt))}).catch(()=>{}),M(Ae=>Ae===pe.batchId?"":Ae)}},[a,n]),ke=u.useCallback(async pe=>{const De=await DN(n,pe);return J(De),De},[n,J]),Le=u.useCallback((pe,De)=>{ne.current.has(pe.batchId)||(ne.current.add(pe.batchId),k(Oe=>[...Oe,{type:"task",id:no("task"),batchId:pe.batchId,agentRunId:De,operation:pe.operation||"diagnostics.collect",instruction:pe.instructionPreview,states:gf(pe,a),status:pe.status}])),J(pe)},[a,J]),Be=u.useCallback(async pe=>{const De=await kN(n,pe);for(const Ae of De.taskBatches||[])Le(Ae,pe);H(De.approvals||[]);const Oe=["running","queued","waiting-approval"].includes(De.status);if(ee(Oe?{runId:pe,stage:De.stage||De.status,message:De.progressMessage||(De.status==="waiting-approval"?"Review the requested action to continue.":"Codex is preparing the answer.")}:Ae=>Ae?.runId===pe?null:Ae),!Oe&&!Fe.current.has(pe)){Fe.current.add(pe);const Ae=[De.error,De.errorMessage].filter(Boolean).join(" — "),ft=De.finalResponse?.trim()||(De.status==="cancelled"?"Codex 작업을 취소했습니다.":Ae?`Codex 작업이 완료되지 않았습니다: ${Ae}`:"Codex 작업이 완료되었습니다.");k(xt=>[...xt,{type:De.status==="failed"?"error":"agent",id:no("agent-run-result"),text:ft}])}return De},[Le,n]);u.useEffect(()=>{if(!N)return;let pe=!0;const De=async()=>{try{const Ae=await ke(N);pe&&!["running","queued"].includes(Ae.status)&&M("")}catch(Ae){pe&&Q(Ae instanceof Error?Ae.message:String(Ae))}};De();const Oe=window.setInterval(()=>{De()},800);return()=>{pe=!1,window.clearInterval(Oe)}},[N,ke]),u.useEffect(()=>{if(!T)return;let pe=!0;const De=async()=>{try{const Ae=await Be(T);pe&&!["running","queued","waiting-approval"].includes(Ae.status)&&(D(""),le(!1))}catch(Ae){pe&&Q(Ae instanceof Error?Ae.message:String(Ae))}};De();const Oe=window.setInterval(()=>{De()},800);return()=>{pe=!1,window.clearInterval(Oe)}},[T,Be]);const _e=async(pe="",De,Oe=!1)=>{const Ae=(pe||w).trim();if(!Ae||N||T)return;let ft=null;const xt=De||(m==="all"||m==="auto"?Pe:g.filter(at=>Pe.includes(at)));if(xt.length===0){Q("Select at least one connected Client.");return}if(q==="full-access"&&!O&&!Oe){W({instruction:Ae,targetIds:xt});return}if(k(at=>[...at,{type:"user",id:no("user"),text:Ae}]),A(""),he(!1),Q(""),xt.length===0){k(at=>[...at,{type:"error",id:no("no-targets"),text:"연결된 대상 장비를 하나 이상 선택해 주세요."}]);return}const na=x==="ask"?`Read-only request. Inspect and answer without changing Client state.
17
17
 
18
- ${je}`:x==="plan"?`Plan only. Produce a safe execution plan, but do not change Client state.
18
+ ${Ae}`:x==="plan"?`Plan only. Produce a safe execution plan, but do not change Client state.
19
19
 
20
- ${je}`:x==="execute"?`Execute this request within the configured LiveDesk approval policy.
20
+ ${Ae}`:x==="execute"?`Execute this request within the configured LiveDesk approval policy.
21
21
 
22
- ${je}`:je,zn=m==="auto"?`Auto target selection is enabled. Inspect the allowed Clients and use only the most suitable target or targets for this request.
22
+ ${Ae}`:Ae,wn=m==="auto"?`Auto target selection is enabled. Inspect the allowed Clients and use only the most suitable target or targets for this request.
23
23
 
24
- ${aa}`:aa;if(!ct){try{if(G==="custom"){const Ot=await TN(n,Q,q);if(!Ot.ok)throw new Error(Ot.error||"Custom Agent policy could not be saved.")}const nt=await CN(n,{instruction:zn,deviceIds:bt,permissionMode:G,customPolicyId:Q});if(!nt.ok||!nt.runId)throw new Error(nt.error||"Codex Agent run could not be started.");H(nt.approvals||[]),ee({runId:nt.runId,stage:nt.stage||nt.status||"queued",message:nt.progressMessage||"Codex request queued on the Hub."}),D(nt.runId);return}catch(nt){try{const Ot=await SN(n,zn);Ot.ok&&Ot.plan&&(ct={operation:Ot.plan.operation,query:Ot.plan.targetQuery})}catch{k(Ot=>[...Ot,{type:"error",id:no("unsupported"),text:$N(nt)}])}}if(!ct)return}try{const nt=await EN(n,{instruction:zn,deviceIds:bt,operation:ct.operation,targetQuery:ct.query});if(!nt.ok||!nt.batch||!nt.batchId)throw new Error(nt.error||"작업을 만들지 못했습니다.");const Ot={type:"task",id:no("task"),batchId:nt.batchId,operation:ct.operation,instruction:je,states:gf(nt.batch,a),status:nt.batch.status};ne.current.add(nt.batchId),k(Nn=>[...Nn,Ot]),M(nt.batchId)}catch(nt){K(nt instanceof Error?nt.message:String(nt))}},Xe=async(pe,De)=>{de(pe.approvalId);try{const $e=await MN(n,pe.runId,pe.approvalId,De);if(!$e.ok)throw new Error($e.error||"Agent approval could not be applied.");await Fe(pe.runId)}catch($e){K($e instanceof Error?$e.message:String($e))}finally{de("")}},We=async pe=>{de(pe.approvalId);try{const De=await NN(n,pe.runId,pe.approvalId);if(!De.ok)throw new Error(De.error||"Agent approval could not be rejected.");await Fe(pe.runId)}catch(De){K(De instanceof Error?De.message:String(De))}finally{de("")}},Ze=async(pe,De)=>{$(pe);try{if(De){const je=await jN(n,De);for(const ct of je.taskBatches||[])J(ct);D(ct=>ct===De?"":ct),ee(ct=>ct?.runId===De?null:ct);return}const $e=await LN(n,pe);J($e),M(je=>je===pe?"":je)}catch($e){K($e instanceof Error?$e.message:String($e))}finally{$("")}},dt=async()=>{if(!(Z||!N&&!T)){z(!0);try{const pe=await AN(n);if(!pe.ok)throw new Error(pe.error||"모든 Agent 작업을 취소하지 못했습니다.");M(""),D(""),ee(null),H([]),k(De=>De.map($e=>$e.type==="task"&&["queued","running"].includes($e.status)?{...$e,status:"cancelled",states:$e.states.map(je=>["queued","running"].includes(je.status)?{...je,status:"cancelled",stage:"Cancelled",error:"Cancelled by user."}:je)}:$e))}catch(pe){K(pe instanceof Error?pe.message:String(pe))}finally{z(!1)}}},U=async pe=>{$(pe);try{const De=await _N(n,pe);if(!De.ok||!De.batch||!De.batchId)throw new Error(De.error||"재시도하지 못했습니다.");Me.current.delete(De.batchId),k($e=>$e.map(je=>je.type==="task"&&je.batchId===pe?{...je,batchId:De.batchId,states:gf(De.batch,a),status:De.batch.status}:je)),M(De.batchId)}catch(De){K(De instanceof Error?De.message:String(De))}finally{$("")}},ve=pe=>{A(pe),he(!1),window.requestAnimationFrame(()=>we.current?.focus())},Ae=u.useMemo(()=>a.filter(Hf),[a]),Be=u.useMemo(()=>Ae.filter(pe=>g.includes(pe.deviceId)),[Ae,g]),ft=m==="auto"?`Auto · ${Ae.length} available`:m==="all"?`All ${Ae.length} computers`:Be.length===1?Of(Be[0]):`${Be.length} selected`,it=m==="auto"?"LiveDesk chooses the best computer for each task.":m==="all"?"The Agent may coordinate every connected computer.":Be.length>0?Be.map(Of).join(" · "):"Select one or more computers on the Wall.",yt=m==="selected"&&Be.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"],ot=m==="selected"?Be.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 r.jsxs("section",{className:`agents-page ${d?"agents-dock-console":""}`,children:[d&&r.jsxs("header",{className:"agent-console-header",children:[r.jsxs("div",{className:"agent-console-title",children:[r.jsx("span",{className:"agent-console-mark",children:r.jsx(yl,{size:16})}),r.jsxs("div",{children:[r.jsx("small",{children:"Live agent"}),r.jsx("strong",{children:"Agent Console"})]}),r.jsx("i",{children:"Ready"})]}),r.jsxs("section",{className:"agent-console-target","aria-label":"Agent target scope",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Target"}),r.jsx("strong",{children:ft}),r.jsx("small",{children:it})]}),r.jsxs("div",{className:"agent-console-target-modes",children:[r.jsxs("button",{className:m==="selected"?"active":"",onClick:()=>h("selected"),type:"button",children:[r.jsx(Ir,{size:12})," Selected"]}),r.jsxs("button",{className:m==="all"?"active":"",onClick:()=>h("all"),type:"button",children:[r.jsx(Pu,{size:12})," All"]}),r.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[r.jsx(Pu,{size:12})," Group"]}),r.jsxs("button",{className:m==="auto"?"active":"",onClick:()=>h("auto"),type:"button",children:[r.jsx(yl,{size:12})," Auto"]})]})]}),r.jsx("div",{className:"agent-console-interaction-modes","aria-label":"Agent interaction mode",children:["auto","ask","plan","execute"].map(pe=>r.jsxs("button",{className:x===pe?"active":"",onClick:()=>b(pe),type:"button",children:[pe==="auto"?r.jsx(yl,{size:12}):pe==="execute"?r.jsx(Ta,{size:12}):null,pe[0].toUpperCase()+pe.slice(1)]},pe))})]}),r.jsxs("div",{className:"agents-workspace",children:[(N||T)&&r.jsxs("div",{className:"agents-page-status",children:[r.jsxs("span",{children:[qe.length," Clients · ",HN(G)]}),r.jsx("button",{type:"button",className:"agents-stop-all",onClick:()=>{dt()},disabled:Z,children:Z?"Stopping…":"Stop all"})]}),se&&r.jsx("div",{className:"agents-permission-modal-backdrop",role:"presentation",children:r.jsxs("section",{className:"agents-permission-modal",role:"dialog","aria-modal":"true","aria-labelledby":"full-access-title",children:[r.jsx("span",{className:"agents-permission-modal-icon",children:r.jsx(Bf,{size:20})}),r.jsx("h3",{id:"full-access-title",children:"Confirm Full Access"}),r.jsx("p",{children:"Codex may change files, run commands, manage applications, and modify system state on the selected Clients. This run is still limited to the selected devices, the fixed policy, and the tool budget."}),r.jsxs("div",{className:"agents-permission-modal-actions",children:[r.jsx("button",{type:"button",onClick:()=>W(null),children:"Cancel"}),r.jsx("button",{type:"button",className:"danger",onClick:()=>{const pe=se;W(null),le(!0),_e(pe.instruction,pe.targetIds,!0)},children:"Run with Full Access"})]})]})}),ce&&r.jsx("div",{className:"agents-error",role:"alert",children:ce}),r.jsx(sN,{items:j,onCancel:Ze,onRetry:U,busyBatchId:F,approvals:Y,onApprove:Xe,onReject:We,busyApprovalId:ye,progress:fe,emptyTitle:d?ot:void 0,emptyBody:d?kt:void 0}),d&&j.length===0&&!fe&&r.jsx("div",{className:"agent-console-suggestions","aria-label":"Suggested Agent commands",children:yt.map(pe=>r.jsx("button",{type:"button",onClick:()=>ve(pe),children:pe},pe))}),r.jsxs("div",{className:"agents-composer-shell",children:[be&&r.jsx(xN,{devices:a,targetMode:m,selectedIds:g,permissionMode:G,customCategories:q,onSelectPrompt:ve,onClose:()=>he(!1)}),r.jsx(VM,{ref:we,value:w,onChange:A,onSubmit:()=>{_e()},onOpenSuggestedTasks:()=>he(pe=>!pe),suggestedOpen:be,suggestedTaskCount:mt,disabled:!!N||!!T,placeholder:d?"Tell LiveDesk what outcome you want...":void 0,compact:d})]})]}),!d&&r.jsxs("aside",{className:"agents-target-sidebar","aria-label":"Agent targets and permissions",children:[r.jsx(wN,{devices:a,mode:m,selectedIds:g,onModeChange:h,onToggle:pe=>y(De=>De.includes(pe)?De.filter($e=>$e!==pe):[...De,pe]),permissionMode:G,onPermissionModeChange:pe=>{L(pe),pe!=="full-access"&&le(!1)}}),G==="custom"&&r.jsxs("section",{className:"agents-custom-policy","aria-label":"Custom Agent permissions",children:[r.jsxs("div",{className:"agents-custom-policy-head",children:[r.jsxs("div",{children:[r.jsx("span",{className:"agents-section-label",children:"Custom policy"}),r.jsx("strong",{children:"Choose what Codex may do automatically."})]}),r.jsx("span",{children:"Denied actions never reach a device."})]}),r.jsx("div",{className:"agents-custom-policy-grid",children:WM.map(pe=>r.jsxs("label",{children:[r.jsx("span",{children:FN(pe)}),r.jsxs("select",{value:q[pe],onChange:De=>P($e=>({...$e,[pe]:De.target.value})),children:[r.jsx("option",{value:"allow",children:"Allow automatically"}),r.jsx("option",{value:"ask",children:"Ask every time"}),r.jsx("option",{value:"deny",children:"Deny"})]})]},pe))})]})]})]})}function Ew(n){return{type:n.type,deviceIds:n.deviceIds,monitorIndex:n.monitorIndex,label:n.label}}async function Dw(n){try{return(await n.json()).error||`${n.status} ${n.statusText}`}catch{return`${n.status} ${n.statusText}`}}async function Lw(n,a,i){const l=encodeURIComponent(JSON.stringify({kind:a.kind,fileName:a.fileName,mimeType:n.type||"application/octet-stream",durationMs:a.durationMs,target:Ew(a.target)})),c=await fetch(`${wl(i)}/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 Dw(c));return await c.json()}async function BN(n,a){return await Ve("/api/capture-sessions",{method:"POST",body:JSON.stringify({...n,target:Ew(n.target)})},a)}async function PN(n,a,i,l){const c=await fetch(`${wl(l)}/api/capture-sessions/${encodeURIComponent(n)}/chunks/${a}`,{method:"PUT",headers:{"Content-Type":i.type||"application/octet-stream"},body:i,cache:"no-store"});if(!c.ok)throw new Error(await Dw(c));return await c.json()}async function UN(n,a,i){return await Ve(`/api/capture-sessions/${encodeURIComponent(n)}/finalize`,{method:"POST",body:JSON.stringify({durationMs:a})},i)}async function _b(n,a){await Ve(`/api/capture-sessions/${encodeURIComponent(n)}`,{method:"DELETE"},a)}async function qN(n){return await Ve("/api/captures",void 0,n)}function Ib(n,a){return`${wl(a)}/api/captures/${encodeURIComponent(n)}/content`}async function GN(n,a){return await Ve(`/api/captures/${encodeURIComponent(n)}`,{method:"DELETE"},a)}function VN({hubUrl:n,onToast:a}){const[i,l]=u.useState([]),[c,d]=u.useState(!0),m=u.useCallback(async()=>{d(!0);try{l((await qN(n)).captures||[])}catch(g){a(g instanceof Error?g.message:String(g))}finally{d(!1)}},[n,a]);u.useEffect(()=>{m()},[m]);const h=async g=>{const y=Ib(g.id,n);if(navigator.share)try{await navigator.share({title:g.fileName,url:y});return}catch{}window.open(y,"_blank","noopener,noreferrer")};return r.jsxs("section",{className:"capture-gallery",children:[r.jsxs("header",{children:[r.jsxs("div",{children:[r.jsx("span",{className:"settings-eyebrow",children:"Capture Gallery"}),r.jsx("h2",{children:"Saved captures"})]}),r.jsxs("button",{className:"text-button",onClick:()=>{m()},type:"button",children:[r.jsx(Sc,{size:15})," Refresh"]})]}),c?r.jsx("p",{className:"settings-help",children:"Loading captures..."}):i.length===0?r.jsx("p",{className:"settings-help",children:"No captures saved yet."}):r.jsx("div",{className:"capture-gallery-grid",children:i.map(g=>{const y=Ib(g.id,n);return r.jsxs("article",{className:"capture-gallery-card",children:[g.mimeType.startsWith("image/")?r.jsx("img",{src:y,alt:g.target.label}):r.jsx("video",{src:y,controls:!0,preload:"metadata"}),r.jsxs("div",{className:"capture-gallery-card-body",children:[r.jsx("strong",{children:g.fileName}),r.jsxs("small",{children:[g.target.label," · ",new Date(g.createdAt).toLocaleString()," · ",Math.ceil(g.sizeBytes/1024)," KB"]}),r.jsxs("div",{children:[r.jsx("button",{className:"icon-button",title:"Open","aria-label":"Open",onClick:()=>window.open(y,"_blank","noopener,noreferrer"),type:"button",children:r.jsx(T0,{size:15})}),r.jsx("a",{className:"icon-button",title:"Download","aria-label":"Download",href:`${y}?download=1`,download:g.fileName,children:r.jsx(xp,{size:15})}),r.jsx("button",{className:"icon-button",title:"Share","aria-label":"Share",onClick:()=>{h(g)},type:"button",children:r.jsx(R0,{size:15})}),r.jsx("button",{className:"icon-button danger",title:"Delete","aria-label":"Delete",onClick:()=>{window.confirm(`Delete ${g.fileName}?`)&&GN(g.id,n).then(()=>m()).catch(x=>a(x instanceof Error?x.message:String(x)))},type:"button",children:r.jsx(Sp,{size:15})})]})]})]},g.id)})})]})}function vf(n){if(!n)return"";const a=Math.max(0,Math.floor((Date.now()-n)/1e3)),i=Math.floor(a/3600),l=Math.floor(a%3600/60),c=a%60;return i>0?`${String(i).padStart(2,"0")}:${String(l).padStart(2,"0")}:${String(c).padStart(2,"0")}`:`${String(l).padStart(2,"0")}:${String(c).padStart(2,"0")}`}function zb({controller:n,compact:a=!1,onFirstRollingUse:i,onError:l}){const{state:c,settings:d,videoSupported:m}=n,h=async b=>{try{await b()}catch(w){l?.(w instanceof Error?w.message:String(w))}},g=async()=>{if(d.rollingEnabled){n.setRollingEnabled(!1);return}(i?await i():window.confirm(`Keep the most recent 30 seconds in memory temporarily?
25
- Nothing is saved until you press Save Last 30s.`))&&n.setRollingEnabled(!0)},y=c.recording?`Stop recording · ${vf(c.recordingStartedAt)}`:`Start recording · ${c.targetLabel}`,x=c.timelapse?`Stop timelapse · ${vf(c.timelapseStartedAt)}`:`Start timelapse · ${d.timelapseIntervalSeconds}s interval`;return r.jsxs("div",{className:`capture-toolbar ${a?"compact":""} ${c.recording?"recording-active":""}`,"aria-label":"Capture actions",children:[r.jsx("button",{className:"capture-action","aria-label":`Take screenshot · ${c.targetLabel}`,title:`Take screenshot · ${c.targetLabel}`,disabled:c.busy,onClick:()=>{h(n.takeScreenshot)},type:"button",children:r.jsx(E0,{size:17})}),r.jsx("button",{className:`capture-action ${c.recording?"active":""}`,"aria-label":y,title:y,disabled:!m||c.busy||c.timelapse,onClick:()=>{h(c.recording?n.stopRecording:n.startRecording)},type:"button",children:c.recording?r.jsxs(r.Fragment,{children:[r.jsx(py,{size:14,fill:"currentColor"}),r.jsx("span",{children:vf(c.recordingStartedAt)})]}):r.jsx(px,{size:18})}),r.jsxs("button",{className:"capture-action","aria-label":c.bufferEnabled?`Save last 30 seconds · ${c.bufferSeconds}s ready`:"Enable Last 30s memory buffer",title:c.bufferEnabled?`Save last 30 seconds · ${c.bufferSeconds}s ready`:"Enable Last 30s memory buffer",disabled:!m||c.recording||c.timelapse||c.busy||c.bufferEnabled&&c.bufferSeconds<1,onClick:()=>c.bufferEnabled?void h(n.saveLast30Seconds):void g(),type:"button",children:[r.jsx(D0,{size:17}),r.jsx("small",{children:"30s"})]}),r.jsx("button",{className:`capture-action ${c.timelapse?"timelapse-active":""}`,"aria-label":x,title:x,disabled:!m||c.busy||c.recording,onClick:()=>{h(c.timelapse?n.stopTimelapse:n.startTimelapse)},type:"button",children:c.timelapse?r.jsxs(r.Fragment,{children:[r.jsx(py,{size:14,fill:"currentColor"}),r.jsx("span",{children:vf(c.timelapseStartedAt)})]}):r.jsx(L0,{size:17})})]})}function _w({state:n}){return n==="ok"?r.jsx(Zn,{size:15,"aria-hidden":"true"}):r.jsx(vx,{size:15,"aria-hidden":"true"})}function Ob({active:n,refreshing:a,onClick:i}){return r.jsx("button",{className:`remote-status-button ${n?"active":""}`,type:"button",title:"Check Remote Status","aria-label":"Check Remote Status","aria-pressed":n,"aria-busy":a,onClick:i,children:a?r.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):r.jsx(_0,{size:18,"aria-hidden":"true"})})}function Hb({active:n,refreshing:a,onClick:i}){return r.jsx("button",{className:`remote-status-button debug-status-button ${n?"active":""}`,type:"button",title:"Check Debug Status","aria-label":"Check Debug Status","aria-pressed":n,"aria-busy":a,onClick:i,children:a?r.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):r.jsx(ox,{size:18,"aria-hidden":"true"})})}function Fb({active:n,refreshing:a,onClick:i}){return r.jsx("button",{className:`remote-status-button hub-status-button ${n?"active":""}`,type:"button",title:"Check Hub Status","aria-label":"Check Hub Status","aria-pressed":n,"aria-busy":a,onClick:i,children:a?r.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):r.jsx(zr,{size:18,"aria-hidden":"true"})})}function WN({items:n,mode:a="remote"}){return r.jsx("span",{className:`remote-status-lines mode-${a}`,role:"status","aria-label":a==="debug"?"Debug status":"Remote status",children:n.map(i=>r.jsxs("span",{className:`remote-status-line state-${i.state}`,title:i.detail,children:[r.jsx(_w,{state:i.state}),r.jsxs("span",{children:[r.jsx("strong",{children:i.label}),r.jsx("small",{children:i.detail})]})]},i.id))})}function YN({items:n,collectedAt:a,onClose:i}){return r.jsxs("section",{className:"remote-status-dialog hub-status-dialog",role:"dialog","aria-modal":"false","aria-labelledby":"hub-status-dialog-title",children:[r.jsxs("header",{children:[r.jsx("span",{className:"remote-status-dialog-mark","aria-hidden":"true",children:r.jsx(zr,{size:19})}),r.jsxs("span",{children:[r.jsx("small",{children:"Hub measurements"}),r.jsx("h2",{id:"hub-status-dialog-title",children:"Hub Status"})]}),r.jsx("button",{type:"button",onClick:i,title:"Close Hub status","aria-label":"Close Hub status",children:r.jsx(Na,{size:17})})]}),r.jsx("p",{children:"LiveDesk collects these Hub and browser signals continuously. This check refreshed the latest snapshot instead of starting a one-time benchmark."}),r.jsx("div",{className:"remote-status-dialog-list",children:n.map(l=>r.jsxs("article",{className:`remote-status-dialog-row state-${l.state}`,children:[r.jsx(_w,{state:l.state}),r.jsxs("span",{children:[r.jsx("strong",{children:l.label}),r.jsx("small",{children:l.detail})]})]},l.id))}),r.jsxs("footer",{children:["Checked ",new Date(a).toLocaleTimeString()]})]})}const KN=/(nvenc|videotoolbox|qsv|quick\s*sync|amf|vaapi|v4l2m2m|mediafoundation|h264_mf)/i,QN=/(libx264|openh264|software|cpu)/i,Et=Object.freeze({frameAgeWarningMs:2500,networkDelayWarningMs:120,receiveRatioWarning:.62,deliveryRatioWarning:.82,decoderInputRatioWarning:.82,decoderOutputRatioWarning:.62,captureBudgetMultiplier:2.5,minimumCaptureBudgetMs:80,cpuWarningRatio:.82,memoryWarningRatio:.86,gpuWarningRatio:.92,gpuMemoryWarningRatio:.92,gpuTemperatureWarningC:85,networkUsageWarningRatio:.85,networkLatencyWarningMs:80,minimumClientStatusFreshMs:15e3,clientStatusFreshMultiplier:3,hubMinimumTotalMemoryBytes:8*1024**3,hubMinimumBrowserMemoryGb:4});function Mn(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function Vp(n,a){let i=n;for(const l of String(a).split(".")){if(!i||typeof i!="object")return;i=i[l]}return i}function is(n,...a){for(const i of a){const l=Vp(n,i);if(l==null||l==="")continue;const c=Number(l);if(Number.isFinite(c))return c}}function Ut(n,...a){for(const i of a){const l=Vp(n,i);if(typeof l=="string"&&l.trim())return l.trim()}return""}function Iw(n,...a){for(const i of a){const l=Vp(n,i);if(typeof l=="boolean")return l;if(l===1||l==="1"||String(l).toLowerCase()==="true")return!0;if(l===0||l==="0"||String(l).toLowerCase()==="false")return!1}}function oo(n,...a){const i=is(n,...a);if(i!==void 0)return Math.max(0,Math.min(1,i>1?i/100:i))}function tt(n,a,i,l){return{id:n,state:a,label:i,detail:l}}function Nf(n){const a=Date.parse(String(n||""));return Number.isFinite(a)&&a>0?a:void 0}function $b(n){return`${(Math.max(0,Number(n||0))/1024**3).toFixed(1)} GB`}function XN(n){const a=String(n||"").replace(/^::ffff:/,"").trim().toLowerCase();if(!a||a==="::1"||a==="localhost"||a==="127.0.0.1"||/^10\./.test(a)||/^192\.168\./.test(a))return!0;const i=a.match(/^172\.(\d{1,3})\./);return!!i&&Number(i[1])>=16&&Number(i[1])<=31||a.startsWith("fe80:")||a.startsWith("fc")||a.startsWith("fd")}function zw(n,a){const i=Number(n?.browserReceivedEpochMs);return Number.isFinite(i)&&i>0?Math.max(0,a-i):Number.POSITIVE_INFINITY}function Ow(n,a,i){const l=Mn(a?.frameTransport),c=Ut(n,"frameTransportChangedAt"),d=Ut(l,"changedAt"),m=Nf(c),h=Nf(d),g=h!==void 0&&(m===void 0||h>m),y=g?l:n,x=g?n:l,b=Ut(n,"transport").toLowerCase(),w=Ut(y,g?"active":"frameTransportActive")||Ut(x,g?"frameTransportActive":"active"),A=Ut(y,g?"protocol":"frameTransportProtocol")||Ut(x,g?"frameTransportProtocol":"protocol"),k=(g?Ut(l,"videoTransport","activeTransport")||[w,A].filter(Boolean).join("-")||Ut(n,"videoTransport"):Ut(n,"videoTransport")||Ut(l,"videoTransport","activeTransport")||[w,A].filter(Boolean).join("-")).toLowerCase(),N=/(?:^|[-_])ws(?:$|[-_])|websocket/.test(k)||/(?:^|[-_])ws(?:$|[-_])|websocket/.test(b),M=/p2p|udp/.test(k)||b==="udp-p2p"?"p2p-udp":/direct|tcp|ws|websocket/.test(k)||b==="binary"||N?N?"direct-ws":"direct-tcp":"",T=(Ut(y,g?"state":"frameTransportState")||Ut(x,g?"frameTransportState":"state")||(M?"active":"")).toLowerCase(),D=Ut(y,g?"reason":"frameTransportReason")||Ut(x,g?"frameTransportReason":"reason"),F=g?d||c:c||d,$=Nf(F),G=$===void 0?void 0:Math.max(0,i-$),L=G===void 0?"":G<1e3?"changed now":G<6e4?`changed ${Math.round(G/1e3)}s ago`:G<36e5?`changed ${Math.round(G/6e4)}m ago`:`changed ${F}`,Q=g?l.switchCount??n?.frameTransportSwitchCount:n?.frameTransportSwitchCount??l.switchCount,q=g?l.tcpFailureCount??n?.frameTransportTcpFailureCount:n?.frameTransportTcpFailureCount??l.tcpFailureCount,P=g?typeof l.p2pReady=="boolean"?l.p2pReady:n?.frameTransportP2pReady===!0:typeof n?.frameTransportP2pReady=="boolean"?n.frameTransportP2pReady:l.p2pReady===!0;return{rawTransport:b,videoTransport:M,state:T,reason:D,changedAt:F,changedLabel:L,switchCount:Math.max(0,Number(Q??0)||0),tcpFailureCount:Math.max(0,Number(q??0)||0),p2pReady:P}}function ZN(n,a,i){const l=Ow(n,a,i),c=/(connecting|recovering|failed|error|degraded|unavailable)/.test(l.state);if(l.videoTransport==="p2p-udp")return tt("transport",c?"warning":"ok",c?"P2P video connection needs attention":"P2P video connection",c?`Encrypted UDP P2P is ${l.state||"not ready"}; open Debug Status for the technical reason${l.changedLabel?` · ${l.changedLabel}`:""}.`:`Encrypted UDP P2P fallback is active${l.changedLabel?` · ${l.changedLabel}`:""}.`);if(l.videoTransport==="direct-tcp"||l.videoTransport==="direct-ws"){const d=l.videoTransport==="direct-ws"?"WebSocket":"TCP";return tt("transport",c?"warning":"ok",c?"Direct video connection needs attention":"Direct video connection",c?`Direct ${d} to Hub is ${l.state||"not ready"}; open Debug Status for the technical reason${l.changedLabel?` · ${l.changedLabel}`:""}.`:`Direct ${d} to Hub is active${l.changedLabel?` · ${l.changedLabel}`:""}.`)}return tt("transport","warning","Video transport is not identified",l.reason||"Waiting for Direct TCP or encrypted UDP P2P transport data.")}function JN(n){const a=String(n?.frameMode||n?.mode||n?.codec||"").toLowerCase(),i=[n?.hardwareEncoder,n?.platformProfile].filter(Boolean).join(" · "),l=Iw(n,"nativeEncoderHardwareAccelerated"),c=n?.nativeEncoderHardwareAccelerationKnown===!0||l!==void 0;return!n||!/h264/.test(a)?tt("encoder","warning","Video encoder unavailable","Waiting for an H.264 frame."):c&&l===!1?tt("encoder","warning","H.264 hardware acceleration is not active",`${i||"Native encoder"} is running without confirmed hardware acceleration.`):c&&l===!0?tt("encoder","ok","Hardware H.264 encoding",`${i||"Native encoder"} · hardware acceleration confirmed`):KN.test(i)?tt("encoder","ok","Hardware H.264 encoding",i):QN.test(i)?tt("encoder","warning","Software H.264 encoding",`${i||"CPU encoder"} may limit frame rate.`):tt("encoder","warning","H.264 encoder not identified",i||"The Client has not reported its active encoder profile.")}function eT({device:n,frame:a,receiveStat:i,paintStat:l,codec:c,selectedMonitorIndex:d=0,control:m=!1,controlInputReady:h=!1,controlBinding:g,capturePaused:y=!1,capturePauseConfirmed:x=!0,capturePauseError:b="",clientHeartbeatMs:w=5e3,now:A=Date.now()}={}){const j=Mn(n),k=Mn(j.status),N=Mn(l?.lastInfo),M=[],T=zw(a,A);M.push(y?x?tt("connection","ok","Video capture is paused","Client screen capture and FFmpeg shutdown were confirmed by the Client."):tt("connection","warning","Video stop needs attention",String(b||"The Hub is blocking video restart, but the Client did not confirm capture and FFmpeg shutdown.")):j.connected===!0&&T<=Et.frameAgeWarningMs?tt("connection","ok","Video connection is current",`${Math.round(T)}ms since the latest frame.`):tt("connection","warning",j.connected===!0?"Video frame is stale":"Client is offline",j.connected===!0&&Number.isFinite(T)?`${Math.round(T)}ms since the latest frame.`:String(j.lastDisconnectReason||"No current Client session."))),M.push(ZN(a,k,A)),M.push(JN(a));const D=Math.max(0,Number(a?.requestedFps||a?.effectiveFps||0)),F=Math.max(0,Number(i?.framesPerSecond||0)),$=Math.max(0,Number(a?.sourceGapMs||0)),G=Math.max(0,Number(a?.nativeCaptureFps||0)),L=Math.max(0,Number(a?.nativeEncodedFps||0)),Q=Math.max(0,Number(a?.nativeCaptureSampleCount||0)),q=a?.nativeCaptureTelemetryAvailable===!0&&Q>0,P=is(a,"captureP95Ms","captureAverageMs","captureStageMs"),Y=Math.max(0,Number(P||0)),H=a?.captureTimingAvailable===!0&&D>0&&Number(i?.sampleMs||0)>0&&P!==void 0,ye=H||q,de=Math.max(Et.minimumCaptureBudgetMs,D>0?1e3/D*Et.captureBudgetMultiplier:0),Z=D>0?1e3/D:100,z=q&&D>0&&(G<D*Et.receiveRatioWarning||L>0&&L<D*Et.receiveRatioWarning||$>Math.max(Et.networkDelayWarningMs,Z*3)),se=q?z:H&&Y>de;M.push(ye?se?tt("capture","warning","Screen capture cannot keep target speed",q?`${G.toFixed(1)} native capture · ${L.toFixed(1)} encoded · ${D||"?"} requested fps`:`${Y?`capture p95 ${Math.round(Y)}ms`:"capture timing unavailable"} · ${F.toFixed(1)}/${D||"?"} fps`):tt("capture","ok","Screen capture speed is healthy",q?`${G.toFixed(1)} native capture · ${L.toFixed(1)} encoded · ${D||"?"} requested fps`:`${Y?`capture p95 ${Math.round(Y)}ms`:"no slow capture reported"}${D?` · ${F.toFixed(1)}/${D} fps`:""}`):tt("capture","warning","Screen capture data is still collecting","A current frame-rate and capture-time sample is required."));const W=is(a,"hubPacketTransitAgeMs"),O=Math.max(0,Number(W||0)),le=Math.max(0,Number(a?.agentSendGapMs||0)),ce=Math.max(0,Number(a?.agentSendDurationMs||0)),K=!XN(j.remoteAddress),be=oo(k,"network.usageRatio"),he=is(k,"network.latencyMs"),fe=(be??0)>=Et.networkUsageWarningRatio||(he??0)>=Et.networkLatencyWarningMs,ee=Math.max(0,Number(a?.hubClientQueueDepth||0)),we=Math.max(0,Number(a?.hubClientQueueLimit||0)),Me=we>0&&ee>=we,He=W!==void 0&&Number(i?.sampleMs||0)>0,ne=D>0&&Number(i?.sampleMs||0)>0&&F<D*Et.deliveryRatioWarning,qe=O>Et.networkDelayWarningMs||le>Math.max(Et.networkDelayWarningMs,Z*3)||ce>Et.networkDelayWarningMs||ne||T>Et.frameAgeWarningMs||fe||Me;M.push(He?qe||K?tt("network","warning",K?"External network route may add delay":fe?"Client network adapter needs attention":Me?"Hub browser video queue needs attention":"Video delivery is uneven",[O?`${Math.round(O)}ms Hub-to-browser`:"",le?`${Math.round(le)}ms Client send gap`:"",ce?`${Math.round(ce)}ms Client send time`:"",ne?`${F.toFixed(1)} of ${D} requested fps`:"",he!==void 0?`${Math.round(he)}ms Client network latency`:"",be!==void 0?`${Math.round(be*100)}% Client link use`:"",we>0?`Hub queue ${ee}/${we}`:"",K?String(j.remoteAddress||"external route"):""].filter(Boolean).join(" · ")||"Frame delivery is not current."):tt("network","ok","Network delivery is healthy",`${Math.round(O)}ms Hub-to-browser · the current video rate is on target.`):tt("network","warning","Network delivery data is still collecting","A calibrated Hub-to-browser transit sample is required."));const mt=oo(k,"cpu.usageRatio","cpu.usedRatio","cpu.percent"),J=oo(k,"memory.usedRatio","usedMemRatio"),Ce=oo(k,"gpu.usageRatio"),Le=oo(k,"gpu.memory.usedRatio"),Fe=is(k,"gpu.temperatureC","thermal.gpuC"),_e=mt!==void 0&&J!==void 0,Xe=Nf(j.lastStatusAt),We=Xe===void 0?Number.POSITIVE_INFINITY:Math.max(0,A-Xe),Ze=Math.max(Et.minimumClientStatusFreshMs,Math.max(1e3,Number(w||0))*Et.clientStatusFreshMultiplier),dt=We<=Ze,U=(mt??0)>=Et.cpuWarningRatio||(J??0)>=Et.memoryWarningRatio||(Ce??0)>=Et.gpuWarningRatio||(Le??0)>=Et.gpuMemoryWarningRatio||(Fe??0)>=Et.gpuTemperatureWarningC;M.push(_e?dt?U?tt("computer","warning",(Ce??0)>=Et.gpuWarningRatio||(Le??0)>=Et.gpuMemoryWarningRatio||(Fe??0)>=Et.gpuTemperatureWarningC?"Client GPU is under load":"Client computer is under load",[`CPU ${Math.round(mt*100)}%`,`memory ${Math.round(J*100)}%`,Ce!==void 0?`GPU ${Math.round(Ce*100)}%`:"",Le!==void 0?`GPU memory ${Math.round(Le*100)}%`:"",Fe!==void 0?`GPU ${Math.round(Fe)}C`:""].filter(Boolean).join(" · ")):tt("computer","ok","Client computer has working capacity",[`CPU ${Math.round(mt*100)}%`,`memory ${Math.round(J*100)}%`,Ce!==void 0?`GPU ${Math.round(Ce*100)}%`:""].filter(Boolean).join(" · ")):tt("computer","warning","Client performance snapshot is stale",Number.isFinite(We)?`The latest CPU and memory report is ${Math.round(We/1e3)} seconds old.`:"No current Client performance heartbeat has been received."):tt("computer","warning","Client performance data is unavailable","CPU and memory telemetry have not been reported yet."));const ve=Number(a?.monitorIndex),Ae=Number.isInteger(ve)&&ve===Number(d),Be=Mn(j.channels),ft=Mn(j.capabilities),it=Be.input!==!1&&ft.remoteInput!==!1&&ft.accessibilityPermission!==!1,yt=ft.screenRecordingPermission!==!1,ot=Mn(g),kt=!m||String(a?.sessionId||"")&&String(a?.sessionId||"")===String(ot.sessionId||"")&&String(a?.commandId||"")&&String(a?.commandId||"")===String(ot.commandId||"")&&Number(a?.captureGeneration||0)>0&&Number(a?.captureGeneration||0)===Number(ot.captureGeneration||0)&&Number(a?.monitorIndex)===Number(ot.monitorIndex),pe=!m||h&&kt;M.push(Ae&&pe&&it&&yt?tt("display","ok",m?"Display and remote input are bound":"Display and remote input are available",`Display ${Number(d)+1} · generation ${Number(a?.captureGeneration||0)||"current"}.`):tt("display","warning",yt?it?m?"Remote input is not bound to this display":"Waiting for the selected display":"Remote input permission is missing":"Screen capture permission is missing",`Selected display ${Number(d)+1}; latest frame ${Number.isInteger(ve)?ve+1:"not available"}.`));const De=Mn(c),$e=Array.isArray(De.canvases)?Mn(De.canvases[0]):{},je=Math.max(0,Number(l?.decoderInputFps||0)),ct=Math.max(0,Number(l?.decoderOutputFps||0)),bt=je>0&&Number(l?.sampleMs||i?.sampleMs||0)>0,aa=F>0&&Number(i?.sampleMs||0)>0&&Number(l?.sampleMs||0)>0&&je<F*Et.decoderInputRatioWarning,zn=je>0?ct/je:0,nt=Ut($e,"configuredAcceleration","requestedAcceleration")||Ut(N,"h264DecodeAcceleration"),Ot=Ut($e,"softwareFallbackReason"),Nn=!!Ot||nt==="prefer-software";return M.push(aa?tt("decoder","warning","Browser decoder input is dropping frames",`${F.toFixed(1)} received / ${je.toFixed(1)} decoder input / ${ct.toFixed(1)} output fps.`):bt?Nn||zn<Et.decoderOutputRatioWarning?tt("decoder","warning",Nn?"Browser is using software H.264 fallback":"Browser decoder output is slow",`${Ot||String(N.decoderLabel||nt||"decoder")} · ${je.toFixed(1)} in / ${ct.toFixed(1)} out fps.`):tt("decoder","ok",nt==="prefer-hardware"?"Browser requests hardware H.264":"Browser H.264 path is responsive",`${je.toFixed(1)} in / ${ct.toFixed(1)} out fps. Chrome does not expose definitive hardware acceptance.`):tt("decoder","warning","Browser decoder data is still collecting","Decoder input and output samples are required before this path can be marked healthy.")),M}function Dr(n){const a=String(n||"").trim();return a?a.length<=14?a:`${a.slice(0,6)}…${a.slice(-5)}`:"-"}function mn(n,a=1){const i=Number(n);return Number.isFinite(i)?i.toFixed(a):"-"}function tT({device:n,frame:a,receiveStat:i,paintStat:l,codec:c,selectedMonitorIndex:d=0,control:m=!1,controlInputReady:h=!1,controlBinding:g,now:y=Date.now()}={}){const x=Mn(n),b=Mn(x.status),w=Mn(g),A=Mn(l?.lastInfo),j=Mn(c),k=Array.isArray(j.canvases)?Mn(j.canvases[0]):{},N=[],M=Number(d),T=Number(a?.monitorIndex),D=Number.isInteger(T)&&T===M,F=Number(a?.captureGeneration||0),$=Number(w.captureGeneration||0),G=!m||D&&String(a?.sessionId||"")===String(w.sessionId||"")&&String(a?.commandId||"")===String(w.commandId||"")&&F>0&&F===$,L=Math.max(0,Number(a?.requestedFps||a?.effectiveFps||0)),Q=Math.max(0,Number(i?.framesPerSecond||0)),q=Math.max(0,Number(l?.framesPerSecond||0)),P=Math.max(0,Number(l?.decoderInputFps||0)),Y=Math.max(0,Number(l?.decoderOutputFps||0)),H=Number(i?.sampleMs||0)>0&&Number(l?.sampleMs||0)>0,ye=L>0&&H&&Math.min(Q,q||Q,Y||Q)<L*Et.deliveryRatioWarning,de=Math.max(0,Number(a?.sourceGapMs||0)),Z=Math.max(0,Number(a?.agentSendGapMs||0)),z=Math.max(0,Number(a?.agentSendDurationMs||0)),se=Math.max(0,Number(a?.agentSendDurationFrameSeq||0)),W=Math.max(0,Number(a?.agentQueueBeforePaceMs||0)),O=Math.max(0,Number(a?.agentFrameAgeMs||0)),le=is(a,"hubPacketTransitAgeMs"),ce=Math.max(0,Number(a?.droppedByAgent||0)),K=Math.max(0,Number(a?.hubIngressDropped||0)),be=Math.max(0,Number(a?.hubClientDropped||0)),he=Math.max(0,Number(a?.hubClientQueueDepth||0)),fe=Math.max(0,Number(a?.hubClientQueueLimit||0)),ee=Math.max(0,Number(a?.hubClientBufferedBytes||0)),we=Math.max(0,Number(a?.udpIncompleteFrames||0)),Me=ce+K+be,He=zw(a,y),ne=Ut(k,"configuredAcceleration","requestedAcceleration")||Ut(A,"h264DecodeAcceleration"),qe=Ut(k,"softwareFallbackReason"),mt=H&&Q>0&&P<Q*Et.decoderInputRatioWarning,J=Ow(a,b,y),Ce=Ut(x,"deviceId")||Ut(a,"deviceId"),Le=Ut(a,"sessionId")||Ut(x,"sessionId"),Fe=Ut(x,"productVersion")||Ut(b,"productVersion","runtime.productVersion"),_e=Ut(x,"agentVersion")||Ut(b,"agentVersion","runtime.agentVersion"),Xe=is(x,"pid","runtimePid")??is(b,"pid","runtimePid","process.pid"),We=!!(Ce&&Le&&Fe&&_e&&(Xe??0)>0),Ze=a?.nativeCaptureTelemetryAvailable===!0,dt=Iw(a,"nativeEncoderHardwareAccelerated"),U=a?.nativeEncoderHardwareAccelerationKnown===!0||dt!==void 0,ve=Ut(a,"nativeEncoderHardwareQueryStatus"),Ae=ve==="0"?"confirmed":ve,Be=Math.max(0,Number(a?.nativeCaptureFps||0)),ft=Math.max(0,Number(a?.nativeEncodedFps||0)),it=Math.max(0,Number(a?.nativeCaptureSampleCount||0)),yt=Math.max(0,Number(a?.nativeEncodableFrameCount||0)),ot=Math.max(0,Number(a?.nativeSkippedFrameCount||0)),kt=Math.max(0,Number(a?.nativeEncodedFrameCount||0)),pe=Ze&&it>0,De=L>0?1e3/L:100,$e=pe&&L>0&&(Be<L*Et.receiveRatioWarning||ft>0&&ft<L*Et.receiveRatioWarning||de>Math.max(Et.networkDelayWarningMs,De*3));N.push(We?tt("debug-runtime","ok",`LiveDesk ${Fe} · Agent ${_e}`,`pid ${Xe} · session ${Dr(Le)} · device ${Dr(Ce)}`):tt("debug-runtime","warning","Runtime identity is incomplete",`LiveDesk ${Fe||"-"} · Agent ${_e||"-"} · pid ${Xe??"-"} · session ${Dr(Le)} · device ${Dr(Ce)}`)),N.push(a?tt("debug-frame","ok",`Frame #${Number(a.frameSeq||0)} · ${String(a.streamPurpose||(m?"control":"wall"))}`,`stream ${Dr(a.streamId)} · ${a.width||0}x${a.height||0} · ${Math.round(Number(a.byteLength||0)/1024)} KB · age ${Number.isFinite(He)?Math.round(He):"-"}ms`):tt("debug-frame","warning","No current frame",`Device ${Dr(x.deviceId)} has not produced a frame.`));const je=/(connecting|recovering|failed|error|degraded|unavailable)/.test(J.state);N.push(J.videoTransport&&!je?tt("debug-transport","ok",`${J.videoTransport==="p2p-udp"?"P2P UDP":J.videoTransport==="direct-ws"?"Direct WebSocket":"Direct TCP"} · ${J.state||"active"}`,[`raw ${J.rawTransport||"-"}`,`P2P ${J.p2pReady?"ready":"standby unavailable"}`,`switch ${J.switchCount}`,`TCP failure ${J.tcpFailureCount}`,J.changedLabel,J.reason].filter(Boolean).join(" · ")):tt("debug-transport","warning",J.videoTransport?`Video transport ${J.state||"needs attention"}`:"Video transport is not identified",[J.videoTransport||"no active path",`raw ${J.rawTransport||"-"}`,`P2P ${J.p2pReady?"ready":"not ready"}`,J.changedLabel,J.reason].filter(Boolean).join(" · "))),N.push(D?tt("debug-monitor","ok",`Monitor selected ${M+1} · frame ${T+1}`,`reported ${Number(a?.monitorCount||0)||"?"} displays · generation ${F||"-"}`):tt("debug-monitor","warning",`Monitor mismatch: selected ${M+1} · frame ${Number.isInteger(T)?T+1:"-"}`,`reported ${Number(a?.monitorCount||0)||"?"} displays · generation ${F||"-"}`)),N.push(G&&(!m||h)?tt("debug-binding","ok",m?"Control generation is bound":"Wall capture generation is current",`session ${Dr(a?.sessionId)} · command ${Dr(a?.commandId)} · generation ${F||"-"}`):tt("debug-binding","warning",m?"Control generation is not bound":"Wall capture generation is unavailable",`frame ${Dr(a?.commandId)}/${F||"-"} · expected ${Dr(w.commandId)}/${$||"-"} · input ${h?"ready":"waiting"}`)),N.push(H&&!ye?tt("debug-cadence","ok",`Cadence ${mn(Q)} rx · ${mn(q)} paint · ${mn(Y)} decode`,`requested ${mn(L)} · decoder input ${mn(P)} fps · receive p95 ${mn(i?.p95IntervalMs)}ms`):tt("debug-cadence","warning",H?"Frame cadence is below request":"Frame cadence sample is collecting",`requested ${mn(L)} · receive ${mn(Q)} · paint ${mn(q)} · decode ${mn(Y)} fps`)),N.push(pe&&!$e&&dt!==!1?tt("debug-native-capture","ok",`Native capture ${mn(Be)} fps · encode ${mn(ft)} fps`,`telemetry yes · hardware ${U?dt?"yes":"no":"unknown"}${Ae?` (${Ae})`:""} · capture samples ${it} · encodable ${yt} · skipped ${ot} · encoded ${kt} · native source gap ${Math.round(de)}ms`):tt("debug-native-capture","warning",pe?"Native capture or encoder needs attention":"Native capture telemetry is unavailable",`telemetry ${Ze?"yes, waiting for samples":"no"} · hardware ${U?dt?"yes":"no":"unknown"}${Ae?` (${Ae})`:""} · capture ${mn(Be)} fps · encode ${mn(ft)} fps · capture samples ${it} · encodable ${yt} · skipped ${ot} · encoded ${kt} · native source gap ${Math.round(de)}ms`)),N.push(Me===0&&we===0&&(fe<=0||he<fe)&&Z<=Math.max(Et.networkDelayWarningMs,De*3)&&z<=Et.networkDelayWarningMs&&O<=Et.networkDelayWarningMs&&(le===void 0||le<=Et.networkDelayWarningMs)?tt("debug-delivery","ok","Delivery counters are clear",`native source gap ${Math.round(de)}ms · Client send gap ${Math.round(Z)}ms · Client send time ${Math.round(z)}ms (frame ${se||"-"}) · Agent queue ${Math.round(W)}ms · Agent age ${Math.round(O)}ms · Agent drop ${ce} · Hub transit ${le===void 0?"-":Math.round(le)}ms · Hub ingress drop ${K} · browser queue drop ${be} (${he}/${fe||"-"}) · buffered ${Math.round(ee/1024)} KB · UDP incomplete ${we}`):tt("debug-delivery","warning","Delivery counters show loss or delay",`native source gap ${Math.round(de)}ms · Client send gap ${Math.round(Z)}ms · Client send time ${Math.round(z)}ms (frame ${se||"-"}) · Agent queue ${Math.round(W)}ms · Agent age ${Math.round(O)}ms · Agent drop ${ce} · Hub transit ${le===void 0?"-":Math.round(le)}ms · Hub ingress drop ${K} · browser queue drop ${be} (${he}/${fe||"-"}) · buffered ${Math.round(ee/1024)} KB · UDP incomplete ${we}`));const ct=is(a,"captureP95Ms");return N.push(a?.captureTimingAvailable===!0&&ct!==void 0?tt("debug-capture","ok",`Capture p95 ${mn(ct)}ms · avg ${mn(a?.captureAverageMs)}ms`,`stage ${mn(a?.captureStageMs)}ms · slow ${Number(a?.slowFrameCount||0)} · helper restart ${Number(a?.captureHelperRestarts||0)} · source skip ${Number(a?.captureSourceSkipped||0)}`):tt("debug-capture","warning","Capture timing sample is unavailable",`stage ${mn(a?.captureStageMs)}ms · helper restart ${Number(a?.captureHelperRestarts||0)} · source serial ${Number(a?.captureSourceSerial||0)}`)),N.push(!qe&&ne!=="prefer-software"&&!mt?tt("debug-decoder","ok",`Decoder ${ne||"acceleration unknown"}`,`${String(a?.frameMode||a?.codec||"-")} · ${String(a?.hardwareEncoder||"-")} · ${String(a?.platformProfile||"-")}`):tt("debug-decoder","warning",mt?"Decoder input is losing received frames":"Decoder software fallback is active",mt?`${mn(Q)} received / ${mn(P)} decoder input / ${mn(Y)} output fps`:`${qe||ne||"software"} · ${mn(P)} in / ${mn(Y)} out fps`)),N}function nT({status:n,deviceDiagnostics:a=[],codec:i,browser:l,frameStats:c}={}){const d=Mn(n),m=Mn(d.diagnostics),h=Mn(m.system),g=Mn(m.network),y=Mn(i),x=Mn(l),b=Array.isArray(a)?a:[],w=b.reduce((ye,de)=>ye+(Array.isArray(de)&&de.some(Z=>Z?.state==="warning")?1:0),0),A=oo(h,"cpuUsageRatio","processCpuRatio"),j=oo(h,"memoryUsedRatio"),k=is(h,"totalMemoryBytes"),N=is(h,"cpuLogicalCores")??is(x,"hardwareConcurrency"),M=is(x,"deviceMemory"),T=(N??0)>0&&A!==void 0&&j!==void 0&&(k??0)>0,D=(k??0)>0&&k<Et.hubMinimumTotalMemoryBytes,F=(M??0)>0&&M<Et.hubMinimumBrowserMemoryGb,$=(N??0)>0&&N<4||(A??0)>=Et.cpuWarningRatio||(j??0)>=Et.memoryWarningRatio||D||F,G=Math.max(0,Number(y.activeSoftwareFallbackCount??y.softwareFallbackCount??0)),L=Math.max(0,Number(y.activeDecoderCount||0)),Q=Math.max(0,Number(c?.bytesPerSecond||0)*8/1e6),q=is(g,"externalDeviceCount"),P=Ut(g,"route"),Y=q!==void 0&&!!P,H=(q??0)>0||P==="external";return[d.started&&!d.lastError?tt("hub-runtime","ok","Hub runtime is ready",`${d.connectedDeviceCount||0} Clients connected.`):tt("hub-runtime","warning","Hub runtime needs attention",String(d.lastError||"Hub is not ready.")),T?$?tt("hub-computer","warning",D?"Hub has limited system memory":F?"Browser reports limited memory capacity":"Hub computer may limit remote performance",[`${N||"?"} logical cores`,`${$b(k)} RAM`,M!==void 0?`${M} GB browser memory class`:"",`CPU ${A===void 0?"?":Math.round(A*100)}%`,`memory ${j===void 0?"?":Math.round(j*100)}%`].filter(Boolean).join(" · ")):tt("hub-computer","ok","Hub computer capacity is healthy",`${N||"?"} logical cores · ${$b(k)} RAM · CPU ${A===void 0?"not reported":`${Math.round(A*100)}%`}.`):tt("hub-computer","warning","Hub performance data is unavailable","Logical-core, CPU, used-memory, and total-memory telemetry are required."),L<=0?tt("hub-codec","warning","No active browser H.264 decoder to check","Open Wall or Control and wait for a video frame."):G>0?tt("hub-codec","warning","Some browser decoders use software fallback",`${L} active H.264 decoders · ${G} software fallbacks. Chrome does not expose definitive hardware acceptance.`):tt("hub-codec","ok","All active streams request hardware H.264",`${L} active decoders. Chrome hardware acceptance is inferred from health, not directly exposed.`),w>0?tt("hub-clients","warning",`${w} Clients need attention`,"Open the matching Wall slot lines for the exact cause."):tt("hub-clients","ok","Connected Clients report healthy remote paths",`${b.length} Client reports checked.`),tt("hub-network",!Y||H||Q>120?"warning":"ok",Y?H?`${q} Clients use an external network route`:Q>120?"Hub receive load is high":"Hub receive load is within range":"Hub network route data is unavailable",Y?`${P.toUpperCase()} route · ${Q.toFixed(Q>=10?0:1)} Mbps received by this browser.`:"The Hub has not reported LAN/external route classification yet.")]}async function aT(n,a={}){const i=n.filter(b=>b.canvas&&b.canvas.width>0&&b.canvas.height>0),l=Math.max(320,a.maxWidth||1920),c=Math.max(180,a.maxHeight||1080),d=i.length<=1?1:i.length<=4?2:i.length<=9?3:4,m=Math.max(1,Math.ceil(Math.max(1,i.length)/d)),h=Math.floor(l/d),g=Math.floor(c/m),y=document.createElement("canvas");y.width=Math.max(320,h*d),y.height=Math.max(180,g*m);const x=y.getContext("2d",{alpha:!1});if(!x)return y;x.fillStyle="#0b1220",x.fillRect(0,0,y.width,y.height),x.font="600 14px system-ui, sans-serif",x.textBaseline="bottom";for(let b=0;b<i.length;b+=1){const w=i[b],A=b%d,j=Math.floor(b/d),k=A*h,N=j*g,M=w.canvas,T=Math.min(h/M.width,g/M.height),D=Math.max(1,Math.floor(M.width*T)),F=Math.max(1,Math.floor(M.height*T)),$=k+Math.floor((h-D)/2),G=N+Math.floor((g-F)/2);x.drawImage(M,$,G,D,F),a.includeLabels!==!1&&(x.fillStyle="rgba(4, 10, 20, .74)",x.fillRect(k,N+g-28,h,28),x.fillStyle="#f8fafc",x.fillText(w.label,k+9,N+g-9))}return y}function sT(n){return n?.signature||"none"}function rT(n){return n?.label||"No capture target"}function Bb(n){return{...n,deviceIds:[...n.deviceIds],sourceCanvas:n.sourceCanvas||null}}function iT(){const n=new Date,a=i=>String(i).padStart(2,"0");return`${n.getFullYear()}${a(n.getMonth()+1)}${a(n.getDate())}_${a(n.getHours())}${a(n.getMinutes())}${a(n.getSeconds())}`}function lT(n){return n.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function oT(n){return`LiveDesk_${n.type==="wall"||n.type==="selection"?"Wall":`${lT(n.label)}_Monitor-${Number(n.monitorIndex||0)+1}`}_${iT()}.png`}async function cT(n,a,i){const l=await new Promise((d,m)=>n.toBlob(h=>h?d(h):m(new Error("Screenshot could not be encoded.")),"image/png")),c=await Lw(l,{kind:"screenshot",fileName:oT(a),target:a},i);try{await navigator.clipboard.write([new ClipboardItem({"image/png":l})])}catch{}return c.capture}function Hw(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(a=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(a))||""}function uT(n,a){const i=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","_"),l=a.label.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,70)||"Wall";return n==="timelapse"?`LiveDesk_Timelapse_${l}_${i}.webm`:`LiveDesk_Recording_${l}_${i}.webm`}async function Fw(n){if(typeof MediaRecorder>"u"||typeof n.canvas.captureStream!="function")throw new Error("This browser does not support video recording.");const a=Hw();if(!a)throw new Error("This browser does not support WebM recording.");const i=n.kind||"recording",l=await BN({kind:i,fileName:uT(i,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:i==="timelapse"?2e6:4e6}),m=performance.now();let h=0,g=!1,y=null,x=Promise.resolve();return d.ondataavailable=b=>{if(!b.data||b.data.size===0)return;const w=h++;x=x.then(()=>PN(l.sessionId,w,b.data,n.hubUrl).then(()=>{})).catch(A=>{y=y||(A instanceof Error?A:new Error(String(A))),n.onError?.(y)})},d.onerror=()=>{y=new Error("Video recording stopped unexpectedly."),n.onError?.(y)},d.start(1e3),{requestFrame:()=>{c.getVideoTracks()[0]?.requestFrame?.()},stop:async()=>{if(!g){if(g=!0,await new Promise(b=>{d.addEventListener("stop",()=>b(),{once:!0}),d.stop()}),c.getTracks().forEach(b=>b.stop()),await x,y)throw await _b(l.sessionId,n.hubUrl).catch(()=>{}),y;await UN(l.sessionId,Math.max(0,performance.now()-m),n.hubUrl)}},cancel:async()=>{g||(g=!0,d.stop(),c.getTracks().forEach(b=>b.stop()),await _b(l.sessionId,n.hubUrl).catch(()=>{}))}}}class dT{recorder=null;stream=null;segments=[];totalBytes=0;targetSignature="";startedAt=0;maxDurationMs=3e4;maxBytes=128*1024*1024;get seconds(){return!this.startedAt||this.segments.length===0?0:Math.min(30,Math.max(0,(performance.now()-this.segments[0].at)/1e3))}get active(){return this.recorder!==null}async start(a,i){if(this.recorder&&this.targetSignature===i.signature)return;if(this.stop(),typeof MediaRecorder>"u"||typeof a.captureStream!="function")throw new Error("This browser does not support Last 30s.");const l=Hw();if(!l)throw new Error("This browser does not support WebM recording.");this.targetSignature=i.signature,this.stream=a.captureStream(20),this.recorder=new MediaRecorder(this.stream,{mimeType:l,videoBitsPerSecond:3e6}),this.startedAt=performance.now(),this.recorder.ondataavailable=c=>{if(!c.data.size)return;const 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(i=>i.stop()),this.stream=null,this.segments=[],this.totalBytes=0,this.startedAt=0}async save(a,i){if(this.segments.length===0)throw new Error("The Last 30s buffer is not ready yet.");const l=new Blob(this.segments.map(m=>m.blob),{type:this.segments[0].blob.type||"video/webm"}),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 Lw(l,{kind:"last-30s",fileName:d,target:a,durationMs:Math.min(3e4,this.segments.length*1e3)},i)}}async function fT(n,a,i,l,c){const d=await Fw({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,i)*1e3);return{stop:async()=>{window.clearInterval(m),await d.stop()},cancel:async()=>{window.clearInterval(m),await d.cancel()}}}const $w="livedesk.captureSettings";function mT(){const n={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const a=JSON.parse(localStorage.getItem($w)||"null");return{...n,...a&&typeof a=="object"?a:{}}}catch{return n}}function hT(n){const[a,i]=u.useState(mT),[l,c]=u.useState(0),[d,m]=u.useState(0),[h,g]=u.useState(0),[y,x]=u.useState(!1),b=u.useRef(void 0),w=u.useRef(!1),A=u.useRef(""),j=u.useRef(null),k=u.useRef(null),N=u.useRef(null),M=u.useRef(null),T=u.useRef(new dT),D=n.sourceRegistry.resolveCurrentTarget(),F=sT(D),$=rT(D),G=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;u.useEffect(()=>{if(localStorage.setItem($w,JSON.stringify(a)),!w.current)return;const W=JSON.stringify(a);W!==A.current&&(A.current=W,Ve("/api/settings",{method:"PATCH",body:JSON.stringify({revision:b.current,filesAudio:{rollingBufferEnabled:a.rollingEnabled,recordingQuality:a.recordingQuality,timelapseIntervalSeconds:a.timelapseIntervalSeconds,includeRemoteCursor:a.includeRemoteCursor}})},n.hubUrl).then(O=>{b.current=Number(O.revision||b.current||0)}).catch(()=>{}))},[n.hubUrl,a]),u.useEffect(()=>{let W=!0;return Ve("/api/settings",void 0,n.hubUrl).then(O=>{if(!W)return;const le=O.settings?.filesAudio||{},ce=typeof le.rollingBufferEnabled=="boolean"?le.rollingBufferEnabled:a.rollingEnabled,K=le.recordingQuality==="high"?"high":"standard",be=[5,10,30,60].includes(Number(le.timelapseIntervalSeconds))?Number(le.timelapseIntervalSeconds):a.timelapseIntervalSeconds,he=typeof le.includeRemoteCursor=="boolean"?le.includeRemoteCursor:a.includeRemoteCursor,fe={rollingEnabled:ce,recordingQuality:K,timelapseIntervalSeconds:be,includeRemoteCursor:he};b.current=Number(O.revision||0),A.current=JSON.stringify(fe),w.current=!0,i(fe)}).catch(()=>{w.current=!0}),()=>{W=!1}},[n.hubUrl]);const L=u.useCallback(async W=>{if(W.sourceCanvas&&W.sourceCanvas.width>0&&W.sourceCanvas.height>0)return{target:Bb(W),canvas:W.sourceCanvas,cleanup:()=>{}};const O=await n.sourceRegistry.composeWall(W.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let le=!1;const ce=window.setInterval(async()=>{if(le)return;const K=await n.sourceRegistry.composeWall(W.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0}).catch(()=>null);!K||le||((O.width!==K.width||O.height!==K.height)&&(O.width=K.width,O.height=K.height),O.getContext("2d")?.drawImage(K,0,0))},100);return{target:Bb(W),canvas:O,cleanup:()=>{le=!0,window.clearInterval(ce)}}},[n.sourceRegistry]);u.useEffect(()=>{const W=T.current;if(!a.rollingEnabled||!D||!G){W.stop(),g(0);return}let O=!1,le=null;return(async()=>{try{if(le=await L(D),O)return;await W.start(le.canvas,le.target);const K=window.setInterval(()=>g(Math.round(W.seconds)),500),be=()=>{window.clearInterval(K),le?.cleanup()};W.__cleanup=be}catch(K){O||n.onToast(K instanceof Error?K.message:String(K))}})(),()=>{O=!0,W.stop(),W.__cleanup?.(),W.__cleanup=void 0,g(0)}},[L,n.onToast,a.rollingEnabled,F,G]);const Q=u.useCallback(W=>i(O=>({...O,rollingEnabled:W})),[]),q=u.useCallback(W=>i(O=>({...O,recordingQuality:W})),[]),P=u.useCallback(W=>i(O=>({...O,timelapseIntervalSeconds:W})),[]),Y=u.useCallback(async()=>{const W=n.sourceRegistry.resolveCurrentTarget();if(!W)throw new Error("화면이 준비된 후 다시 시도하세요.");x(!0);let O=null;try{O=await L(W),await cT(O.canvas,O.target,n.hubUrl),n.onToast("Screenshot saved")}finally{O?.cleanup(),x(!1)}},[L,n.hubUrl,n.onToast,n.sourceRegistry]),H=u.useCallback(async()=>{if(N.current)throw new Error("Stop the timelapse before recording.");const W=n.sourceRegistry.resolveCurrentTarget();if(!W)throw new Error("화면이 준비된 후 다시 시도하세요.");const O=await L(W),le=await Fw({canvas:O.canvas,target:O.target,fps:W.type==="control"?30:15,hubUrl:n.hubUrl,onError:ce=>n.onToast(ce.message)});k.current=O.cleanup,j.current=le,c(Date.now()),n.onToast("Recording started")},[L,n.hubUrl,n.onToast,n.sourceRegistry]),ye=u.useCallback(async()=>{const W=j.current;if(W){x(!0);try{await W.stop(),n.onToast("Recording saved")}finally{j.current=null,k.current?.(),k.current=null,c(0),x(!1)}}},[n.onToast]),de=u.useCallback(async()=>{if(j.current||N.current)throw new Error("Last 30s is unavailable during a recording.");const W=n.sourceRegistry.resolveCurrentTarget();if(!W)throw new Error("화면이 준비된 후 다시 시도하세요.");x(!0);try{await T.current.save(W,n.hubUrl),n.onToast("Last 30 seconds saved")}finally{x(!1)}},[n.hubUrl,n.onToast,n.sourceRegistry]),Z=u.useCallback(async()=>{if(j.current)throw new Error("Stop the recording before starting a timelapse.");const W=n.sourceRegistry.resolveCurrentTarget();if(!W)throw new Error("화면이 준비된 후 다시 시도하세요.");const O=await L(W),le=await fT(O.canvas,O.target,a.timelapseIntervalSeconds,n.hubUrl,ce=>n.onToast(ce.message));M.current=O.cleanup,N.current=le,m(Date.now()),n.onToast("Timelapse started")},[L,n.hubUrl,n.onToast,n.sourceRegistry,a.timelapseIntervalSeconds]),z=u.useCallback(async()=>{const W=N.current;if(W){x(!0);try{await W.stop(),n.onToast("Timelapse saved")}finally{N.current=null,M.current?.(),M.current=null,m(0),x(!1)}}},[n.onToast]);return u.useEffect(()=>{const W=O=>{!j.current&&!N.current||(O.preventDefault(),O.returnValue="")};return window.addEventListener("beforeunload",W),()=>window.removeEventListener("beforeunload",W)},[]),u.useEffect(()=>()=>{T.current.stop(),j.current?.cancel(),N.current?.cancel(),k.current?.(),M.current?.()},[]),{state:u.useMemo(()=>({recording:!!j.current,recordingStartedAt:l,timelapse:!!N.current,timelapseStartedAt:d,bufferSeconds:h,bufferEnabled:a.rollingEnabled,busy:y,targetLabel:$}),[h,y,l,a.rollingEnabled,$,d]),settings:a,videoSupported:G,targetKey:F,setRollingEnabled:Q,setRecordingQuality:q,setTimelapseInterval:P,takeScreenshot:Y,startRecording:H,stopRecording:ye,saveLast30Seconds:de,startTimelapse:Z,stopTimelapse:z}}const pT=120,gT=999,Eu=5,Du=30,vT=Number.POSITIVE_INFINITY,Bw="livedesk.remoteDirectory",yp="livedesk.localHubAccessEnabled",yT="livedesk.streamSettings",bT=18,xT="livedesk.controlStreamSettings",wT=8,Pw="livedesk.wallMonitorSelections",Uw=2,Hh=512*1024,bp="".trim(),qw="".trim(),Pb="livedesk-adsense-script",Fh=!!bp&&!!qw,ST=Object.freeze([{code:"ShiftLeft",label:"Shift"},{code:"ControlLeft",label:"Ctrl"},{code:"AltLeft",label:"Alt"},{code:"MetaLeft",label:"Win"}]),CT=1e3/60,$h=1500,kT=650,jT=1800,AT=650,MT=2500,Ub=1500,qb=15e3,NT=6e4,Gb=240,TT=1024,RT=640,ET=360,Vb="Connected LiveDesk clients are updating in batches. Hub will restart after every target reconnects on the requested versions.",yf="LiveDesk is replacing the Hub and verifying the requested version.",bf=5*6e4,DT=5e3,LT=8e3;function ao({label:n,tooltip:a,disabled:i=!1,active:l=!1,danger:c=!1,pressed:d,onClick:m,children:h}){return r.jsx("span",{className:`manual-action-tooltip ${i?"disabled":""}`.trim(),"data-tooltip":a,children:r.jsx("button",{className:`manual-action ${l?"active":""} ${c?"danger":""}`.trim(),onClick:m,disabled:i,"aria-label":n,"aria-pressed":d,type:"button",children:h})})}function _T(n,a){if(a.deviceId!==n.deviceId)return!1;const i=Number(a.browserReceivedEpochMs);if(!Number.isFinite(i)||i<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 so={free:{name:"Free",price:"$0",limit:Eu,audience:"Personal trial",note:"5 devices with a standard ad banner."},ltd:{name:"Plus",price:"$79 LTD",ltd:"$79 LTD",limit:Du,audience:"Creators and homelabs",note:"30 devices, no ads, personal use."},pro:{name:"Pro",price:"$199 LTD",ltd:"$199 LTD",limit:vT,audience:"Business and studios",note:"Commercial use and larger Client walls."}},IT={"mode3-h264-hw":30};function Wb(n,a){const i=m=>{const g=String(m||"").trim().replace(/^v/i,"").match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/);if(!g)return null;const y=g[4]?g[4].split(".").map(x=>/^\d+$/.test(x)?x.length>1&&x.startsWith("0")?Number.NaN:Number(x):x):[];return y.some(x=>typeof x=="number"&&!Number.isFinite(x))?null:{core:[Number(g[1]),Number(g[2]),Number(g[3])],prerelease:y}},l=i(n),c=i(a);if(!l||!c)return!1;for(let m=0;m<3;m+=1){if(l.core[m]>c.core[m])return!0;if(l.core[m]<c.core[m])return!1}if(l.prerelease.length===0||c.prerelease.length===0)return l.prerelease.length===0;const d=Math.max(l.prerelease.length,c.prerelease.length);for(let m=0;m<d;m+=1){const h=l.prerelease[m],g=c.prerelease[m];if(h===void 0||g===void 0)return g===void 0;if(h!==g){if(typeof h=="number"&&typeof g=="number")return h>g;if(typeof h=="number")return!1;if(typeof g=="number"||h>g)return!0;if(h<g)return!1}}return!0}function rs(n,a){return`${n}:${a}`}const zT={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:IT["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},OT={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:30,maxWidth:1920,maxHeight:1080,quality:75,showScreenStatus:!1};function Bh(n,a){if(n.length===0)return 0;const i=[...n].sort((c,d)=>c-d),l=Math.max(0,Math.min(i.length-1,Math.ceil(i.length*a)-1));return i[l]}function Gw(n,a){n.push(a),n.length>Gb&&n.splice(0,n.length-Gb)}function Yb(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 Kb(n,a,i){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),Gw(n.intervalSamplesMs,l)}if(n.lastFrameSeq!==void 0){const l=i-n.lastFrameSeq;l!==1&&(n.seqGapCount+=1,n.maxSeqGap=Math.max(n.maxSeqGap,Math.abs(l)))}n.lastAt=a,n.lastFrameSeq=i}function Qb(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 Xb(n){return!n||n.seqGapCount<=0?"none":`${n.seqGapCount} gaps / max ${n.maxSeqGap}`}function HT(n){return Number.isFinite(n)?String(n):"30+"}const Vw=[1,2,5,8,12,20,30],Zb={large:{maxWidth:1280,maxHeight:720},medium:{maxWidth:960,maxHeight:540},list:{maxWidth:640,maxHeight:360}},Ma={preserveConfiguredFpsDeviceCount:6,visibleRootMargin:"520px 0px 760px 0px",fallbackVisibleCounts:{large:12,medium:18,list:32},maxWallFramesPerSecond:bs.maxDirectFramesPerSecond,maxWallBytesPerSecond:80*1024*1024,maxFrameGapMs:280,lowLoadFrameRatio:.58,lowLoadByteRatio:.52,downshiftCooldownMs:1800,recoveryCooldownMs:14e3,minFps:5},Jb=2200,FT=8e3,$T=3500,BT=7e3,PT=2,UT=7e3,qT=2600,GT=4200,VT=750,WT=2,ex=4200;function tx(n,a){return Math.min(3e4,n*2**Math.min(3,Math.max(0,a)))}function $u(n,a){const i=n.capabilities?.[a];return typeof i=="boolean"?i:/^(1|true|yes|on)$/i.test(String(i||"").trim())}function ha(n){return n.deviceName||n.hostname||n.deviceId}function YT(){return"npx -y --prefer-online livedesk@latest client"}function KT(){return"npx -y --prefer-online livedesk@latest"}function QT(){try{return localStorage.getItem(Bw)||""}catch{return""}}function XT(){try{return localStorage.getItem(yp)==="1"}catch{return!1}}function hc(n){try{n?localStorage.setItem(yp,"1"):localStorage.removeItem(yp)}catch{}}function _r(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function Gn(n){const a=_r(n.status),i=_r(a.screens),l=_r(n.capabilities),c=_r(n.latestLiveFrame),d=_r(n.activeLiveStream),h=[a.monitorCount,a.screenCount,i.count,l.monitorCount,l.screenCount,c.monitorCount,d.monitorCount,Array.isArray(i.displays)?i.displays.length:0,Array.isArray(a.displays)?a.displays.length:0,Array.isArray(a.monitors)?a.monitors.length:0].map(Number).filter(g=>Number.isFinite(g)&&g>0).map(g=>Math.max(1,Math.min(64,Math.floor(g))));return h.length>0?Math.max(...h):1}function vl(n){const a=Number(n);return Number.isFinite(a)&&a>0?Math.floor(a):0}function Ww(n){const a=_r(n.status),l=[_r(a.screens).displays,a.displays,a.monitors];for(const c of l)if(!(!Array.isArray(c)||c.length===0))return c.map(d=>_r(d));return[]}function Yw(n,a){const i=Ww(n),l=i.find(g=>Number(g.index)===a)||i[a]||i[0]||{},c=vl(l.width),d=vl(l.height),m=[l.name,l.displayName,l.deviceName,l.id].find(g=>typeof g=="string"&&g.trim()),h=typeof m=="string"?m.trim():`Display ${a+1}`;return{index:a,name:h,width:c,height:d,primary:l.primary===!0||l.isPrimary===!0}}function ZT(n){const a=Gn(n);return Array.from({length:a},(i,l)=>Yw(n,l))}function JT(n){const a=Ww(n);if(a.length===0)return"";const i=a.map((l,c)=>{const d=Number(l.index),m=[l.name,l.displayName,l.deviceName,l.id].find(g=>typeof g=="string"&&g.trim()),h=g=>{const y=Number(g);return Number.isFinite(y)?y:null};return[Number.isFinite(d)?Math.floor(d):c,typeof m=="string"?m.trim().toLowerCase():"",h(l.left),h(l.top),h(l.width),h(l.height),l.primary===!0||l.isPrimary===!0]}).sort((l,c)=>l[0]-c[0]);return JSON.stringify(i)}function eR(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 Kw(n,a){const i=Yw(n,a);if(i.width>0&&i.height>0)return{width:i.width,height:i.height};const l=_r(n.status),c=vl(l.screenWidth||l.width),d=vl(l.screenHeight||l.height);return c>0&&d>0?{width:c,height:d}:null}function Qw(n){if(!n)return null;const a=vl(n.sourceWidth)||vl(n.width),i=vl(n.sourceHeight)||vl(n.height);return a>0&&i>0?{width:a,height:i}:null}function tR(n,a,i){const d=((typeof a?.monitorIndex=="number"?Vn(a.monitorIndex,Math.max(1,a.monitorCount||1)):i)===i?Qw(a):null)||Kw(n,i);return d?Math.max(.25,Math.min(4,d.width/d.height)):16/9}const xf=16/9;function Vn(n,a){const i=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(i-1,l)):0}function nR(){try{const n=localStorage.getItem(Pw);if(!n)return{selections:{},topologyFingerprints:{}};const a=JSON.parse(n),i=a&&typeof a=="object"&&!Array.isArray(a)?a.selections:void 0;if(Number(a?.version)!==Uw||!i||typeof i!="object"||Array.isArray(i))return{selections:{},topologyFingerprints:{}};const l={},c={};for(const[d,m]of Object.entries(i)){const h=d.trim(),g=_r(m),y=g.monitorIndex,x=Math.floor(Number(y));if(!h||!Number.isFinite(x))continue;l[h]=Math.max(0,Math.min(63,x));const b=typeof g.topologyFingerprint=="string"?g.topologyFingerprint.trim():"";b&&(c[h]=b)}return{selections:l,topologyFingerprints:c}}catch{return{selections:{},topologyFingerprints:{}}}}function aR(n,a){try{const i=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,{monitorIndex:c,topologyFingerprint:a[l]||""}]));localStorage.setItem(Pw,JSON.stringify({version:Uw,selections:i}))}catch{}}function sR(){return{...zT}}function rR(n){try{localStorage.setItem(yT,JSON.stringify({...n,version:bT}))}catch{}}function iR(){return{...OT}}function lR(n){try{localStorage.setItem(xT,JSON.stringify({...n,version:wT}))}catch{}}function Ph(n,a){return n.length!==a.length?!1:n.every((i,l)=>i===a[l])}function Uh(n){return[...new Set(n.filter(Boolean))].sort()}function oR(n){return Ma.fallbackVisibleCounts[n]||Ma.fallbackVisibleCounts.large}function cR(n,a,i){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=Zb[a]||Zb.large;return{maxWidth:Math.min(n.maxWidth,l.maxWidth),maxHeight:Math.min(n.maxHeight,l.maxHeight)}}function uR(n,a=Ma.minFps){const i=[...Vw].sort((c,d)=>c-d),l=Math.max(a,Math.floor(n/2));return[...i].reverse().find(c=>c<n&&c>=a)||l}function dR(n,a){return[...Vw].sort((l,c)=>l-c).find(l=>l>n&&l<=a)||a}function Lu(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let i=n,l=0;for(;i>=1024&&l<a.length-1;)i/=1024,l+=1;const c=l===0||i>=100?0:1;return`${i.toFixed(c)} ${a[l]}`}function nx(n){if(!Number.isFinite(n)||!n||n<=0)return"0GB";const a=1024**4,i=1024**3;return n>=a?`${Math.max(1,Math.round(n/a))}TB`:`${Math.max(1,Math.round(n/i))}GB`}function qh(n,a){if(!Number.isFinite(n)||!n||n<=0)return"not reported";const i=Math.max(0,n-Math.max(0,Number(a||0)));return`${nx(i)} / ${nx(n)}`}function fR(n){const a=new Uint8Array(n),i=32768;let l="";for(let c=0;c<a.length;c+=i){const d=a.subarray(c,c+i);l+=String.fromCharCode(...d)}return btoa(l)}function ax(n){return Array.from(n).filter(a=>a.size>=0).map(a=>{const i=a.webkitRelativePath||a.name;return{file:a,relativePath:i,fingerprint:`${a.size}:${a.lastModified}`}})}function mR(n){return n===1?"middle":n===2?"right":"left"}function sx(n,...a){for(const i of a){const l=n?.[i];if(typeof l=="string"&&l.trim())return l.trim()}return""}function rx(n){const a=Number(n);return Number.isInteger(a)&&a>=1&&a<=gT?a:0}const hR={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function pR(n,a,i){if(n==="online")return"Online";if(n==="busy")return"Busy";if(n==="stale")return"Stale";if(n==="offline")return"Offline";if(i==="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=hR[c.id]||c.label;return c.value&&c.value!=="-"?`${d} ${c.value}`:d}function Kf(n,a){const i=a.split(".");let l=n;for(const c of i){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 i of a){const l=Kf(n,i),c=Number(l);if(Number.isFinite(c))return c}}function ys(n,...a){for(const i of a){const l=Kf(n,i);if(typeof l=="string"&&l.trim())return l.trim();if(typeof l=="number"&&Number.isFinite(l))return String(l)}return""}function gR(n,...a){for(const i of a){const l=Kf(n,i);if(typeof l=="boolean")return l;if(/^(1|true|yes|on|online|running|ready)$/i.test(String(l||"").trim()))return!0;if(/^(0|false|no|off|offline|stopped|missing)$/i.test(String(l||"").trim()))return!1}}function Mi(n){const a=Number(n);if(Number.isFinite(a))return Math.max(0,Math.min(1,a>1?a/100:a))}function Gh(n,a){if(!(typeof n!="number"||typeof a!="number"||!Number.isFinite(n)||!Number.isFinite(a)||n<=0))return Mi((n-Math.max(0,a))/n)}function pc(n){return n===void 0?"-":`${Math.round(n*100)}%`}function Vh(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 ro(n,a=.92,i=.78){return n===void 0?"unknown":n>=a?"critical":n>=i?"warn":"good"}function vR(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 wf(n,a,i){const l=Kf(n,`tools.${a}`),c=ys(n,`tools.${a}.status`,`tooling.${a}.status`,`${a}.status`).toLowerCase(),d=gR(n,`tools.${a}.running`,`tooling.${a}.running`,`${a}.running`),m=ys(n,`tools.${a}.version`,`tooling.${a}.version`,`${a}.version`),h=ys(n,`tools.${a}.port`,`tooling.${a}.port`,`${a}.port`);let g="unknown";return c==="busy"?g="busy":["online","running","ready","active"].includes(c)||d===!0?g="online":(["offline","stopped","missing","not-found"].includes(c)||d===!1||l===!1)&&(g="offline"),{id:a,label:i,status:g,detail:g==="offline"?"offline":m||(h?`:${h}`:g==="unknown"?"not reported":g)}}function Xw(n){const a=n.status||{},i=xn(a,"cpu.cores","cpuCores","processorCount"),l=xn(a,"loadavg.0","cpu.load1"),c=Mi(xn(a,"cpu.usedRatio","cpu.usageRatio","cpu.ratio","cpu.usedPct","cpu.usagePct","cpu.percent")??(i&&l!==void 0?l/Math.max(1,i):void 0)),d=xn(a,"memory.totalBytes","totalMem"),m=xn(a,"memory.freeBytes","freeMem"),h=Mi(xn(a,"memory.usedRatio","memory.usedPct","usedMemRatio"))??Gh(d,m),g=xn(a,"disk.totalBytes","rootDisk.totalBytes","storage.totalBytes"),y=xn(a,"disk.freeBytes","rootDisk.freeBytes","storage.freeBytes"),x=Mi(xn(a,"disk.usedRatio","disk.usedPct","rootDisk.usedRatio","storage.usedRatio"))??Gh(g,y),b=xn(a,"thermal.cpuC","temperatureC","cpu.temperatureC","gpu.temperatureC"),w=Mi(xn(a,"gpu.usedRatio","gpu.usageRatio","gpu.usedPct","gpu.usagePct","gpu.percent","accelerators.gpu.usageRatio")),A=ys(a,"gpu.name","gpu.model","accelerators.gpu.name"),j=xn(a,"gpu.memory.totalBytes","gpu.totalMemoryBytes","gpu.vramTotalBytes"),k=xn(a,"gpu.memory.freeBytes","gpu.freeMemoryBytes","gpu.vramFreeBytes"),N=Mi(xn(a,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??Gh(j,k),M=xn(a,"gpu.temperatureC","thermal.gpuC"),T=Mi(xn(a,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),D=ys(a,"npu.name","npu.model","accelerators.npu.name"),F=xn(a,"npu.tops","npu.topsInt8","accelerators.npu.tops"),$=xn(a,"network.rxMbps","network.receiveMbps","network.downMbps"),G=xn(a,"network.txMbps","network.transmitMbps","network.upMbps"),L=xn(a,"network.latencyMs","network.rttMs"),Q=Mi(xn(a,"network.usedRatio","network.usageRatio","network.saturationRatio")),q=ys(a,"network.link","network.interface","network.name"),P=Math.max(b??Number.NEGATIVE_INFINITY,M??Number.NEGATIVE_INFINITY),Y=Number.isFinite(P)?P:void 0,H=Y===void 0?void 0:Mi((Y-35)/60),ye=b!==void 0&&M!==void 0?`CPU ${Math.round(b)}° · GPU ${Math.round(M)}°`:b!==void 0?`CPU ${Math.round(b)}°`:M!==void 0?`GPU ${Math.round(M)}°`:"-",de=ys(a,"workload.role","role","lane")||($u(n,"aiAssist")?"Agent worker":$u(n,"taskDispatch")?"Task worker":"Local machine"),Z=ys(n.latestTask,"status")||ys(a,"workload.status")||"idle",z=ys(n.latestTask,"title","instructionPreview")||ys(a,"workload.title"),se=ys(n.latestTask,"resultSummary","error","instructionPreview")||ys(a,"workload.summary"),W=[wf(a,"ollama","Ollama"),wf(a,"lmStudio","LM Studio"),wf(a,"comfyui","ComfyUI"),wf(a,"stableDiffusion","Stable Diffusion")],O=W.some(fe=>fe.status!=="unknown"),le=Date.parse(n.lastSeenAt||n.connectedAt||""),ce=Number.isFinite(le)?Date.now()-le:0;let K="online";n.connected?ce>5*6e4?K="stale":(b??0)>=86||(M??0)>=88||(c??0)>=.94||(w??0)>=.96||(N??0)>=.96||(T??0)>=.96||(h??0)>=.94||(x??0)>=.94||(L??0)>=200||Z==="failed"?K="critical":(b??0)>=78||(M??0)>=80||(c??0)>=.82||(w??0)>=.86||(N??0)>=.88||(T??0)>=.86||(h??0)>=.82||(x??0)>=.86||(L??0)>=80?K="warn":(["queued","running","targeted"].includes(Z)||W.some(fe=>fe.status==="busy"))&&(K="busy"):K="offline";const be=W.filter(fe=>fe.status==="online"||fe.status==="busy").length,he=[{id:"cpu",label:"CPU",value:pc(c),detail:i?`${i} cores`:l!==void 0?`load ${l.toFixed(1)}`:"not reported",ratio:c,state:ro(c,.92,.78)},{id:"memory",label:"RAM",value:pc(h),detail:qh(d,m),ratio:h,state:ro(h,.92,.78)},{id:"disk",label:"DISK",value:pc(x),detail:qh(g,y),ratio:x,state:ro(x,.92,.82)},{id:"gpu",label:"GPU",value:pc(w),detail:A||(j&&k!==void 0?`${Lu(k)} VRAM free`:M!==void 0?`${Math.round(M)}C`:"not reported"),ratio:w,state:M!==void 0&&M>=88?"critical":M!==void 0&&M>=80?"warn":ro(w,.96,.86)},{id:"vram",label:"VRAM",value:pc(N),detail:qh(j,k),ratio:N,state:ro(N,.96,.88)},{id:"npu",label:"NPU",value:T!==void 0?pc(T):F!==void 0?`${Math.round(F)} TOPS`:"-",detail:D||(F!==void 0?"neural engine":"not reported"),ratio:T,state:ro(T,.96,.86)},{id:"temp",label:"TEMP",value:ye,detail:be>0?`${be} local tools`:`uptime ${vR(xn(a,"uptimeSec"))}`,ratio:H,state:Y===void 0?"unknown":Y>=86?"critical":Y>=78?"warn":"good"},{id:"network",label:"NET",value:Vh($)||(L!==void 0?`${Math.round(L)}ms`:q||"-"),detail:Vh(G)?`${Vh(G)} up`:q||"not reported",ratio:Q,state:L!==void 0&&L>=200?"critical":L!==void 0&&L>=80?"warn":ro(Q,.9,.75)}];return{state:K,label:pR(K,he,Z),role:de,taskLabel:z||(Z==="idle"?"idle":Z),taskStatus:Z,taskSummary:se,tools:O?W:W.map(fe=>({...fe,detail:"not reported"})),metrics:he}}const yR=[{id:"list",label:"List"},{id:"medium",label:"Small"},{id:"large",label:"Large"}],bR=[{id:"sync-server",label:"Hub",icon:zr,accent:"blue",tooltip:"hub"},{id:"wall",label:"Wall",icon:I0,accent:"blue",tooltip:"wall"},{id:"control",label:"Control",icon:Xh,accent:"red",tooltip:"control"},{id:"share-files",label:"Share Files",icon:Sf,accent:"green",tooltip:"share-files"},{id:"agents",label:"Agents",icon:Zh,accent:"violet",tooltip:"agents"}],xR=[{id:"doc",label:"Doc",icon:Tf,accent:"amber"},{id:"support",label:"Support",icon:_u,accent:"violet"},{id:"pricing",label:"Pricing",icon:Iu,accent:"green"}];function wR(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 hn(n){return wR(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 io(n){return n.map(a=>hn(a))}function ja(n){return{languageName:n.languageName,languageLabel:n.languageLabel,eyebrow:n.eyebrow,title:hn(n.title),intro:hn(n.intro),sections:[{title:hn(n.managerTitle),body:hn(n.managerBody),points:io(n.managerPoints)},{title:hn(n.clientTitle),body:hn(n.clientBody),points:io(n.clientPoints)},{title:hn(n.syncTitle),body:hn(n.syncBody),points:io(n.syncPoints)},...n.agentTitle&&n.agentBody&&n.agentPoints?[{title:hn(n.agentTitle),body:hn(n.agentBody),points:io(n.agentPoints)}]:[],{title:hn(n.platformTitle),body:hn(n.platformBody),points:io(n.platformPoints)}],sync:{title:hn(n.syncTitle),body:hn(n.syncBody),points:io(n.syncPoints)},firewall:{title:hn(n.firewallTitle),body:hn(n.firewallBody),points:io(n.firewallPoints)},commands:{title:hn(n.commandsTitle),body:hn(n.commandsBody),manager:hn(n.managerCommandLabel),primary:hn(n.clientCommandLabel),slot:hn(n.slotCommandLabel),manual:hn(n.manualCommandLabel)}}}const wc={ko:ja({languageName:"한국어",languageLabel:"문서 언어",eyebrow:"LiveDesk Manual",title:"한 줄로 여는 로컬 Screen Wall",intro:"LiveDesk는 매니저 PC 한 대에서 여러 작업 PC, AI 박스, 맥미니, 개발 장비를 한 화면에 모니터링하고 필요한 제어를 실행하는 npm-first 원격 작업 데크입니다.",managerTitle:"1. 매니저 실행",managerBody:"화면을 모아 볼 컴퓨터에서 LiveDesk 매니저를 실행합니다. 매니저는 UI와 로컬 서버를 같이 열고 브라우저를 http://127.0.0.1:5179 로 띄웁니다.",managerPoints:["명령은 npx -y livedesk 입니다.","매니저는 Screen Wall/API 포트 5179와 클라이언트 접속 포트 5197을 사용합니다.","기존 LiveDesk 포트가 남아 있으면 기본적으로 정리하고 새로 시작합니다. 필요하면 --no-clean 을 붙입니다."],clientTitle:"2. 워크스테이션 연결",clientBody:"모니터링할 PC에서는 Google 로그인 또는 Hub 화면의 6자리 PIN으로 연결합니다. Hub가 꺼져 있으면 실시간 온라인 알림을 기다리고 적응형 간격으로 다시 확인합니다.",clientPoints:["빈 자리에 자동 배치하려면 npx -y livedesk client 를 실행합니다.","자리 번호를 고정하려면 npx -y livedesk client 3 처럼 번호를 붙입니다.","브라우저 연결 페이지에서 Google 버튼 또는 6자리 PIN 입력 중 하나를 선택합니다."],syncTitle:"3. Sync Server와 자동 발견",syncBody:"Sync Server는 이 매니저를 현재 계정의 활성 Screen Wall로 Supabase에 등록합니다. 클라이언트는 같은 Google 계정으로 로그인한 뒤 그 기록을 읽고 접속 후보들을 순서대로 시도합니다.",syncPoints:["등록 정보에는 host instance, LAN/private 주소, public 후보 주소, pair token, 짧은 lease가 포함됩니다.","같은 LAN 후보를 먼저 쓰고, 필요하면 외부 주소 후보를 시도합니다.","매니저 위치, VPN, 방화벽, 공유기 설정이 바뀌었거나 개발 중 활성 매니저를 바꿀 때 Sync Server를 누릅니다.","이제 livedesk.pages.dev의 Chrome Local Network Access 허용은 기본 실행 경로가 아닙니다. npm 매니저 앱이 실제 서버입니다."],agentTitle:"4. Agent로 여러 장비 작업하기",agentBody:"Agents 화면은 Hub에서 실행되는 Codex 기반 Agent가 연결된 장비를 확인하고, 선택한 권한 범위 안에서 작업을 실행하는 공간입니다. 클라이언트 PC에 Codex 앱이나 Codex SDK를 설치할 필요는 없습니다.",agentPoints:["Suggested tasks에는 현재 72개의 읽기·운영 작업 템플릿이 있으며, 검색과 권한·플랫폼·capability 조건으로 실행 가능 항목을 안내합니다.","Ask, Safe Auto, Full Access, Custom 권한 모드를 선택할 수 있습니다. 위험한 변경 작업은 승인 카드와 장비 capability 검사를 거칩니다.","All connected 또는 Selected로 대상 장비를 제한하고, 결과는 장비별 상태 칩과 실제 RAM·디스크·GPU·프로세스 요약으로 확인합니다.","Agent 실행은 Hub의 격리된 runtime과 LiveDesk MCP 도구를 통해서만 장비에 전달되며, 모든 작업은 timeout·취소·tool limit·감사 로그 경계를 가집니다."],platformTitle:"5. 현재 플랫폼과 스트림 상태",platformBody:"Windows의 Wall, Control, 파일 전송, 원격 오디오와 RemoteFast 경로를 현재 기준으로 확인했습니다. macOS와 Linux는 같은 npm 명령 경로를 유지하면서 권한과 캡처 백엔드를 확장하고 있습니다.",platformPoints:["자동 Wall과 Control은 모든 Client에서 직접 H.264를 사용합니다. RGB565/LZO Atlas는 내부 진단 실험에만 남고 자동 전송 경로에는 사용되지 않습니다.","원격 오디오는 선택한 장비가 capability를 광고할 때 사용할 수 있으며, 브라우저는 queue·drop·resync·automatic restart 상태를 진단합니다.","macOS: 화면 캡처와 제어에는 Screen Recording/Accessibility 권한이 필요합니다. RemoteFast 로그는 필요한 상태 중심으로 제한됩니다.","Linux: linux-x64 runtime, X11/XTEST 입력과 PipeWire/PulseAudio 기본 출력 오디오 캡처를 지원합니다."],firewallTitle:"방화벽과 외부 장소 연결",firewallBody:"같은 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:ja({languageName:"English",languageLabel:"Document language",eyebrow:"LiveDesk Manual",title:"Open a local Screen Wall with one command",intro:"LiveDesk is an npm-first remote work deck for monitoring many Clients, AI boxes, Mac minis, and dev machines from one manager PC.",managerTitle:"1. Run the manager",managerBody:"Run LiveDesk on the computer that will watch the screens. The manager starts the UI and local server together, then opens http://127.0.0.1:5179.",managerPoints:["The command is npx -y livedesk.","The manager uses port 5179 for the Screen Wall/API and port 5197 for client connections.","If an old LiveDesk process still owns those ports, startup cleans it by default. Add --no-clean when you want to keep it."],clientTitle:"2. Connect a Client",clientBody:"On each monitored computer, connect with Google sign-in or the 6-digit PIN shown on the Hub screen. If no manager is online yet, the client waits for a live online signal and falls back to adaptive retries.",clientPoints:["Run npx -y livedesk client for first available placement.","Run npx -y livedesk client 3 to pin the machine to slot 3.","The browser connection page lets you choose Google or a 6-digit PIN."],syncTitle:"3. Sync Server and discovery",syncBody:"Sync Server publishes this manager as the active Screen Wall for the signed-in account. Clients read that Supabase record after Google sign-in and try the endpoint candidates in order.",syncPoints:["The record includes host instance, LAN/private addresses, public endpoint candidates, pair token, and a short lease.","LAN candidates are preferred first, then public candidates if needed.","Press Sync Server after manager moves, VPN/firewall/router changes, or when this development machine should take over as active manager.","Chrome Local Network Access on livedesk.pages.dev is no longer the default runtime path. The npm manager app is the real server."],agentTitle:"4. Run multi-Client tasks with Agent",agentBody:"The Agents page runs a Codex-based Agent in the Hub to inspect connected Clients and perform actions within the selected permission scope. Client PCs do not need the Codex app or Codex SDK installed.",agentPoints:["Suggested tasks currently contains 72 read-only and operational templates with search plus permission, platform, and capability availability checks.","Choose Ask, Safe Auto, Full Access, or Custom. Risky changes go through approval cards and explicit client capability checks.","Limit targets with All connected or Selected. Results use compact per-device status chips and show real RAM, disk, GPU, and process summaries.","Runs stay inside the Hub-isolated runtime and LiveDesk MCP tools, with timeout, cancellation, tool-call limits, and audit-log boundaries."],platformTitle:"5. Current platform and stream state",platformBody:"Windows Wall, Control, file transfer, remote audio, and the RemoteFast path are verified against the current implementation. macOS and Linux keep the same npm command path while capture and permission backends expand.",platformPoints:["Automatic Wall and Control use direct H.264 for every Client. The RGB565/LZO Atlas remains only for internal diagnostic experiments and is never selected automatically.","Remote audio is available when the selected Client advertises the capability, with queue, drop, resync, and automatic-restart diagnostics in the browser.","macOS requires Screen Recording and Accessibility permissions for capture and control. RemoteFast logs focus on actionable state.","Linux includes the linux-x64 runtime, X11/XTEST input, and default-output audio capture through PipeWire or PulseAudio."],firewallTitle:"Firewall and remote locations",firewallBody:"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 Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ja:ja({languageName:"日本語",languageLabel:"ドキュメント言語",eyebrow:"LiveDesk Manual",title:"1行でローカル Screen Wall を開く",intro:"LiveDesk は、複数の作業 PC、AI マシン、Mac mini、開発機を1台の manager PC から監視する npm-first のリモート作業デッキです。",managerTitle:"1. manager を実行",managerBody:"画面を集めて見るコンピューターで LiveDesk manager を実行します。UI とローカルサーバーが同時に起動し、http://127.0.0.1:5179 が開きます。",managerPoints:["コマンドは npx -y livedesk です。","Screen Wall/API は 5179、client 接続は 5197 を使います。","古い LiveDesk プロセスがポートを使っている場合は、基本的に自動で整理して起動します。"],clientTitle:"2. Client を接続",clientBody:"監視される PC で同じ Google アカウントにログインします。manager がまだ無い場合、client はオンライン通知を待ち、適応型の間隔で再確認します。",clientPoints:["空きスロットに入れるには npx -y livedesk client を実行します。","スロットを固定するには npx -y livedesk client 3 のように番号を付けます。","大量の PC でも再ログインなしで待ち続けます。"],syncTitle:"3. Sync Server と自動検出",syncBody:"Sync Server はこの manager を現在の Google アカウントの active Screen Wall として Supabase に登録します。",syncPoints:["host instance、LAN/private アドレス、public 候補、pair token、短い lease を登録します。","client は LAN 候補を優先し、必要なら public 候補も試します。","VPN、firewall、router、manager の場所が変わったら Sync Server を押します。","livedesk.pages.dev の Chrome Local Network Access は標準実行経路ではありません。npm manager アプリが実際のサーバーです。"],platformTitle:"4. 現在のプラットフォーム状態",platformBody:"Windows は live screen transfer まで確認済みです。macOS と Linux も同じ npm コマンド経路を目標に対応を広げています。",platformPoints:["Windows: 動作確認済み。","macOS: 画面取得と制御には Screen Recording/Accessibility 権限が必要です。","Linux: linux-x64 runtime、grim/gnome-screenshot/import/scrot capture、X11/XTEST input backend を追加済み。audio は未対応です。"],firewallTitle:"Firewall と外部拠点",firewallBody:"同じ 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:"Client 接続",slotCommandLabel:"slot 3 に固定",manualCommandLabel:"高度な手動接続"}),"zh-CN":ja({languageName:"简体中文",languageLabel:"文档语言",eyebrow:"LiveDesk Manual",title:"用一条命令打开本地 Screen Wall",intro:"LiveDesk 是 npm-first 的远程工作台,用一台 manager PC 监控多台工作站、AI 主机、Mac mini 和开发机器。",managerTitle:"1. 运行 manager",managerBody:"在负责查看屏幕的电脑上运行 LiveDesk manager。它会同时启动 UI 和本地服务器,并打开 http://127.0.0.1:5179。",managerPoints:["命令是 npx -y livedesk。","Screen Wall/API 使用 5179,client 连接使用 5197。","如果旧的 LiveDesk 进程占用端口,默认会清理后重新启动。"],clientTitle:"2. 连接 Client",clientBody:"在被监控的电脑上使用同一个 Google 账号登录。如果 manager 尚未在线,client 会等待上线通知,并以自适应间隔重新检查。",clientPoints:["自动放入空位: npx -y livedesk client。","固定到 3 号位置: npx -y livedesk client 3。","大量电脑也可以持续等待,不需要反复登录。"],syncTitle:"3. Sync Server 和自动发现",syncBody:"Sync Server 会把当前 manager 作为该账号的 active Screen Wall 写入 Supabase。client 登录后读取记录并依次尝试连接候选地址。",syncPoints:["记录包括 host instance、LAN/private 地址、public 候选、pair token 和短 lease。","优先尝试同一 LAN 地址,需要时再尝试外部地址。","manager 位置、VPN、防火墙或路由变化后请点击 Sync Server。","livedesk.pages.dev 的 Chrome Local Network Access 不再是默认运行方式。npm manager app 才是真正服务器。"],platformTitle:"4. 当前平台状态",platformBody:"Windows 已确认可传输实时画面。macOS 和 Linux 正按同一 npm 命令路径扩展支持。",platformPoints:["Windows: 已确认可用。","macOS: 画面捕获和控制需要 Screen Recording/Accessibility 权限。","Linux: 已加入 linux-x64 runtime、grim/gnome-screenshot/import/scrot 捕获、X11/XTEST 输入后端。音频尚未启用。"],firewallTitle:"防火墙和外部地点",firewallBody:"同一 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:"连接 Client",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"高级手动连接"}),"zh-TW":ja({languageName:"繁體中文",languageLabel:"文件語言",eyebrow:"LiveDesk Manual",title:"用一行指令開啟本機 Screen Wall",intro:"LiveDesk 是 npm-first 的遠端工作台,用一台 manager PC 監看多台工作站、AI 主機、Mac mini 與開發機。",managerTitle:"1. 執行 manager",managerBody:"在負責看畫面的電腦上執行 LiveDesk manager。它會同時啟動 UI 與本機伺服器,並開啟 http://127.0.0.1:5179。",managerPoints:["指令是 npx -y livedesk。","Screen Wall/API 使用 5179,client 連線使用 5197。","若舊的 LiveDesk 程序占用連接埠,預設會清理後重新啟動。"],clientTitle:"2. 連接 Client",clientBody:"在被監看的電腦上使用同一個 Google 帳號登入。如果 manager 尚未上線,client 會等待上線通知,並以自適應間隔重新檢查。",clientPoints:["自動放入空位: npx -y livedesk client。","固定到 3 號位置: npx -y livedesk client 3。","大量電腦也能持續等待,不需要反覆登入。"],syncTitle:"3. Sync Server 與自動探索",syncBody:"Sync Server 會把目前 manager 登錄為此帳號的 active Screen Wall。client 登入後讀取 Supabase 記錄並依序嘗試連線候選地址。",syncPoints:["記錄包含 host instance、LAN/private 位址、public 候選、pair token 與短 lease。","優先嘗試 LAN 位址,需要時再嘗試外部位址。","manager 位置、VPN、防火牆或路由設定改變後請按 Sync Server。","livedesk.pages.dev 的 Chrome Local Network Access 不再是預設執行路徑。npm manager app 才是真正伺服器。"],platformTitle:"4. 目前平台狀態",platformBody:"Windows 已確認可傳輸即時畫面。macOS 與 Linux 也沿用相同 npm 指令路徑擴充支援。",platformPoints:["Windows: 已確認可用。","macOS: 畫面擷取與控制需要 Screen Recording/Accessibility 權限。","Linux: 已加入 linux-x64 runtime、grim/gnome-screenshot/import/scrot capture、X11/XTEST input backend。音訊尚未啟用。"],firewallTitle:"防火牆與外部地點",firewallBody:"同一 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:"連接 Client",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"進階手動連線"}),es:ja({languageName:"Español",languageLabel:"Idioma del documento",eyebrow:"LiveDesk Manual",title:"Abre un Screen Wall local con un comando",intro:"LiveDesk es una consola npm-first para vigilar muchas estaciones, cajas de IA, Mac mini y equipos de desarrollo desde un PC manager.",managerTitle:"1. Ejecuta el manager",managerBody:"Ejecuta LiveDesk en el equipo que verá las pantallas. El manager inicia la UI y el servidor local juntos y abre http://127.0.0.1:5179.",managerPoints:["El comando es npx -y livedesk.","El manager usa 5179 para Screen Wall/API y 5197 para conexiones client.","Si un proceso antiguo ocupa los puertos, el arranque lo limpia por defecto."],clientTitle:"2. Conecta una Client",clientBody:"En cada equipo monitoreado, inicia sesión con la misma cuenta Google. Si el manager aún no está activo, el client espera una señal en tiempo real y vuelve a comprobar con intervalos adaptativos.",clientPoints:["Usa npx -y livedesk client para el primer slot libre.","Usa npx -y livedesk client 3 para fijar el equipo al slot 3.","Los clients siguen esperando para no repetir login en muchas máquinas."],syncTitle:"3. Sync Server y descubrimiento",syncBody:"Sync Server publica este manager como Screen Wall activo para la cuenta. Los clients leen el registro en Supabase y prueban los endpoints.",syncPoints:["Incluye host instance, direcciones LAN/private, candidatos public, pair token y lease corto.","Primero se prueban candidatos LAN, luego públicos si hace falta.","Pulsa Sync Server después de cambios de manager, VPN, firewall o router.","Chrome Local Network Access en livedesk.pages.dev ya no es el flujo principal. La app npm manager es el servidor real."],platformTitle:"4. Estado de plataformas",platformBody:"Windows ya fue verificado con transferencia de pantalla. macOS y Linux siguen el mismo camino npm.",platformPoints:["Windows: verificado.","macOS: captura y control requieren permisos Screen Recording/Accessibility.","Linux: runtime linux-x64, entrada X11/XTEST y audio de salida mediante PipeWire o PulseAudio."],firewallTitle:"Firewall y sedes remotas",firewallBody:"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 Client",slotCommandLabel:"Fijar al slot 3",manualCommandLabel:"Conexión manual avanzada"}),fr:ja({languageName:"Français",languageLabel:"Langue du document",eyebrow:"LiveDesk Manual",title:"Ouvrir un Screen Wall local en une commande",intro:"LiveDesk est un deck npm-first pour surveiller plusieurs postes, machines IA, Mac mini et machines dev depuis un PC manager.",managerTitle:"1. Lancer le manager",managerBody:"Lancez LiveDesk sur l’ordinateur qui observe les écrans. Le manager démarre l’UI et le serveur local, puis ouvre http://127.0.0.1:5179.",managerPoints:["La commande est npx -y livedesk.","Le manager utilise 5179 pour Screen Wall/API et 5197 pour les connexions client.","Si un ancien processus utilise les ports, le démarrage le nettoie par défaut."],clientTitle:"2. Connecter une Client",clientBody:"Sur chaque ordinateur surveillé, connectez-vous avec le même compte Google. Si le manager n’est pas encore actif, le client réessaie toutes les 5 secondes.",clientPoints:["Utilisez npx -y livedesk client pour le premier slot libre.","Utilisez npx -y livedesk client 3 pour fixer la machine au slot 3.","Les clients continuent d’attendre pour éviter les reconnexions répétées."],syncTitle:"3. Sync Server et découverte",syncBody:"Sync Server publie ce manager comme Screen Wall actif du compte. Les clients lisent l’enregistrement Supabase et testent les endpoints.",syncPoints:["Il contient host instance, adresses LAN/private, candidats public, pair token et lease court.","Les candidats LAN sont essayés en premier, puis les candidats publics si besoin.","Cliquez Sync Server après un changement de manager, VPN, firewall ou routeur.","Chrome Local Network Access sur livedesk.pages.dev n’est plus le chemin par défaut. L’app npm manager est le vrai serveur."],platformTitle:"4. État des plateformes",platformBody:"Windows est vérifié avec transfert d’écran live. macOS et Linux suivent le même chemin npm.",platformPoints:["Windows: vérifié.","macOS: capture et contrôle nécessitent Screen Recording/Accessibility.","Linux: runtime linux-x64, entrée X11/XTEST et audio de sortie via PipeWire ou PulseAudio."],firewallTitle:"Firewall et sites distants",firewallBody:"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 Client",slotCommandLabel:"Fixer au slot 3",manualCommandLabel:"Connexion manuelle avancée"}),de:ja({languageName:"Deutsch",languageLabel:"Dokumentsprache",eyebrow:"LiveDesk Manual",title:"Lokale Screen Wall mit einem Befehl öffnen",intro:"LiveDesk ist ein npm-first Arbeitsdeck, um viele Clients, AI-Boxen, Mac minis und Dev-Rechner von einem Manager-PC zu überwachen.",managerTitle:"1. Manager starten",managerBody:"Starte LiveDesk auf dem Computer, der die Screens sieht. Der Manager startet UI und lokalen Server zusammen und öffnet http://127.0.0.1:5179.",managerPoints:["Der Befehl ist npx -y livedesk.","Der Manager nutzt 5179 für Screen Wall/API und 5197 für Client-Verbindungen.","Wenn alte LiveDesk-Prozesse Ports belegen, werden sie beim Start standardmäßig bereinigt."],clientTitle:"2. Client verbinden",clientBody:"Melde dich auf jedem überwachten Computer mit demselben Google-Konto an. Wenn kein Manager online ist, wartet der Client auf ein Live-Signal und prüft mit adaptiven Intervallen erneut.",clientPoints:["npx -y livedesk client nutzt den ersten freien Slot.","npx -y livedesk client 3 fixiert den Rechner auf Slot 3.","Clients warten weiter, damit große Setups kein wiederholtes Login brauchen."],syncTitle:"3. Sync Server und Discovery",syncBody:"Sync Server veröffentlicht diesen Manager als aktive Screen Wall des Kontos. Clients lesen den Supabase-Eintrag und testen Endpoints der Reihe nach.",syncPoints:["Enthält host instance, LAN/private Adressen, public Kandidaten, pair token und kurze lease.","LAN-Kandidaten werden zuerst versucht, danach public Kandidaten.","Nach Änderungen an Manager, VPN, Firewall oder Router Sync Server drücken.","Chrome Local Network Access auf livedesk.pages.dev ist nicht mehr der Standardpfad. Die npm Manager App ist der echte Server."],platformTitle:"4. Plattformstatus",platformBody:"Windows wurde mit Live-Screen-Transfer geprüft. macOS und Linux folgen demselben npm-Pfad.",platformPoints:["Windows: verifiziert.","macOS: Capture und Control brauchen Screen Recording/Accessibility Rechte.","Linux: linux-x64 Runtime, X11/XTEST Eingabe und Ausgangsaudio über PipeWire oder PulseAudio."],firewallTitle:"Firewall und entfernte Standorte",firewallBody:"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:"Client verbinden",slotCommandLabel:"An Slot 3 fixieren",manualCommandLabel:"Erweiterte manuelle Verbindung"}),"pt-BR":ja({languageName:"Português",languageLabel:"Idioma do documento",eyebrow:"LiveDesk Manual",title:"Abra um Screen Wall local com um comando",intro:"LiveDesk é um deck npm-first para monitorar várias estações, caixas de IA, Mac minis e máquinas dev a partir de um PC manager.",managerTitle:"1. Execute o manager",managerBody:"Rode LiveDesk no computador que verá as telas. O manager inicia a UI e o servidor local juntos e abre http://127.0.0.1:5179.",managerPoints:["O comando é npx -y livedesk.","O manager usa 5179 para Screen Wall/API e 5197 para conexões client.","Se um processo antigo ocupa as portas, a inicialização limpa por padrão."],clientTitle:"2. Conecte uma Client",clientBody:"Em cada computador monitorado, entre com a mesma conta Google. Se o manager ainda não estiver online, o client aguarda um sinal em tempo real e verifica novamente em intervalos adaptativos.",clientPoints:["Use npx -y livedesk client para o primeiro slot livre.","Use npx -y livedesk client 3 para fixar no slot 3.","Clients continuam tentando para evitar login repetido em muitos PCs."],syncTitle:"3. Sync Server e descoberta",syncBody:"Sync Server publica este manager como Screen Wall ativo da conta. Clients leem o registro no Supabase e testam endpoints.",syncPoints:["Inclui host instance, endereços LAN/private, candidatos public, pair token e lease curto.","Candidatos LAN vêm primeiro; public depois se necessário.","Clique Sync Server após mudanças de manager, VPN, firewall ou roteador.","Chrome Local Network Access em livedesk.pages.dev não é mais o caminho padrão. O app npm manager é o servidor real."],platformTitle:"4. Estado das plataformas",platformBody:"Windows foi verificado com transferência de tela. macOS e Linux seguem o mesmo caminho npm.",platformPoints:["Windows: verificado.","macOS: captura e controle precisam de permissões Screen Recording/Accessibility.","Linux: runtime linux-x64, captura grim/gnome-screenshot/import/scrot e entrada X11/XTEST adicionados. Áudio ainda desativado."],firewallTitle:"Firewall e locais remotos",firewallBody:"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 Client",slotCommandLabel:"Fixar no slot 3",manualCommandLabel:"Conexão manual avançada"}),it:ja({languageName:"Italiano",languageLabel:"Lingua documento",eyebrow:"LiveDesk Manual",title:"Apri uno Screen Wall locale con un comando",intro:"LiveDesk è un deck npm-first per monitorare Client, box AI, Mac mini e macchine dev da un solo PC manager.",managerTitle:"1. Avvia il manager",managerBody:"Esegui LiveDesk sul computer che guarderà gli schermi. Il manager avvia UI e server locale e apre http://127.0.0.1:5179.",managerPoints:["Il comando è npx -y livedesk.","Il manager usa 5179 per Screen Wall/API e 5197 per connessioni client.","Se vecchi processi occupano le porte, l’avvio le pulisce di default."],clientTitle:"2. Connetti una Client",clientBody:"Su ogni computer monitorato, accedi con lo stesso account Google. Se il manager non è online, il client riprova ogni 5 secondi.",clientPoints:["npx -y livedesk client usa il primo slot libero.","npx -y livedesk client 3 fissa la macchina allo slot 3.","I client continuano a provare per evitare login ripetuti."],syncTitle:"3. Sync Server e discovery",syncBody:"Sync Server pubblica questo manager come Screen Wall attivo dell’account. I client leggono Supabase e provano gli endpoint.",syncPoints:["Include host instance, indirizzi LAN/private, candidati public, pair token e lease breve.","Prima LAN, poi public se necessario.","Premi Sync Server dopo cambi di manager, VPN, firewall o router.","Chrome Local Network Access su livedesk.pages.dev non è più il percorso principale. L’app npm manager è il server reale."],platformTitle:"4. Stato piattaforme",platformBody:"Windows è verificato con trasferimento schermo live. macOS e Linux seguono lo stesso percorso npm.",platformPoints:["Windows: verificato.","macOS: capture e control richiedono permessi Screen Recording/Accessibility.","Linux: aggiunti runtime linux-x64, capture grim/gnome-screenshot/import/scrot e input X11/XTEST. Audio disattivato."],firewallTitle:"Firewall e sedi remote",firewallBody:"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 Client",slotCommandLabel:"Fissa allo slot 3",manualCommandLabel:"Connessione manuale avanzata"}),id:ja({languageName:"Bahasa Indonesia",languageLabel:"Bahasa dokumen",eyebrow:"LiveDesk Manual",title:"Buka Screen Wall lokal dengan satu perintah",intro:"LiveDesk adalah deck npm-first untuk memantau banyak Client, AI box, Mac mini, dan mesin dev dari satu PC manager.",managerTitle:"1. Jalankan manager",managerBody:"Jalankan LiveDesk di komputer yang melihat layar. Manager membuka UI dan server lokal bersama, lalu membuka http://127.0.0.1:5179.",managerPoints:["Perintahnya npx -y livedesk.","Manager memakai 5179 untuk Screen Wall/API dan 5197 untuk koneksi client.","Jika proses lama memakai port itu, startup membersihkannya secara default."],clientTitle:"2. Hubungkan Client",clientBody:"Di komputer yang dipantau, masuk dengan akun Google yang sama. Jika manager belum online, client tetap mencoba tiap 5 detik.",clientPoints:["npx -y livedesk client memakai slot kosong pertama.","npx -y livedesk client 3 mengunci mesin ke slot 3.","Client terus mencoba agar banyak PC tidak perlu login berulang."],syncTitle:"3. Sync Server dan discovery",syncBody:"Sync Server menerbitkan manager ini sebagai Screen Wall aktif untuk akun. Client membaca Supabase dan mencoba endpoint.",syncPoints:["Berisi host instance, alamat LAN/private, kandidat public, pair token, dan lease pendek.","Kandidat LAN dicoba lebih dulu, lalu public jika perlu.","Tekan Sync Server setelah perubahan manager, VPN, firewall, atau router.","Chrome Local Network Access di livedesk.pages.dev bukan jalur utama lagi. App npm manager adalah server sebenarnya."],platformTitle:"4. Status platform",platformBody:"Windows sudah diverifikasi dengan live screen transfer. macOS dan Linux mengikuti jalur npm yang sama.",platformPoints:["Windows: terverifikasi.","macOS: capture dan control perlu izin Screen Recording/Accessibility.","Linux: runtime linux-x64, capture grim/gnome-screenshot/import/scrot, dan input X11/XTEST sudah ditambahkan. Audio belum aktif."],firewallTitle:"Firewall dan lokasi luar",firewallBody:"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 Client",slotCommandLabel:"Kunci ke slot 3",manualCommandLabel:"Koneksi manual lanjutan"}),vi:ja({languageName:"Tiếng Việt",languageLabel:"Ngôn ngữ tài liệu",eyebrow:"LiveDesk Manual",title:"Mở Screen Wall cục bộ bằng một lệnh",intro:"LiveDesk là deck npm-first để giám sát nhiều Client, máy AI, Mac mini và máy dev từ một PC manager.",managerTitle:"1. Chạy manager",managerBody:"Chạy LiveDesk trên máy dùng để xem màn hình. Manager khởi động UI và server cục bộ cùng lúc, rồi mở http://127.0.0.1:5179.",managerPoints:["Lệnh là npx -y livedesk.","Manager dùng 5179 cho Screen Wall/API và 5197 cho kết nối client.","Nếu tiến trình cũ giữ port, startup mặc định sẽ dọn và khởi động lại."],clientTitle:"2. Kết nối Client",clientBody:"Trên mỗi máy được giám sát, đăng nhập cùng tài khoản Google. Nếu manager chưa online, client tiếp tục thử mỗi 5 giây.",clientPoints:["npx -y livedesk client dùng slot trống đầu tiên.","npx -y livedesk client 3 ghim máy vào slot 3.","Client tiếp tục chờ để nhiều máy không cần đăng nhập lại."],syncTitle:"3. Sync Server và tự phát hiện",syncBody:"Sync Server đăng manager này là Screen Wall đang hoạt động của tài khoản. Client đọc Supabase và thử các endpoint.",syncPoints:["Bao gồm host instance, địa chỉ LAN/private, public candidate, pair token và lease ngắn.","Ưu tiên LAN trước, sau đó thử public nếu cần.","Bấm Sync Server sau thay đổi manager, VPN, firewall hoặc router.","Chrome Local Network Access trên livedesk.pages.dev không còn là đường chạy chính. App npm manager mới là server thật."],platformTitle:"4. Trạng thái nền tảng",platformBody:"Windows đã được kiểm chứng với truyền màn hình live. macOS và Linux đi theo cùng đường npm.",platformPoints:["Windows: đã kiểm chứng.","macOS: capture và control cần quyền Screen Recording/Accessibility.","Linux: đã thêm runtime linux-x64, capture grim/gnome-screenshot/import/scrot và input X11/XTEST. Audio chưa bật."],firewallTitle:"Firewall và địa điểm ngoài",firewallBody:"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 Client",slotCommandLabel:"Ghim vào slot 3",manualCommandLabel:"Kết nối thủ công nâng cao"}),th:ja({languageName:"ไทย",languageLabel:"ภาษาของเอกสาร",eyebrow:"LiveDesk Manual",title:"เปิด Screen Wall ภายในด้วยคำสั่งเดียว",intro:"LiveDesk คือ deck แบบ npm-first สำหรับดู Client, กล่อง AI, Mac mini และเครื่อง dev หลายเครื่องจาก manager PC เครื่องเดียว",managerTitle:"1. รัน manager",managerBody:"รัน LiveDesk บนเครื่องที่ใช้ดูหน้าจอ Manager จะเปิด UI และ local server พร้อมกัน แล้วเปิด http://127.0.0.1:5179",managerPoints:["คำสั่งคือ npx -y livedesk","Manager ใช้ 5179 สำหรับ Screen Wall/API และ 5197 สำหรับ client connection","ถ้า process เก่ายังใช้ port อยู่ startup จะล้างให้โดย default"],clientTitle:"2. เชื่อม Client",clientBody:"บนเครื่องที่ต้อง monitor ให้ login ด้วย Google account เดียวกัน ถ้า manager ยังไม่ออนไลน์ client จะลองใหม่ทุก 5 วินาที",clientPoints:["npx -y livedesk client จะใช้ slot ว่างแรก","npx -y livedesk client 3 จะตรึงเครื่องไว้ที่ slot 3","Client จะรอต่อเนื่องเพื่อไม่ต้อง login ซ้ำเมื่อมีหลายเครื่อง"],syncTitle:"3. Sync Server และ discovery",syncBody:"Sync Server จะ publish manager นี้เป็น active Screen Wall ของ account แล้ว client อ่านข้อมูลจาก Supabase และลอง endpoint ต่างๆ",syncPoints:["มี host instance, LAN/private address, public candidate, pair token และ short lease","ลอง LAN ก่อน แล้วค่อยลอง public ถ้าจำเป็น","กด Sync Server หลังเปลี่ยน manager, VPN, firewall หรือ router","Chrome Local Network Access บน livedesk.pages.dev ไม่ใช่ runtime หลักแล้ว app npm manager คือ server จริง"],platformTitle:"4. สถานะ platform",platformBody:"Windows ตรวจสอบแล้วว่าส่งภาพ live ได้ macOS และ Linux ใช้เส้นทาง npm เดียวกัน",platformPoints:["Windows: verified","macOS: capture/control ต้องใช้สิทธิ์ Screen Recording/Accessibility","Linux: เพิ่ม linux-x64 runtime, grim/gnome-screenshot/import/scrot capture และ X11/XTEST input แล้ว audio ยังปิดอยู่"],firewallTitle:"Firewall และเครื่องต่างสถานที่",firewallBody:"ใน 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:"เชื่อม Client",slotCommandLabel:"ตรึง slot 3",manualCommandLabel:"manual connection ขั้นสูง"}),hi:ja({languageName:"हिन्दी",languageLabel:"दस्तावेज़ भाषा",eyebrow:"LiveDesk Manual",title:"एक कमांड से local Screen Wall खोलें",intro:"LiveDesk एक npm-first remote work deck है जिससे एक manager PC से कई Client, AI box, Mac mini और dev machines देखे जा सकते हैं।",managerTitle:"1. manager चलाएं",managerBody:"जिस computer से screens देखनी हैं उस पर LiveDesk manager चलाएं। यह UI और local server साथ में शुरू करता है और http://127.0.0.1:5179 खोलता है।",managerPoints:["कमांड है npx -y livedesk।","Manager Screen Wall/API के लिए 5179 और client connections के लिए 5197 इस्तेमाल करता है।","अगर पुराने LiveDesk ports बचे हों तो startup default रूप से साफ करता है।"],clientTitle:"2. Client जोड़ें",clientBody:"हर monitored computer पर उसी Google account से sign in करें। Manager online न हो तब भी client बंद नहीं होता और हर 5 सेकंड retry करता है।",clientPoints:["npx -y livedesk client पहला खाली slot लेता है।","npx -y livedesk client 3 machine को slot 3 पर pin करता है।","बहुत सी machines हों तब भी बार-बार login की जरूरत नहीं रहती।"],syncTitle:"3. Sync Server और discovery",syncBody:"Sync Server इस manager को account का active Screen Wall बनाकर Supabase में publish करता है। Clients record पढ़कर endpoints try करते हैं।",syncPoints:["इसमें host instance, LAN/private addresses, public candidates, pair token और short lease होता है।","LAN candidates पहले try होते हैं, जरूरत हो तो public candidates।","Manager, VPN, firewall या router बदलने के बाद Sync Server दबाएं।","livedesk.pages.dev का Chrome Local Network Access अब default runtime नहीं है। npm manager app ही real server है।"],platformTitle:"4. Platform status",platformBody:"Windows live screen transfer के साथ verified है। macOS और Linux भी इसी npm path पर आगे बढ़ रहे हैं।",platformPoints:["Windows: verified.","macOS: capture/control के लिए Screen Recording/Accessibility permissions चाहिए।","Linux: linux-x64 runtime, X11/XTEST input और PipeWire/PulseAudio output audio capture उपलब्ध हैं।"],firewallTitle:"Firewall और remote locations",firewallBody:"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 Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ar:ja({languageName:"العربية",languageLabel:"لغة المستند",eyebrow:"LiveDesk Manual",title:"افتح Screen Wall محلي بأمر واحد",intro:"LiveDesk هو deck بنمط npm-first لمراقبة عدة Clients وأجهزة AI وMac mini وأجهزة تطوير من كمبيوتر manager واحد.",managerTitle:"1. شغل manager",managerBody:"شغل LiveDesk على الكمبيوتر الذي سيعرض الشاشات. يبدأ manager الواجهة والخادم المحلي معا ويفتح http://127.0.0.1:5179.",managerPoints:["الأمر هو npx -y livedesk.","يستخدم manager المنفذ 5179 للواجهة/API والمنفذ 5197 لاتصالات client.","إذا بقيت عملية LiveDesk قديمة على المنافذ، يتم تنظيفها افتراضيا عند التشغيل."],clientTitle:"2. وصل Client",clientBody:"على كل كمبيوتر تتم مراقبته، سجل الدخول بنفس حساب Google. إذا لم يكن manager متاحا، يبقى client يعمل ويحاول كل 5 ثوان.",clientPoints:["npx -y livedesk client يختار أول slot فارغ.","npx -y livedesk client 3 يثبت الجهاز في slot 3.","clients تستمر بالمحاولة لتجنب تكرار تسجيل الدخول عند كثرة الأجهزة."],syncTitle:"3. Sync Server والاكتشاف",syncBody:"Sync Server ينشر هذا manager كـ active Screen Wall للحساب. يقرأ clients سجل Supabase ويجربون endpoints بالترتيب.",syncPoints:["السجل يتضمن host instance وعناوين LAN/private وpublic candidates وpair token وlease قصير.","يتم تفضيل LAN أولا، ثم public عند الحاجة.","اضغط Sync Server بعد تغيير manager أو VPN أو firewall أو router.","Chrome Local Network Access على livedesk.pages.dev لم يعد مسار التشغيل الافتراضي. تطبيق npm manager هو الخادم الحقيقي."],platformTitle:"4. حالة المنصات",platformBody:"Windows تم التحقق منه مع نقل شاشة live. macOS وLinux يتبعان نفس مسار npm.",platformPoints:["Windows: تم التحقق.","macOS: capture/control يحتاجان أذونات Screen Recording/Accessibility.","Linux: تمت إضافة linux-x64 runtime وgrim/gnome-screenshot/import/scrot capture وX11/XTEST input. الصوت ما زال معطلا."],firewallTitle:"Firewall والمواقع البعيدة",firewallBody:"داخل نفس 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 Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),tr:ja({languageName:"Türkçe",languageLabel:"Belge dili",eyebrow:"LiveDesk Manual",title:"Yerel Screen Wall tek komutla açılsın",intro:"LiveDesk, tek bir manager PC üzerinden birçok Client, AI box, Mac mini ve dev machine izlemek için npm-first bir çalışma deckidir.",managerTitle:"1. Manager çalıştır",managerBody:"Ekranları izleyecek bilgisayarda LiveDesk manager çalıştır. Manager UI ve local server birlikte başlar ve http://127.0.0.1:5179 açılır.",managerPoints:["Komut: npx -y livedesk.","Manager Screen Wall/API için 5179, client bağlantıları için 5197 kullanır.","Eski LiveDesk process portları tutuyorsa başlangıç varsayılan olarak temizler."],clientTitle:"2. Client bağla",clientBody:"İzlenecek bilgisayarda aynı Google hesabıyla giriş yap. Manager henüz online değilse client kapanmaz ve her 5 saniyede tekrar dener.",clientPoints:["npx -y livedesk client ilk boş slota yerleşir.","npx -y livedesk client 3 makineyi slot 3’e sabitler.","Çok makinede tekrar tekrar login gerekmesin diye client beklemeye devam eder."],syncTitle:"3. Sync Server ve discovery",syncBody:"Sync Server bu managerı hesabın active Screen Wall kaydı olarak Supabase’e yazar. Clients bu kaydı okuyup endpoint adaylarını dener.",syncPoints:["Host instance, LAN/private adresler, public adaylar, pair token ve kısa lease içerir.","Önce LAN adayları, gerekirse public adaylar denenir.","Manager, VPN, firewall veya router değişince Sync Server’a bas.","livedesk.pages.dev üzerindeki Chrome Local Network Access artık default runtime yolu değil. Gerçek server npm manager app."],platformTitle:"4. Platform durumu",platformBody:"Windows live screen transfer ile doğrulandı. macOS ve Linux aynı npm yolunu takip ediyor.",platformPoints:["Windows: doğrulandı.","macOS: capture/control için Screen Recording/Accessibility izinleri gerekir.","Linux: linux-x64 runtime, grim/gnome-screenshot/import/scrot capture ve X11/XTEST input backend eklendi. Audio kapalı."],firewallTitle:"Firewall ve uzak konumlar",firewallBody:"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:"Client bağla",slotCommandLabel:"Slot 3’e sabitle",manualCommandLabel:"Gelişmiş manuel bağlantı"})},SR=Object.entries(wc).map(([n,a])=>({id:n,label:a.languageName}));function CR(){if(typeof navigator>"u")return"en";const n=navigator.languages?.length?navigator.languages:[navigator.language];for(const a of n){const i=a.toLowerCase();if(wc[a])return a;if(i.startsWith("zh-tw")||i.startsWith("zh-hk"))return"zh-TW";if(i.startsWith("pt"))return"pt-BR";const l=i.split("-")[0];if(wc[l])return l}return"en"}function ix({index:n}){const a=n+1;return r.jsx("article",{className:"device-tile placeholder-tile","aria-label":`Empty slot ${a}`,children:r.jsxs("div",{className:"tile-screen","aria-hidden":"true",children:[r.jsx("span",{className:"slot-grid","aria-hidden":"true"}),r.jsxs("span",{className:"empty-screen",children:[r.jsx(Ta,{size:24}),r.jsxs("strong",{children:["Slot ",String(a).padStart(3,"0")]})]})]})})}const kR=["cpu","gpu","memory","vram","network","disk","temp"];function jR({device:n,slotNumber:a,selected:i,updateIndicator:l,onSelect:c,onOpenControl:d}){const m=Xw(n),h=new Map(m.metrics.map(y=>[y.id,y])),g=l?.label||m.label;return r.jsxs("div",{className:`wall-device-list-row state-${m.state} ${i?"selected":""}`,role:"row","aria-selected":i,tabIndex:0,onClick:c,onDoubleClick:y=>{y.preventDefault(),d()},onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),c())},children:[r.jsxs("span",{className:"wall-device-name",role:"gridcell",children:[r.jsx("span",{className:"wall-device-icon","aria-hidden":"true",children:r.jsx(Ta,{size:17})}),r.jsxs("span",{children:[r.jsx("strong",{children:ha(n)}),r.jsxs("small",{children:["Slot ",String(a).padStart(3,"0"),n.platform?` · ${n.platform}`:"",n.arch?` · ${n.arch}`:""]})]}),i&&r.jsx(Ir,{size:16,strokeWidth:3,"aria-label":"Selected"})]}),r.jsxs("span",{className:`wall-device-list-status state-${m.state} ${l?`update-${l.state}`:""}`,role:"gridcell",title:l?.error||g,children:[r.jsx("i",{"aria-hidden":"true"}),r.jsx("strong",{children:g})]}),kR.map(y=>{const x=h.get(y);return r.jsxs("span",{className:`wall-device-list-metric state-${x?.state||"unknown"}`,role:"gridcell",title:x?`${x.label}: ${x.value} · ${x.detail}`:"Not reported",children:[r.jsx("strong",{children:x?.value||"-"}),r.jsx("small",{children:x?.detail||"not reported"}),x?.ratio!==void 0&&r.jsx("i",{style:{width:`${Math.round(x.ratio*100)}%`},"aria-hidden":"true"})]},y)})]})}function AR(n){if(!n)return!1;const a=String(n.platform||"").trim().toLowerCase();return Ni(a)&&n.capabilities?.screenRecordingPermission===!1}function Ni(n){const a=String(n||"").trim().toLowerCase();return a==="macos"||a==="darwin"||a==="mac"||a==="macosx"}function MR(n){const a=String(n||"").trim().toLowerCase();return a==="linux"||a.startsWith("linux ")}function Wh({device:n,frame:a,selected:i,controlEnabled:l,showStatus:c,monitorIndex:d,monitorCount:m,onSelect:h,onFocusDevice:g,onOpenControl:y,onCycleMonitor:x,onCanvasReady:b,sendInput:w,remoteModifierState:A,updateIndicator:j,presentationReady:k,showPresentationSpinner:N=!1,remoteDiagnostics:M,diagnosticsMode:T="remote"}){const D=u.useRef(null),F=u.useRef(null),$=u.useRef(0),G=u.useRef(null),L=Xw(n),Q=["cpu","gpu","memory","vram"].map(ee=>L.metrics.find(we=>we.id===ee)).filter(ee=>!!ee),q=Vn(d,m),P=m>1,Y=k??!!a,H=AR(n)&&!Y,ye=N&&n.connected&&!Y&&!H,de=tR(n,a,q),Z=de>=xf?100:de/xf*100,z=de>=xf?xf/de*100:100,se={"--screen-aspect":de.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,Z)).toFixed(3)}%`,"--screen-content-height":`${Math.max(1,Math.min(100,z)).toFixed(3)}%`},W=u.useCallback(ee=>{D.current=ee,b(n.deviceId,ee)},[n.deviceId,b]),O=ee=>{const we=ee.currentTarget.getBoundingClientRect();return J1(ee.clientX,ee.clientY,we)},le=ee=>tk(ee,A),ce=u.useCallback(()=>{G.current!==null&&(window.cancelAnimationFrame(G.current),G.current=null)},[]),K=u.useCallback(()=>{const ee=F.current;if(!ee)return;F.current=null;const we=Number(ee.input.normalizedX),Me=Number(ee.input.normalizedY);if(!Number.isFinite(we)||!Number.isFinite(Me))return;w(n.deviceId,{...ee.input,normalizedX:we,normalizedY:Me})&&($.current=performance.now())},[n.deviceId,w]),be=u.useCallback(()=>{G.current===null&&(G.current=window.requestAnimationFrame(()=>{G.current=null,K()}))},[K]);u.useEffect(()=>()=>{ce(),F.current=null},[ce]);const he=(ee,we)=>{if(!l)return;const Me={type:we,monitorIndex:q,...O(ee),button:mR(ee.button),...le(ee)};if(we==="pointermove"){const He=performance.now();F.current={input:Me},He-$.current>=CT&&(ce(),K()),be();return}F.current&&(ce(),K()),w(n.deviceId,Me)},fe=u.useCallback(ee=>{const we=document.activeElement;we instanceof HTMLElement&&ee.contains(we)&&we.classList.contains("monitor-cycle-button")&&we.blur()},[]);return r.jsx("article",{className:`device-tile ${i?"selected":""} ${n.connected?"online":"offline"}`,"data-live-device-id":n.deviceId,style:se,children:r.jsxs("div",{className:`tile-screen ${Y?"has-frame":"is-empty"}`,role:"button",tabIndex:l?-1:0,"aria-pressed":i,onClick:ee=>{ee.target instanceof Element&&ee.target.closest(".monitor-cycle")||l||h()},onKeyDown:ee=>{ee.target instanceof Element&&ee.target.closest(".monitor-cycle")||l||(ee.key==="Enter"||ee.key===" ")&&(ee.preventDefault(),h())},onDoubleClick:ee=>{ee.target instanceof Element&&ee.target.closest(".monitor-cycle")||(ee.preventDefault(),y())},onPointerLeave:ee=>fe(ee.currentTarget),children:[r.jsx("span",{className:`screen-content ${Y?"has-frame":"is-empty"}`,children:r.jsx("canvas",{ref:W,className:`remote-canvas ${Y?"has-frame":"is-empty"}`,"data-monitor-index":q,tabIndex:l?0:-1,onPointerDown:ee=>{l&&(ee.preventDefault(),ee.stopPropagation(),g(),ee.currentTarget.focus(),ee.currentTarget.setPointerCapture(ee.pointerId),he(ee,"pointerdown"))},onPointerMove:ee=>{l&&ee.preventDefault(),he(ee,"pointermove")},onPointerLeave:ee=>{l&&(he(ee,"pointermove"),ce(),K())},onPointerUp:ee=>{l&&(ee.preventDefault(),ee.stopPropagation(),he(ee,"pointerup"),ee.currentTarget.hasPointerCapture(ee.pointerId)&&ee.currentTarget.releasePointerCapture(ee.pointerId))},onPointerCancel:ee=>{ee.currentTarget.hasPointerCapture(ee.pointerId)&&ee.currentTarget.releasePointerCapture(ee.pointerId)},onWheel:ee=>{l&&(ee.preventDefault(),w(n.deviceId,{type:"wheel",monitorIndex:q,...O(ee),deltaX:ee.deltaX,deltaY:ee.deltaY,...le(ee)}))},onContextMenu:ee=>l&&ee.preventDefault()},`${n.deviceId}:monitor:${q}`)}),!Y&&r.jsx("span",{className:"empty-screen",children:r.jsx(Ta,{size:26})}),r.jsx("span",{className:"wall-device-title",title:ha(n),children:ha(n)}),ye&&r.jsxs("span",{className:"wall-presentation-loading",role:"status","aria-live":"polite",children:[r.jsx("span",{className:"wall-presentation-spinner","aria-hidden":"true"}),r.jsx("strong",{children:"Preparing video"})]}),H&&r.jsxs("span",{className:"wall-presentation-loading permission-required",role:"status","aria-live":"polite",children:[r.jsx(Wn,{size:24,"aria-hidden":"true"}),r.jsx("strong",{children:"Screen Recording permission required"}),r.jsx("small",{children:"Allow the terminal app on this Mac, then restart LiveDesk."})]}),j&&r.jsxs("span",{className:`wall-update-status state-${j.state}`,role:"status","aria-live":"polite",title:j.error||j.label,children:[j.state==="updated"?r.jsx(Zn,{size:20,"aria-hidden":"true"}):j.state==="failed"?r.jsx(Na,{size:22,"aria-hidden":"true"}):j.state==="offline"?r.jsx($f,{size:22,"aria-hidden":"true"}):r.jsx("span",{className:"wall-update-spinner","aria-hidden":"true"}),r.jsx("strong",{children:j.label}),j.error?r.jsx("small",{children:j.error}):null]}),c&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:`tile-health-pill state-${L.state}`,children:L.label}),r.jsx("span",{className:"tile-metrics","aria-label":`${ha(n)} status`,children:Q.map(ee=>r.jsxs("span",{className:`tile-metric state-${ee.state}`,children:[r.jsx("b",{children:ee.label}),r.jsx("em",{children:ee.value}),ee.ratio!==void 0&&r.jsx("i",{style:{width:`${Math.round(ee.ratio*100)}%`}})]},ee.id))})]}),M&&r.jsx(WN,{items:M,mode:T}),P&&r.jsxs("span",{className:"monitor-cycle","aria-label":`${ha(n)} display ${q+1} of ${m}`,onPointerDown:ee=>ee.stopPropagation(),onClick:ee=>ee.stopPropagation(),onDoubleClick:ee=>ee.stopPropagation(),children:[r.jsx("button",{className:"monitor-cycle-button previous",onClick:ee=>{ee.preventDefault(),ee.stopPropagation(),x(-1),ee.currentTarget.blur()},title:"Previous display",type:"button",children:r.jsx(yx,{size:18})}),r.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",q+1,"/",m]}),r.jsx("button",{className:"monitor-cycle-button next",onClick:ee=>{ee.preventDefault(),ee.stopPropagation(),x(1),ee.currentTarget.blur()},title:"Next display",type:"button",children:r.jsx(Ap,{size:18})})]}),i&&r.jsx("span",{className:"device-selection-check","aria-hidden":"true",children:r.jsx(Ir,{size:23,strokeWidth:3.5})})]})})}function NR({visible:n}){return u.useEffect(()=>{if(!n||!Fh)return;if(!document.getElementById(Pb)){const i=document.createElement("script");i.id=Pb,i.async=!0,i.crossOrigin="anonymous",i.src=`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${encodeURIComponent(bp)}`,document.head.appendChild(i)}const a=window.setTimeout(()=>{try{window.adsbygoogle=window.adsbygoogle||[],window.adsbygoogle.push({})}catch{}},120);return()=>window.clearTimeout(a)},[n]),n?r.jsxs("aside",{className:`free-ad-banner ${Fh?"adsense-ready":"house-ad"}`,"aria-label":"Advertisement",children:[r.jsx("span",{className:"ad-label",children:"Advertisement"}),Fh?r.jsx("ins",{className:"adsbygoogle livedesk-ad-unit",style:{display:"block"},"data-ad-client":bp,"data-ad-slot":qw,"data-ad-format":"auto","data-full-width-responsive":"true"}):r.jsxs("div",{className:"house-ad-copy",children:[r.jsx("strong",{children:"Sponsored placement"}),r.jsx("span",{children:"Local AI gear, mini PCs, GPUs, NAS, and developer tools."})]})]}):null}function TR(){const{session:n,loading:a}=R1(),{target:i,error:l,refresh:c}=D1(n),d=u.useMemo(()=>{if(!i?.active)return null;const v=i.expires_at?Date.parse(i.expires_at):Number.POSITIVE_INFINITY;return Number.isFinite(v)&&v<=Date.now()?null:i},[i]),m=u.useMemo(()=>Ty(d),[d]),h=u.useMemo(()=>m.length>0?[...new Set([...m,An])]:[An],[m]),[g,y]=u.useState(XT),x=u.useMemo(()=>h.some(v=>!!Ou(v)),[h]),b=!x||g,{status:w,devices:A,error:j,refresh:k,hubBaseUrl:N}=E1(h,b),{entitlement:M,licensed:T,loading:D,error:F,refresh:$}=L1(n),[G,L]=u.useState([]),[Q,q]=u.useState(""),[P,Y]=u.useState(""),[H,ye]=u.useState(""),[de,Z]=u.useState(""),[z,se]=u.useState(""),[W,O]=u.useState("idle"),[le,ce]=u.useState(!1),[K,be]=u.useState(null),he=u.useRef(null),[fe,ee]=u.useState(""),we=u.useRef("");we.current=de;const[Me,He]=u.useState(!1),[ne,qe]=u.useState([]),mt=u.useRef(null),[J,Ce]=u.useState(!1),Le=u.useRef(""),Fe=u.useRef(new Map),_e=u.useRef(0),[Xe,We]=u.useState({}),Ze=u.useRef({}),dt=u.useRef(new Map),U=u.useRef(new Map),[ve,Ae]=u.useState({}),Be=u.useMemo(()=>new Set(Object.keys(Xe)),[Xe]),ft=u.useCallback((v,C)=>{if(!v)return;const E={...Ze.current};C?E[v]=C:delete E[v],Ze.current=E,We(E)},[]),it=u.useCallback((v,C)=>{v&&Ae(E=>{if(!!E[v]===C)return E;const I={...E};return C?I[v]=!0:delete I[v],I})},[]),yt=u.useCallback((v,C)=>{v&&U.current.set(v,{paused:C,expiresAt:Date.now()+LT})},[]),[ot,kt]=u.useState(""),[pe,De]=u.useState(""),[$e,je]=u.useState(!1),ct=u.useRef(null),bt=u.useRef(null);u.useEffect(()=>{ot==="auth"&&n?.access_token&&kt("")},[ot,n?.access_token]);const[ze,aa]=u.useState(""),[zn,nt]=u.useState(null),Ot=u.useRef(null),Nn=u.useRef(0),pa=u.useCallback((v,C,E)=>{const I=String(v||"").trim();if(aa(I),Ot.current!==null&&(window.clearTimeout(Ot.current),Ot.current=null),!I){nt(null);return}const _=++Nn.current;if(nt({id:_,message:I,tone:C}),!E)return;const te=window.setTimeout(()=>{nt(ie=>ie?.id===_?null:ie),Ot.current===te&&(Ot.current=null)},5e3);Ot.current=te},[]),Oe=u.useCallback((v,C="info")=>{pa(v,C,!0)},[pa]),wn=u.useCallback(v=>{pa(v,"progress",!1)},[pa]);u.useEffect(()=>()=>{Ot.current!==null&&window.clearTimeout(Ot.current)},[]);const[On,ws]=u.useState(()=>typeof window<"u"&&window.location.pathname.startsWith("/support")?"support":"wall");u.useEffect(()=>{const v=()=>{ws(window.location.pathname.startsWith("/support")?"support":C=>C==="support"?"wall":C)};return window.addEventListener("popstate",v),()=>window.removeEventListener("popstate",v)},[]);const[pn,qs]=u.useState("large"),[Yn,Gs]=u.useState(!1),[B,Ke]=u.useState(!1),[ht,fn]=u.useState(!1),[Fa,Di]=u.useState(!1),[Ss,re]=u.useState(Date.now),Te=u.useRef(null);u.useEffect(()=>()=>{Te.current!==null&&window.clearTimeout(Te.current)},[]);const[Pe,vt]=u.useState(CR),[qt,Yt]=u.useState(!1),[st,Mt]=u.useState(!1),[sa,Hn]=u.useState(!1),[gn,nn]=u.useState(QT),[Ye]=u.useState(sR),[At]=u.useState(iR),[Vs]=u.useState(nR),[zt,Sn]=u.useState(Vs.selections),Tn=u.useRef({...Vs.topologyFingerprints}),go=u.useRef({...Vs.selections}),[Nt,ga]=u.useState(null),[Mc,Fr]=u.useState([]),[Fn,$a]=u.useState(Ye.fps),[Kn,Qu]=u.useState(""),[Qf,Nc]=u.useState(0),[Xu,Sl]=u.useState(0),[Xf,Ba]=u.useState(0),[vo,Li]=u.useState(()=>new Set),$n=u.useRef(new Map),Ra=u.useRef(new Map),Ws=u.useRef(new Map),$r=u.useRef(new Map),Cn=u.useRef(new Map),Cl=u.useRef(new Map),Ys=u.useRef(new Set),kl=u.useRef(new Map),Br=u.useRef(""),os=u.useRef(null),Zu=u.useRef(Promise.resolve()),Pr=u.useRef(0),ra=u.useRef(null),Cs=u.useRef(new Map),_i=u.useRef(null),vr=u.useRef(0),Ks=u.useRef(new Map),[jl,yo]=u.useState({}),Al=u.useRef(new Map),[yr,ks]=u.useState({}),[bo,ia]=u.useState(!1),js=u.useRef(null),Pa=u.useRef(null),va=u.useRef(0),la=u.useRef(""),Ml=u.useRef(Promise.resolve()),Nl=u.useRef(""),Tt=u.useRef(null),Zt=u.useRef(""),Ea=u.useRef(null),Qs=u.useRef(0),Xs=u.useRef(""),br=u.useRef(new Map),Zs=u.useRef(new Map),Ii=u.useRef(performance.now()),As=u.useRef(new Map),Ms=u.useRef(new Map),xr=u.useRef(new Map),zi=u.useRef(new Map),xo=u.useRef(new Map),Tl=u.useRef(0),Oi=u.useRef(0),wo=u.useRef(0),So=u.useRef(0),Tc=u.useRef(0),Ju=u.useRef(new Map),Js=u.useRef(new Map),cs=u.useCallback((v,C)=>{const E=rs(v,C),I=performance.now();br.current.delete(E),Zs.current.delete(E),As.current.delete(E),xo.current.delete(E),Js.current.delete(E),Al.current.delete(E),Ks.current.delete(E),ks(_=>{if(!Object.prototype.hasOwnProperty.call(_,E))return _;const te={..._};return delete te[E],te}),yo(_=>{if(!Object.prototype.hasOwnProperty.call(_,E))return _;const te={..._};return delete te[E],te}),v==="control"?(Ms.current.delete(E),xr.current.set(E,I)):zi.current.set(E,I)},[]),[Ur,wr]=u.useState(null),[Zf,Rc]=u.useState(!1),[ed,Jf]=u.useState([]),[Hi,em]=u.useState("all"),[qr,Ec]=u.useState([]),[Wp,Yp]=u.useState(!1),[Kp,tm]=u.useState(!0),td=u.useRef(null),nd=u.useRef(null),nm=u.useRef(null),am=u.useRef(null),Dc=u.useRef(!1),Gr=u.useRef(!1),Lc=u.useRef(!1),Fi=u.useRef(0),er=u.useRef(0),Rl=On==="settings",_c=On==="pricing",Ic=On==="doc",Vr=On==="support",El=On==="share-files",zc=On==="agents",Dl=!Rl&&!_c&&!Ic&&!Vr&&!El&&!zc,pt=On==="control";u.useEffect(()=>{Dl||(Gs(!1),Ke(!1),fn(!1))},[Dl]);const Rt=Ye.frameMode==="mode4-h264-atlas",Bn=z||At.frameMode,tr=Bn!=="mode3-h264-hw"?Math.min(30,At.fps):At.fps,sm=A.find(v=>v.deviceId===P)?.platform,Ll=MR(sm)?{maxWidth:1280,maxHeight:720}:{maxWidth:3840,maxHeight:2160},Wr={maxWidth:Math.min(Bn!=="mode3-h264-hw"?1920:3840,Ll.maxWidth,At.maxWidth),maxHeight:Math.min(Bn!=="mode3-h264-hw"?1080:2160,Ll.maxHeight,At.maxHeight)};u.useEffect(()=>{if(w?.started){if(!n?.access_token){Ve("/api/remote/license",{method:"DELETE"},N).catch(()=>{});return}Ve("/api/remote/license/sync",{method:"POST",headers:{Authorization:`Bearer ${n.access_token}`}},N).catch(v=>{console.warn("[LiveDesk] Hub license sync failed",v)})}},[M?.updated_at,N,n?.access_token,w?.started]),u.useEffect(()=>{!n?.access_token||!w?.started||w.runtimeRole!=="hub"||!w.deviceId||(async()=>{try{const{data:v,error:C}=await Ct.rpc("register_livedesk_device",{p_device_id:w.deviceId,p_device_name:w.deviceName||w.deviceId,p_role:"hub",p_assigned_hub_id:null,p_platform:navigator.platform||navigator.userAgent,p_os_version:navigator.userAgent,p_app_version:w.managerVersion||w.managerPackage||""}),E=Array.isArray(v)?v[0]:v;(C||E?.ok===!1)&&console.warn("[LiveDesk] Hub device role registration failed",C||E?.reason||"unknown-error")}catch(v){console.warn("[LiveDesk] Hub device role registration failed",v)}})()},[n?.access_token,w?.deviceId,w?.deviceName,w?.managerPackage,w?.managerVersion,w?.runtimeRole,w?.started]),u.useEffect(()=>{!n?.access_token||!n.refresh_token||!w?.started||w.runtimeRole!=="hub"||Lc.current||(Lc.current=!0,Ve("/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}})},N||An).then(v=>{v.hostTarget?.ok===!1&&console.warn("[LiveDesk] Hub host target publish is waiting for a valid Hub role:",v.hostTarget.error||"unknown-error"),k()}).catch(v=>{console.warn("[LiveDesk] Hub session sync failed:",v)}).finally(()=>{Lc.current=!1}))},[N,k,n?.access_token,n?.expires_at,n?.refresh_token,n?.user?.email,n?.user?.id,w?.runtimeRole,w?.started]);const lt=u.useMemo(()=>A.filter(v=>v.connected),[A]);u.useEffect(()=>{const v={...Ze.current},C=Date.now();let E=!1;Ae(I=>{const _={...I};let te=!1;for(const ie of A){const Ne=String(ie.liveCapturePause?.token||"").trim(),Re=U.current.get(ie.deviceId);if(Re)if((Re.paused?!!Ne:!Ne)||Re.expiresAt<=C)U.current.delete(ie.deviceId);else continue;const Ue=!!Ne&&(ie.liveCapturePause?.captureStopConfirmed!==!0||ie.liveCapturePause?.phase==="stop-unconfirmed");!!_[ie.deviceId]!==Ue&&(te=!0,Ue?_[ie.deviceId]=!0:delete _[ie.deviceId])}return te?_:I});for(const I of A){const _=String(I.liveCapturePause?.token||"").trim(),te=String(v[I.deviceId]||""),ie=U.current.get(I.deviceId);if(ie)if((ie.paused?!!_:!_)||ie.expiresAt<=C)U.current.delete(I.deviceId);else continue;_&&_!==te?(v[I.deviceId]=_,E=!0):!_&&te&&(delete v[I.deviceId],dt.current.delete(I.deviceId),E=!0)}E&&(Ze.current=v,We(v))},[A]);const Co=Hi==="all"?lt.length:qr.filter(v=>lt.some(C=>C.deviceId===v)).length,Oc=u.useMemo(()=>lt.reduce((v,C)=>Math.max(v,rx(C.slotNumber)),0),[lt]),ko=Math.max(pT,lt.length,Oc),Sr=u.useMemo(()=>{const v=Array(ko).fill(null),C=[];for(const E of lt){const I=rx(E.slotNumber);I>0&&I<=ko&&!v[I-1]?v[I-1]=E:C.push(E)}for(const E of C){const I=v.findIndex(_=>!_);I<0?v.push(E):v[I]=E}return v},[lt]),Hc=u.useMemo(()=>Sr.flatMap((v,C)=>v?[{device:v,slotNumber:C+1}]:[]),[Sr]),Fc=u.useMemo(()=>lt.map(v=>v.deviceId),[lt]),Yr=u.useMemo(()=>new Set(G),[G]),Da=u.useMemo(()=>lt.filter(v=>Yr.has(v.deviceId)),[lt,Yr]),$i=u.useMemo(()=>A.find(v=>v.deviceId===Q)||Da[0]||null,[A,Q,Da]),oa=u.useMemo(()=>A.find(v=>v.deviceId===P)||null,[P,A]),an=oa?Vn(zt[oa.deviceId],Gn(oa)):0,Ee=pt?oa:$i,$c=u.useMemo(()=>new Set(qr),[qr]),ad=u.useMemo(()=>Hi==="all"?lt.map(v=>v.deviceId):lt.filter(v=>$c.has(v.deviceId)).map(v=>v.deviceId),[lt,$c,Hi]),sd=Ee?$u(Ee,"control"):!1,jo=Ni(Ee?.platform)&&(Ee?.capabilities?.controlPermission===!1||Ee?.capabilities?.accessibilityPermission===!1),Kr=Ee?$u(Ee,"audio")||$u(Ee,"remoteAudio"):!1,Qr=(Array.isArray(Ee?.capabilities?.agentTools)?Ee.capabilities.agentTools.map(String):[]).includes("system.power"),un=T?M?.plan==="pro"?"pro":"ltd":"free",Bi=so[un],Pi=Bi.limit,Xr=u.useMemo(()=>{if(!Number.isFinite(Pi))return new Set(lt.map(C=>C.deviceId));const v=Ee?[Ee,...lt.filter(C=>C.deviceId!==Ee.deviceId)]:lt;return new Set(v.slice(0,Pi).map(C=>C.deviceId))},[Pi,lt,Ee]),Zr=!Ee||Xr.has(Ee.deviceId),Ui=un==="free",Kt=Zr,Jr=un==="ltd"?`Plus includes up to ${Du} Clients. Upgrade to Pro for commercial use and larger walls.`:`Free includes up to ${Eu} Clients. Upgrade to Plus for ${Du} devices and no ads.`,ei=un==="free",Ns=Kt&&!!Ee&&sd,Bc=Kt&&!!Ee&&Kr,qi=!!Ee&&Be.has(Ee.deviceId),Pc=!!Ee&&ve[Ee.deviceId]===!0,Ao=u.useMemo(()=>Sr.filter(v=>!!v?.connected).slice(0,oR(pn)).map(v=>v.deviceId),[Sr,pn]),Mo=u.useMemo(()=>pn==="list"?[]:Rt?Fc:Ye.visibleOnlyLive?Mc.length>0?Mc:Ao:Fc,[Ao,Rt,Mc,Ye.visibleOnlyLive,Fc,pn]),Ua=u.useMemo(()=>Uh(Mo.filter(v=>Xr.has(v))),[Xr,Mo]),nr=u.useMemo(()=>Ua.filter(v=>v!==Kn&&!Be.has(v)),[Be,Ua,Kn]),Gi=u.useMemo(()=>new Map(lt.map(v=>[v.deviceId,v.platform])),[lt]),vn=sk(Rt,Ua.length),Pn=u.useMemo(()=>Rt?nr.filter(v=>Mu({mode4Enabled:Rt,directMode4WallEnabled:vn,isMac:Ni(Gi.get(v))})==="atlas"):[],[vn,Rt,Gi,nr]),sn=u.useMemo(()=>nr.filter(v=>Mu({mode4Enabled:Rt,directMode4WallEnabled:vn,isMac:Ni(Gi.get(v))})==="direct"),[vn,Rt,Gi,nr]);u.useEffect(()=>{const v=new Set(Ua);Li(C=>{let E=!1;const I=new Set;for(const _ of C)v.has(_)?I.add(_):E=!0;return E?I:C})},[Ua]);const Vi=u.useMemo(()=>{const v=_=>lt.find(te=>te.deviceId===_)||null,C=_=>Vn(zt[_],v(_)?Gn(v(_)):0),E=(_,te=C(_))=>_===H&&(W==="connecting"||W==="active"||W==="warm")?Cn.current.get(_)||Ra.current.get(_)||null:Rt?Cs.current.get(_)||$n.current.get(_)||null:$n.current.get(_)||null,I=(_,te=C(_))=>{const ie=v(_);return`${ie?ha(ie):_} · Monitor ${te+1}`};return{resolveCurrentTarget(){if(pt&&oa){const Re=an;return{type:"control",deviceIds:[oa.deviceId],monitorIndex:Re,label:`${ha(oa)} · Monitor ${Re+1}`,sourceCanvas:E(oa.deviceId,Re),signature:`control:${oa.deviceId}:${Re}:${At.frameMode}`}}const _=Da.map(Re=>Re.deviceId).filter(Re=>nr.includes(Re)),te=$i&&nr.includes($i.deviceId)?$i.deviceId:"",ie=_.length>0?_:te?[te]:nr,Ne=_.length===0&&!te;if(ie.length===0)return null;if(ie.length===1){const Re=ie[0],Ue=C(Re);return{type:Ne?"wall":_.length>1?"selection":"device",deviceIds:ie,monitorIndex:Ue,label:Ne?"Wall":I(Re,Ue),sourceCanvas:Ne?null:E(Re,Ue),signature:`${Ne?"wall":"device"}:${Re}:${Ue}:${Rt?"atlas":"direct"}`}}return{type:_.length>1?"selection":"wall",deviceIds:ie,label:_.length>1?`${ie.length} selected Clients`:"Wall",sourceCanvas:null,signature:`${_.length>1?"selection":"wall"}:${ie.join(",")}:${pn}`}},getDeviceCanvas:E,composeWall(_,te={}){return aT(_.map(ie=>{const Ne=C(ie);return{deviceId:ie,label:I(ie,Ne),canvas:E(ie,Ne)}}),te)}}},[lt,oa,H,W,At.frameMode,$n,Rt,zt,an,Da,pt,nr,$i,pn]),No=hT({hubUrl:N,sourceRegistry:Vi,onToast:Oe}),ar=u.useMemo(()=>Kt&&H&&Xr.has(H)&&(W==="connecting"||W==="active"||W==="warm")?[H]:[],[H,W,Kt,Xr]),To=u.useMemo(()=>Uh([...Ua,...ar]),[ar,Ua]),La=u.useMemo(()=>cR(Ye,pn),[Ye,pn]),_a=rk({mode4Enabled:Rt,directMode4WallEnabled:vn,adaptiveFps:Fn,directDeviceCount:sn.length,adaptive:Ye.adaptiveLoadShedding}),Ro=ik({deviceCount:Pn.length,targetFps:Fn,adaptive:Ye.adaptiveLoadShedding});Rt&&Pn.length>0;const Rn=u.useCallback((v,C,E)=>{if(v.width<=0||v.height<=0)return!1;const I=E?Math.min(1,E.maxWidth/v.width,E.maxHeight/v.height):1,_=Math.max(1,Math.round(v.width*I)),te=Math.max(1,Math.round(v.height*I));(C.width!==_||C.height!==te)&&(C.width=_,C.height=te);const ie=C.getContext("2d",{alpha:!1});return ie?(ie.imageSmoothingEnabled=!0,ie.imageSmoothingQuality="high",ie.drawImage(v,0,0,v.width,v.height,0,0,C.width,C.height),!0):!1},[]),ca=u.useCallback(v=>{v&&Li(C=>{if(C.has(v))return C;const E=new Set(C);return E.add(v),E})},[]),Eo=u.useCallback(v=>{v&&Li(C=>{if(!C.has(v))return C;const E=new Set(C);return E.delete(v),E})},[]),En=u.useCallback((v,C)=>{if(!C||C.width<=0||C.height<=0)return!1;const E=document.createElement("canvas");return E.width=C.width,E.height=C.height,Rn(C,E)?(Ws.current.set(v,E),ca(v),!0):!1},[ca,Rn]),Ts=u.useCallback(v=>{const C=$r.current.get(v);C!==void 0&&(window.cancelAnimationFrame(C),$r.current.delete(v))},[]),ya=u.useCallback(v=>{Ts(v),Ws.current.delete(v)},[Ts]),_l=u.useCallback((v,C)=>{Ts(v);const E=()=>{const I=Ws.current.get(v),_=$n.current.get(v)===C||Cs.current.get(v)===C;if(!I||!_){$r.current.delete(v);return}Rn(I,C),$r.current.set(v,window.requestAnimationFrame(E))};E()},[Rn,Ts]);u.useEffect(()=>()=>{for(const v of $r.current.values())window.cancelAnimationFrame(v);$r.current.clear()},[]);const qa=u.useCallback((v,C=!1)=>{if(!Ys.current.has(v))return!1;const E=performance.now(),I=kl.current.get(v)||0,_=Math.max(1,Math.min(bs.controlWallReuseMaxFps,tr)),te=tr>_?Math.max(0,1e3/_-2):0;if(!C&&E-I<te)return!1;const ie=Cn.current.get(v)||Ra.current.get(v),Ne=$n.current.get(v)||Cs.current.get(v);return!ie||!Ne||!Rn(ie,Ne,La)?!1:(kl.current.set(v,E),ca(v),ya(v),!0)},[tr,La,ca,Rn,ya]);u.useEffect(()=>{Br.current=Kn},[Kn]);const Cr=u.useCallback((v,C)=>{const E=$n.current.get(v);if(E&&E!==C&&(Ts(v),En(v,E),dc(E)),C){$n.current.set(v,C);const I=Ws.current.get(v);I&&Rn(I,C)&&(ca(v),_l(v,C)),qa(v,!0);return}$n.current.delete(v),Ws.current.has(v)||Eo(v)},[Eo,_l,ca,Rn,qa,En,Ts]),Uc=u.useCallback((v,C)=>{const E=Ra.current.get(v);if(E&&E!==C&&dc(E),C){Ra.current.set(v,C);const I=H===v&&le?Cn.current.get(v):null;I&&Rn(I,C)&&v===P&&ia(!0);return}Ra.current.delete(v)},[P,H,le,Rn]),Il=u.useCallback((v,C,E)=>{const I=performance.now(),_=rs(v,E.deviceId);let te=E;if(v==="control"&&E.visualChanged){const Ne=F1(E.deviceId),Re=Ju.current.get(E.deviceId)||0,Ue=Ne?I-Ne.sentAt:Number.POSITIVE_INFINITY;Ne&&Ne.inputSeq>Re&&Ue<=Ub&&(te={...E,inputFeedbackSeq:Ne.inputSeq,inputFeedbackMs:Math.max(0,Ue),inputFeedbackAt:I},Ju.current.set(E.deviceId,Ne.inputSeq))}Zs.current.set(_,I);const ie=Ks.current.get(_)||{totalFrames:0,totalChangedFrames:0,sampleFrames:0,sampleChangedFrames:0,sampleStartedAt:I,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleDecoderInputBase:0,sampleDecoderOutputBase:0};v==="control"&&te.inputFeedbackMs===void 0&&ie.lastInfo?.inputFeedbackMs!==void 0&&ie.lastInfo.inputFeedbackAt!==void 0&&I-ie.lastInfo.inputFeedbackAt<=Ub&&(te={...te,inputFeedbackSeq:ie.lastInfo.inputFeedbackSeq,inputFeedbackMs:ie.lastInfo.inputFeedbackMs,inputFeedbackAt:ie.lastInfo.inputFeedbackAt}),ie.totalFrames+=1,ie.sampleFrames+=1,Kb(ie,I,te.frameSeq),te.visualChanged&&(ie.totalChangedFrames+=1,ie.sampleChangedFrames+=1),ie.lastInfo=te,Ks.current.set(_,ie)},[]),Wi=u.useCallback((v,C)=>{Il("wall",v,C),v.kind==="live"&&(ca(v.deviceId),ya(v.deviceId));const E=le&&H===v.deviceId;Br.current!==v.deviceId&&!E&&(Ys.current.delete(v.deviceId),kl.current.delete(v.deviceId))},[H,le,ca,Il,ya]),qc=u.useCallback((v,C)=>{if(Ze.current[v.deviceId]||!Ky(v,Tt.current))return;Il("control",v,C),ee(te=>te&&"");const E=Cn.current.get(v.deviceId),I=Ra.current.get(v.deviceId);E&&E.width>0&&E.height>0&&(I&&Rn(E,I),Cl.current.set(v.deviceId,{...v,payload:new Uint8Array(0),byteLength:0}),Ys.current.add(v.deviceId),v.deviceId===H&&(ce(!0),O(te=>te==="connecting"?"active":te)),qa(v.deviceId));const _=js.current;!_||!_T(_,v)||ia(!0)},[H,Rn,qa,Il]);u.useEffect(()=>{const v=window.setInterval(()=>{const C=performance.now(),E={};for(const[I,_]of Ks.current.entries()){const te=Math.max(1,C-_.sampleStartedAt);E[I]={totalFrames:_.totalFrames,totalChangedFrames:_.totalChangedFrames,framesPerSecond:_.sampleFrames*1e3/te,changedFramesPerSecond:_.sampleChangedFrames*1e3/te,averageIntervalMs:_.intervalCount>0?_.intervalSumMs/_.intervalCount:0,minIntervalMs:Number.isFinite(_.minIntervalMs)?_.minIntervalMs:0,maxIntervalMs:_.maxIntervalMs,p95IntervalMs:Bh(_.intervalSamplesMs,.95),intervalCount:_.intervalCount,seqGapCount:_.seqGapCount,maxSeqGap:_.maxSeqGap,decoderInputFps:Math.max(0,(Number(_.lastInfo?.decoderInputCount||0)-_.sampleDecoderInputBase)*1e3/te),decoderOutputFps:Math.max(0,(Number(_.lastInfo?.decoderOutputCount||0)-_.sampleDecoderOutputBase)*1e3/te),sampleMs:te,lastInfo:_.lastInfo},_.sampleDecoderInputBase=Number(_.lastInfo?.decoderInputCount||0),_.sampleDecoderOutputBase=Number(_.lastInfo?.decoderOutputCount||0),_.sampleChangedFrames=0,Yb(_,C)}yo(E)},1e3);return()=>window.clearInterval(v)},[]);const Un=u.useCallback((v,C)=>{const E=performance.now(),I=rs(v,C.deviceId);br.current.set(I,E),Js.current.delete(I),v==="control"?Ms.current.delete(I):zi.current.delete(I);const _=Al.current.get(I)||{totalFrames:0,sampleFrames:0,sampleStartedAt:E,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleBytes:0,sampleH264Frames:0,sampleTinyFrames:0,sampleRepeatedFrames:0,sourceSendIntervalsMs:[]};if(_.totalFrames+=1,_.sampleFrames+=1,_.sampleBytes+=Math.max(0,Number(C.byteLength||0)),String(C.frameMode||C.mode||C.codec||C.mimeType||"").toLowerCase().includes("h264")){_.sampleH264Frames+=1,Number(C.byteLength||0)<=TT&&(_.sampleTinyFrames+=1);const Re=String(C.contentHash||"");Re&&_.lastContentHash===Re&&(_.sampleRepeatedFrames+=1),_.lastContentHash=Re}const Ne=Number(C.agentSendGapMs||0);Ne>0&&Ne<1e3&&Gw(_.sourceSendIntervalsMs,Ne),_.lastFrame=C,Kb(_,E,C.frameSeq),Al.current.set(I,_)},[]);u.useEffect(()=>{const v=window.setInterval(()=>{const C=performance.now(),E={};for(const[I,_]of Al.current.entries()){const te=Math.max(1,C-_.sampleStartedAt);E[I]={totalFrames:_.totalFrames,framesPerSecond:_.sampleFrames*1e3/te,averageIntervalMs:_.intervalCount>0?_.intervalSumMs/_.intervalCount:0,minIntervalMs:Number.isFinite(_.minIntervalMs)?_.minIntervalMs:0,maxIntervalMs:_.maxIntervalMs,p95IntervalMs:Bh(_.intervalSamplesMs,.95),intervalCount:_.intervalCount,seqGapCount:_.seqGapCount,maxSeqGap:_.maxSeqGap,averageFrameBytes:_.sampleFrames>0?_.sampleBytes/_.sampleFrames:0,tinyFrameRatio:_.sampleH264Frames>0?_.sampleTinyFrames/_.sampleH264Frames:0,repeatedFrameRatio:_.sampleH264Frames>0?_.sampleRepeatedFrames/_.sampleH264Frames:0,sourceSendAverageMs:_.sourceSendIntervalsMs.length>0?_.sourceSendIntervalsMs.reduce((ie,Ne)=>ie+Ne,0)/_.sourceSendIntervalsMs.length:0,sourceSendP95Ms:Bh(_.sourceSendIntervalsMs,.95),sourceSendSampleCount:_.sourceSendIntervalsMs.length,sampleMs:te,lastFrame:_.lastFrame},_.sampleBytes=0,_.sampleH264Frames=0,_.sampleTinyFrames=0,_.sampleRepeatedFrames=0,_.sourceSendIntervalsMs.length=0,Yb(_,C)}ks(E)},1e3);return()=>window.clearInterval(v)},[]);const ti=u.useCallback(v=>{if(Br.current===v.deviceId)return;Un("wall",v);const C=$n.current.get(v.deviceId);if(!C)return;const E=lk(Rt,Ye.h264DecodeAcceleration);jh(C,v,()=>$n.current.get(v.deviceId)!==C,Wi,E.acceleration,E.latencyMode).catch(()=>{})},[Wi,Rt,Un,Ye.h264DecodeAcceleration]),ni=u.useCallback(v=>{if(Ze.current[v.deviceId]||!Ky(v,Tt.current))return;Un("control",v);let C=Cn.current.get(v.deviceId);C||(C=document.createElement("canvas"),C.setAttribute("aria-hidden","true"),Cn.current.set(v.deviceId,C));const E=C,I=we.current;jh(E,v,()=>Cn.current.get(v.deviceId)!==E,qc,At.h264DecodeAcceleration,"interactive").catch(_=>{we.current!==I||Cn.current.get(v.deviceId)!==E||H!==v.deviceId||ee(_ instanceof Error?_.message:String(_||"Control H.264 decode failed"))})},[H,At.h264DecodeAcceleration,qc,Un]),Do=u.useCallback(v=>{const C=ra.current;C&&C!==v&&dc(C),ra.current=v,Tl.current=0,Oi.current=0,wo.current=0,So.current=0,Tc.current=0,vr.current=0},[]),Rs=u.useCallback(()=>{const v=new Set,C=ra.current,E=_i.current;if(!C||!E||C.width<=0||C.height<=0||vr.current!==E.layoutVersion)return v;for(const I of E.tiles){const _=Cs.current.get(I.deviceId);if(!_||I.width<=0||I.height<=0)continue;const te=Math.max(1,Math.round(I.width)),ie=Math.max(1,Math.round(I.height)),Ne=RT,Re=ET;(_.width!==Ne||_.height!==Re)&&(_.width=Ne,_.height=Re);const Ue=_.getContext("2d",{alpha:!1});if(Ue){Ue.imageSmoothingEnabled=!0,Ue.imageSmoothingQuality="high";try{Ue.drawImage(C,Math.round(I.x),Math.round(I.y),te,ie,0,0,Ne,Re),v.add(I.deviceId)}catch{}}}return v},[]),Ga=u.useCallback((v,C)=>{if(C){Cs.current.set(v,C);const I=Ws.current.get(v);I&&Rn(I,C)&&(ca(v),_l(v,C)),window.requestAnimationFrame(()=>{Rs().has(v)&&ya(v)}),window.requestAnimationFrame(()=>qa(v,!0));return}const E=Cs.current.get(v);Ts(v),En(v,E),Cs.current.delete(v),Ws.current.has(v)||Eo(v)},[Eo,_l,ca,Rs,Rn,qa,En,ya,Ts]),Ia=u.useCallback((v,C)=>{wo.current=performance.now(),vr.current=Number(v.layoutVersion||0),Rs();const E=_i.current?.tiles||[],I=E.length>0?Math.round(v.byteLength/E.length):v.byteLength;for(const _ of E){const te={...v,deviceId:_.deviceId,width:_.width,height:_.height,sourceWidth:_.width,sourceHeight:_.height,byteLength:I};Wi(te,{...C,deviceId:_.deviceId,width:_.width,height:_.height,byteLength:I}),Br.current===_.deviceId&&qa(_.deviceId,!0)}},[Wi,Rs,qa]),kr=u.useCallback(v=>{const C=performance.now();Tl.current<=0&&(Tl.current=C),Oi.current=C;const E=ra.current;if(!E)return;const I=_i.current?.tiles||[],_=I.length>0?Math.round(v.byteLength/I.length):v.byteLength;for(const te of I)Un("wall",{...v,deviceId:te.deviceId,width:te.width,height:te.height,sourceWidth:te.width,sourceHeight:te.height,byteLength:_});jh(E,v,()=>ra.current!==E,Ia).catch(()=>{})},[Ia,Un]),Es=u.useMemo(()=>({fps:_a,maxWidth:La.maxWidth,maxHeight:La.maxHeight,quality:Ye.quality,mode:Rt?"mode3-h264-hw":Ye.frameMode,frameMode:Rt?"mode3-h264-hw":Ye.frameMode,streamPurpose:"wall",monitorSelections:zt,onFrame:ti}),[_a,ti,La,Rt,zt,Ye]),us=u.useCallback(v=>{const C=Tt.current;if(Ze.current[v.deviceId]||!C||C.deviceId!==v.deviceId||v.deviceId!==H||v.streamPurpose!=="control"||v.monitorIndex!==an)return;const E=lt.find(I=>I.deviceId===v.deviceId);!E?.sessionId||E.sessionId!==v.sessionId||(Tt.current=af(C.deviceId,C.transitionGeneration,v),he.current=v,be(v),O(I=>I==="connecting"?"active":I))},[lt,H,an]);u.useEffect(()=>{he.current=null;const v=Tt.current;v&&v.deviceId===H&&(Tt.current=af(v.deviceId,v.transitionGeneration,{sessionId:v.sessionId,monitorIndex:an})),be(null)},[H,de,Bn,an]);const Va=de?`${de}-monitor-${an}`:"",rd=u.useMemo(()=>({fps:tr,maxWidth:Wr.maxWidth,maxHeight:Wr.maxHeight,quality:At.quality,mode:Bn,frameMode:Bn,streamPurpose:"control",forceRestart:Va!=="",forceRestartToken:Va,restartReason:Va?"control-session-or-monitor-change":"",monitorSelections:zt,onFrame:ni,onStreamReady:us}),[Va,At.quality,ni,tr,Bn,Wr.maxHeight,Wr.maxWidth,us,zt]),{frames:Lo,state:ai,error:Gc,stats:rn,restartLive:Gt}=Py(sn,Ye.autoStartLive&&sn.length>0,N,Es),{frame:wt,layout:ba,state:xa,stats:Vc,refreshInputs:sr}=B1(Pn,Rt&&Ye.autoStartLive&&Pn.length>0,N,{fps:bs.atlasOutputFps,inputFps:Ro,width:1920,height:1080,tileWidth:La.maxWidth,tileHeight:La.maxHeight,captureDeviceIds:Pn,monitorSelections:zt,onFrame:kr});u.useEffect(()=>{_i.current=ba,ba&&window.requestAnimationFrame(Rs)},[ba,Rs]),u.useEffect(()=>{if(!Rt||xa!=="open"){Tl.current=0,Oi.current=0,wo.current=0;return}const v=window.setInterval(()=>{const C=ra.current,E=performance.now();if(!C||document.visibilityState!=="visible"||E-Ii.current<$h)return;const I=Oi.current,_=Tl.current;if(I<=0||_<=0||E-I>500)return;const te=wo.current||_,ie=E-te;if(ie>=jT&&E-Tc.current>=MT){ju(C)&&(Tc.current=E,So.current=E);return}ie>=kT&&E-So.current>=AT&&k1(C)&&(So.current=E)},250);return()=>window.clearInterval(v)},[xa,Rt]);const{frames:zl,state:_o,error:Ds,stats:si,restartLive:Yi,reconnectLive:Ki}=Py(ar,ar.length>0,N,rd);u.useEffect(()=>{const v=go.current,C=new Set([...Object.keys(v),...Object.keys(zt)]);for(const E of C){const I=Math.max(0,Math.floor(Number(v[E])||0)),_=Math.max(0,Math.floor(Number(zt[E])||0));I!==_&&(cs("wall",E),cs("control",E),ju($n.current.get(E)||null),ju(Cn.current.get(E)||null))}go.current={...zt}},[zt,cs]);const ri=u.useMemo(()=>{const v=(E,I)=>{const _=lt.find(ie=>ie.deviceId===E),te=Vn(zt[E],_?Gn(_):1);return!Number.isFinite(Number(I.monitorIndex))||Number(I.monitorIndex)===te},C=new Map;for(const[E,I]of Lo.entries())v(E,I)&&C.set(E,I);if(Rt&&wt&&Pn.length>0){const E=new Map((ba?.tiles||[]).map(_=>[_.deviceId,_])),I=Math.max(1,E.size);for(const _ of Pn){const te=E.get(_);te&&C.set(_,{...wt,deviceId:_,width:te.width,height:te.height,sourceWidth:te.width,sourceHeight:te.height,byteLength:Math.round(wt.byteLength/I)})}}for(const[E,I]of zl.entries())v(E,I)&&C.set(E,I);for(const E of Mo){if(!Ys.current.has(E)||C.has(E))continue;const I=Cl.current.get(E);I&&v(E,I)&&C.set(E,I)}return C},[wt,ba,lt,zl,Pn,Rt,zt,Lo,Mo,Xf]),rr=pt&&ar.length>0?_o:Pn.length>0?xa:ai,Wa=pt&&ar.length>0?si:Pn.length>0?Vc:rn;u.useCallback((v,C="browser-stale")=>{const E=Gt(v,C),I=Yi(v,C);return E||I},[Yi,Gt]),u.useEffect(()=>{Rt&&Pn.length>0&&!pt&&sr()},[Pn.length,Rt,sr,pt]);const ds=u.useCallback((v,C,E)=>{const I=C==="control"?Cn.current.get(v)||null:$n.current.get(v)||null;if(!I||!ju(I))return!1;const _=performance.now();return xo.current.set(rs(C,v),_),!0},[]),Ya=u.useCallback(v=>{if(Bn!=="mode3-h264-hw"||!H||z)return!1;const C=lt.find(Ne=>Ne.deviceId===H)||oa,E=String(C?.platform||"").toLowerCase();if(!["win32","windows","win32nt"].includes(E))return!1;const I="mode5-lzo-delta",_=rs("control",H),te=performance.now();xr.current.set(_,te),br.current.delete(_),Zs.current.delete(_),As.current.delete(_),Ms.current.delete(_),Js.current.delete(_),ju(Cn.current.get(H)||null),Ki([H],"control-decode-fallback"),se(I),Z(`control-${I}-fallback-${H}-${Date.now()}`),ce(!1),ia(!1);const ie=v==="no first frame"||v==="control-first-frame-timeout";return ee(Ne=>Ne||(ie?`Control frame transport timeout; retrying Control with Mode 5 (${v})`:`H.264 decode failed; retrying Control with Mode 5 (${v})`)),O("connecting"),!0},[lt,oa,H,z,Bn,Ki]);u.useEffect(()=>{const v=pt?oa:null;if(v){js.current={deviceId:v.deviceId,monitorIndex:an,frameMode:Bn,startedAtEpochMs:Date.now()},ia(H===v.deviceId&&le);return}js.current=null,ia(!1)},[oa?.sessionId,P,H,le,Bn,an,pt]);const ir=u.useCallback(async v=>{if(Ze.current[v])throw new Error("LIVE_CAPTURE_PAUSED");const C=A.find(te=>te.deviceId===v);Mu({mode4Enabled:Rt,directMode4WallEnabled:vn,isMac:Ni(C?.platform)});const E=Vn(zt[v],C?Gn(C):1),I={fps:Rt?_a:Fn,maxWidth:La.maxWidth,maxHeight:La.maxHeight,quality:Ye.quality,mode:Rt?"mode3-h264-hw":Ye.frameMode,frameMode:Rt?"mode3-h264-hw":Ye.frameMode,streamPurpose:"wall",monitorIndex:E},_=await Ve(`/api/remote/devices/${encodeURIComponent(v)}/live/start`,{method:"POST",body:JSON.stringify(I)},N);if(_?.ok===!1)throw new Error(_.error||"wall-stream-start-failed");return _},[Fn,Ro,A,vn,_a,La.maxHeight,La.maxWidth,N,Rt,zt,Ye.frameMode,Ye.quality]),Io=u.useCallback(async v=>{const C=A.find(I=>I.deviceId===v);Mu({mode4Enabled:Rt,directMode4WallEnabled:vn,isMac:Ni(C?.platform)});const E=await Ve(`/api/remote/devices/${encodeURIComponent(v)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"wall",reason:"control-active"})},N);if(E?.ok===!1)throw new Error(E.error||"wall-stream-stop-failed");return E},[A,vn,N,Rt]),ii=u.useCallback(async(v,C="control-session-stop")=>{const E=await Ve(`/api/remote/devices/${encodeURIComponent(v)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"control",reason:C})},N);if(E?.ok===!1)throw new Error(E.error||"control-stream-stop-failed");return E},[N]),lr=u.useCallback(v=>{const C=Cn.current.get(v);C&&(Ws.current.has(v)||$n.current.has(v)||Cs.current.has(v)||En(v,C),dc(C),Cn.current.delete(v));const E=Ra.current.get(v);E&&dc(E),Cl.current.delete(v),Ys.current.delete(v),kl.current.delete(v)},[En]),Ka=u.useCallback(v=>{const C=Yy(Zu.current,v);return Zu.current=C.tail,C.result},[]),ln=u.useCallback(v=>{const C=Yy(Ml.current,v);return Ml.current=C.tail,C.result},[]),za=u.useCallback(v=>{os.current=v,Pr.current=0;const C=v?.deviceId||"";Br.current=C,Qu(C),C&&Ys.current.add(C)},[]),li=u.useCallback(v=>Ka(async()=>{if(Ze.current[v.deviceId])return!1;const C=os.current;return!gs(C,v)||!sf(v.deviceId,v,Tt.current)?!1:(await ir(v.deviceId),gs(os.current,v)&&za(null),!0)}),[za,Ka,ir]),id=u.useCallback((v,C,E)=>Ka(async()=>{const I=os.current;if(gs(I,v))return E.stoppedWallDeviceId=v.deviceId,!0;if(I)if(Ze.current[I.deviceId])gs(os.current,I)&&za(null);else{if(!sf(I.deviceId,I,Tt.current))return!1;await ir(I.deviceId),gs(os.current,I)&&za(null)}if(!C())return!1;if(await Io(v.deviceId),E.stoppedWallDeviceId=v.deviceId,!C()){if(sf(E.stoppedWallDeviceId,v,Tt.current))try{await ir(E.stoppedWallDeviceId)}catch(_){throw za(v),_}finally{E.stoppedWallDeviceId=""}return!1}return dc($n.current.get(v.deviceId)||null),za(v),!0}),[za,Ka,ir,Io]),zo=u.useCallback(async(v,C)=>{if(C.stoppedWallDeviceId){if(gs(os.current,v)){try{await li(v)}catch(E){Oe(E instanceof Error?E.message:String(E))}finally{C.stoppedWallDeviceId=""}return}await Ka(async()=>{if(!C.stoppedWallDeviceId||!sf(C.stoppedWallDeviceId,v,Tt.current))return;const E=C.stoppedWallDeviceId;try{await ir(E)}catch(I){za(v),Oe(I instanceof Error?I.message:String(I))}finally{C.stoppedWallDeviceId=""}})}},[za,Ka,li,Oe,ir]),jr=u.useCallback(async(v,C,E=!1)=>{try{await ii(v.deviceId,C)}catch(I){if(!E)throw I}if(!gs(Tt.current,v))return!1;Tt.current=null,he.current=null,be(null),lr(v.deviceId),ce(!1),Z(""),se(""),ee(""),ye(I=>I===v.deviceId?"":I);try{await li(v)}catch(I){Oe(I instanceof Error?I.message:String(I))}return!0},[lr,li,Oe,ii]),Oo=(pt&&Kt&&P&&!Be.has(P)&&lt.find(v=>v.deviceId===P)||null)?.deviceId||"";u.useEffect(()=>{Nl.current=Oo},[Oo]),u.useEffect(()=>{const v=P&&lt.find(te=>te.deviceId===P)||null;if(!pt||!Kt||!v){la.current&&(++va.current,la.current="");return}if(Ze.current[v.deviceId]){la.current&&(++va.current,la.current=""),H===v.deviceId&&O("paused");return}if(Zt.current){if(Zt.current===v.deviceId)return;Zt.current=""}if(H===v.deviceId&&(W==="active"||W==="warm"||W==="connecting")){O(te=>te==="warm"?"active":te);return}if(la.current===v.deviceId)return;const C=++va.current,E=af(v.deviceId,C,{sessionId:v.sessionId,monitorIndex:an});la.current=v.deviceId;const I={stoppedWallDeviceId:""},_=()=>C===va.current&&Nl.current===E.deviceId;ln(async()=>{if(!_())return;const te=Tt.current;if(te){O("stopping");try{await jr(te,"control-session-switch")}catch(Re){_()&&(O("error"),Oe(Re instanceof Error?Re.message:String(Re)));return}if(!_()){Tt.current||O("idle");return}}try{if(!await id(E,_,I)||!_()){await zo(E,I),Tt.current||O("idle");return}}catch(Re){await zo(E,I),_()&&(O("error"),Oe(Re instanceof Error?Re.message:String(Re)));return}if(!_()){await zo(E,I);return}Tt.current=E,Zt.current="",Ea.current=null,Qs.current=0,Xs.current="",I.stoppedWallDeviceId="";const ie=rs("control",E.deviceId),Ne=`control-session-${C}-${E.deviceId}`;xr.current.set(ie,performance.now()),br.current.delete(ie),Zs.current.delete(ie),Js.current.delete(ie),Ms.current.delete(ie),se(""),ee(""),Z(Ne),ye(E.deviceId),ce(!1),O("connecting")}).catch(te=>{_()&&(O("error"),Oe(te instanceof Error?te.message:String(te)))}).finally(()=>{va.current===C&&la.current===E.deviceId&&(la.current="")})},[lt,P,H,W,ln,Kt,id,zo,an,Oe,pt,jr,Xe]),u.useEffect(()=>{if(!H||lt.some(E=>E.deviceId===H))return;const v=H;++va.current,la.current="";const C=Tt.current;O("stopping"),ln(async()=>{C&&C.deviceId===v?await jr(C,"control-device-disconnected",!0):(lr(v),ye(E=>E===v?"":E)),Tt.current||O("idle")})},[lt,H,ln,lr,jr]),u.useEffect(()=>{if(Pa.current!==null&&(window.clearTimeout(Pa.current),Pa.current=null),!H||W==="idle"||W==="paused"||W==="stopping"||W==="error"||pt||On==="wall"){H&&!pt&&On==="wall"&&O(C=>C==="warm"||C==="active"?"active":C);return}O(C=>C==="idle"||C==="stopping"?C:"warm");const v=H;return Pa.current=window.setTimeout(()=>{Pa.current=null,++va.current,la.current="";const C=Tt.current;O("stopping"),ln(async()=>{if(C&&C.deviceId===v)try{await jr(C,"control-session-warm-timeout")}catch(E){O("error"),Oe(E instanceof Error?E.message:String(E));return}else lr(v),ye(E=>E===v?"":E);Tt.current||O("idle")})},NT),()=>{Pa.current!==null&&(window.clearTimeout(Pa.current),Pa.current=null)}},[On,H,W,ln,lr,Oe,pt,jr]),u.useEffect(()=>()=>{Pa.current!==null&&window.clearTimeout(Pa.current)},[]),u.useEffect(()=>{const v=os.current,C=Tt.current;if(!v||Ze.current[v.deviceId]||C&&C.deviceId===v.deviceId){Pr.current=0;return}const E=Pr.current,I=Math.min(5e3,500*2**Math.min(E,4)),_=window.setTimeout(()=>{const te=os.current;!te||Ze.current[te.deviceId]||!gs(te,v)||(Pr.current=E+1,li(te).catch(ie=>{Oe(ie instanceof Error?ie.message:String(ie)),gs(os.current,te)&&!Tt.current&&Nc(Ne=>Ne+1)}))},I);return()=>window.clearTimeout(_)},[W,li,Oe,Qf,Kn]);const or=H&&lt.find(v=>v.deviceId===H)||null,Ar=!!(pt&&Me&&W==="active"&&le&&or?.sessionId&&K?.deviceId===or.deviceId&&K.sessionId===or.sessionId&&K.streamPurpose==="control"&&K.commandId&&K.captureGeneration>0&&K.monitorIndex===an),{state:Ol,sendInput:oi,stats:ua,error:ld}=P1(Ns&&Ar,N),Ho=or?.deviceId||"",Wc=or?.sessionId||"",Fo=K?.commandId||"",cr=Number(K?.captureGeneration||0),$o=Number(K?.monitorIndex||0),Mr=u.useCallback((v,C)=>!Ar||!Ho||!Wc||!Fo||cr<=0||v!==Ho?!1:oi(v,{...C,monitorIndex:$o,controlSessionId:Wc,controlCommandId:Fo,captureGeneration:cr}),[Ar,cr,Fo,Ho,$o,Wc,oi]),Ls=Ar&&Ol==="open",Nr={shiftKey:ne.includes("ShiftLeft"),ctrlKey:ne.includes("ControlLeft"),altKey:ne.includes("AltLeft"),metaKey:ne.includes("MetaLeft")},{state:Yc,lastFrame:Hl,stats:Dn,error:Kc}=X1(Ee?.deviceId||"",Bc&&J,N),Fl=u.useRef(new Map);u.useEffect(()=>{const v=[["hub",j],["registry",l],["license",F],["wall-stream",Gc],["control-stream",Ds],["control-decode",fe],["remote-input",ld],["remote-audio",Kc]];for(const[C,E]of v){const I=String(E||"").trim();if(C==="hub"&&Nt?.requiresHubRestart&&Nt.stage==="updating"){Fl.current.delete(C);continue}if(!I){Fl.current.delete(C);continue}Fl.current.get(C)!==I&&(Fl.current.set(C,I),Oe(I))}},[Kc,fe,Ds,j,ld,F,l,Oe,Gc,Nt]);const _s=Ee?.deviceId||"",Tr=Ee?Vn(zt[_s],Gn(Ee)):0;u.useEffect(()=>{if(!Me||!Ns||!Ls||!_s)return;const v=ak(),C=_s,E=Tr,I=xt=>xt?Mr(C,{...xt,monitorIndex:E}):!1,_=(xt,en)=>{const Ca=xt.target,Qn=Ca?.tagName?.toLowerCase(),Za=Ca?.isContentEditable||Qn==="input"||Qn==="textarea"||Qn==="select",vi=v.snapshot().pressedCodes.includes(xt.code);if(Za&&(en==="keydown"||!vi))return;const el=v.event(xt,en);el&&(xt.preventDefault(),xt.stopPropagation(),I(el))},te=xt=>_(xt,"keydown"),ie=xt=>_(xt,"keyup"),Ne=(xt,en=!1)=>{const Ca=v.reset(xt,en);Ca&&(I(Ca),qe([]))};mt.current=xt=>{const en=v.snapshot().latchedCodes.includes(xt),Ca=v.modifier(xt,!en);Ca&&(I(Ca),qe(Qn=>en?Qn.filter(Za=>Za!==xt):[...Qn.filter(Za=>Za!==xt),xt]))};const Re=()=>Ne("browser-window-blur"),Ue=()=>Ne("browser-page-hidden"),Bt=()=>{document.visibilityState==="hidden"&&Ne("browser-document-hidden")};return window.addEventListener("keydown",te),window.addEventListener("keyup",ie),window.addEventListener("blur",Re),window.addEventListener("pagehide",Ue),document.addEventListener("visibilitychange",Bt),()=>{window.removeEventListener("keydown",te),window.removeEventListener("keyup",ie),window.removeEventListener("blur",Re),window.removeEventListener("pagehide",Ue),document.removeEventListener("visibilitychange",Bt),mt.current=null,Ne("control-keyboard-owner-changed",!0)}},[Ns,Ls,_s,Tr,Me,Mr]),u.useEffect(()=>{const v=()=>{document.visibilityState==="visible"&&(Ii.current=performance.now())};return document.addEventListener("visibilitychange",v),window.addEventListener("pageshow",v),()=>{document.removeEventListener("visibilitychange",v),window.removeEventListener("pageshow",v)}},[]),u.useEffect(()=>{if(!H||W!=="connecting"&&W!=="active"&&W!=="warm"||_o!=="open")return;const v=H,C=rs("control",v),E=window.setInterval(()=>{const I=performance.now();if(document.visibilityState!=="visible"||I-Ii.current<$h)return;const _=br.current.get(C)||0,te=Zs.current.get(C)||0,ie=As.current.get(C)||0,Ne=xr.current.get(C)||I;xr.current.has(C)||xr.current.set(C,Ne);const Re=_<=0,Ue=Re?I-Ne>FT:I-_>Jb,Bt=_>0&&(te<=0||I-te>Jb);if(!Ue&&Bt){const Qn=xo.current.get(C)||0;I-Qn>=ex&&ds(v,"control","decoder-paint-stale");return}if(!Ue)return;const xt=Ms.current.get(C)||0;if(xt>0){if(I-xt<BT)return;Ms.current.delete(C)}const en=Js.current.get(C)||0;if(en>=PT){if(Ya(Re?"no first frame":"stale stream"))return;ce(!1),ia(!1),Zt.current=v,O("error");return}if(I-ie<tx($T,en))return;Yi([v],Re?"control-first-frame-timeout":"control-receive-stale")&&(As.current.set(C,I),Ms.current.set(C,I),xr.current.set(C,I),Js.current.set(C,en+1))},650);return()=>window.clearInterval(E)},[_o,H,W,Ya,ds,Yi]),u.useEffect(()=>{!fe||H&&Ze.current[H]||Bn!=="mode3-h264-hw"||Ya(fe)||(ce(!1),ia(!1),Zt.current=Tt.current?.deviceId||"",O("error"))},[fe,H,Bn,Ya]),u.useEffect(()=>{!pt||!H||Ze.current[H]||!Ds||(Zt.current=H,O(v=>v==="error"?v:"error"))},[Ds,H,pt]),u.useEffect(()=>{if(W!=="error")return;const v=Tt.current;if(!v)return;Zt.current=v.deviceId,gs(Ea.current,v)||(Ea.current=v,Qs.current=0);const C=Qs.current,E=C===0?0:Math.min(5e3,500*2**Math.min(C-1,4)),I=window.setTimeout(()=>{gs(Tt.current,v)&&(++va.current,la.current="",O("stopping"),ln(async()=>{if(gs(Tt.current,v))try{if(!await jr(v,"control-session-terminal-error"))return;Ea.current=null,Qs.current=0,Xs.current===v.deviceId?(Xs.current="",Zt.current="",O("idle")):O("error")}catch(_){if(!gs(Tt.current,v))return;Qs.current+=1,Oe(_ instanceof Error?_.message:String(_)),O("error"),Sl(te=>te+1)}}))},E);return()=>window.clearTimeout(I)},[W,Xu,ln,Oe,jr]);const Qi=u.useCallback(v=>{if(!v||Zt.current!==v)return!1;const C=Tt.current;return++va.current,la.current="",Qs.current=0,C&&C.deviceId===v?(Xs.current=v,Ea.current=null,O("error"),Sl(E=>E+1),!0):(Xs.current="",Zt.current="",Ea.current=null,O("idle"),!0)},[]);u.useEffect(()=>{if(ai!=="open"||!Ye.autoStartLive||sn.length===0)return;const v=window.setInterval(()=>{const C=performance.now();if(document.visibilityState!=="visible"||C-Ii.current<$h)return;const E=1e3/Math.max(1,_a||Ye.fps||1),I=Math.max(qT,Math.ceil(E*4)),_=[];for(const te of sn){if(_.length>=WT)break;const ie=rs("wall",te),Ne=br.current.get(ie)||0,Re=Ne<=0,Ue=zi.current.get(ie)||C;if(zi.current.has(ie)||zi.current.set(ie,Ue),Re&&C-Ue<=UT)continue;const Bt=As.current.get(ie)||0,xt=Zs.current.get(ie)||0,en=Re||C-Ne>I,Ca=!Re&&(xt<=0||C-xt>I);if(!en&&Ca){const Za=xo.current.get(ie)||0;C-Za>=ex&&ds(te,"wall","decoder-paint-stale");continue}if(!en)continue;const Qn=Js.current.get(ie)||0;C-Bt>=tx(GT,Qn)&&_.push(te)}if(_.length>0&&Gt(_,_.some(te=>(br.current.get(rs("wall",te))||0)<=0)?"wall-first-frame-timeout":"wall-frame-stale"))for(const te of _){const ie=rs("wall",te);As.current.set(ie,C),zi.current.set(ie,C),br.current.delete(ie),Zs.current.delete(ie),Js.current.set(ie,(Js.current.get(ie)||0)+1)}},VT);return()=>window.clearInterval(v)},[_a,sn,ds,Gt,Ye.autoStartLive,Ye.fps,ai]),u.useEffect(()=>{$a(Ye.fps),Fi.current=Date.now(),er.current=0},[Ye.fps,Ye.frameMode,Ye.adaptiveLoadShedding]),u.useEffect(()=>{h1({h264DecodeAcceleration:Ye.h264DecodeAcceleration})},[Ye.h264DecodeAcceleration]),u.useEffect(()=>{if(!Kt||pt||pn==="list"||!Ye.visibleOnlyLive){Fr([]);return}const v=td.current;if(!v||typeof IntersectionObserver>"u"){Fr(Ao);return}const C=Array.from(v.querySelectorAll("[data-live-device-id]"));if(C.length===0){Fr([]);return}const E=new Map,I=()=>{const te=Uh(C.map(ie=>String(ie.dataset.liveDeviceId||"")).filter(ie=>(E.get(ie)||0)>0));Fr(ie=>Ph(ie,te)?ie:te)},_=new IntersectionObserver(te=>{for(const ie of te){const Ne=String(ie.target.dataset.liveDeviceId||"");Ne&&E.set(Ne,ie.isIntersecting?ie.intersectionRatio||.01:0)}I()},{root:null,rootMargin:Ma.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return C.forEach(te=>_.observe(te)),I(),()=>_.disconnect()},[Ao,Kt,pt,Sr,Ye.visibleOnlyLive,pn]),u.useEffect(()=>{if(!Ye.adaptiveLoadShedding||!Ye.autoStartLive||sn.length===0)return;const v=Ye.fps;if(sn.length<=Ma.preserveConfiguredFpsDeviceCount){Fn!==v&&($a(v),Fi.current=Date.now(),er.current=0);return}if(ai!=="open"||rn.sampleMs<500)return;const C=Date.now(),E=sn.length*Fn,I=rn.framesPerSecond,_=rn.bytesPerSecond,te=Math.max(0,...sn.map(Bt=>yr[rs("wall",Bt)]?.maxIntervalMs||0)),ie=Math.max(0,...sn.map(Bt=>jl[rs("wall",Bt)]?.maxIntervalMs||0)),Ne=E>8&&I>0&&I<E*.72;if(I>Ma.maxWallFramesPerSecond||_>Ma.maxWallBytesPerSecond||te>Ma.maxFrameGapMs||ie>Ma.maxFrameGapMs||Ne){er.current=0;const Bt=Ma.minFps;if(C-Fi.current>=Ma.downshiftCooldownMs&&Fn>Bt){const xt=Math.max(Bt,uR(Fn,Bt));xt<Fn&&($a(xt),Fi.current=C)}return}const Ue=I<Ma.maxWallFramesPerSecond*Ma.lowLoadFrameRatio&&_<Ma.maxWallBytesPerSecond*Ma.lowLoadByteRatio;if(!Ue||Fn>=v){Ue||(er.current=0);return}if(!er.current){er.current=C;return}if(C-er.current>=Ma.recoveryCooldownMs){const Bt=Math.min(v,dR(Fn,v));Bt>Fn&&($a(Bt),Fi.current=C,er.current=0)}},[Fn,sn.length,sn,jl,yr,ai,rn.bytesPerSecond,rn.framesPerSecond,rn.lastUpdatedAt,rn.sampleMs,Ye.adaptiveLoadShedding,Ye.autoStartLive,Ye.frameMode,Ye.fps]),u.useEffect(()=>{const v=new URLSearchParams(window.location.search).get("checkout");if(v==="success"){Oe("Checkout returned. Waiting for Dodo confirmation."),$();const C=window.setInterval(()=>{$()},4e3),E=window.setTimeout(()=>{window.clearInterval(C)},45e3);return()=>{window.clearInterval(C),window.clearTimeout(E)}}v==="cancelled"&&Oe("Checkout cancelled.")},[$]),u.useEffect(()=>{!Kt&&Me&&He(!1),!Kt&&J&&Ce(!1)},[J,Me,Kt]),u.useEffect(()=>{const v=Ee?.deviceId||"",C=Le.current;if(Le.current=v,!C||C===v)return;const E=++_e.current,I=v?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";v&&J&&Fe.current.set(v,I);let _=!0;return(async()=>{try{const ie=Fe.current.get(C);if(Fe.current.delete(C),await Ve(`/api/remote/devices/${encodeURIComponent(C)}/audio/stop`,{method:"POST",body:JSON.stringify(ie?{streamId:ie}:{})},N),!_||E!==_e.current||!J||!v||!Kt||!Kr)return;const Ne=await Ve(`/api/remote/devices/${encodeURIComponent(v)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:I,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},N);if(Ne.ok===!1)throw new Error(Ne.error||"Remote audio start failed.")}catch(ie){_&&(Fe.current.delete(v),Ce(!1),Oe(ie instanceof Error?ie.message:String(ie)))}})(),()=>{_=!1}},[J,Kt,N,Kr,Ee?.deviceId]),u.useEffect(()=>{const v=lt.map(I=>I.deviceId),C=new Set(v),E=new Map(lt.map(I=>[I.deviceId,I]));for(const I of lt){const _=JT(I);_&&(Tn.current[I.deviceId]=_)}L(I=>{const _=I.filter(te=>C.has(te));return Ph(I,_)?I:_}),q(I=>I&&C.has(I)?I:""),Y(I=>I&&C.has(I)?I:""),Sn(I=>{let _=!1;const te={};for(const[ie,Ne]of Object.entries(I)){const Re=E.get(ie);if(!Re){te[ie]=Ne;continue}const Ue=Vn(Ne,Gn(Re));te[ie]=Ue,Ue!==Ne&&(_=!0)}return _?te:I}),Ec(I=>{const _=I.filter(te=>C.has(te));return Ph(I,_)?I:_})},[lt,ko]),u.useEffect(()=>{Jf([]),tm(!1)},[qa]),u.useEffect(()=>{!El||Hi!=="selected"||qr.length>0||Da.length===0||Ec(Da.map(v=>v.deviceId))},[Da,qr.length,Hi,El]),u.useEffect(()=>{try{localStorage.setItem(Bw,gn)}catch{}},[gn]),u.useEffect(()=>{rR(Ye)},[Ye]),u.useEffect(()=>{lR(At)},[At]),u.useEffect(()=>{aR(zt,Tn.current)},[lt,zt]);const Bo=u.useCallback(async()=>{const v=new Set(h);v.add(An);try{const te=await Ve("/api/remote/status",void 0,An);Ty({endpoint:te.agentEndpoint,endpoint_candidates:[...te.agentEndpointCandidates||[],...te.hostTargetEndpointCandidates||[]]}).forEach(ie=>v.add(ie))}catch{}const C=[...v].sort((te,ie)=>{const Ne=Re=>{const Ue=Ou(Re);return Ue==="local"?0:Ue==="loopback"?1:2};return Ne(te)-Ne(ie)||te.localeCompare(ie)});let E=!1,I="",_=!1;try{for(const te of C){const ie=Ou(te);try{if(await Ve("/api/health",void 0,te),ie==="local")return y(!0),hc(!0),te;ie==="loopback"&&(E=!0,I=te)}catch{ie==="local"&&(_=!0)}}return E?(_&&Oe("LiveDesk Hub is reachable on this PC, but not through the LAN address yet. Restart LiveDesk Hub to bind 5179 on the network."),y(!0),hc(!0),I||An):(y(!1),hc(!1),"")}catch{return y(!1),hc(!1),""}},[h]),Is=async()=>{if(kt("auth"),Mt(!1),await Bo(),window.liveDesk?.auth?.signInWithGoogle){const E=await window.liveDesk.auth.signInWithGoogle();E?.ok===!1&&(Oe(E.error||"LiveDesk could not open the system browser for Google sign-in."),kt(""));return}const{data:v,error:C}=await Ct.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}/callback`}});C&&(Oe(C.message),kt(""))},$l=async()=>{kt("auth"),Mt(!1),await Ct.auth.signOut(),(await window.liveDesk?.auth?.persistSession?.(null))?.runtimeCleared===!1?Oe("Signed out locally. The LiveDesk runtime could not be reached to clear its session."):window.liveDesk?.auth?.persistSession||await Ve("/api/auth/session",{method:"DELETE"},An).catch(()=>{}),kt("")};u.useEffect(()=>{if(!st)return;const v=E=>{E.target instanceof Element&&(E.target.closest(".account-popover, .rail-account")||Mt(!1))},C=E=>{E.key==="Escape"&&Mt(!1)};return window.addEventListener("pointerdown",v),window.addEventListener("keydown",C),()=>{window.removeEventListener("pointerdown",v),window.removeEventListener("keydown",C)}},[st]);const Bl=u.useCallback(async(v={})=>{const C=v.silent===!0,E=v.takeover===!0,I=v.requestLocalAccess===!0;if(!n?.user){C||Oe("Sign in before publishing this host.","error");return}if(!Gr.current){Gr.current=!0,C||(kt("host"),wn("Hub · 1/4 · Checking the local runtime…"));try{const te=(I?await Bo():"")||N||An;if(!(w||await Ve("/api/remote/status",void 0,te)).started)throw new Error("Start LiveDesk on this computer before syncing the server.");C||wn("Hub · 2/4 · Sending the signed-in session to the Hub…");const Ne=await Ve("/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}})},te);if(!Ne.ok||!Ne.authenticated)throw new Error(Ne.error||"hub-session-sync-failed");C||wn("Hub · 3/4 · Claiming the Hub role and publishing its endpoint…");const Re=await Ve("/api/hub/sync",{method:"POST",body:JSON.stringify({takeover:E})},te);if(!Re.ok)throw new Error(Re.error||"host-target-failed");if(!C){wn("Hub · 4/4 · Verifying the endpoint and lease renewal…");const Ue=await Ve("/api/hub/status",void 0,te);if(!Ue.hostTargetActive)throw new Error(Ue.hostTargetLease?.lastError||"host-target-not-active-after-sync");const Bt=Ue.hostTargetEndpoint||Ue.agentEndpoint||"endpoint ready",xt=Number(Ue.connectedDeviceCount||0),en=xt>0?`${xt} client${xt===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";Oe(`Hub ready · ${Bt} · lease auto-renewal active. ${en}`,"success"),(I||x)&&(y(!0),hc(!0)),k()}c()}catch(_){if(!C){const te=_ instanceof Error?_.message:String(_);te.includes("local network access")&&(y(!1),hc(!1)),Oe(`Hub setup failed · ${te}`,"error")}}finally{Gr.current=!1,C||kt("")}}},[N,x,k,c,Bo,n,Oe,wn,w]),ur=u.useCallback((v=!0)=>{ot!=="host"&&(je(!1),v&&window.requestAnimationFrame(()=>bt.current?.focus()))},[ot]),Po=u.useCallback(()=>{ot!=="host"&&(bt.current=document.activeElement instanceof HTMLElement?document.activeElement:null,Mt(!1),je(!0))},[ot]),od=u.useCallback(()=>{je(!1),Bl({takeover:!0,requestLocalAccess:!0})},[Bl]);u.useEffect(()=>{if(!$e)return;const v=window.requestAnimationFrame(()=>ct.current?.focus()),C=I=>{I.target instanceof Element&&I.target.closest(".client-hub-switch-popover, .hub-sync-trigger")||ur(!1)},E=I=>{I.key==="Escape"&&ur()};return window.addEventListener("pointerdown",C),window.addEventListener("keydown",E),()=>{window.cancelAnimationFrame(v),window.removeEventListener("pointerdown",C),window.removeEventListener("keydown",E)}},[ur,$e]);const ci=u.useCallback(async()=>{if(!(!w?.update?.canApply||ot==="update")){kt("update");try{const v=await Ve("/api/update/apply",{method:"POST",body:JSON.stringify({})},N||An);if(!v.ok)throw new Error(v.error||"LiveDesk update could not be started.");const C=[...new Set((v.targets||[]).map(_=>String(_.deviceId||"").trim()).filter(Boolean))],E=!!(v.managerUpdateAvailable||v.clientPackageUpdateAvailable),I=v.state==="hub-restart-requested"?Date.now():void 0;(C.length>0||E)&&ga({operationId:String(v.operationId||`wall-update-${Date.now()}`),targetIds:C,stage:v.state==="clients-updated"?"updated":"updating",requiresHubRestart:E,initialHostInstanceId:String(w.hostInstanceId||""),targetManagerVersion:String(v.latestVersion||w.update?.latestVersion||""),targetClientVersion:String(v.latestClientVersion||w.update?.latestClientVersion||""),restartRequestedAt:I,restartDeadlineAt:I?I+bf:void 0}),wn(v.state==="hub-restart-requested"?yf:Vb),k()}catch(v){Oe(v instanceof Error?v.message:String(v),"error")}finally{kt("")}}},[ot,N,k,Oe,wn,w]);u.useEffect(()=>{const v=Nt,C=w?.update;if(!v||v.stage!=="updating"||!C)return;const E=C.restartResult?.operationId===v.operationId?C.restartResult:null;if(E?.outcome==="restored"){const Re=E.error||`The requested Hub ${E.targetVersion||v.targetManagerVersion||"version"} failed verification.`;ga(Ue=>Ue?.operationId===v.operationId?{...Ue,stage:"restored",error:Re}:Ue),Oe(`LiveDesk update did not complete. Hub ${E.fallbackVersion||E.appVersion||"the previous version"} was restored. ${Re}`,"error");return}if(E?.outcome==="failed"){const Re=E.error||"No verified LiveDesk Hub replacement could be started.";ga(Ue=>Ue?.operationId===v.operationId?{...Ue,stage:"failed",error:Re}:Ue),Oe(`LiveDesk Hub update failed. ${Re}`,"error");return}if(C.operationId===v.operationId&&C.state==="failed"){const Re=C.error||"LiveDesk update failed before the Hub replacement completed.";ga(Ue=>Ue?.operationId===v.operationId?{...Ue,stage:"failed",error:Re}:Ue),Oe(Re,"error");return}if(C.operationId===v.operationId){if(C.state==="hub-restart-requested"&&!v.restartDeadlineAt){const Re=Date.now();ga(Ue=>Ue?.operationId===v.operationId?{...Ue,restartRequestedAt:Re,restartDeadlineAt:Re+bf}:Ue),wn(yf)}!v.requiresHubRestart&&C.state==="clients-updated"&&(ga(Re=>Re?.operationId===v.operationId?{...Re,stage:"updated"}:Re),Oe("LiveDesk clients updated and reconnected successfully.","success"));return}if(!v.requiresHubRestart)return;const I=w.started===!0&&(!v.initialHostInstanceId||w.hostInstanceId&&w.hostInstanceId!==v.initialHostInstanceId),_=!!C.checkedAt,te=Wb(C.currentVersion,v.targetManagerVersion),ie=!v.targetClientVersion||Wb(C.currentClientVersion,v.targetClientVersion),Ne=_&&C.state==="idle"&&C.updateAvailable===!1&&te&&ie;I&&Ne&&(ga(Re=>Re?.operationId===v.operationId?{...Re,stage:"updated"}:Re),Oe(`LiveDesk Hub ${C.currentVersion||E?.appVersion||v.targetManagerVersion} restarted and passed version verification.`,"success"))},[Oe,wn,w,Nt]),u.useEffect(()=>{const v=Nt;if(!v||v.stage!=="updating"||!v.requiresHubRestart||v.restartDeadlineAt)return;const C=()=>{const I=Date.now();ga(_=>_?.operationId===v.operationId&&_.stage==="updating"&&!_.restartDeadlineAt?{..._,restartRequestedAt:I,restartDeadlineAt:I+bf}:_),wn(yf)};if(w?.update?.state==="hub-restart-requested"){C();return}if(!j)return;const E=window.setTimeout(C,DT);return()=>window.clearTimeout(E)},[j,wn,w?.update?.state,Nt]),u.useEffect(()=>{const v=Nt;if(!v||v.stage!=="updating"||!v.requiresHubRestart||!v.restartDeadlineAt)return;const C=Math.max(0,v.restartDeadlineAt-Date.now()),E=v.operationId,I=window.setTimeout(()=>{const _=`LiveDesk Hub did not return and verify ${v.targetManagerVersion||"the requested version"} within ${Math.round(bf/6e4)} minutes. Check the Hub terminal or restart log, then run livedesk@latest manually if the Hub is still offline.`;ga(te=>te?.operationId===E&&te.stage==="updating"?{...te,stage:"failed",error:_}:te),Oe(_,"error")},C);return()=>window.clearTimeout(I)},[Oe,Nt]),u.useEffect(()=>{if(!Nt||Nt.stage!=="updated")return;const v=Nt.operationId,C=window.setTimeout(()=>{ga(E=>E?.operationId===v?null:E)},8e3);return()=>window.clearTimeout(C)},[Nt]),u.useEffect(()=>{if(ze!==Vb&&ze!==yf)return;const v=w?.update;if(String(v?.state||"")==="failed"){Oe(v?.error||"LiveDesk update failed.","error");return}Nt?.stage==="updated"&&Oe("")},[ze,Oe,w?.update?.error,w?.update?.state,Nt?.stage]);const cd=u.useCallback(async()=>{if(!ot){kt("pin");try{const C=await Ve("/api/remote/pairing-pin",{method:"POST"},N||An);if(!C.ok)throw new Error(C.error||"pin-rotation-failed");await k(),Oe("New PIN published.")}catch(v){Oe(v instanceof Error?v.message:String(v))}finally{kt("")}}},[ot,N,k]),zs=u.useCallback(v=>{v&&(q(v),L(C=>C.includes(v)?C:[...C,v]))},[]),Pl=u.useCallback(v=>{if(!v)return;const C=Yr.has(v);q(E=>C?E===v?"":E:v),L(E=>C?E.filter(I=>I!==v):E.includes(v)?E:[...E,v])},[Yr]),ui=u.useCallback(()=>{L([]),q("")},[Rn]),dr=u.useCallback(()=>{L(lt.map(v=>v.deviceId)),q("")},[lt]),Os=u.useCallback((v,C)=>{const E=lt.find(_=>_.deviceId===v);if(!E)return;const I=Gn(E);if(!(I<=1)&&(Sn(_=>{const te=Vn(_[v],I),ie=(te+C+I)%I;return ie===te?_:{..._,[v]:ie}}),cs("wall",v),cs("control",v),Li(_=>{if(!_.has(v))return _;const te=new Set(_);return te.delete(v),te}),Cl.current.delete(v),Ys.current.delete(v),pt)){const _=Qi(v);ce(!1),_||O("connecting"),ia(!1),Y(v)}},[lt,cs,Qi,pt]);u.useEffect(()=>{const v=C=>{if(Me&&Ns&&Ls)return;const E=C.target,I=E?.tagName?.toLowerCase();E?.isContentEditable||I==="input"||I==="textarea"||I==="select"||((C.ctrlKey||C.metaKey)&&C.key.toLowerCase()==="a"&&(C.preventDefault(),dr()),C.key==="Escape"&&ui())};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[Ns,ui,Ls,Me,dr]);const Ul=(v,C)=>{const E=lt.find(ie=>ie.deviceId===v),I=E?Gn(E):1,_=Vn(zt[v],I),te=Vn(C,I);if(_!==te&&(Sn(ie=>({...ie,[v]:te})),Li(ie=>{if(!ie.has(v))return ie;const Ne=new Set(ie);return Ne.delete(v),Ne}),Cl.current.delete(v),Ys.current.delete(v),cs("wall",v),cs("control",v)),pt){const ie=Qi(v);_!==te&&(ce(!1),ie||O("connecting")),ia(!1),Y(v)}else zs(v)},di=async v=>{if(Qi(v),ia(!1),Y(v),ws("control"),!Xr.has(v)){He(!1),Oe(Jr);return}const C=lt.find(I=>I.deviceId===v);if(Ni(C?.platform)&&(C?.capabilities?.controlPermission===!1||C?.capabilities?.accessibilityPermission===!1)){He(!1),Oe("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts LiveDesk, then restart the Mac client.","error");return}He(!0),Oe(`Opening remote control${C?` for ${ha(C)}`:""}.`,"success")},Qc=async()=>{if(!Ee){Oe("Select a Client before playing audio.");return}if(!Kt){Oe(Jr);return}if(!Kr){Oe("Selected Client does not report remote audio support yet.");return}if(pe)return;const v=!J,C=v?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:Fe.current.get(Ee.deviceId);v&&C?Fe.current.set(Ee.deviceId,C):v||Fe.current.delete(Ee.deviceId),De("audio"),Ce(v);try{await Ve(`/api/remote/devices/${encodeURIComponent(Ee.deviceId)}/audio/${v?"start":"stop"}`,{method:"POST",body:JSON.stringify({...C?{streamId:C}:{},mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},N),Oe(`${v?"Audio started":"Audio stopped"} for ${ha(Ee)}.`,"success")}catch(E){v&&Fe.current.delete(Ee.deviceId),Ce(!1),Oe(E instanceof Error?E.message:String(E),"error")}finally{De("")}},ql=async()=>{if(!Ee){Oe("Select a Client before pausing video.");return}if(!Kt){Oe(Jr);return}if(pe)return;const v=Ee,C=v.deviceId,E=String(Ze.current[C]||""),I=!!E&&ve[C]===!0,_=!E||I;if(De("video"),_){const te=E||`pending:${Date.now()}:${C}`,ie=Tt.current?.deviceId===C?Tt.current:null,Ne=dt.current.get(C);dt.current.set(C,{deviceId:C,monitorIndex:Vn(zt[C]??Ne?.monitorIndex,Gn(v)),previousControlOwner:ie||Ne?.previousControlOwner||null}),yt(C,!0),it(C,!1),ft(C,te),(ie||H===C)&&(++va.current,la.current="",O("paused"));try{const Re=await Ve(`/api/remote/devices/${encodeURIComponent(C)}/live/pause`,{method:"POST",body:JSON.stringify({reason:"user-video-pause"})},N);if(!Re?.pauseToken){U.current.delete(C),ft(C,""),it(C,!1),dt.current.delete(C),(ie||H===C)&&(he.current=null,be(null),ce(!1),Z(`control-pause-rollback-${Date.now()}-${C}`),O("connecting")),Oe(Re?.error||"video-capture-pause-failed","error");return}const Ue=Tt.current?.deviceId===C?Tt.current:ie,Bt=dt.current.get(C);Bt&&(Bt.previousControlOwner=Ue),Tt.current?.deviceId===C&&(Tt.current=null),he.current=null,be(null),ft(C,Re.pauseToken),(Ue||H===C)&&O("paused"),Re.ok===!1||Re.captureStopConfirmed!==!0?(it(C,!0),Oe(`Video restart is blocked for ${ha(v)}, but Client capture shutdown was not confirmed: ${Re.stopError||Re.error||"unknown stop error"}. Press Retry pause to check again.`,"error")):(it(C,!1),Oe(`Video paused for ${ha(v)}. Client capture and FFmpeg shutdown were confirmed.`,"success")),k()}catch(Re){it(C,!0),k(),Oe(`Video pause could not be confirmed: ${Re instanceof Error?Re.message:String(Re)}. LiveDesk will reconcile Hub status before allowing restart.`,"error")}finally{De("")}return}if(E.startsWith("pending:")){De("");return}try{yt(C,!1);const te=await Ve(`/api/remote/devices/${encodeURIComponent(C)}/live/resume`,{method:"POST",body:JSON.stringify({pauseToken:E})},N);if(te?.ok===!1)throw new Error(te.error||"video-capture-resume-failed");const ie=dt.current.get(C),Ne=ie?.previousControlOwner||null,Re=H===C&&(Ne!==null||os.current?.deviceId===C||W==="paused");if(ft(C,""),it(C,!1),dt.current.delete(C),Re){const Ue=++va.current;la.current="";const Bt=af(C,Ue,{sessionId:v.sessionId||Ne?.sessionId,monitorIndex:Vn(zt[C]??ie?.monitorIndex,Gn(v))});Tt.current=Bt,za(Bt),Zt.current="",Ea.current=null,he.current=null,be(null),se(""),ee(""),ce(!1),cs("control",C);const xt=`control-video-resume-${Ue}-${C}`;Z(xt),ye(C),O("connecting")}else cs("wall",C);k(),Oe(`Video resumed for ${ha(v)}.`,"success")}catch(te){U.current.delete(C),k(),Oe(te instanceof Error?te.message:String(te),"error")}finally{De("")}},Gl=v=>{const C=v instanceof Error?v.message:String(v);return/remote-actions-disabled|allowAgent-blocked-by-settings/i.test(C)?"Remote actions are off. Turn on Settings > Agent > Enable AI Agent first.":/power-actions-disabled/i.test(C)?"Power actions are off. Turn on Settings > Agent > Allow power actions first.":/agent-tool-capability-unavailable|unsupported-agent-operation/i.test(C)?"This Client needs a newer LiveDesk Client for power actions.":/device-not-connected|404 device-not-found/i.test(C)?"The Client disconnected before the action could be sent.":C},Uo=async v=>{if(!Ee||pe)return;const C=Ee,I={sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[v];if(window.confirm(`${I} ${ha(C)}? Unsaved work on that computer may be lost.`)){De(v),Oe(`Sending ${I.toLowerCase()} request to ${ha(C)}...`);try{const _=await Ve(`/api/remote/devices/${encodeURIComponent(C.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:v})},N);if(!_.ok)throw new Error(_.error||"The remote action could not be sent.");Oe(`${I} request sent to ${ha(C)}.`,"success"),k()}catch(_){Oe(Gl(_),"error")}finally{De("")}}},Xc=async(v,C,E="files")=>{const I=v.filter(Ne=>Ne.file.size>=0);if(I.length===0)return{files:0,bytes:0};if(!Kt)throw new Error(Jr);if(C.length===0)throw new Error("Select at least one connected Client.");const _=crypto.randomUUID(),te=I.reduce((Ne,Re)=>Ne+Re.file.size,0);let ie=0;wr({id:_,status:"reading",progress:1,message:`Preparing ${I.length} ${E}`});try{for(let Ne=0;Ne<I.length;Ne+=1){const Re=I[Ne],Ue=Re.file,Bt=Math.max(1,Math.ceil(Ue.size/Hh));for(let xt=0;xt<Bt;xt+=1){const en=xt*Hh,Ca=Math.min(Ue.size,en+Hh),Qn=Ue.size===0?new ArrayBuffer(0):await Ue.slice(en,Ca).arrayBuffer(),Za=xt===Bt-1;wr({id:_,status:"sending",progress:Math.max(2,Math.min(98,Math.round(ie/Math.max(1,te)*96))),message:`${Ne+1}/${I.length} ${Re.relativePath}`});const vi=await Ve("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:_,deviceIds:C,remoteDirectory:gn.trim(),name:Ue.name,relativePath:Re.relativePath,size:Ue.size,type:Ue.type,lastModified:Ue.lastModified,offset:en,totalBytes:Ue.size,final:Za,dataBase64:fR(Qn)})},N);if(!vi.ok||vi.queued!==C.length)throw new Error(vi.error||`file-chunk-not-queued-${vi.queued}/${C.length}`);ie+=Qn.byteLength,await new Promise(el=>window.setTimeout(el,0))}}return wr({id:_,status:"queued",progress:100,message:`Sent ${I.length} file${I.length===1?"":"s"} to ${C.length} Client${C.length===1?"":"s"}`}),window.setTimeout(()=>{wr(Ne=>Ne?.id===_&&Ne.status==="queued"?null:Ne)},4500),{files:I.length,bytes:te}}catch(Ne){throw wr({id:_,status:"failed",progress:100,message:Ne instanceof Error?Ne.message:String(Ne)}),Ne}},fi=async v=>{const C=Da.length>0?Da.map(E=>E.deviceId):Ee?[Ee.deviceId]:[];try{await Xc(ax(v),C)}catch(E){Oe(E instanceof Error?E.message:String(E))}},Vl=async v=>{try{await Xc(ax(v),ad)}catch(C){Oe(C instanceof Error?C.message:String(C))}};u.useEffect(()=>{Dc.current=!1},[]);const ud=v=>{v.preventDefault(),v.stopPropagation(),Rc(!1),fi(v.dataTransfer.files)},Wl=async(v="ltd")=>{if(!n){Oe("Sign in with Google before checkout.");return}if(T&&v===un){Oe("LiveDesk license is already active.");return}if(T&&un==="pro"){Oe("LiveDesk Pro is already active.");return}kt("checkout");try{const{data:C,error:E}=await Ct.functions.invoke("dodo-checkout",{body:{plan:v}});if(E)throw E;if(!C?.checkout_url)throw new Error("Checkout function did not return a checkout URL.");window.location.assign(C.checkout_url)}catch(C){Oe(C instanceof Error?C.message:String(C)),kt("")}},Xi=YT(),wa=KT(),Sa=To.filter(v=>ri.has(v)).length,Hs=rr==="open"&&Wa.sampleMs>0?`${Wa.framesPerSecond.toFixed(1)} fps`:rr,Ie=Ee?pt?zl.get(Ee.deviceId):ri.get(Ee.deviceId):void 0,Yl=Ee?Vn(zt[Ee.deviceId],Gn(Ee)):0,fr=Ee?ZT(Ee):[],Oa=typeof Ie?.monitorIndex=="number"?Vn(Ie.monitorIndex,Math.max(1,Ie.monitorCount||1)):Yl,Zi=(Ie&&Oa===Yl?Qw(Ie):null)||(Ee?Kw(Ee,Yl):null);Zi&&`${Zi.width}${Zi.height}`;const Qa=Ee?rs(pt?"control":"wall",Ee.deviceId):"",et=Qa?yr[Qa]:void 0,St=Qa?jl[Qa]:void 0,at=St?.lastInfo,qo=et&&et.sampleMs>0?`${et.framesPerSecond.toFixed(1)} fps`:"waiting";et&&`${et.totalFrames}${qo}`,St&&St.sampleMs>0&&`${St.framesPerSecond.toFixed(1)}`,St&&St.sampleMs>0&&`${St.changedFramesPerSecond.toFixed(1)}`,at&&(`${at.frameSeq}${at.decoderLabel}${at.queueSize}${at.renderQueueSize}${at.droppedForLatency}${at.decoderFlushCount}${at.decoderTimestampFallbacks}${at.decoderInputCount}${at.decoderOutputCount}`,at.visualChanged),at&&`${Math.round(at.queuedForMs)}${Math.round(at.decodedForMs)}${Math.round(at.scheduledForMs)}${at.drawMs.toFixed(1)}`,at?.targetPaintIntervalMs&&`${at.targetPaintIntervalMs.toFixed(1)}${(1e3/at.targetPaintIntervalMs).toFixed(1)}`,St&&`${St.decoderInputFps.toFixed(1)}${St.decoderOutputFps.toFixed(1)}`,at?.canvasPresentation,at&&`${at.interactiveBufferWaitCount}${Math.round(at.interactiveBufferWaitMs)}${at.interactiveQueueDrainCount}`,et&&(Ie?.frameMode==="mode5-lzo-delta"?`${Lu(et.averageFrameBytes)}${Ie.deltaVisualTileCount||0}${Ie.deltaRefreshTileCount||0}${Ie.deltaTotalTiles||0}`:`${Lu(et.averageFrameBytes)}${Math.round(et.tinyFrameRatio*100)}${Math.round(et.repeatedFrameRatio*100)}`),et&&et.sourceSendSampleCount>0&&`${et.sourceSendAverageMs.toFixed(1)}${et.sourceSendP95Ms.toFixed(1)}`,Qb(et),Qb(St),et&&St&&`${Xb(et)}${Xb(St)}`,Ie?Ie.frameMode||Ie.mode||Ie.codec||Ie.mimeType:pt?At.frameMode:Ye.frameMode,pt?At.frameMode:Ye.frameMode,Ie?`${Ie.width}${Ie.height}${Lu(Ie.byteLength)}`:pt?`${Wr.maxWidth}${Wr.maxHeight}`:`${Ye.maxWidth}${Ye.maxHeight}`,Ie&&`${Ie.isKeyFrame?"key":String(Ie.chunkType||"delta")}`,Ie&&Ie.monitorCount&&((Ie.monitorIndex??0)+1,`${Ie.monitorCount}`),Ie&&[`src ${Math.round(Ie.sourceGapMs||0)}ms`,`gap ${Math.round(Ie.agentSendGapMs||0)}ms`,`tx ${Math.round(Ie.agentSendDurationMs||0)}ms`,`pace ${Math.round(Ie.agentPaceMs||0)}ms`,`queue ${Math.round(Ie.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(Ie.agentFrameAgeMs||0)}ms`,Ie.hubPacketTransitAgeMs!==void 0?`sock ${Math.max(0,Math.round(Ie.hubPacketTransitAgeMs))}ms`:"",Ie.droppedByAgent?`drop ${Ie.droppedByAgent}`:"",Ie.hubIngressDropped?`ingress-drop ${Ie.hubIngressDropped}`:"",Ie.hubClientDropped?`ws-drop ${Ie.hubClientDropped}`:"",Ie.captureStageMs?`capture ${Math.round(Ie.captureStageMs)}ms`:"",Ie.requestedFps?`req ${Math.round(Ie.requestedFps)}fps`:"",Ie.effectiveFps?`eff ${Math.round(Ie.effectiveFps)}fps`:"",Ie.captureAverageMs?`avg ${Math.round(Ie.captureAverageMs)}ms`:"",Ie.captureP95Ms?`p95 ${Math.round(Ie.captureP95Ms)}ms`:"",Ie.slowFrameCount?`slow ${Math.round(Ie.slowFrameCount)}`:"",Ie.captureHelperRestarts?`helper ${Math.round(Ie.captureHelperRestarts)}`:"",Ie.convertMs?`rgb565 ${Math.round(Ie.convertMs)}ms`:"",Ie.compressMs?`lzo ${Math.round(Ie.compressMs)}ms`:"",Ie.captureSourceSerial?`cap #${Ie.captureSourceSerial}`:"",Ie.captureSourceSkipped?`cap skip ${Ie.captureSourceSkipped}`:"",Ie.frameMode==="mode5-lzo-delta"?`tiles ${Ie.deltaVisualTileCount||0}+${Ie.deltaRefreshTileCount||0}/${Ie.deltaTotalTiles||0}@${Ie.deltaTileSize||0}`:"",Ie.platformProfile||Ie.hardwareEncoder||"-",Ie.atlasComposeMs?`atlas ${Ie.atlasComposeMs.toFixed(1)}ms`:"",Ie.atlasPoolStarved?`pool ${Ie.atlasPoolStarved}`:"",Ie.atlasTileCount?`tiles ${Ie.atlasReadyTiles||0}/${Ie.atlasTileCount}`:"",Ie.atlasInputRevision?`input #${Ie.atlasInputRevision}`:"",Ie.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(Ie.atlasSourceMaxAgeMs)}ms`:"",at?.inputFeedbackMs!==void 0&&at.inputFeedbackAt!==void 0&&performance.now()-at.inputFeedbackAt<=qb?`feedback ${Math.round(at.inputFeedbackMs)}ms`:"",Ie.contentHash?`enc ${Ie.contentHash.slice(0,6)}`:"",at?.visualHash?`pix ${at.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "),Ol==="open"&&[`${ua.sentPerSecond.toFixed(1)} hz`,ua.lastInputSeq>0?`rtt ${Math.round(ua.lastRoundTripMs)}ms`:"",ua.lastInputSeq>0?`apply ${ua.lastAgentApplyMs.toFixed(1)}ms`:"",ua.droppedPerSecond>0?`drop ${ua.droppedPerSecond.toFixed(1)}/s`:"",ua.bufferedAmount>0?`buf ${Lu(ua.bufferedAmount)}`:"",ua.lastInputType||"ready"].filter(Boolean).join(" / "),at?.inputFeedbackMs!==void 0&&at.inputFeedbackAt!==void 0&&performance.now()-at.inputFeedbackAt<=qb&&`${Math.round(at.inputFeedbackMs)}${at.inputFeedbackSeq||0}`,J&&[Yc,`context ${Dn.audioContextState}`,`queue ${Math.round(Dn.queuedMs)}ms`,`last ${Math.round(Dn.lastPacketAgeMs)}ms`,`accepted ${Math.round(Dn.lastAcceptedAgeMs)}ms`,`process ${Math.round(Dn.localProcessingAgeMs)}ms`,`remote ${Math.round(Dn.browserAgeMs)}/${Math.round(Dn.captureAgeMs)}ms`,`heartbeat ${Math.round(Dn.captureStatusAgeMs)}ms`,`capture ${Dn.captureAlive&&Dn.helperAlive?"alive":"down"}`,`drop ${Dn.drops}`,`resync ${Dn.resyncs}`,`restart ${Dn.automaticRestarts}`,Dn.pendingDecodes>0?`decode ${Dn.pendingDecodes}`:"",Hl?`#${Hl.frameSeq}`:"waiting"].filter(Boolean).join(" / "),Ie&&`${Ie.frameSeq}${Cx(Ie.receivedAt||Ie.capturedAt)}`;const fs=Math.max(0,Wa.bytesPerSecond*8/1e6),Xa=u.useCallback(()=>{Di(!0),re(Date.now()),k(),Te.current!==null&&window.clearTimeout(Te.current),Te.current=window.setTimeout(()=>{Te.current=null,re(Date.now()),Di(!1)},650)},[k]),Kl=u.useCallback(()=>{if(Yn){Gs(!1);return}Ke(!1),Gs(!0),Xa()},[Xa,Yn]),Ji=u.useCallback(()=>{if(B){Ke(!1);return}Gs(!1),Ke(!0),Xa()},[B,Xa]),mi=u.useCallback(()=>{if(ht){fn(!1);return}fn(!0),Xa()},[ht,Xa]),Ql=new Map,Jt=new Map;if(Yn||B||ht)for(const v of lt){const C=v.deviceId,E=pt&&H===C,_=rs(E?"control":"wall",C),te=E?zl.get(C):ri.get(C),ie=E?Cn.current.get(C)||Ra.current.get(C)||null:$n.current.get(C)||(Rt?ra.current:null),Ne={device:v,frame:te,receiveStat:yr[_],paintStat:jl[_],codec:ie?Hy(ie):{},selectedMonitorIndex:Vn(zt[C],Gn(v)),control:E,controlInputReady:E&&Ls,controlBinding:E&&K?.deviceId===C?K:void 0,capturePaused:Be.has(C),capturePauseConfirmed:v.liveCapturePause?.captureStopConfirmed===!0,capturePauseError:v.liveCapturePause?.stopError||"",clientHeartbeatMs:Number(w?.heartbeatMs||5e3),now:Date.now()};(Yn||ht)&&Ql.set(C,eT(Ne)),B&&Jt.set(C,tT(Ne))}const Zc=ht?nT({status:w||{},deviceDiagnostics:[...Ql.values()],codec:Hy(),browser:{hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:Number(navigator.deviceMemory||0)},frameStats:Wa}):[],Go=wt?.atlasReadyTiles??Sa,Vo=wt?.atlasTileCount??Sa,dd=Go===Vo?`${Vo} tiles`:`${Go}/${Vo} tiles`,rm=Pn.length>0;pt?`${Hs}${fs.toFixed(fs>=10?0:1)}`:rm?`${dd}${Hs}${fs.toFixed(fs>=10?0:1)}`:`${Sa}${Hs}${fs.toFixed(fs>=10?0:1)}`;const Xl=Da.length,Jc=pt?Ee?ha(Ee):"No Client":Xl===0?"No Client":Xl>1?`${Xl} selected`:Ee?ha(Ee):"No Client",eu=pt?[Ee?.deviceId].filter(v=>!!v):Da.map(v=>v.deviceId),$t=wc[Pe]||wc.en,on=$t.sync||wc.en.sync,Wo=a||D?"checking":T?un==="pro"?"Pro LTD active":`Plus LTD ${lt.length}/${Du}`:Ui?`Free ${lt.length}/${Eu}`:`Upgrade ${lt.length}/${Eu}`,Ko=T?un==="pro"?"Pro active":"Upgrade to Pro LTD":n?ot==="checkout"?"Opening checkout":un==="ltd"?"Buy Pro LTD":"Buy Plus LTD":ot==="auth"?"Opening Google":"Sign in to buy",tu=un==="pro"||ot==="checkout"||ot==="auth"||a||D,Fs=n?.user?.user_metadata,hi=sx(Fs,"avatar_url","picture"),pi=sx(Fs,"full_name","name")||n?.user?.email||"Google",Qo=pi.slice(0,1).toUpperCase(),fd=w?.started?"Local app ready":"Start LiveDesk",md=i?.active?"Published":n?"Not published":"Sign in required",hd=/^\d{6}$/.test(w?.pairingPin||"")?w?.pairingPin:"------",Xo=v=>{if(typeof window<"u"&&(v==="support"?window.history.pushState({},"","/support"):On==="support"&&window.history.pushState({},"","/")),v==="control"){const C=oa||$i;if(C&&(Qi(C.deviceId),ia(!1),Y(C.deviceId)),ws(v),!Kt){He(!1),Oe(Jr);return}He(!0);return}v==="wall"&&Ba(C=>C+1),ws(v),He(!1)},gi=ot==="update"||Nt?.stage==="updating"||["dispatching","waiting-for-clients","hub-restart-requested"].includes(w?.update?.state||""),pd=!!(w?.update?.updateAvailable&&w.update.canApply||gi||Nt?.error||!w&&Nt),mr=FC(Pe),Zo=u.useCallback(v=>{if(!Nt?.targetIds.includes(v))return;const C=w?.update?.operationId===Nt.operationId?w.update.targets?.find(E=>E.deviceId===v):void 0;switch(C?.state){case"completed":return{state:"updated",label:"Updated"};case"failed":return{state:"failed",label:"Update failed",error:C.error};case"pending-offline":return{state:"offline",label:"Waiting for reconnect"};case"queued":return Nt.stage==="updating"?{state:"queued",label:"Queued"}:void 0;case"waiting":return Nt.stage==="updating"?C.candidateSince?{state:"updating",label:"Verifying restart..."}:{state:"updating",label:"Restarting..."}:void 0;default:return Nt.stage==="updated"?{state:"updated",label:"Updated"}:Nt.stage==="updating"?{state:"updating",label:"Verifying..."}:void 0}},[w?.update,Nt]);return r.jsxs("main",{className:"app-shell",children:[r.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk tools",children:[r.jsx("div",{className:"rail-brand",title:"LiveDesk",children:r.jsx(kx,{size:25})}),r.jsx("nav",{className:"rail-tools",children:bR.map(v=>{const C=v.icon,E=Rf(v.tooltip,Pe);return r.jsxs("button",{className:`rail-tool ${v.id==="sync-server"?"sync-server hub-sync-trigger":""} ${On===v.id?"active":""} accent-${v.accent}`,onClick:()=>v.id==="sync-server"?Po():Xo(v.id),"data-tooltip":v.id==="sync-server"&&$e?void 0:tp(v.label,v.tooltip,Pe),"aria-label":`${v.label}. ${E}`,type:"button",disabled:v.id==="sync-server"&&ot==="host","aria-busy":v.id==="sync-server"&&ot==="host","aria-expanded":v.id==="sync-server"?$e:void 0,"aria-haspopup":v.id==="sync-server"?"dialog":void 0,"aria-controls":v.id==="sync-server"&&$e?"hub-sync-popover":void 0,children:[v.id==="sync-server"&&ot==="host"?r.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):r.jsx(C,{size:19}),r.jsx("span",{children:v.id==="sync-server"&&ot==="host"?"Syncing…":v.label})]},v.id)})}),r.jsxs("div",{className:"rail-footer",children:[xR.map(v=>{const C=v.icon;return r.jsxs("button",{className:`rail-tool compact ${On===v.id?"active":""} accent-${v.accent}`,onClick:()=>Xo(v.id),title:v.label,type:"button",children:[r.jsx(C,{size:18}),r.jsx("span",{children:v.label})]},v.id)}),r.jsxs("button",{className:`rail-tool compact local-settings ${Rl?"active":""}`,onClick:()=>{ws("settings"),typeof window<"u"&&window.history.pushState({},"","/"),Mt(!1),He(!1),Yt(!1)},title:"Settings",type:"button",children:[r.jsx(wp,{size:18}),r.jsx("span",{children:"Settings"})]}),r.jsxs("button",{className:`rail-account ${n?"signed-in":""}`,onClick:()=>{Mt(v=>!v)},disabled:a||ot==="auth","aria-expanded":st,title:n?`Account: ${n.user?.email||pi}`:"Sign in with Google",type:"button",children:[n?hi?r.jsx("img",{src:hi,alt:pi,referrerPolicy:"no-referrer"}):r.jsx("span",{className:"avatar-fallback",children:Qo}):r.jsx(mo,{size:18}),r.jsx("span",{children:n?"Account":"Google"})]}),st&&r.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[r.jsxs("div",{className:"account-popover-head",children:[r.jsx("div",{className:"account-popover-avatar",children:n&&hi?r.jsx("img",{src:hi,alt:pi,referrerPolicy:"no-referrer"}):n?r.jsx("span",{children:Qo}):r.jsx(mo,{size:18})}),r.jsxs("div",{children:[r.jsx("strong",{children:n?pi:"Account"}),r.jsx("p",{children:n?.user?.email||"Not signed in"})]})]}),r.jsxs("dl",{className:"account-popover-facts",children:[r.jsx("dt",{children:"User"}),r.jsx("dd",{children:n?.user?.email||"Not signed in"}),r.jsx("dt",{children:"Network"}),r.jsx("dd",{children:fd}),r.jsx("dt",{children:"Access"}),r.jsx("dd",{children:md}),r.jsx("dt",{children:"Plan"}),r.jsx("dd",{children:Wo}),r.jsx("dt",{children:"Ads"}),r.jsx("dd",{children:un==="free"?"Standard banner":"Removed"})]}),n?r.jsxs("button",{className:"account-popover-action",onClick:$l,disabled:ot==="auth",type:"button",children:[r.jsx(cx,{size:16}),"Logout"]}):r.jsxs("button",{className:"account-popover-action primary",onClick:Is,disabled:ot==="auth",type:"button",children:[r.jsx(mo,{size:16}),"Sign in with Google"]})]})]})]}),$e&&r.jsxs("section",{id:"hub-sync-popover",className:"client-hub-switch-popover hub-sync-popover",role:"dialog","aria-modal":"false","aria-labelledby":"hub-sync-title","aria-describedby":"hub-sync-description hub-sync-notice",children:[r.jsxs("header",{className:"client-hub-switch-head",children:[r.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:r.jsx(zr,{size:19})}),r.jsx("span",{className:"client-hub-switch-eyebrow",children:mr.eyebrow}),r.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>ur(),"aria-label":mr.closeLabel,children:r.jsx(Na,{size:17})})]}),r.jsx("h2",{id:"hub-sync-title",children:mr.title}),r.jsx("p",{id:"hub-sync-description",children:mr.description}),r.jsxs("p",{id:"hub-sync-notice",className:"client-hub-switch-notice",children:[r.jsx(Wn,{size:16,"aria-hidden":"true"}),r.jsx("span",{children:mr.restartNotice})]}),r.jsxs("div",{className:"client-hub-switch-actions",children:[r.jsx("button",{type:"button",onClick:()=>ur(),children:mr.cancel}),r.jsxs("button",{ref:ct,className:"primary",type:"button",onClick:od,disabled:ot==="host",children:[r.jsx(zr,{size:16}),mr.confirm]})]})]}),r.jsxs("section",{className:`desk-stage ${Dl&&!qt?"dock-open":""} ${pt?"control-stage":""} ${zc?"agents-stage":""}`,children:[r.jsxs("header",{className:"topbar",children:[r.jsxs("div",{className:"brand",children:[r.jsx("span",{className:"brand-mark",children:r.jsx(ho,{size:18})}),r.jsxs("div",{className:"brand-copy",children:[r.jsx("h1",{children:"LiveDesk"}),r.jsx("p",{children:"Control wall for local machines"})]}),pd?r.jsxs("button",{className:"topbar-update-button",onClick:()=>{ci()},title:Nt?.error?`LiveDesk Hub update failed: ${Nt.error}`:`Update LiveDesk to ${w?.update?.latestVersion||Nt?.targetManagerVersion||"latest"}`,"aria-label":Nt?.error?`LiveDesk Hub update failed: ${Nt.error}`:gi?"LiveDesk update in progress":`Update LiveDesk to ${w?.update?.latestVersion||Nt?.targetManagerVersion||"latest"}`,type:"button",disabled:gi||!w?.update?.canApply,"aria-busy":gi,children:[gi?r.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):r.jsx(xp,{size:19,"aria-hidden":"true"}),gi&&w?.update?.targetCount?r.jsxs("span",{className:"topbar-update-count","aria-hidden":"true",children:[w.update.completedCount||0,"/",w.update.targetCount]}):null]}):null]}),r.jsxs("div",{className:"topbar-tray",children:[El&&!pt&&r.jsxs("div",{className:"file-share-top-route","aria-label":"File distribution route",children:[r.jsxs("div",{children:[r.jsx(co,{size:17}),r.jsxs("span",{children:[r.jsx("small",{children:"Source"}),r.jsx("strong",{children:"LiveDesk Hub"})]})]}),r.jsx(jp,{size:15}),r.jsx(z0,{size:16}),r.jsxs("div",{children:[r.jsx("span",{className:"file-share-top-route-laptops",children:"▣ ▣ ▣"}),r.jsxs("span",{children:[r.jsx("small",{children:"Destination"}),r.jsxs("strong",{children:[Co," Client",Co===1?"":"s"]}),r.jsx("em",{children:gn.trim()||"Desktop/LiveDeskFiles"})]})]})]}),Dl&&!pt&&r.jsxs("div",{className:"top-actions",children:[r.jsx(Fb,{active:ht,refreshing:ht&&Fa,onClick:mi}),r.jsx(Ob,{active:Yn,refreshing:Yn&&Fa,onClick:Kl}),r.jsx(Hb,{active:B,refreshing:B&&Fa,onClick:Ji}),r.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),r.jsx(zb,{controller:No,onError:Oe}),r.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),r.jsx("div",{className:"segmented-control","aria-label":"Wall view",children:yR.map(v=>r.jsx("button",{className:pn===v.id?"active":"",onClick:()=>qs(v.id),type:"button",children:v.label},v.id))})]}),pt&&r.jsxs("div",{className:"top-actions",children:[r.jsx(Fb,{active:ht,refreshing:ht&&Fa,onClick:mi}),r.jsx(Ob,{active:Yn,refreshing:Yn&&Fa,onClick:Kl}),r.jsx(Hb,{active:B,refreshing:B&&Fa,onClick:Ji}),r.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),r.jsx(zb,{controller:No,onError:Oe})]})]})]}),ht&&Dl&&r.jsx(YN,{items:Zc,collectedAt:Ss,onClose:()=>fn(!1)}),Ic?r.jsxs("section",{className:"doc-page",lang:Pe,dir:Pe==="ar"?"rtl":"ltr",children:[r.jsxs("section",{className:"doc-hero",children:[r.jsxs("div",{className:"doc-hero-copy",children:[r.jsxs("span",{className:"pricing-eyebrow",children:[r.jsx(Tf,{size:16}),$t.eyebrow]}),r.jsx("h2",{children:$t.title}),r.jsx("p",{children:$t.intro})]}),r.jsxs("label",{className:"doc-language-picker",children:[r.jsxs("span",{children:[r.jsx(O0,{size:17}),$t.languageLabel]}),r.jsx("select",{value:Pe,onChange:v=>vt(v.target.value),children:SR.map(v=>r.jsx("option",{value:v.id,children:v.label},v.id))})]})]}),r.jsx("section",{className:"doc-grid",children:$t.sections.map((v,C)=>{const I=[zr,Zh,gy,Wn,$f][C]||Tf;return r.jsxs("article",{className:"doc-card",children:[r.jsx("div",{className:"doc-card-icon",children:r.jsx(I,{size:19})}),r.jsxs("div",{children:[r.jsx("h3",{children:v.title}),r.jsx("p",{children:v.body}),r.jsx("ul",{children:v.points.map(_=>r.jsx("li",{children:_},_))})]})]},v.title)})}),on&&r.jsxs("section",{className:"doc-sync",children:[r.jsxs("div",{className:"doc-sync-head",children:[r.jsx(gy,{size:20}),r.jsxs("div",{children:[r.jsx("h3",{children:on.title}),r.jsx("p",{children:on.body})]})]}),r.jsx("ul",{children:on.points.map(v=>r.jsx("li",{children:v},v))})]}),r.jsxs("section",{className:"doc-firewall",children:[r.jsxs("div",{className:"doc-firewall-head",children:[r.jsx(Wn,{size:20}),r.jsxs("div",{children:[r.jsx("h3",{children:$t.firewall.title}),r.jsx("p",{children:$t.firewall.body})]})]}),r.jsx("ul",{children:$t.firewall.points.map(v=>r.jsx("li",{children:v},v))})]}),r.jsxs("section",{className:"doc-command-panel",children:[r.jsxs("div",{className:"doc-command-head",children:[r.jsx(Zh,{size:20}),r.jsxs("div",{children:[r.jsx("h3",{children:$t.commands.title}),r.jsx("p",{children:$t.commands.body})]})]}),r.jsxs("div",{className:"doc-command-list",children:[$t.commands.manager&&r.jsxs("div",{className:"doc-command-row",children:[r.jsx("span",{children:$t.commands.manager}),r.jsx("code",{children:wa}),r.jsx("button",{className:"icon-button",onClick:()=>Cf(wa),title:"Copy command",type:"button",children:r.jsx(mh,{size:16})})]}),r.jsxs("div",{className:"doc-command-row",children:[r.jsx("span",{children:$t.commands.primary}),r.jsx("code",{children:Xi}),r.jsx("button",{className:"icon-button",onClick:()=>Cf(Xi),title:"Copy command",type:"button",children:r.jsx(mh,{size:16})})]}),r.jsxs("div",{className:"doc-command-row",children:[r.jsx("span",{children:$t.commands.slot}),r.jsx("code",{children:`${Xi} 3`}),r.jsx("button",{className:"icon-button",onClick:()=>Cf(`${Xi} 3`),title:"Copy command",type:"button",children:r.jsx(mh,{size:16})})]})]})]})]}):zc?r.jsx(Lb,{hubUrl:N,devices:A}):El?r.jsx(GM,{hubUrl:N,devices:lt,localFeatureAccess:Kt,upgradeNotice:Jr,remoteDirectory:gn,onRemoteDirectoryChange:nn,targetMode:Hi,selectedTargetIds:qr,onTargetModeChange:em,onTargetToggle:v=>Ec(C=>C.includes(v)?C.filter(E=>E!==v):[...C,v]),filePickerRef:nm,folderPickerRef:am,onBrowserFileImport:v=>{Vl(v)},onBrowserFolderImport:v=>{Vl(v)},onNotice:Oe,onTransferChange:v=>{if(!v){wr(null);return}const C=v.state==="failed"||v.state==="partially-failed"||v.state==="cancelled"?"failed":v.state==="completed"?"queued":v.state==="sending"?"sending":"reading";wr({id:v.id,status:C,progress:v.progress,message:v.message}),["completed","partially-failed","failed","cancelled"].includes(v.state)&&window.setTimeout(()=>wr(E=>E?.id===v.id?null:E),4500)}}):Vr?r.jsx(xx,{session:n,currentProductKey:"livedesk",appVersion:"",onSignIn:Is}):Rl?r.jsx(ck,{hubUrl:N,runtimeRole:w?.runtimeRole||"hub",runtimeDeviceId:w?.deviceId||"",sessionAccessToken:n?.access_token||"",pin:r.jsxs(uk,{children:[r.jsx("div",{className:"settings-section-grid",children:r.jsxs("section",{className:"settings-section-card settings-pairing-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Pair a Client"}),r.jsx("h3",{children:"Connect another local PC"})]}),r.jsx(Ta,{size:20})]}),r.jsxs("div",{className:"settings-pin-display",children:[r.jsx("span",{children:"Hub PIN"}),r.jsx("strong",{children:hd}),r.jsxs("button",{className:"text-button ghost compact",onClick:cd,disabled:!w?.started||ot==="pin",type:"button",children:[r.jsx(Ti,{size:15}),ot==="pin"?"Creating":"New PIN"]})]})]})}),r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"File transfer"}),r.jsx("h3",{children:"Client destination folder"})]}),r.jsx(gc,{size:20})]}),r.jsxs("label",{className:"settings-field",children:[r.jsx("span",{children:"Remote folder"}),r.jsx("input",{value:gn,onChange:v=>nn(v.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),r.jsx("p",{className:"settings-help",children:"Blank uses Desktop/LiveDeskFiles on each Client."})]})]}),agent:r.jsx(fk,{hubUrl:N}),captureGallery:r.jsx(VN,{hubUrl:N,onToast:Oe})}):_c?r.jsxs("section",{className:"pricing-page",children:[r.jsxs("header",{className:"pricing-header",children:[r.jsxs("div",{children:[r.jsxs("span",{className:"pricing-eyebrow",children:[r.jsx(Qh,{size:15})," LiveDesk plans"]}),r.jsx("h2",{children:"Choose the plan that fits your wall"}),r.jsx("p",{children:"Start free with a local screen wall. Upgrade when you need ad-free monitoring, more Clients, or commercial controls."})]}),r.jsx("button",{className:"pricing-close",onClick:()=>Xo("wall"),title:"Close pricing",type:"button",children:r.jsx(Na,{size:18})})]}),r.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[r.jsx("span",{children:"Current plan"}),r.jsx("strong",{children:Bi.name}),r.jsxs("small",{children:[lt.length,"/",HT(Pi)," connected devices"]})]}),r.jsxs("div",{className:"pricing-cards","aria-label":"LiveDesk plans",children:[r.jsxs("article",{className:`pricing-plan-card ${un==="free"?"current":""}`,children:[r.jsxs("div",{className:"pricing-plan-topline",children:[r.jsx("span",{className:"pricing-plan-badge free",children:"Free"}),r.jsx("strong",{children:"$0"})]}),r.jsx("p",{className:"pricing-plan-audience",children:so.free.audience}),r.jsx("h3",{children:"Monitor your local wall"}),r.jsx("p",{children:so.free.note}),r.jsxs("ul",{children:[r.jsxs("li",{children:[r.jsx(Zn,{size:16})," Up to ",Eu," devices"]}),r.jsxs("li",{children:[r.jsx(Zn,{size:16})," Live view and local control"]}),r.jsxs("li",{children:[r.jsx(Zn,{size:16})," Standard ad-supported banner"]})]}),r.jsx("span",{className:"pricing-current-label",children:un==="free"?"Current plan":"Included for everyone"})]}),r.jsxs("article",{className:`pricing-plan-card featured ${un==="ltd"?"current":""}`,children:[r.jsxs("div",{className:"pricing-plan-topline",children:[r.jsxs("span",{className:"pricing-plan-badge plus",children:[r.jsx(H0,{size:14})," Plus"]}),r.jsx("strong",{children:"$5"})]}),r.jsx("p",{className:"pricing-plan-audience",children:so.ltd.audience}),r.jsx("h3",{children:"Ad-free monitoring"}),r.jsx("p",{children:"More room for personal AI Clients without the standard banner."}),r.jsxs("ul",{children:[r.jsxs("li",{children:[r.jsx(Zn,{size:16})," Up to ",Du," devices"]}),r.jsxs("li",{children:[r.jsx(Zn,{size:16})," No standard ad banner"]}),r.jsxs("li",{children:[r.jsx(Zn,{size:16})," ",so.ltd.ltd]})]}),r.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>Wl("ltd"):Is,disabled:un!=="free"||ot==="checkout"||ot==="auth"||a||D,type:"button",children:[r.jsx(Iu,{size:16}),un==="free"?n?"Choose Plus":"Sign in for Plus":"Plus active"]})]}),r.jsxs("article",{className:`pricing-plan-card pro ${un==="pro"?"current":""}`,children:[r.jsxs("div",{className:"pricing-plan-topline",children:[r.jsxs("span",{className:"pricing-plan-badge pro",children:[r.jsx(Wn,{size:14})," Pro"]}),r.jsx("strong",{children:"$15"})]}),r.jsx("p",{className:"pricing-plan-audience",children:so.pro.audience}),r.jsx("h3",{children:"For serious operations"}),r.jsx("p",{children:"Commercial-ready monitoring for larger AI labs, studios, and teams."}),r.jsxs("ul",{children:[r.jsxs("li",{children:[r.jsx(Zn,{size:16})," 30+ Client walls"]}),r.jsxs("li",{children:[r.jsx(Zn,{size:16})," Commercial use included"]}),r.jsxs("li",{children:[r.jsx(Zn,{size:16})," ",so.pro.ltd]})]}),r.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>Wl("pro"):Is,disabled:un==="pro"||ot==="checkout"||ot==="auth"||a||D,type:"button",children:[r.jsx(Iu,{size:16}),un==="pro"?"Pro active":n?"Choose Pro":"Sign in for Pro"]})]})]}),r.jsxs("section",{className:"pricing-includes",children:[r.jsxs("div",{children:[r.jsx(Ta,{size:17}),r.jsx("span",{children:"Screen wall"}),r.jsx("strong",{children:"120+ slots"})]}),r.jsxs("div",{children:[r.jsx(Xh,{size:17}),r.jsx("span",{children:"Focused control"}),r.jsx("strong",{children:"Local-first"})]}),r.jsxs("div",{children:[r.jsx(vy,{size:17}),r.jsx("span",{children:"Remote audio"}),r.jsx("strong",{children:"Available"})]}),r.jsxs("div",{children:[r.jsx(gc,{size:17}),r.jsx("span",{children:"File transfer"}),r.jsx("strong",{children:"Included"})]})]}),r.jsxs("p",{className:"pricing-note",children:[r.jsx(Zn,{size:15})," Commercial use requires Pro. Plus LTD is for personal, creator, and homelab use."]}),r.jsxs("button",{className:"pricing-primary-cta",onClick:n?()=>Wl(un==="ltd"?"pro":"ltd"):Is,disabled:tu,type:"button",children:[r.jsx(Iu,{size:18}),Ko]})]}):r.jsx(r.Fragment,{children:r.jsxs("section",{className:`monitor-layout ${qt?"dock-collapsed":""}`,children:[r.jsxs("section",{ref:td,className:`screen-wall-panel ${Zf?"drop-active":""}`,onClick:v=>{v.currentTarget===v.target&&ui()},onDragEnter:v=>{v.preventDefault(),Rc(!0)},onDragOver:v=>{v.preventDefault(),v.dataTransfer.dropEffect="copy"},onDragLeave:v=>{v.currentTarget===v.target&&Rc(!1)},onDrop:ud,children:[Pn.length>0&&r.jsx("canvas",{ref:Do,className:"atlas-source-canvas",width:ba?.width||1920,height:ba?.height||1080,"aria-hidden":"true"}),pt?r.jsx("section",{className:"control-focus",children:r.jsxs("div",{className:"control-wall",children:[Ee&&fr.length>1&&r.jsx("div",{className:"control-monitor-tabs","aria-label":"Select monitor",children:fr.map(v=>r.jsxs("button",{className:v.index===Yl?"active":"",onClick:()=>Ul(Ee.deviceId,v.index),title:eR(v),type:"button",children:[r.jsx("span",{children:v.name||`Display ${v.index+1}`}),v.width>0&&v.height>0&&r.jsxs("small",{children:[v.width,"x",v.height]})]},v.index))}),Ee&&Ls&&r.jsx("div",{className:"control-modifier-bar","aria-label":"Hold remote modifier keys",children:ST.map(v=>{const C=v.code==="MetaLeft"&&Ni(Ee.platform)?"Cmd":v.label,E=ne.includes(v.code);return r.jsx("button",{className:E?"active":"",type:"button","aria-pressed":E,title:`Hold ${C} on the remote computer`,onClick:()=>mt.current?.(v.code),children:C},v.code)})}),Ee?r.jsx(Wh,{device:Ee,frame:Ie,selected:!1,controlEnabled:Ns&&Me&&Ls,showStatus:At.showScreenStatus,monitorIndex:Vn(zt[Ee.deviceId],Gn(Ee)),monitorCount:Gn(Ee),onSelect:()=>{},onFocusDevice:()=>Y(Ee.deviceId),onOpenControl:()=>di(Ee.deviceId),onCycleMonitor:v=>Os(Ee.deviceId,v),onCanvasReady:Uc,sendInput:Mr,remoteModifierState:Nr,presentationReady:bo,remoteDiagnostics:B?Jt.get(Ee.deviceId):Yn?Ql.get(Ee.deviceId):void 0,diagnosticsMode:B?"debug":"remote"},Ee.deviceId):r.jsxs("div",{className:"control-empty",children:[r.jsx(Ta,{size:30}),r.jsx("strong",{children:"No Client"}),r.jsx("span",{children:"Open a Client from the Wall."})]}),Ee&&jo&&r.jsxs("div",{className:"control-connection-overlay",role:"alert",children:[r.jsx(Wn,{size:22,"aria-hidden":"true"}),r.jsx("strong",{children:"Accessibility permission required"}),r.jsx("small",{children:"On the Mac, allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client."})]}),Ee&&!jo&&!bo&&r.jsxs("div",{className:"control-connection-overlay",role:"status","aria-live":"polite",children:[W!=="error"&&r.jsx("span",{className:"control-connection-spinner","aria-hidden":"true"}),r.jsx("strong",{children:W==="error"?"Connection failed":"Connecting"}),r.jsx("small",{children:W==="error"?"See the notification for details. Reopen Control to retry.":Ds||fe?"Control stream is recovering. See the notification for details.":rr==="open"?"Preparing the first control frame":"Opening the Control stream"})]})]})}):pn==="list"?r.jsxs("div",{className:"wall-device-list",role:"grid","aria-label":"Computer status list",children:[r.jsxs("div",{className:"wall-device-list-head",role:"row",children:[r.jsx("span",{role:"columnheader",children:"Computer"}),r.jsx("span",{role:"columnheader",children:"Status"}),r.jsx("span",{role:"columnheader",children:"CPU"}),r.jsx("span",{role:"columnheader",children:"GPU"}),r.jsx("span",{role:"columnheader",children:"RAM"}),r.jsx("span",{role:"columnheader",children:"VRAM"}),r.jsx("span",{role:"columnheader",children:"Network"}),r.jsx("span",{role:"columnheader",children:"HDD"}),r.jsx("span",{role:"columnheader",children:"Temp"})]}),Hc.length>0?Hc.map(({device:v,slotNumber:C})=>r.jsx(jR,{device:v,slotNumber:C,selected:Yr.has(v.deviceId),updateIndicator:Zo(v.deviceId),onSelect:()=>Pl(v.deviceId),onOpenControl:()=>di(v.deviceId)},v.deviceId)):r.jsxs("div",{className:"wall-device-list-empty",children:[r.jsx(Ta,{size:24,"aria-hidden":"true"}),r.jsx("strong",{children:"No connected computers"})]})]}):Rt?r.jsx("div",{className:`screen-wall atlas-slot-wall size-${pn}`,onClick:v=>{v.currentTarget===v.target&&ui()},children:Sr.map((v,C)=>v?r.jsx(Wh,{device:v,frame:ri.get(v.deviceId),selected:Yr.has(v.deviceId),controlEnabled:!1,showStatus:Ye.showScreenStatus,monitorIndex:Vn(zt[v.deviceId],Gn(v)),monitorCount:Gn(v),onSelect:()=>Pl(v.deviceId),onFocusDevice:()=>zs(v.deviceId),onOpenControl:()=>di(v.deviceId),onCycleMonitor:E=>Os(v.deviceId,E),onCanvasReady:Mu({mode4Enabled:Rt,directMode4WallEnabled:vn,isMac:Ni(v.platform)})==="direct"?Cr:Ga,sendInput:Mr,remoteModifierState:Nr,updateIndicator:Zo(v.deviceId),presentationReady:Ye.autoStartLive&&Ua.includes(v.deviceId)?vo.has(v.deviceId):void 0,showPresentationSpinner:Ye.autoStartLive&&Ua.includes(v.deviceId),remoteDiagnostics:B?Jt.get(v.deviceId):Yn?Ql.get(v.deviceId):void 0,diagnosticsMode:B?"debug":"remote"},v.deviceId):r.jsx(ix,{index:C},`slot-${C}`))}):r.jsx("div",{className:`screen-wall size-${pn}`,onClick:v=>{v.currentTarget===v.target&&ui()},children:Sr.map((v,C)=>v?r.jsx(Wh,{device:v,frame:ri.get(v.deviceId),selected:Yr.has(v.deviceId),controlEnabled:Ns&&Me&&Ls&&Ee?.deviceId===v.deviceId,showStatus:Ye.showScreenStatus,monitorIndex:Vn(zt[v.deviceId],Gn(v)),monitorCount:Gn(v),onSelect:()=>Pl(v.deviceId),onFocusDevice:()=>zs(v.deviceId),onOpenControl:()=>di(v.deviceId),onCycleMonitor:E=>Os(v.deviceId,E),onCanvasReady:Cr,sendInput:Mr,remoteModifierState:Nr,updateIndicator:Zo(v.deviceId),presentationReady:Ye.autoStartLive&&Ua.includes(v.deviceId)?vo.has(v.deviceId):void 0,showPresentationSpinner:Ye.autoStartLive&&Ua.includes(v.deviceId),remoteDiagnostics:B?Jt.get(v.deviceId):Yn?Ql.get(v.deviceId):void 0,diagnosticsMode:B?"debug":"remote"},v.deviceId):r.jsx(ix,{index:C},`slot-${C}`))}),r.jsx(NR,{visible:ei&&!pt})]}),!Rl&&r.jsxs("aside",{className:`right-dock actions-mode ${qt?"collapsed":""}`,"aria-label":"LiveDesk tools",children:[r.jsx("button",{className:"dock-toggle",onClick:()=>Yt(v=>!v),"aria-label":qt?"Show control panel":"Hide control panel",title:qt?"Show control panel":"Hide control panel",type:"button",children:qt?r.jsx(yx,{size:18}):r.jsx(Ap,{size:18})}),!qt&&r.jsxs(r.Fragment,{children:[r.jsxs("section",{className:"action-dock",children:[r.jsx("input",{ref:nd,className:"hidden-file-input",type:"file",multiple:!0,onChange:v=>{v.currentTarget.files&&fi(v.currentTarget.files),v.currentTarget.value=""}}),r.jsxs("div",{className:"manual-action-bar",role:"toolbar","aria-label":"Manual Client controls",children:[r.jsx(ao,{label:"Control",tooltip:Ee?jo?"Allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client.":Ns?Ls?"Keyboard and mouse control is ready":"Waiting for the current Control capture session":"Remote control is not available on this Client":"Select a Client to use Control",onClick:()=>{if(Ee){if(pt&&Me){He(!1),Oe("Remote control paused. Screen viewing stays on.");return}di(Ee.deviceId)}},disabled:!Ns||!!pe,active:Me,pressed:pt&&Me,children:r.jsx(Xh,{size:17})}),r.jsx(ao,{label:"Audio",tooltip:Ee?Kr?J?"Stop hearing this Client":"Hear this Client":"Audio is not available on this Client":"Select a Client to use Audio",onClick:()=>{Qc()},disabled:!Bc||!!pe,active:J,pressed:J,children:pe==="audio"?r.jsx(Lr,{className:"spin",size:17}):r.jsx(vy,{size:17})}),r.jsx(ao,{label:Pc?"Retry pause":qi?"Resume video":"Pause video",tooltip:Ee?Pc?"Retry stopping Client screen capture and wait for FFmpeg shutdown confirmation":qi?"Resume Client screen capture and video encoding":"Pause Client screen capture and stop FFmpeg encoding":"Select a Client to pause video",onClick:()=>{ql()},disabled:!Ee||!Kt||!!pe,active:qi,pressed:qi,children:pe==="video"?r.jsx(Lr,{className:"spin",size:17}):qi&&!Pc?r.jsx(F0,{size:17}):r.jsx($0,{size:17})}),r.jsx(ao,{label:"Send files",tooltip:Da.length===0&&!pt?"Select one or more Clients to send files":Ee?"Choose files and send them to the selected Client":"Select a Client to send files",onClick:()=>{Oe(`Choose files to send to ${Jc}.`),nd.current?.click()},disabled:!!pe||!Kt||(pt?!Ee:Da.length===0),children:r.jsx(gc,{size:17})}),r.jsx(ao,{label:"Restart",tooltip:Ee?Qr?"Restart Client":"Restart is not available on this Client":"Select a Client to restart",onClick:()=>{Uo("restart")},disabled:!Ee||!Kt||!!pe||!Qr,children:pe==="restart"?r.jsx(Lr,{className:"spin",size:17}):r.jsx(Cp,{size:17})}),r.jsx(ao,{label:"Sleep",tooltip:Ee?"Put Client to sleep":"Select a Client to put to sleep",onClick:()=>{Uo("sleep")},disabled:!Ee||!Kt||!!pe,children:pe==="sleep"?r.jsx(Lr,{className:"spin",size:17}):r.jsx(B0,{size:17})}),r.jsx(ao,{label:"Shut down",tooltip:Ee?"Shut down Client":"Select a Client to shut down",onClick:()=>{Uo("shutdown")},disabled:!Ee||!Kt||!!pe,danger:!0,children:pe==="shutdown"?r.jsx(Lr,{className:"spin",size:17}):r.jsx(P0,{size:17})})]})]}),r.jsx(Lb,{hubUrl:N,devices:A,variant:"dock",selectedDeviceIds:eu})]})]})]})})]}),Ur&&r.jsxs("aside",{className:`transfer-bar state-${Ur.status}`,"aria-live":"polite",children:[r.jsx("span",{className:"transfer-bar-icon","aria-hidden":"true",children:Ur.status==="queued"?r.jsx(Zn,{size:18}):Ur.status==="failed"?r.jsx(Na,{size:18}):r.jsx(hx,{size:18})}),r.jsxs("div",{className:"transfer-bar-copy",children:[r.jsx("p",{children:Ur.message}),r.jsx("div",{className:"transfer-bar-track",children:r.jsx("span",{style:{width:`${Math.max(0,Math.min(100,Ur.progress))}%`}})})]}),r.jsxs("strong",{children:[Math.max(0,Math.min(100,Ur.progress)),"%"]})]}),zn&&r.jsxs("aside",{className:`livedesk-toast tone-${zn.tone}`,role:zn.tone==="error"?"alert":"status","aria-live":zn.tone==="error"?"assertive":"polite","aria-busy":zn.tone==="progress",children:[zn.tone==="progress"&&r.jsx("span",{className:"livedesk-toast-spinner","aria-hidden":"true"}),r.jsx("span",{children:zn.message}),r.jsx("button",{className:"livedesk-toast-close",onClick:()=>Oe(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:r.jsx(Na,{size:15})})]})]})}function RR(){if(typeof window>"u")return[];const n=window.location.origin;return window.location.port==="5179"?[n]:["http://127.0.0.1:5179"]}function ER(){const[a,i]=u.useState(null);return u.useEffect(()=>{let l=!1,c=!1;const d=async()=>{for(const g of RR())try{const y=await fetch(`${g}/api/runtime`,{cache:"no-store"});if(!y.ok)continue;const b=(await y.json()).role==="hub"?"hub":"client";c=!0,l||i(b);return}catch{}};d();const m=window.setInterval(()=>{d()},1e3),h=window.setTimeout(()=>{!l&&!c&&i("client")},2500);return()=>{l=!0,window.clearInterval(m),window.clearTimeout(h)}},[null]),a?a==="client"?r.jsx(KC,{}):r.jsx(TR,{}):r.jsxs("main",{className:"runtime-role-boot","aria-busy":"true","aria-label":"Starting LiveDesk",children:[r.jsx("span",{className:"runtime-role-boot-mark","aria-hidden":"true"}),r.jsx("strong",{children:"Starting LiveDesk"}),r.jsx("p",{children:"Loading this computer's assigned role..."})]})}Q0.createRoot(document.getElementById("root")).render(r.jsx(u.StrictMode,{children:r.jsx(ER,{})}));
24
+ ${na}`:na;if(!ft){try{if(q==="custom"){const Ot=await TN(n,Y,G);if(!Ot.ok)throw new Error(Ot.error||"Custom Agent policy could not be saved.")}const at=await CN(n,{instruction:wn,deviceIds:xt,permissionMode:q,customPolicyId:Y});if(!at.ok||!at.runId)throw new Error(at.error||"Codex Agent run could not be started.");H(at.approvals||[]),ee({runId:at.runId,stage:at.stage||at.status||"queued",message:at.progressMessage||"Codex request queued on the Hub."}),D(at.runId);return}catch(at){try{const Ot=await SN(n,wn);Ot.ok&&Ot.plan&&(ft={operation:Ot.plan.operation,query:Ot.plan.targetQuery})}catch{k(Ot=>[...Ot,{type:"error",id:no("unsupported"),text:$N(at)}])}}if(!ft)return}try{const at=await EN(n,{instruction:wn,deviceIds:xt,operation:ft.operation,targetQuery:ft.query});if(!at.ok||!at.batch||!at.batchId)throw new Error(at.error||"작업을 만들지 못했습니다.");const Ot={type:"task",id:no("task"),batchId:at.batchId,operation:ft.operation,instruction:Ae,states:gf(at.batch,a),status:at.batch.status};ne.current.add(at.batchId),k(aa=>[...aa,Ot]),M(at.batchId)}catch(at){Q(at instanceof Error?at.message:String(at))}},Qe=async(pe,De)=>{de(pe.approvalId);try{const Oe=await MN(n,pe.runId,pe.approvalId,De);if(!Oe.ok)throw new Error(Oe.error||"Agent approval could not be applied.");await Be(pe.runId)}catch(Oe){Q(Oe instanceof Error?Oe.message:String(Oe))}finally{de("")}},Ye=async pe=>{de(pe.approvalId);try{const De=await NN(n,pe.runId,pe.approvalId);if(!De.ok)throw new Error(De.error||"Agent approval could not be rejected.");await Be(pe.runId)}catch(De){Q(De instanceof Error?De.message:String(De))}finally{de("")}},Ze=async(pe,De)=>{$(pe);try{if(De){const Ae=await jN(n,De);for(const ft of Ae.taskBatches||[])J(ft);D(ft=>ft===De?"":ft),ee(ft=>ft?.runId===De?null:ft);return}const Oe=await LN(n,pe);J(Oe),M(Ae=>Ae===pe?"":Ae)}catch(Oe){Q(Oe instanceof Error?Oe.message:String(Oe))}finally{$("")}},ut=async()=>{if(!(Z||!N&&!T)){z(!0);try{const pe=await AN(n);if(!pe.ok)throw new Error(pe.error||"모든 Agent 작업을 취소하지 못했습니다.");M(""),D(""),ee(null),H([]),k(De=>De.map(Oe=>Oe.type==="task"&&["queued","running"].includes(Oe.status)?{...Oe,status:"cancelled",states:Oe.states.map(Ae=>["queued","running"].includes(Ae.status)?{...Ae,status:"cancelled",stage:"Cancelled",error:"Cancelled by user."}:Ae)}:Oe))}catch(pe){Q(pe instanceof Error?pe.message:String(pe))}finally{z(!1)}}},U=async pe=>{$(pe);try{const De=await _N(n,pe);if(!De.ok||!De.batch||!De.batchId)throw new Error(De.error||"재시도하지 못했습니다.");Ne.current.delete(De.batchId),k(Oe=>Oe.map(Ae=>Ae.type==="task"&&Ae.batchId===pe?{...Ae,batchId:De.batchId,states:gf(De.batch,a),status:De.batch.status}:Ae)),M(De.batchId)}catch(De){Q(De instanceof Error?De.message:String(De))}finally{$("")}},ve=pe=>{A(pe),he(!1),window.requestAnimationFrame(()=>Se.current?.focus())},je=u.useMemo(()=>a.filter(Hf),[a]),$e=u.useMemo(()=>je.filter(pe=>g.includes(pe.deviceId)),[je,g]),dt=m==="auto"?`Auto · ${je.length} available`:m==="all"?`All ${je.length} computers`:$e.length===1?Of($e[0]):`${$e.length} selected`,it=m==="auto"?"LiveDesk chooses the best computer for each task.":m==="all"?"The Agent may coordinate every connected computer.":$e.length>0?$e.map(Of).join(" · "):"Select one or more computers on the Wall.",pt=m==="selected"&&$e.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"],ct=m==="selected"?$e.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 r.jsxs("section",{className:`agents-page ${d?"agents-dock-console":""}`,children:[d&&r.jsxs("header",{className:"agent-console-header",children:[r.jsxs("div",{className:"agent-console-title",children:[r.jsx("span",{className:"agent-console-mark",children:r.jsx(yl,{size:16})}),r.jsxs("div",{children:[r.jsx("small",{children:"Live agent"}),r.jsx("strong",{children:"Agent Console"})]}),r.jsx("i",{children:"Ready"})]}),r.jsxs("section",{className:"agent-console-target","aria-label":"Agent target scope",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Target"}),r.jsx("strong",{children:dt}),r.jsx("small",{children:it})]}),r.jsxs("div",{className:"agent-console-target-modes",children:[r.jsxs("button",{className:m==="selected"?"active":"",onClick:()=>h("selected"),type:"button",children:[r.jsx(Ir,{size:12})," Selected"]}),r.jsxs("button",{className:m==="all"?"active":"",onClick:()=>h("all"),type:"button",children:[r.jsx(Pu,{size:12})," All"]}),r.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[r.jsx(Pu,{size:12})," Group"]}),r.jsxs("button",{className:m==="auto"?"active":"",onClick:()=>h("auto"),type:"button",children:[r.jsx(yl,{size:12})," Auto"]})]})]}),r.jsx("div",{className:"agent-console-interaction-modes","aria-label":"Agent interaction mode",children:["auto","ask","plan","execute"].map(pe=>r.jsxs("button",{className:x===pe?"active":"",onClick:()=>b(pe),type:"button",children:[pe==="auto"?r.jsx(yl,{size:12}):pe==="execute"?r.jsx(Ta,{size:12}):null,pe[0].toUpperCase()+pe.slice(1)]},pe))})]}),r.jsxs("div",{className:"agents-workspace",children:[(N||T)&&r.jsxs("div",{className:"agents-page-status",children:[r.jsxs("span",{children:[Pe.length," Clients · ",HN(q)]}),r.jsx("button",{type:"button",className:"agents-stop-all",onClick:()=>{ut()},disabled:Z,children:Z?"Stopping…":"Stop all"})]}),se&&r.jsx("div",{className:"agents-permission-modal-backdrop",role:"presentation",children:r.jsxs("section",{className:"agents-permission-modal",role:"dialog","aria-modal":"true","aria-labelledby":"full-access-title",children:[r.jsx("span",{className:"agents-permission-modal-icon",children:r.jsx(Bf,{size:20})}),r.jsx("h3",{id:"full-access-title",children:"Confirm Full Access"}),r.jsx("p",{children:"Codex may change files, run commands, manage applications, and modify system state on the selected Clients. This run is still limited to the selected devices, the fixed policy, and the tool budget."}),r.jsxs("div",{className:"agents-permission-modal-actions",children:[r.jsx("button",{type:"button",onClick:()=>W(null),children:"Cancel"}),r.jsx("button",{type:"button",className:"danger",onClick:()=>{const pe=se;W(null),le(!0),_e(pe.instruction,pe.targetIds,!0)},children:"Run with Full Access"})]})]})}),ce&&r.jsx("div",{className:"agents-error",role:"alert",children:ce}),r.jsx(sN,{items:j,onCancel:Ze,onRetry:U,busyBatchId:F,approvals:K,onApprove:Qe,onReject:Ye,busyApprovalId:ye,progress:fe,emptyTitle:d?ct:void 0,emptyBody:d?kt:void 0}),d&&j.length===0&&!fe&&r.jsx("div",{className:"agent-console-suggestions","aria-label":"Suggested Agent commands",children:pt.map(pe=>r.jsx("button",{type:"button",onClick:()=>ve(pe),children:pe},pe))}),r.jsxs("div",{className:"agents-composer-shell",children:[be&&r.jsx(xN,{devices:a,targetMode:m,selectedIds:g,permissionMode:q,customCategories:G,onSelectPrompt:ve,onClose:()=>he(!1)}),r.jsx(VM,{ref:Se,value:w,onChange:A,onSubmit:()=>{_e()},onOpenSuggestedTasks:()=>he(pe=>!pe),suggestedOpen:be,suggestedTaskCount:mt,disabled:!!N||!!T,placeholder:d?"Tell LiveDesk what outcome you want...":void 0,compact:d})]})]}),!d&&r.jsxs("aside",{className:"agents-target-sidebar","aria-label":"Agent targets and permissions",children:[r.jsx(wN,{devices:a,mode:m,selectedIds:g,onModeChange:h,onToggle:pe=>y(De=>De.includes(pe)?De.filter(Oe=>Oe!==pe):[...De,pe]),permissionMode:q,onPermissionModeChange:pe=>{L(pe),pe!=="full-access"&&le(!1)}}),q==="custom"&&r.jsxs("section",{className:"agents-custom-policy","aria-label":"Custom Agent permissions",children:[r.jsxs("div",{className:"agents-custom-policy-head",children:[r.jsxs("div",{children:[r.jsx("span",{className:"agents-section-label",children:"Custom policy"}),r.jsx("strong",{children:"Choose what Codex may do automatically."})]}),r.jsx("span",{children:"Denied actions never reach a device."})]}),r.jsx("div",{className:"agents-custom-policy-grid",children:WM.map(pe=>r.jsxs("label",{children:[r.jsx("span",{children:FN(pe)}),r.jsxs("select",{value:G[pe],onChange:De=>P(Oe=>({...Oe,[pe]:De.target.value})),children:[r.jsx("option",{value:"allow",children:"Allow automatically"}),r.jsx("option",{value:"ask",children:"Ask every time"}),r.jsx("option",{value:"deny",children:"Deny"})]})]},pe))})]})]})]})}function Ew(n){return{type:n.type,deviceIds:n.deviceIds,monitorIndex:n.monitorIndex,label:n.label}}async function Dw(n){try{return(await n.json()).error||`${n.status} ${n.statusText}`}catch{return`${n.status} ${n.statusText}`}}async function Lw(n,a,i){const l=encodeURIComponent(JSON.stringify({kind:a.kind,fileName:a.fileName,mimeType:n.type||"application/octet-stream",durationMs:a.durationMs,target:Ew(a.target)})),c=await fetch(`${wl(i)}/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 Dw(c));return await c.json()}async function BN(n,a){return await Ve("/api/capture-sessions",{method:"POST",body:JSON.stringify({...n,target:Ew(n.target)})},a)}async function PN(n,a,i,l){const c=await fetch(`${wl(l)}/api/capture-sessions/${encodeURIComponent(n)}/chunks/${a}`,{method:"PUT",headers:{"Content-Type":i.type||"application/octet-stream"},body:i,cache:"no-store"});if(!c.ok)throw new Error(await Dw(c));return await c.json()}async function UN(n,a,i){return await Ve(`/api/capture-sessions/${encodeURIComponent(n)}/finalize`,{method:"POST",body:JSON.stringify({durationMs:a})},i)}async function _b(n,a){await Ve(`/api/capture-sessions/${encodeURIComponent(n)}`,{method:"DELETE"},a)}async function qN(n){return await Ve("/api/captures",void 0,n)}function Ib(n,a){return`${wl(a)}/api/captures/${encodeURIComponent(n)}/content`}async function GN(n,a){return await Ve(`/api/captures/${encodeURIComponent(n)}`,{method:"DELETE"},a)}function VN({hubUrl:n,onToast:a}){const[i,l]=u.useState([]),[c,d]=u.useState(!0),m=u.useCallback(async()=>{d(!0);try{l((await qN(n)).captures||[])}catch(g){a(g instanceof Error?g.message:String(g))}finally{d(!1)}},[n,a]);u.useEffect(()=>{m()},[m]);const h=async g=>{const y=Ib(g.id,n);if(navigator.share)try{await navigator.share({title:g.fileName,url:y});return}catch{}window.open(y,"_blank","noopener,noreferrer")};return r.jsxs("section",{className:"capture-gallery",children:[r.jsxs("header",{children:[r.jsxs("div",{children:[r.jsx("span",{className:"settings-eyebrow",children:"Capture Gallery"}),r.jsx("h2",{children:"Saved captures"})]}),r.jsxs("button",{className:"text-button",onClick:()=>{m()},type:"button",children:[r.jsx(Sc,{size:15})," Refresh"]})]}),c?r.jsx("p",{className:"settings-help",children:"Loading captures..."}):i.length===0?r.jsx("p",{className:"settings-help",children:"No captures saved yet."}):r.jsx("div",{className:"capture-gallery-grid",children:i.map(g=>{const y=Ib(g.id,n);return r.jsxs("article",{className:"capture-gallery-card",children:[g.mimeType.startsWith("image/")?r.jsx("img",{src:y,alt:g.target.label}):r.jsx("video",{src:y,controls:!0,preload:"metadata"}),r.jsxs("div",{className:"capture-gallery-card-body",children:[r.jsx("strong",{children:g.fileName}),r.jsxs("small",{children:[g.target.label," · ",new Date(g.createdAt).toLocaleString()," · ",Math.ceil(g.sizeBytes/1024)," KB"]}),r.jsxs("div",{children:[r.jsx("button",{className:"icon-button",title:"Open","aria-label":"Open",onClick:()=>window.open(y,"_blank","noopener,noreferrer"),type:"button",children:r.jsx(T0,{size:15})}),r.jsx("a",{className:"icon-button",title:"Download","aria-label":"Download",href:`${y}?download=1`,download:g.fileName,children:r.jsx(xp,{size:15})}),r.jsx("button",{className:"icon-button",title:"Share","aria-label":"Share",onClick:()=>{h(g)},type:"button",children:r.jsx(R0,{size:15})}),r.jsx("button",{className:"icon-button danger",title:"Delete","aria-label":"Delete",onClick:()=>{window.confirm(`Delete ${g.fileName}?`)&&GN(g.id,n).then(()=>m()).catch(x=>a(x instanceof Error?x.message:String(x)))},type:"button",children:r.jsx(Sp,{size:15})})]})]})]},g.id)})})]})}function vf(n){if(!n)return"";const a=Math.max(0,Math.floor((Date.now()-n)/1e3)),i=Math.floor(a/3600),l=Math.floor(a%3600/60),c=a%60;return i>0?`${String(i).padStart(2,"0")}:${String(l).padStart(2,"0")}:${String(c).padStart(2,"0")}`:`${String(l).padStart(2,"0")}:${String(c).padStart(2,"0")}`}function zb({controller:n,compact:a=!1,onFirstRollingUse:i,onError:l}){const{state:c,settings:d,videoSupported:m}=n,h=async b=>{try{await b()}catch(w){l?.(w instanceof Error?w.message:String(w))}},g=async()=>{if(d.rollingEnabled){n.setRollingEnabled(!1);return}(i?await i():window.confirm(`Keep the most recent 30 seconds in memory temporarily?
25
+ Nothing is saved until you press Save Last 30s.`))&&n.setRollingEnabled(!0)},y=c.recording?`Stop recording · ${vf(c.recordingStartedAt)}`:`Start recording · ${c.targetLabel}`,x=c.timelapse?`Stop timelapse · ${vf(c.timelapseStartedAt)}`:`Start timelapse · ${d.timelapseIntervalSeconds}s interval`;return r.jsxs("div",{className:`capture-toolbar ${a?"compact":""} ${c.recording?"recording-active":""}`,"aria-label":"Capture actions",children:[r.jsx("button",{className:"capture-action","aria-label":`Take screenshot · ${c.targetLabel}`,title:`Take screenshot · ${c.targetLabel}`,disabled:c.busy,onClick:()=>{h(n.takeScreenshot)},type:"button",children:r.jsx(E0,{size:17})}),r.jsx("button",{className:`capture-action ${c.recording?"active":""}`,"aria-label":y,title:y,disabled:!m||c.busy||c.timelapse,onClick:()=>{h(c.recording?n.stopRecording:n.startRecording)},type:"button",children:c.recording?r.jsxs(r.Fragment,{children:[r.jsx(py,{size:14,fill:"currentColor"}),r.jsx("span",{children:vf(c.recordingStartedAt)})]}):r.jsx(px,{size:18})}),r.jsxs("button",{className:"capture-action","aria-label":c.bufferEnabled?`Save last 30 seconds · ${c.bufferSeconds}s ready`:"Enable Last 30s memory buffer",title:c.bufferEnabled?`Save last 30 seconds · ${c.bufferSeconds}s ready`:"Enable Last 30s memory buffer",disabled:!m||c.recording||c.timelapse||c.busy||c.bufferEnabled&&c.bufferSeconds<1,onClick:()=>c.bufferEnabled?void h(n.saveLast30Seconds):void g(),type:"button",children:[r.jsx(D0,{size:17}),r.jsx("small",{children:"30s"})]}),r.jsx("button",{className:`capture-action ${c.timelapse?"timelapse-active":""}`,"aria-label":x,title:x,disabled:!m||c.busy||c.recording,onClick:()=>{h(c.timelapse?n.stopTimelapse:n.startTimelapse)},type:"button",children:c.timelapse?r.jsxs(r.Fragment,{children:[r.jsx(py,{size:14,fill:"currentColor"}),r.jsx("span",{children:vf(c.timelapseStartedAt)})]}):r.jsx(L0,{size:17})})]})}function _w({state:n}){return n==="ok"?r.jsx(Xn,{size:15,"aria-hidden":"true"}):r.jsx(vx,{size:15,"aria-hidden":"true"})}function Ob({active:n,refreshing:a,onClick:i}){return r.jsx("button",{className:`remote-status-button ${n?"active":""}`,type:"button",title:"Check Remote Status","aria-label":"Check Remote Status","aria-pressed":n,"aria-busy":a,onClick:i,children:a?r.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):r.jsx(_0,{size:18,"aria-hidden":"true"})})}function Hb({active:n,refreshing:a,onClick:i}){return r.jsx("button",{className:`remote-status-button debug-status-button ${n?"active":""}`,type:"button",title:"Check Debug Status","aria-label":"Check Debug Status","aria-pressed":n,"aria-busy":a,onClick:i,children:a?r.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):r.jsx(ox,{size:18,"aria-hidden":"true"})})}function Fb({active:n,refreshing:a,onClick:i}){return r.jsx("button",{className:`remote-status-button hub-status-button ${n?"active":""}`,type:"button",title:"Check Hub Status","aria-label":"Check Hub Status","aria-pressed":n,"aria-busy":a,onClick:i,children:a?r.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):r.jsx(zr,{size:18,"aria-hidden":"true"})})}function WN({items:n,mode:a="remote"}){return r.jsx("span",{className:`remote-status-lines mode-${a}`,role:"status","aria-label":a==="debug"?"Debug status":"Remote status",children:n.map(i=>r.jsxs("span",{className:`remote-status-line state-${i.state}`,title:i.detail,children:[r.jsx(_w,{state:i.state}),r.jsxs("span",{children:[r.jsx("strong",{children:i.label}),r.jsx("small",{children:i.detail})]})]},i.id))})}function YN({items:n,collectedAt:a,onClose:i}){return r.jsxs("section",{className:"remote-status-dialog hub-status-dialog",role:"dialog","aria-modal":"false","aria-labelledby":"hub-status-dialog-title",children:[r.jsxs("header",{children:[r.jsx("span",{className:"remote-status-dialog-mark","aria-hidden":"true",children:r.jsx(zr,{size:19})}),r.jsxs("span",{children:[r.jsx("small",{children:"Hub measurements"}),r.jsx("h2",{id:"hub-status-dialog-title",children:"Hub Status"})]}),r.jsx("button",{type:"button",onClick:i,title:"Close Hub status","aria-label":"Close Hub status",children:r.jsx(Na,{size:17})})]}),r.jsx("p",{children:"LiveDesk collects these Hub and browser signals continuously. This check refreshed the latest snapshot instead of starting a one-time benchmark."}),r.jsx("div",{className:"remote-status-dialog-list",children:n.map(l=>r.jsxs("article",{className:`remote-status-dialog-row state-${l.state}`,children:[r.jsx(_w,{state:l.state}),r.jsxs("span",{children:[r.jsx("strong",{children:l.label}),r.jsx("small",{children:l.detail})]})]},l.id))}),r.jsxs("footer",{children:["Checked ",new Date(a).toLocaleTimeString()]})]})}const KN=/(nvenc|videotoolbox|qsv|quick\s*sync|amf|vaapi|v4l2m2m|mediafoundation|h264_mf)/i,QN=/(libx264|openh264|software|cpu)/i,It=Object.freeze({frameAgeWarningMs:2500,networkDelayWarningMs:120,receiveRatioWarning:.62,deliveryRatioWarning:.82,decoderInputRatioWarning:.82,decoderOutputRatioWarning:.62,captureBudgetMultiplier:2.5,minimumCaptureBudgetMs:80,cpuWarningRatio:.82,memoryWarningRatio:.86,gpuWarningRatio:.92,gpuMemoryWarningRatio:.92,gpuTemperatureWarningC:85,networkUsageWarningRatio:.85,networkLatencyWarningMs:80,minimumClientStatusFreshMs:15e3,clientStatusFreshMultiplier:3,hubMinimumTotalMemoryBytes:8*1024**3,hubMinimumBrowserMemoryGb:4});function Nn(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function Vp(n,a){let i=n;for(const l of String(a).split(".")){if(!i||typeof i!="object")return;i=i[l]}return i}function is(n,...a){for(const i of a){const l=Vp(n,i);if(l==null||l==="")continue;const c=Number(l);if(Number.isFinite(c))return c}}function Ut(n,...a){for(const i of a){const l=Vp(n,i);if(typeof l=="string"&&l.trim())return l.trim()}return""}function Iw(n,...a){for(const i of a){const l=Vp(n,i);if(typeof l=="boolean")return l;if(l===1||l==="1"||String(l).toLowerCase()==="true")return!0;if(l===0||l==="0"||String(l).toLowerCase()==="false")return!1}}function oo(n,...a){const i=is(n,...a);if(i!==void 0)return Math.max(0,Math.min(1,i>1?i/100:i))}function tt(n,a,i,l){return{id:n,state:a,label:i,detail:l}}function Nf(n){const a=Date.parse(String(n||""));return Number.isFinite(a)&&a>0?a:void 0}function $b(n){return`${(Math.max(0,Number(n||0))/1024**3).toFixed(1)} GB`}function XN(n){const a=String(n||"").replace(/^::ffff:/,"").trim().toLowerCase();if(!a||a==="::1"||a==="localhost"||a==="127.0.0.1"||/^10\./.test(a)||/^192\.168\./.test(a))return!0;const i=a.match(/^172\.(\d{1,3})\./);return!!i&&Number(i[1])>=16&&Number(i[1])<=31||a.startsWith("fe80:")||a.startsWith("fc")||a.startsWith("fd")}function zw(n,a){const i=Number(n?.browserReceivedEpochMs);return Number.isFinite(i)&&i>0?Math.max(0,a-i):Number.POSITIVE_INFINITY}function Ow(n,a,i){const l=Nn(a?.frameTransport),c=Ut(n,"frameTransportChangedAt"),d=Ut(l,"changedAt"),m=Nf(c),h=Nf(d),g=h!==void 0&&(m===void 0||h>m),y=g?l:n,x=g?n:l,b=Ut(n,"transport").toLowerCase(),w=Ut(y,g?"active":"frameTransportActive")||Ut(x,g?"frameTransportActive":"active"),A=Ut(y,g?"protocol":"frameTransportProtocol")||Ut(x,g?"frameTransportProtocol":"protocol"),k=(g?Ut(l,"videoTransport","activeTransport")||[w,A].filter(Boolean).join("-")||Ut(n,"videoTransport"):Ut(n,"videoTransport")||Ut(l,"videoTransport","activeTransport")||[w,A].filter(Boolean).join("-")).toLowerCase(),N=/(?:^|[-_])ws(?:$|[-_])|websocket/.test(k)||/(?:^|[-_])ws(?:$|[-_])|websocket/.test(b),M=/p2p|udp/.test(k)||b==="udp-p2p"?"p2p-udp":/direct|tcp|ws|websocket/.test(k)||b==="binary"||N?N?"direct-ws":"direct-tcp":"",T=(Ut(y,g?"state":"frameTransportState")||Ut(x,g?"frameTransportState":"state")||(M?"active":"")).toLowerCase(),D=Ut(y,g?"reason":"frameTransportReason")||Ut(x,g?"frameTransportReason":"reason"),F=g?d||c:c||d,$=Nf(F),q=$===void 0?void 0:Math.max(0,i-$),L=q===void 0?"":q<1e3?"changed now":q<6e4?`changed ${Math.round(q/1e3)}s ago`:q<36e5?`changed ${Math.round(q/6e4)}m ago`:`changed ${F}`,Y=g?l.switchCount??n?.frameTransportSwitchCount:n?.frameTransportSwitchCount??l.switchCount,G=g?l.tcpFailureCount??n?.frameTransportTcpFailureCount:n?.frameTransportTcpFailureCount??l.tcpFailureCount,P=g?typeof l.p2pReady=="boolean"?l.p2pReady:n?.frameTransportP2pReady===!0:typeof n?.frameTransportP2pReady=="boolean"?n.frameTransportP2pReady:l.p2pReady===!0;return{rawTransport:b,videoTransport:M,state:T,reason:D,changedAt:F,changedLabel:L,switchCount:Math.max(0,Number(Y??0)||0),tcpFailureCount:Math.max(0,Number(G??0)||0),p2pReady:P}}function ZN(n,a,i){const l=Ow(n,a,i),c=/(connecting|recovering|failed|error|degraded|unavailable)/.test(l.state);if(l.videoTransport==="p2p-udp")return tt("transport",c?"warning":"ok",c?"P2P video connection needs attention":"P2P video connection",c?`Encrypted UDP P2P is ${l.state||"not ready"}; open Debug Status for the technical reason${l.changedLabel?` · ${l.changedLabel}`:""}.`:`Encrypted UDP P2P fallback is active${l.changedLabel?` · ${l.changedLabel}`:""}.`);if(l.videoTransport==="direct-tcp"||l.videoTransport==="direct-ws"){const d=l.videoTransport==="direct-ws"?"WebSocket":"TCP";return tt("transport",c?"warning":"ok",c?"Direct video connection needs attention":"Direct video connection",c?`Direct ${d} to Hub is ${l.state||"not ready"}; open Debug Status for the technical reason${l.changedLabel?` · ${l.changedLabel}`:""}.`:`Direct ${d} to Hub is active${l.changedLabel?` · ${l.changedLabel}`:""}.`)}return tt("transport","warning","Video transport is not identified",l.reason||"Waiting for Direct TCP or encrypted UDP P2P transport data.")}function JN(n){const a=String(n?.frameMode||n?.mode||n?.codec||"").toLowerCase(),i=[n?.hardwareEncoder,n?.platformProfile].filter(Boolean).join(" · "),l=Iw(n,"nativeEncoderHardwareAccelerated"),c=n?.nativeEncoderHardwareAccelerationKnown===!0||l!==void 0;return!n||!/h264/.test(a)?tt("encoder","warning","Video encoder unavailable","Waiting for an H.264 frame."):c&&l===!1?tt("encoder","warning","H.264 hardware acceleration is not active",`${i||"Native encoder"} is running without confirmed hardware acceleration.`):c&&l===!0?tt("encoder","ok","Hardware H.264 encoding",`${i||"Native encoder"} · hardware acceleration confirmed`):KN.test(i)?tt("encoder","ok","Hardware H.264 encoding",i):QN.test(i)?tt("encoder","warning","Software H.264 encoding",`${i||"CPU encoder"} may limit frame rate.`):tt("encoder","warning","H.264 encoder not identified",i||"The Client has not reported its active encoder profile.")}function eT({device:n,frame:a,receiveStat:i,paintStat:l,codec:c,selectedMonitorIndex:d=0,control:m=!1,controlInputReady:h=!1,controlBinding:g,capturePaused:y=!1,capturePauseConfirmed:x=!0,capturePauseError:b="",clientHeartbeatMs:w=5e3,now:A=Date.now()}={}){const j=Nn(n),k=Nn(j.status),N=Nn(l?.lastInfo),M=[],T=zw(a,A);M.push(y?x?tt("connection","ok","Video capture is paused","Client screen capture and FFmpeg shutdown were confirmed by the Client."):tt("connection","warning","Video stop needs attention",String(b||"The Hub is blocking video restart, but the Client did not confirm capture and FFmpeg shutdown.")):j.connected===!0&&T<=It.frameAgeWarningMs?tt("connection","ok","Video connection is current",`${Math.round(T)}ms since the latest frame.`):tt("connection","warning",j.connected===!0?"Video frame is stale":"Client is offline",j.connected===!0&&Number.isFinite(T)?`${Math.round(T)}ms since the latest frame.`:String(j.lastDisconnectReason||"No current Client session."))),M.push(ZN(a,k,A)),M.push(JN(a));const D=Math.max(0,Number(a?.requestedFps||a?.effectiveFps||0)),F=Math.max(0,Number(i?.framesPerSecond||0));Math.max(0,Number(a?.sourceGapMs||0));const $=Math.max(0,Number(a?.nativeCaptureFps||0)),q=Math.max(0,Number(a?.nativeEncodedFps||0)),L=Math.max(0,Number(a?.nativeCaptureSampleCount||0)),Y=a?.nativeCaptureTelemetryAvailable===!0&&L>0,G=is(a,"captureP95Ms","captureAverageMs","captureStageMs"),P=Math.max(0,Number(G||0)),K=a?.captureTimingAvailable===!0&&D>0&&Number(i?.sampleMs||0)>0&&G!==void 0,H=K||Y,ye=Math.max(It.minimumCaptureBudgetMs,D>0?1e3/D*It.captureBudgetMultiplier:0),de=D>0?1e3/D:100,Z=Y&&D>0&&($<D*It.receiveRatioWarning||q>0&&q<D*It.receiveRatioWarning),z=Y?Z:K&&P>ye;M.push(H?z?tt("capture","warning","Screen capture cannot keep target speed",Y?`${$.toFixed(1)} native capture · ${q.toFixed(1)} encoded · ${D||"?"} requested fps`:`${P?`capture p95 ${Math.round(P)}ms`:"capture timing unavailable"} · ${F.toFixed(1)}/${D||"?"} fps`):tt("capture","ok","Screen capture speed is healthy",Y?`${$.toFixed(1)} native capture · ${q.toFixed(1)} encoded · ${D||"?"} requested fps`:`${P?`capture p95 ${Math.round(P)}ms`:"no slow capture reported"}${D?` · ${F.toFixed(1)}/${D} fps`:""}`):tt("capture","warning","Screen capture data is still collecting","A current frame-rate and capture-time sample is required."));const se=is(a,"hubPacketTransitAgeMs"),W=Math.max(0,Number(se||0)),O=Math.max(0,Number(a?.agentSendGapMs||0)),le=Math.max(0,Number(a?.agentSendDurationMs||0)),ce=!XN(j.remoteAddress),Q=oo(k,"network.usageRatio"),be=is(k,"network.latencyMs"),he=(Q??0)>=It.networkUsageWarningRatio||(be??0)>=It.networkLatencyWarningMs,fe=Math.max(0,Number(a?.hubClientQueueDepth||0)),ee=Math.max(0,Number(a?.hubClientQueueLimit||0)),Se=ee>0&&fe>=ee,Ne=se!==void 0&&Number(i?.sampleMs||0)>0,Fe=D>0&&Number(i?.sampleMs||0)>0&&F<D*It.deliveryRatioWarning,ne=W>It.networkDelayWarningMs||O>Math.max(It.networkDelayWarningMs,de*3)||le>It.networkDelayWarningMs||Fe||T>It.frameAgeWarningMs||he||Se;M.push(Ne?ne||ce?tt("network","warning",ce?"External network route may add delay":he?"Client network adapter needs attention":Se?"Hub browser video queue needs attention":"Video delivery is uneven",[W?`${Math.round(W)}ms Hub-to-browser`:"",O?`${Math.round(O)}ms Client send gap`:"",le?`${Math.round(le)}ms Client send time`:"",Fe?`${F.toFixed(1)} of ${D} requested fps`:"",be!==void 0?`${Math.round(be)}ms Client network latency`:"",Q!==void 0?`${Math.round(Q*100)}% Client link use`:"",ee>0?`Hub queue ${fe}/${ee}`:"",ce?String(j.remoteAddress||"external route"):""].filter(Boolean).join(" · ")||"Frame delivery is not current."):tt("network","ok","Network delivery is healthy",`${Math.round(W)}ms Hub-to-browser · the current video rate is on target.`):tt("network","warning","Network delivery data is still collecting","A calibrated Hub-to-browser transit sample is required."));const Pe=oo(k,"cpu.usageRatio","cpu.usedRatio","cpu.percent"),mt=oo(k,"memory.usedRatio","usedMemRatio"),J=oo(k,"gpu.usageRatio"),ke=oo(k,"gpu.memory.usedRatio"),Le=is(k,"gpu.temperatureC","thermal.gpuC"),Be=Pe!==void 0&&mt!==void 0,_e=Nf(j.lastStatusAt),Qe=_e===void 0?Number.POSITIVE_INFINITY:Math.max(0,A-_e),Ye=Math.max(It.minimumClientStatusFreshMs,Math.max(1e3,Number(w||0))*It.clientStatusFreshMultiplier),Ze=Qe<=Ye,ut=(Pe??0)>=It.cpuWarningRatio||(mt??0)>=It.memoryWarningRatio||(J??0)>=It.gpuWarningRatio||(ke??0)>=It.gpuMemoryWarningRatio||(Le??0)>=It.gpuTemperatureWarningC;M.push(Be?Ze?ut?tt("computer","warning",(J??0)>=It.gpuWarningRatio||(ke??0)>=It.gpuMemoryWarningRatio||(Le??0)>=It.gpuTemperatureWarningC?"Client GPU is under load":"Client computer is under load",[`CPU ${Math.round(Pe*100)}%`,`memory ${Math.round(mt*100)}%`,J!==void 0?`GPU ${Math.round(J*100)}%`:"",ke!==void 0?`GPU memory ${Math.round(ke*100)}%`:"",Le!==void 0?`GPU ${Math.round(Le)}C`:""].filter(Boolean).join(" · ")):tt("computer","ok","Client computer has working capacity",[`CPU ${Math.round(Pe*100)}%`,`memory ${Math.round(mt*100)}%`,J!==void 0?`GPU ${Math.round(J*100)}%`:""].filter(Boolean).join(" · ")):tt("computer","warning","Client performance snapshot is stale",Number.isFinite(Qe)?`The latest CPU and memory report is ${Math.round(Qe/1e3)} seconds old.`:"No current Client performance heartbeat has been received."):tt("computer","warning","Client performance data is unavailable","CPU and memory telemetry have not been reported yet."));const U=Number(a?.monitorIndex),ve=Number.isInteger(U)&&U===Number(d),je=Nn(j.channels),$e=Nn(j.capabilities),dt=je.input!==!1&&$e.remoteInput!==!1&&$e.accessibilityPermission!==!1,it=$e.screenRecordingPermission!==!1,pt=Nn(g),ct=!m||String(a?.sessionId||"")&&String(a?.sessionId||"")===String(pt.sessionId||"")&&String(a?.commandId||"")&&String(a?.commandId||"")===String(pt.commandId||"")&&Number(a?.captureGeneration||0)>0&&Number(a?.captureGeneration||0)===Number(pt.captureGeneration||0)&&Number(a?.monitorIndex)===Number(pt.monitorIndex),kt=!m||h&&ct;M.push(ve&&kt&&dt&&it?tt("display","ok",m?"Display and remote input are bound":"Display and remote input are available",`Display ${Number(d)+1} · generation ${Number(a?.captureGeneration||0)||"current"}.`):tt("display","warning",it?dt?m?"Remote input is not bound to this display":"Waiting for the selected display":"Remote input permission is missing":"Screen capture permission is missing",`Selected display ${Number(d)+1}; latest frame ${Number.isInteger(U)?U+1:"not available"}.`));const pe=Nn(c),De=Array.isArray(pe.canvases)?Nn(pe.canvases[0]):{},Oe=Math.max(0,Number(l?.decoderInputFps||0)),Ae=Math.max(0,Number(l?.decoderOutputFps||0)),ft=Oe>0&&Number(l?.sampleMs||i?.sampleMs||0)>0,Ie=F>0&&Number(i?.sampleMs||0)>0&&Number(l?.sampleMs||0)>0&&Oe<F*It.decoderInputRatioWarning,na=Oe>0?Ae/Oe:0,wn=Ut(De,"configuredAcceleration","requestedAcceleration")||Ut(N,"h264DecodeAcceleration"),at=Ut(De,"softwareFallbackReason"),Ot=!!at||wn==="prefer-software";return M.push(Ie?tt("decoder","warning","Browser decoder input is dropping frames",`${F.toFixed(1)} received / ${Oe.toFixed(1)} decoder input / ${Ae.toFixed(1)} output fps.`):ft?Ot||na<It.decoderOutputRatioWarning?tt("decoder","warning",Ot?"Browser is using software H.264 fallback":"Browser decoder output is slow",`${at||String(N.decoderLabel||wn||"decoder")} · ${Oe.toFixed(1)} in / ${Ae.toFixed(1)} out fps.`):tt("decoder","ok",wn==="prefer-hardware"?"Browser requests hardware H.264":"Browser H.264 path is responsive",`${Oe.toFixed(1)} in / ${Ae.toFixed(1)} out fps. Chrome does not expose definitive hardware acceptance.`):tt("decoder","warning","Browser decoder data is still collecting","Decoder input and output samples are required before this path can be marked healthy.")),M}function Dr(n){const a=String(n||"").trim();return a?a.length<=14?a:`${a.slice(0,6)}…${a.slice(-5)}`:"-"}function mn(n,a=1){const i=Number(n);return Number.isFinite(i)?i.toFixed(a):"-"}function tT({device:n,frame:a,receiveStat:i,paintStat:l,codec:c,selectedMonitorIndex:d=0,control:m=!1,controlInputReady:h=!1,controlBinding:g,now:y=Date.now()}={}){const x=Nn(n),b=Nn(x.status),w=Nn(g),A=Nn(l?.lastInfo),j=Nn(c),k=Array.isArray(j.canvases)?Nn(j.canvases[0]):{},N=[],M=Number(d),T=Number(a?.monitorIndex),D=Number.isInteger(T)&&T===M,F=Number(a?.captureGeneration||0),$=Number(w.captureGeneration||0),q=!m||D&&String(a?.sessionId||"")===String(w.sessionId||"")&&String(a?.commandId||"")===String(w.commandId||"")&&F>0&&F===$,L=Math.max(0,Number(a?.requestedFps||a?.effectiveFps||0)),Y=Math.max(0,Number(i?.framesPerSecond||0)),G=Math.max(0,Number(l?.framesPerSecond||0)),P=Math.max(0,Number(l?.decoderInputFps||0)),K=Math.max(0,Number(l?.decoderOutputFps||0)),H=Number(i?.sampleMs||0)>0&&Number(l?.sampleMs||0)>0,ye=L>0&&H&&Math.min(Y,G||Y,K||Y)<L*It.deliveryRatioWarning,de=Math.max(0,Number(a?.sourceGapMs||0)),Z=Math.max(0,Number(a?.agentSendGapMs||0)),z=Math.max(0,Number(a?.agentSendDurationMs||0)),se=Math.max(0,Number(a?.agentSendDurationFrameSeq||0)),W=Math.max(0,Number(a?.agentQueueBeforePaceMs||0)),O=Math.max(0,Number(a?.agentFrameAgeMs||0)),le=is(a,"hubPacketTransitAgeMs"),ce=Math.max(0,Number(a?.droppedByAgent||0)),Q=Math.max(0,Number(a?.hubIngressDropped||0)),be=Math.max(0,Number(a?.hubClientDropped||0)),he=Math.max(0,Number(a?.hubClientQueueDepth||0)),fe=Math.max(0,Number(a?.hubClientQueueLimit||0)),ee=Math.max(0,Number(a?.hubClientBufferedBytes||0)),Se=Math.max(0,Number(a?.udpIncompleteFrames||0)),Ne=ce+Q+be,Fe=zw(a,y),ne=Ut(k,"configuredAcceleration","requestedAcceleration")||Ut(A,"h264DecodeAcceleration"),Pe=Ut(k,"softwareFallbackReason"),mt=H&&Y>0&&P<Y*It.decoderInputRatioWarning,J=Ow(a,b,y),ke=Ut(x,"deviceId")||Ut(a,"deviceId"),Le=Ut(a,"sessionId")||Ut(x,"sessionId"),Be=Ut(x,"productVersion")||Ut(b,"productVersion","runtime.productVersion"),_e=Ut(x,"agentVersion")||Ut(b,"agentVersion","runtime.agentVersion"),Qe=is(x,"pid","runtimePid")??is(b,"pid","runtimePid","process.pid"),Ye=!!(ke&&Le&&Be&&_e&&(Qe??0)>0),Ze=a?.nativeCaptureTelemetryAvailable===!0,ut=Iw(a,"nativeEncoderHardwareAccelerated"),U=a?.nativeEncoderHardwareAccelerationKnown===!0||ut!==void 0,ve=Ut(a,"nativeEncoderHardwareQueryStatus"),je=ve==="0"?"confirmed":ve,$e=Math.max(0,Number(a?.nativeCaptureFps||0)),dt=Math.max(0,Number(a?.nativeEncodedFps||0)),it=Math.max(0,Number(a?.nativeCaptureSampleCount||0)),pt=Math.max(0,Number(a?.nativeEncodableFrameCount||0)),ct=Math.max(0,Number(a?.nativeSkippedFrameCount||0)),kt=Math.max(0,Number(a?.nativeEncodedFrameCount||0)),pe=Ze&&it>0,De=L>0?1e3/L:100,Oe=pe&&L>0&&($e<L*It.receiveRatioWarning||dt>0&&dt<L*It.receiveRatioWarning);N.push(Ye?tt("debug-runtime","ok",`LiveDesk ${Be} · Agent ${_e}`,`pid ${Qe} · session ${Dr(Le)} · device ${Dr(ke)}`):tt("debug-runtime","warning","Runtime identity is incomplete",`LiveDesk ${Be||"-"} · Agent ${_e||"-"} · pid ${Qe??"-"} · session ${Dr(Le)} · device ${Dr(ke)}`)),N.push(a?tt("debug-frame","ok",`Frame #${Number(a.frameSeq||0)} · ${String(a.streamPurpose||(m?"control":"wall"))}`,`stream ${Dr(a.streamId)} · ${a.width||0}x${a.height||0} · ${Math.round(Number(a.byteLength||0)/1024)} KB · age ${Number.isFinite(Fe)?Math.round(Fe):"-"}ms`):tt("debug-frame","warning","No current frame",`Device ${Dr(x.deviceId)} has not produced a frame.`));const Ae=/(connecting|recovering|failed|error|degraded|unavailable)/.test(J.state);N.push(J.videoTransport&&!Ae?tt("debug-transport","ok",`${J.videoTransport==="p2p-udp"?"P2P UDP":J.videoTransport==="direct-ws"?"Direct WebSocket":"Direct TCP"} · ${J.state||"active"}`,[`raw ${J.rawTransport||"-"}`,`P2P ${J.p2pReady?"ready":"standby unavailable"}`,`switch ${J.switchCount}`,`TCP failure ${J.tcpFailureCount}`,J.changedLabel,J.reason].filter(Boolean).join(" · ")):tt("debug-transport","warning",J.videoTransport?`Video transport ${J.state||"needs attention"}`:"Video transport is not identified",[J.videoTransport||"no active path",`raw ${J.rawTransport||"-"}`,`P2P ${J.p2pReady?"ready":"not ready"}`,J.changedLabel,J.reason].filter(Boolean).join(" · "))),N.push(D?tt("debug-monitor","ok",`Monitor selected ${M+1} · frame ${T+1}`,`reported ${Number(a?.monitorCount||0)||"?"} displays · generation ${F||"-"}`):tt("debug-monitor","warning",`Monitor mismatch: selected ${M+1} · frame ${Number.isInteger(T)?T+1:"-"}`,`reported ${Number(a?.monitorCount||0)||"?"} displays · generation ${F||"-"}`)),N.push(q&&(!m||h)?tt("debug-binding","ok",m?"Control generation is bound":"Wall capture generation is current",`session ${Dr(a?.sessionId)} · command ${Dr(a?.commandId)} · generation ${F||"-"}`):tt("debug-binding","warning",m?"Control generation is not bound":"Wall capture generation is unavailable",`frame ${Dr(a?.commandId)}/${F||"-"} · expected ${Dr(w.commandId)}/${$||"-"} · input ${h?"ready":"waiting"}`)),N.push(H&&!ye?tt("debug-cadence","ok",`Cadence ${mn(Y)} rx · ${mn(G)} paint · ${mn(K)} decode`,`requested ${mn(L)} · decoder input ${mn(P)} fps · receive p95 ${mn(i?.p95IntervalMs)}ms`):tt("debug-cadence","warning",H?"Frame cadence is below request":"Frame cadence sample is collecting",`requested ${mn(L)} · receive ${mn(Y)} · paint ${mn(G)} · decode ${mn(K)} fps`)),N.push(pe&&!Oe&&ut!==!1?tt("debug-native-capture","ok",`Native capture ${mn($e)} fps · encode ${mn(dt)} fps`,`telemetry yes · hardware ${U?ut?"yes":"no":"unknown"}${je?` (${je})`:""} · capture samples ${it} · encodable ${pt} · skipped ${ct} · encoded ${kt} · encoded AU output gap ${Math.round(de)}ms`):tt("debug-native-capture","warning",pe?"Native capture or encoder needs attention":"Native capture telemetry is unavailable",`telemetry ${Ze?"yes, waiting for samples":"no"} · hardware ${U?ut?"yes":"no":"unknown"}${je?` (${je})`:""} · capture ${mn($e)} fps · encode ${mn(dt)} fps · capture samples ${it} · encodable ${pt} · skipped ${ct} · encoded ${kt} · encoded AU output gap ${Math.round(de)}ms`)),N.push(Ne===0&&Se===0&&(fe<=0||he<fe)&&Z<=Math.max(It.networkDelayWarningMs,De*3)&&z<=It.networkDelayWarningMs&&O<=It.networkDelayWarningMs&&(le===void 0||le<=It.networkDelayWarningMs)?tt("debug-delivery","ok","Delivery counters are clear",`encoded AU output gap ${Math.round(de)}ms · Client send gap ${Math.round(Z)}ms · Client send time ${Math.round(z)}ms (frame ${se||"-"}) · Agent queue ${Math.round(W)}ms · Agent age ${Math.round(O)}ms · Agent drop ${ce} · Hub transit ${le===void 0?"-":Math.round(le)}ms · Hub ingress drop ${Q} · browser queue drop ${be} (${he}/${fe||"-"}) · buffered ${Math.round(ee/1024)} KB · UDP incomplete ${Se}`):tt("debug-delivery","warning","Delivery counters show loss or delay",`encoded AU output gap ${Math.round(de)}ms · Client send gap ${Math.round(Z)}ms · Client send time ${Math.round(z)}ms (frame ${se||"-"}) · Agent queue ${Math.round(W)}ms · Agent age ${Math.round(O)}ms · Agent drop ${ce} · Hub transit ${le===void 0?"-":Math.round(le)}ms · Hub ingress drop ${Q} · browser queue drop ${be} (${he}/${fe||"-"}) · buffered ${Math.round(ee/1024)} KB · UDP incomplete ${Se}`));const ft=is(a,"captureP95Ms");return N.push(a?.captureTimingAvailable===!0&&ft!==void 0?tt("debug-capture","ok",`Capture p95 ${mn(ft)}ms · avg ${mn(a?.captureAverageMs)}ms`,`stage ${mn(a?.captureStageMs)}ms · slow ${Number(a?.slowFrameCount||0)} · helper restart ${Number(a?.captureHelperRestarts||0)} · source skip ${Number(a?.captureSourceSkipped||0)}`):tt("debug-capture","warning","Capture timing sample is unavailable",`stage ${mn(a?.captureStageMs)}ms · helper restart ${Number(a?.captureHelperRestarts||0)} · source serial ${Number(a?.captureSourceSerial||0)}`)),N.push(!Pe&&ne!=="prefer-software"&&!mt?tt("debug-decoder","ok",`Decoder ${ne||"acceleration unknown"}`,`${String(a?.frameMode||a?.codec||"-")} · ${String(a?.hardwareEncoder||"-")} · ${String(a?.platformProfile||"-")}`):tt("debug-decoder","warning",mt?"Decoder input is losing received frames":"Decoder software fallback is active",mt?`${mn(Y)} received / ${mn(P)} decoder input / ${mn(K)} output fps`:`${Pe||ne||"software"} · ${mn(P)} in / ${mn(K)} out fps`)),N}function nT({status:n,deviceDiagnostics:a=[],codec:i,browser:l,frameStats:c}={}){const d=Nn(n),m=Nn(d.diagnostics),h=Nn(m.system),g=Nn(m.network),y=Nn(i),x=Nn(l),b=Array.isArray(a)?a:[],w=b.reduce((ye,de)=>ye+(Array.isArray(de)&&de.some(Z=>Z?.state==="warning")?1:0),0),A=oo(h,"cpuUsageRatio","processCpuRatio"),j=oo(h,"memoryUsedRatio"),k=is(h,"totalMemoryBytes"),N=is(h,"cpuLogicalCores")??is(x,"hardwareConcurrency"),M=is(x,"deviceMemory"),T=(N??0)>0&&A!==void 0&&j!==void 0&&(k??0)>0,D=(k??0)>0&&k<It.hubMinimumTotalMemoryBytes,F=(M??0)>0&&M<It.hubMinimumBrowserMemoryGb,$=(N??0)>0&&N<4||(A??0)>=It.cpuWarningRatio||(j??0)>=It.memoryWarningRatio||D||F,q=Math.max(0,Number(y.activeSoftwareFallbackCount??y.softwareFallbackCount??0)),L=Math.max(0,Number(y.activeDecoderCount||0)),Y=Math.max(0,Number(c?.bytesPerSecond||0)*8/1e6),G=is(g,"externalDeviceCount"),P=Ut(g,"route"),K=G!==void 0&&!!P,H=(G??0)>0||P==="external";return[d.started&&!d.lastError?tt("hub-runtime","ok","Hub runtime is ready",`${d.connectedDeviceCount||0} Clients connected.`):tt("hub-runtime","warning","Hub runtime needs attention",String(d.lastError||"Hub is not ready.")),T?$?tt("hub-computer","warning",D?"Hub has limited system memory":F?"Browser reports limited memory capacity":"Hub computer may limit remote performance",[`${N||"?"} logical cores`,`${$b(k)} RAM`,M!==void 0?`${M} GB browser memory class`:"",`CPU ${A===void 0?"?":Math.round(A*100)}%`,`memory ${j===void 0?"?":Math.round(j*100)}%`].filter(Boolean).join(" · ")):tt("hub-computer","ok","Hub computer capacity is healthy",`${N||"?"} logical cores · ${$b(k)} RAM · CPU ${A===void 0?"not reported":`${Math.round(A*100)}%`}.`):tt("hub-computer","warning","Hub performance data is unavailable","Logical-core, CPU, used-memory, and total-memory telemetry are required."),L<=0?tt("hub-codec","warning","No active browser H.264 decoder to check","Open Wall or Control and wait for a video frame."):q>0?tt("hub-codec","warning","Some browser decoders use software fallback",`${L} active H.264 decoders · ${q} software fallbacks. Chrome does not expose definitive hardware acceptance.`):tt("hub-codec","ok","All active streams request hardware H.264",`${L} active decoders. Chrome hardware acceptance is inferred from health, not directly exposed.`),w>0?tt("hub-clients","warning",`${w} Clients need attention`,"Open the matching Wall slot lines for the exact cause."):tt("hub-clients","ok","Connected Clients report healthy remote paths",`${b.length} Client reports checked.`),tt("hub-network",!K||H||Y>120?"warning":"ok",K?H?`${G} Clients use an external network route`:Y>120?"Hub receive load is high":"Hub receive load is within range":"Hub network route data is unavailable",K?`${P.toUpperCase()} route · ${Y.toFixed(Y>=10?0:1)} Mbps received by this browser.`:"The Hub has not reported LAN/external route classification yet.")]}async function aT(n,a={}){const i=n.filter(b=>b.canvas&&b.canvas.width>0&&b.canvas.height>0),l=Math.max(320,a.maxWidth||1920),c=Math.max(180,a.maxHeight||1080),d=i.length<=1?1:i.length<=4?2:i.length<=9?3:4,m=Math.max(1,Math.ceil(Math.max(1,i.length)/d)),h=Math.floor(l/d),g=Math.floor(c/m),y=document.createElement("canvas");y.width=Math.max(320,h*d),y.height=Math.max(180,g*m);const x=y.getContext("2d",{alpha:!1});if(!x)return y;x.fillStyle="#0b1220",x.fillRect(0,0,y.width,y.height),x.font="600 14px system-ui, sans-serif",x.textBaseline="bottom";for(let b=0;b<i.length;b+=1){const w=i[b],A=b%d,j=Math.floor(b/d),k=A*h,N=j*g,M=w.canvas,T=Math.min(h/M.width,g/M.height),D=Math.max(1,Math.floor(M.width*T)),F=Math.max(1,Math.floor(M.height*T)),$=k+Math.floor((h-D)/2),q=N+Math.floor((g-F)/2);x.drawImage(M,$,q,D,F),a.includeLabels!==!1&&(x.fillStyle="rgba(4, 10, 20, .74)",x.fillRect(k,N+g-28,h,28),x.fillStyle="#f8fafc",x.fillText(w.label,k+9,N+g-9))}return y}function sT(n){return n?.signature||"none"}function rT(n){return n?.label||"No capture target"}function Bb(n){return{...n,deviceIds:[...n.deviceIds],sourceCanvas:n.sourceCanvas||null}}function iT(){const n=new Date,a=i=>String(i).padStart(2,"0");return`${n.getFullYear()}${a(n.getMonth()+1)}${a(n.getDate())}_${a(n.getHours())}${a(n.getMinutes())}${a(n.getSeconds())}`}function lT(n){return n.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function oT(n){return`LiveDesk_${n.type==="wall"||n.type==="selection"?"Wall":`${lT(n.label)}_Monitor-${Number(n.monitorIndex||0)+1}`}_${iT()}.png`}async function cT(n,a,i){const l=await new Promise((d,m)=>n.toBlob(h=>h?d(h):m(new Error("Screenshot could not be encoded.")),"image/png")),c=await Lw(l,{kind:"screenshot",fileName:oT(a),target:a},i);try{await navigator.clipboard.write([new ClipboardItem({"image/png":l})])}catch{}return c.capture}function Hw(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(a=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(a))||""}function uT(n,a){const i=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","_"),l=a.label.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,70)||"Wall";return n==="timelapse"?`LiveDesk_Timelapse_${l}_${i}.webm`:`LiveDesk_Recording_${l}_${i}.webm`}async function Fw(n){if(typeof MediaRecorder>"u"||typeof n.canvas.captureStream!="function")throw new Error("This browser does not support video recording.");const a=Hw();if(!a)throw new Error("This browser does not support WebM recording.");const i=n.kind||"recording",l=await BN({kind:i,fileName:uT(i,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:i==="timelapse"?2e6:4e6}),m=performance.now();let h=0,g=!1,y=null,x=Promise.resolve();return d.ondataavailable=b=>{if(!b.data||b.data.size===0)return;const w=h++;x=x.then(()=>PN(l.sessionId,w,b.data,n.hubUrl).then(()=>{})).catch(A=>{y=y||(A instanceof Error?A:new Error(String(A))),n.onError?.(y)})},d.onerror=()=>{y=new Error("Video recording stopped unexpectedly."),n.onError?.(y)},d.start(1e3),{requestFrame:()=>{c.getVideoTracks()[0]?.requestFrame?.()},stop:async()=>{if(!g){if(g=!0,await new Promise(b=>{d.addEventListener("stop",()=>b(),{once:!0}),d.stop()}),c.getTracks().forEach(b=>b.stop()),await x,y)throw await _b(l.sessionId,n.hubUrl).catch(()=>{}),y;await UN(l.sessionId,Math.max(0,performance.now()-m),n.hubUrl)}},cancel:async()=>{g||(g=!0,d.stop(),c.getTracks().forEach(b=>b.stop()),await _b(l.sessionId,n.hubUrl).catch(()=>{}))}}}class dT{recorder=null;stream=null;segments=[];totalBytes=0;targetSignature="";startedAt=0;maxDurationMs=3e4;maxBytes=128*1024*1024;get seconds(){return!this.startedAt||this.segments.length===0?0:Math.min(30,Math.max(0,(performance.now()-this.segments[0].at)/1e3))}get active(){return this.recorder!==null}async start(a,i){if(this.recorder&&this.targetSignature===i.signature)return;if(this.stop(),typeof MediaRecorder>"u"||typeof a.captureStream!="function")throw new Error("This browser does not support Last 30s.");const l=Hw();if(!l)throw new Error("This browser does not support WebM recording.");this.targetSignature=i.signature,this.stream=a.captureStream(20),this.recorder=new MediaRecorder(this.stream,{mimeType:l,videoBitsPerSecond:3e6}),this.startedAt=performance.now(),this.recorder.ondataavailable=c=>{if(!c.data.size)return;const 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(i=>i.stop()),this.stream=null,this.segments=[],this.totalBytes=0,this.startedAt=0}async save(a,i){if(this.segments.length===0)throw new Error("The Last 30s buffer is not ready yet.");const l=new Blob(this.segments.map(m=>m.blob),{type:this.segments[0].blob.type||"video/webm"}),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 Lw(l,{kind:"last-30s",fileName:d,target:a,durationMs:Math.min(3e4,this.segments.length*1e3)},i)}}async function fT(n,a,i,l,c){const d=await Fw({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,i)*1e3);return{stop:async()=>{window.clearInterval(m),await d.stop()},cancel:async()=>{window.clearInterval(m),await d.cancel()}}}const $w="livedesk.captureSettings";function mT(){const n={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const a=JSON.parse(localStorage.getItem($w)||"null");return{...n,...a&&typeof a=="object"?a:{}}}catch{return n}}function hT(n){const[a,i]=u.useState(mT),[l,c]=u.useState(0),[d,m]=u.useState(0),[h,g]=u.useState(0),[y,x]=u.useState(!1),b=u.useRef(void 0),w=u.useRef(!1),A=u.useRef(""),j=u.useRef(null),k=u.useRef(null),N=u.useRef(null),M=u.useRef(null),T=u.useRef(new dT),D=n.sourceRegistry.resolveCurrentTarget(),F=sT(D),$=rT(D),q=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;u.useEffect(()=>{if(localStorage.setItem($w,JSON.stringify(a)),!w.current)return;const W=JSON.stringify(a);W!==A.current&&(A.current=W,Ve("/api/settings",{method:"PATCH",body:JSON.stringify({revision:b.current,filesAudio:{rollingBufferEnabled:a.rollingEnabled,recordingQuality:a.recordingQuality,timelapseIntervalSeconds:a.timelapseIntervalSeconds,includeRemoteCursor:a.includeRemoteCursor}})},n.hubUrl).then(O=>{b.current=Number(O.revision||b.current||0)}).catch(()=>{}))},[n.hubUrl,a]),u.useEffect(()=>{let W=!0;return Ve("/api/settings",void 0,n.hubUrl).then(O=>{if(!W)return;const le=O.settings?.filesAudio||{},ce=typeof le.rollingBufferEnabled=="boolean"?le.rollingBufferEnabled:a.rollingEnabled,Q=le.recordingQuality==="high"?"high":"standard",be=[5,10,30,60].includes(Number(le.timelapseIntervalSeconds))?Number(le.timelapseIntervalSeconds):a.timelapseIntervalSeconds,he=typeof le.includeRemoteCursor=="boolean"?le.includeRemoteCursor:a.includeRemoteCursor,fe={rollingEnabled:ce,recordingQuality:Q,timelapseIntervalSeconds:be,includeRemoteCursor:he};b.current=Number(O.revision||0),A.current=JSON.stringify(fe),w.current=!0,i(fe)}).catch(()=>{w.current=!0}),()=>{W=!1}},[n.hubUrl]);const L=u.useCallback(async W=>{if(W.sourceCanvas&&W.sourceCanvas.width>0&&W.sourceCanvas.height>0)return{target:Bb(W),canvas:W.sourceCanvas,cleanup:()=>{}};const O=await n.sourceRegistry.composeWall(W.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let le=!1;const ce=window.setInterval(async()=>{if(le)return;const Q=await n.sourceRegistry.composeWall(W.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0}).catch(()=>null);!Q||le||((O.width!==Q.width||O.height!==Q.height)&&(O.width=Q.width,O.height=Q.height),O.getContext("2d")?.drawImage(Q,0,0))},100);return{target:Bb(W),canvas:O,cleanup:()=>{le=!0,window.clearInterval(ce)}}},[n.sourceRegistry]);u.useEffect(()=>{const W=T.current;if(!a.rollingEnabled||!D||!q){W.stop(),g(0);return}let O=!1,le=null;return(async()=>{try{if(le=await L(D),O)return;await W.start(le.canvas,le.target);const Q=window.setInterval(()=>g(Math.round(W.seconds)),500),be=()=>{window.clearInterval(Q),le?.cleanup()};W.__cleanup=be}catch(Q){O||n.onToast(Q instanceof Error?Q.message:String(Q))}})(),()=>{O=!0,W.stop(),W.__cleanup?.(),W.__cleanup=void 0,g(0)}},[L,n.onToast,a.rollingEnabled,F,q]);const Y=u.useCallback(W=>i(O=>({...O,rollingEnabled:W})),[]),G=u.useCallback(W=>i(O=>({...O,recordingQuality:W})),[]),P=u.useCallback(W=>i(O=>({...O,timelapseIntervalSeconds:W})),[]),K=u.useCallback(async()=>{const W=n.sourceRegistry.resolveCurrentTarget();if(!W)throw new Error("화면이 준비된 후 다시 시도하세요.");x(!0);let O=null;try{O=await L(W),await cT(O.canvas,O.target,n.hubUrl),n.onToast("Screenshot saved")}finally{O?.cleanup(),x(!1)}},[L,n.hubUrl,n.onToast,n.sourceRegistry]),H=u.useCallback(async()=>{if(N.current)throw new Error("Stop the timelapse before recording.");const W=n.sourceRegistry.resolveCurrentTarget();if(!W)throw new Error("화면이 준비된 후 다시 시도하세요.");const O=await L(W),le=await Fw({canvas:O.canvas,target:O.target,fps:W.type==="control"?30:15,hubUrl:n.hubUrl,onError:ce=>n.onToast(ce.message)});k.current=O.cleanup,j.current=le,c(Date.now()),n.onToast("Recording started")},[L,n.hubUrl,n.onToast,n.sourceRegistry]),ye=u.useCallback(async()=>{const W=j.current;if(W){x(!0);try{await W.stop(),n.onToast("Recording saved")}finally{j.current=null,k.current?.(),k.current=null,c(0),x(!1)}}},[n.onToast]),de=u.useCallback(async()=>{if(j.current||N.current)throw new Error("Last 30s is unavailable during a recording.");const W=n.sourceRegistry.resolveCurrentTarget();if(!W)throw new Error("화면이 준비된 후 다시 시도하세요.");x(!0);try{await T.current.save(W,n.hubUrl),n.onToast("Last 30 seconds saved")}finally{x(!1)}},[n.hubUrl,n.onToast,n.sourceRegistry]),Z=u.useCallback(async()=>{if(j.current)throw new Error("Stop the recording before starting a timelapse.");const W=n.sourceRegistry.resolveCurrentTarget();if(!W)throw new Error("화면이 준비된 후 다시 시도하세요.");const O=await L(W),le=await fT(O.canvas,O.target,a.timelapseIntervalSeconds,n.hubUrl,ce=>n.onToast(ce.message));M.current=O.cleanup,N.current=le,m(Date.now()),n.onToast("Timelapse started")},[L,n.hubUrl,n.onToast,n.sourceRegistry,a.timelapseIntervalSeconds]),z=u.useCallback(async()=>{const W=N.current;if(W){x(!0);try{await W.stop(),n.onToast("Timelapse saved")}finally{N.current=null,M.current?.(),M.current=null,m(0),x(!1)}}},[n.onToast]);return u.useEffect(()=>{const W=O=>{!j.current&&!N.current||(O.preventDefault(),O.returnValue="")};return window.addEventListener("beforeunload",W),()=>window.removeEventListener("beforeunload",W)},[]),u.useEffect(()=>()=>{T.current.stop(),j.current?.cancel(),N.current?.cancel(),k.current?.(),M.current?.()},[]),{state:u.useMemo(()=>({recording:!!j.current,recordingStartedAt:l,timelapse:!!N.current,timelapseStartedAt:d,bufferSeconds:h,bufferEnabled:a.rollingEnabled,busy:y,targetLabel:$}),[h,y,l,a.rollingEnabled,$,d]),settings:a,videoSupported:q,targetKey:F,setRollingEnabled:Y,setRecordingQuality:G,setTimelapseInterval:P,takeScreenshot:K,startRecording:H,stopRecording:ye,saveLast30Seconds:de,startTimelapse:Z,stopTimelapse:z}}const pT=120,gT=999,Eu=5,Du=30,vT=Number.POSITIVE_INFINITY,Bw="livedesk.remoteDirectory",yp="livedesk.localHubAccessEnabled",yT="livedesk.streamSettings",bT=18,xT="livedesk.controlStreamSettings",wT=8,Pw="livedesk.wallMonitorSelections",Uw=2,Hh=512*1024,bp="".trim(),qw="".trim(),Pb="livedesk-adsense-script",Fh=!!bp&&!!qw,ST=Object.freeze([{code:"ShiftLeft",label:"Shift"},{code:"ControlLeft",label:"Ctrl"},{code:"AltLeft",label:"Alt"},{code:"MetaLeft",label:"Win"}]),CT=1e3/60,$h=1500,kT=650,jT=1800,AT=650,MT=2500,Ub=1500,qb=15e3,NT=6e4,Gb=240,TT=1024,RT=640,ET=360,Vb="Connected LiveDesk clients are updating in batches. Hub will restart after every target reconnects on the requested versions.",yf="LiveDesk is replacing the Hub and verifying the requested version.",bf=5*6e4,DT=5e3,LT=8e3;function ao({label:n,tooltip:a,disabled:i=!1,active:l=!1,danger:c=!1,pressed:d,onClick:m,children:h}){return r.jsx("span",{className:`manual-action-tooltip ${i?"disabled":""}`.trim(),"data-tooltip":a,children:r.jsx("button",{className:`manual-action ${l?"active":""} ${c?"danger":""}`.trim(),onClick:m,disabled:i,"aria-label":n,"aria-pressed":d,type:"button",children:h})})}function _T(n,a){if(a.deviceId!==n.deviceId)return!1;const i=Number(a.browserReceivedEpochMs);if(!Number.isFinite(i)||i<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 so={free:{name:"Free",price:"$0",limit:Eu,audience:"Personal trial",note:"5 devices with a standard ad banner."},ltd:{name:"Plus",price:"$79 LTD",ltd:"$79 LTD",limit:Du,audience:"Creators and homelabs",note:"30 devices, no ads, personal use."},pro:{name:"Pro",price:"$199 LTD",ltd:"$199 LTD",limit:vT,audience:"Business and studios",note:"Commercial use and larger Client walls."}},IT={"mode3-h264-hw":30};function Wb(n,a){const i=m=>{const g=String(m||"").trim().replace(/^v/i,"").match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/);if(!g)return null;const y=g[4]?g[4].split(".").map(x=>/^\d+$/.test(x)?x.length>1&&x.startsWith("0")?Number.NaN:Number(x):x):[];return y.some(x=>typeof x=="number"&&!Number.isFinite(x))?null:{core:[Number(g[1]),Number(g[2]),Number(g[3])],prerelease:y}},l=i(n),c=i(a);if(!l||!c)return!1;for(let m=0;m<3;m+=1){if(l.core[m]>c.core[m])return!0;if(l.core[m]<c.core[m])return!1}if(l.prerelease.length===0||c.prerelease.length===0)return l.prerelease.length===0;const d=Math.max(l.prerelease.length,c.prerelease.length);for(let m=0;m<d;m+=1){const h=l.prerelease[m],g=c.prerelease[m];if(h===void 0||g===void 0)return g===void 0;if(h!==g){if(typeof h=="number"&&typeof g=="number")return h>g;if(typeof h=="number")return!1;if(typeof g=="number"||h>g)return!0;if(h<g)return!1}}return!0}function rs(n,a){return`${n}:${a}`}const zT={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:IT["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},OT={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:30,maxWidth:1920,maxHeight:1080,quality:75,showScreenStatus:!1};function Bh(n,a){if(n.length===0)return 0;const i=[...n].sort((c,d)=>c-d),l=Math.max(0,Math.min(i.length-1,Math.ceil(i.length*a)-1));return i[l]}function Gw(n,a){n.push(a),n.length>Gb&&n.splice(0,n.length-Gb)}function Yb(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 Kb(n,a,i){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),Gw(n.intervalSamplesMs,l)}if(n.lastFrameSeq!==void 0){const l=i-n.lastFrameSeq;l!==1&&(n.seqGapCount+=1,n.maxSeqGap=Math.max(n.maxSeqGap,Math.abs(l)))}n.lastAt=a,n.lastFrameSeq=i}function Qb(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 Xb(n){return!n||n.seqGapCount<=0?"none":`${n.seqGapCount} gaps / max ${n.maxSeqGap}`}function HT(n){return Number.isFinite(n)?String(n):"30+"}const Vw=[1,2,5,8,12,20,30],Zb={large:{maxWidth:1280,maxHeight:720},medium:{maxWidth:960,maxHeight:540},list:{maxWidth:640,maxHeight:360}},Ma={preserveConfiguredFpsDeviceCount:6,visibleRootMargin:"520px 0px 760px 0px",fallbackVisibleCounts:{large:12,medium:18,list:32},maxWallFramesPerSecond:bs.maxDirectFramesPerSecond,maxWallBytesPerSecond:80*1024*1024,maxFrameGapMs:280,lowLoadFrameRatio:.58,lowLoadByteRatio:.52,downshiftCooldownMs:1800,recoveryCooldownMs:14e3,minFps:5},Jb=2200,FT=8e3,$T=3500,BT=7e3,PT=2,UT=7e3,qT=2600,GT=4200,VT=750,WT=2,ex=4200;function tx(n,a){return Math.min(3e4,n*2**Math.min(3,Math.max(0,a)))}function $u(n,a){const i=n.capabilities?.[a];return typeof i=="boolean"?i:/^(1|true|yes|on)$/i.test(String(i||"").trim())}function ha(n){return n.deviceName||n.hostname||n.deviceId}function YT(){return"npx -y --prefer-online livedesk@latest client"}function KT(){return"npx -y --prefer-online livedesk@latest"}function QT(){try{return localStorage.getItem(Bw)||""}catch{return""}}function XT(){try{return localStorage.getItem(yp)==="1"}catch{return!1}}function hc(n){try{n?localStorage.setItem(yp,"1"):localStorage.removeItem(yp)}catch{}}function _r(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function qn(n){const a=_r(n.status),i=_r(a.screens),l=_r(n.capabilities),c=_r(n.latestLiveFrame),d=_r(n.activeLiveStream),h=[a.monitorCount,a.screenCount,i.count,l.monitorCount,l.screenCount,c.monitorCount,d.monitorCount,Array.isArray(i.displays)?i.displays.length:0,Array.isArray(a.displays)?a.displays.length:0,Array.isArray(a.monitors)?a.monitors.length:0].map(Number).filter(g=>Number.isFinite(g)&&g>0).map(g=>Math.max(1,Math.min(64,Math.floor(g))));return h.length>0?Math.max(...h):1}function vl(n){const a=Number(n);return Number.isFinite(a)&&a>0?Math.floor(a):0}function Ww(n){const a=_r(n.status),l=[_r(a.screens).displays,a.displays,a.monitors];for(const c of l)if(!(!Array.isArray(c)||c.length===0))return c.map(d=>_r(d));return[]}function Yw(n,a){const i=Ww(n),l=i.find(g=>Number(g.index)===a)||i[a]||i[0]||{},c=vl(l.width),d=vl(l.height),m=[l.name,l.displayName,l.deviceName,l.id].find(g=>typeof g=="string"&&g.trim()),h=typeof m=="string"?m.trim():`Display ${a+1}`;return{index:a,name:h,width:c,height:d,primary:l.primary===!0||l.isPrimary===!0}}function ZT(n){const a=qn(n);return Array.from({length:a},(i,l)=>Yw(n,l))}function JT(n){const a=Ww(n);if(a.length===0)return"";const i=a.map((l,c)=>{const d=Number(l.index),m=[l.name,l.displayName,l.deviceName,l.id].find(g=>typeof g=="string"&&g.trim()),h=g=>{const y=Number(g);return Number.isFinite(y)?y:null};return[Number.isFinite(d)?Math.floor(d):c,typeof m=="string"?m.trim().toLowerCase():"",h(l.left),h(l.top),h(l.width),h(l.height),l.primary===!0||l.isPrimary===!0]}).sort((l,c)=>l[0]-c[0]);return JSON.stringify(i)}function eR(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 Kw(n,a){const i=Yw(n,a);if(i.width>0&&i.height>0)return{width:i.width,height:i.height};const l=_r(n.status),c=vl(l.screenWidth||l.width),d=vl(l.screenHeight||l.height);return c>0&&d>0?{width:c,height:d}:null}function Qw(n){if(!n)return null;const a=vl(n.sourceWidth)||vl(n.width),i=vl(n.sourceHeight)||vl(n.height);return a>0&&i>0?{width:a,height:i}:null}function tR(n,a,i){const d=((typeof a?.monitorIndex=="number"?Gn(a.monitorIndex,Math.max(1,a.monitorCount||1)):i)===i?Qw(a):null)||Kw(n,i);return d?Math.max(.25,Math.min(4,d.width/d.height)):16/9}const xf=16/9;function Gn(n,a){const i=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(i-1,l)):0}function nR(){try{const n=localStorage.getItem(Pw);if(!n)return{selections:{},topologyFingerprints:{}};const a=JSON.parse(n),i=a&&typeof a=="object"&&!Array.isArray(a)?a.selections:void 0;if(Number(a?.version)!==Uw||!i||typeof i!="object"||Array.isArray(i))return{selections:{},topologyFingerprints:{}};const l={},c={};for(const[d,m]of Object.entries(i)){const h=d.trim(),g=_r(m),y=g.monitorIndex,x=Math.floor(Number(y));if(!h||!Number.isFinite(x))continue;l[h]=Math.max(0,Math.min(63,x));const b=typeof g.topologyFingerprint=="string"?g.topologyFingerprint.trim():"";b&&(c[h]=b)}return{selections:l,topologyFingerprints:c}}catch{return{selections:{},topologyFingerprints:{}}}}function aR(n,a){try{const i=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,{monitorIndex:c,topologyFingerprint:a[l]||""}]));localStorage.setItem(Pw,JSON.stringify({version:Uw,selections:i}))}catch{}}function sR(){return{...zT}}function rR(n){try{localStorage.setItem(yT,JSON.stringify({...n,version:bT}))}catch{}}function iR(){return{...OT}}function lR(n){try{localStorage.setItem(xT,JSON.stringify({...n,version:wT}))}catch{}}function Ph(n,a){return n.length!==a.length?!1:n.every((i,l)=>i===a[l])}function Uh(n){return[...new Set(n.filter(Boolean))].sort()}function oR(n){return Ma.fallbackVisibleCounts[n]||Ma.fallbackVisibleCounts.large}function cR(n,a,i){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=Zb[a]||Zb.large;return{maxWidth:Math.min(n.maxWidth,l.maxWidth),maxHeight:Math.min(n.maxHeight,l.maxHeight)}}function uR(n,a=Ma.minFps){const i=[...Vw].sort((c,d)=>c-d),l=Math.max(a,Math.floor(n/2));return[...i].reverse().find(c=>c<n&&c>=a)||l}function dR(n,a){return[...Vw].sort((l,c)=>l-c).find(l=>l>n&&l<=a)||a}function Lu(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let i=n,l=0;for(;i>=1024&&l<a.length-1;)i/=1024,l+=1;const c=l===0||i>=100?0:1;return`${i.toFixed(c)} ${a[l]}`}function nx(n){if(!Number.isFinite(n)||!n||n<=0)return"0GB";const a=1024**4,i=1024**3;return n>=a?`${Math.max(1,Math.round(n/a))}TB`:`${Math.max(1,Math.round(n/i))}GB`}function qh(n,a){if(!Number.isFinite(n)||!n||n<=0)return"not reported";const i=Math.max(0,n-Math.max(0,Number(a||0)));return`${nx(i)} / ${nx(n)}`}function fR(n){const a=new Uint8Array(n),i=32768;let l="";for(let c=0;c<a.length;c+=i){const d=a.subarray(c,c+i);l+=String.fromCharCode(...d)}return btoa(l)}function ax(n){return Array.from(n).filter(a=>a.size>=0).map(a=>{const i=a.webkitRelativePath||a.name;return{file:a,relativePath:i,fingerprint:`${a.size}:${a.lastModified}`}})}function mR(n){return n===1?"middle":n===2?"right":"left"}function sx(n,...a){for(const i of a){const l=n?.[i];if(typeof l=="string"&&l.trim())return l.trim()}return""}function rx(n){const a=Number(n);return Number.isInteger(a)&&a>=1&&a<=gT?a:0}const hR={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function pR(n,a,i){if(n==="online")return"Online";if(n==="busy")return"Busy";if(n==="stale")return"Stale";if(n==="offline")return"Offline";if(i==="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=hR[c.id]||c.label;return c.value&&c.value!=="-"?`${d} ${c.value}`:d}function Kf(n,a){const i=a.split(".");let l=n;for(const c of i){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 i of a){const l=Kf(n,i),c=Number(l);if(Number.isFinite(c))return c}}function ys(n,...a){for(const i of a){const l=Kf(n,i);if(typeof l=="string"&&l.trim())return l.trim();if(typeof l=="number"&&Number.isFinite(l))return String(l)}return""}function gR(n,...a){for(const i of a){const l=Kf(n,i);if(typeof l=="boolean")return l;if(/^(1|true|yes|on|online|running|ready)$/i.test(String(l||"").trim()))return!0;if(/^(0|false|no|off|offline|stopped|missing)$/i.test(String(l||"").trim()))return!1}}function Mi(n){const a=Number(n);if(Number.isFinite(a))return Math.max(0,Math.min(1,a>1?a/100:a))}function Gh(n,a){if(!(typeof n!="number"||typeof a!="number"||!Number.isFinite(n)||!Number.isFinite(a)||n<=0))return Mi((n-Math.max(0,a))/n)}function pc(n){return n===void 0?"-":`${Math.round(n*100)}%`}function Vh(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 ro(n,a=.92,i=.78){return n===void 0?"unknown":n>=a?"critical":n>=i?"warn":"good"}function vR(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 wf(n,a,i){const l=Kf(n,`tools.${a}`),c=ys(n,`tools.${a}.status`,`tooling.${a}.status`,`${a}.status`).toLowerCase(),d=gR(n,`tools.${a}.running`,`tooling.${a}.running`,`${a}.running`),m=ys(n,`tools.${a}.version`,`tooling.${a}.version`,`${a}.version`),h=ys(n,`tools.${a}.port`,`tooling.${a}.port`,`${a}.port`);let g="unknown";return c==="busy"?g="busy":["online","running","ready","active"].includes(c)||d===!0?g="online":(["offline","stopped","missing","not-found"].includes(c)||d===!1||l===!1)&&(g="offline"),{id:a,label:i,status:g,detail:g==="offline"?"offline":m||(h?`:${h}`:g==="unknown"?"not reported":g)}}function Xw(n){const a=n.status||{},i=xn(a,"cpu.cores","cpuCores","processorCount"),l=xn(a,"loadavg.0","cpu.load1"),c=Mi(xn(a,"cpu.usedRatio","cpu.usageRatio","cpu.ratio","cpu.usedPct","cpu.usagePct","cpu.percent")??(i&&l!==void 0?l/Math.max(1,i):void 0)),d=xn(a,"memory.totalBytes","totalMem"),m=xn(a,"memory.freeBytes","freeMem"),h=Mi(xn(a,"memory.usedRatio","memory.usedPct","usedMemRatio"))??Gh(d,m),g=xn(a,"disk.totalBytes","rootDisk.totalBytes","storage.totalBytes"),y=xn(a,"disk.freeBytes","rootDisk.freeBytes","storage.freeBytes"),x=Mi(xn(a,"disk.usedRatio","disk.usedPct","rootDisk.usedRatio","storage.usedRatio"))??Gh(g,y),b=xn(a,"thermal.cpuC","temperatureC","cpu.temperatureC","gpu.temperatureC"),w=Mi(xn(a,"gpu.usedRatio","gpu.usageRatio","gpu.usedPct","gpu.usagePct","gpu.percent","accelerators.gpu.usageRatio")),A=ys(a,"gpu.name","gpu.model","accelerators.gpu.name"),j=xn(a,"gpu.memory.totalBytes","gpu.totalMemoryBytes","gpu.vramTotalBytes"),k=xn(a,"gpu.memory.freeBytes","gpu.freeMemoryBytes","gpu.vramFreeBytes"),N=Mi(xn(a,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??Gh(j,k),M=xn(a,"gpu.temperatureC","thermal.gpuC"),T=Mi(xn(a,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),D=ys(a,"npu.name","npu.model","accelerators.npu.name"),F=xn(a,"npu.tops","npu.topsInt8","accelerators.npu.tops"),$=xn(a,"network.rxMbps","network.receiveMbps","network.downMbps"),q=xn(a,"network.txMbps","network.transmitMbps","network.upMbps"),L=xn(a,"network.latencyMs","network.rttMs"),Y=Mi(xn(a,"network.usedRatio","network.usageRatio","network.saturationRatio")),G=ys(a,"network.link","network.interface","network.name"),P=Math.max(b??Number.NEGATIVE_INFINITY,M??Number.NEGATIVE_INFINITY),K=Number.isFinite(P)?P:void 0,H=K===void 0?void 0:Mi((K-35)/60),ye=b!==void 0&&M!==void 0?`CPU ${Math.round(b)}° · GPU ${Math.round(M)}°`:b!==void 0?`CPU ${Math.round(b)}°`:M!==void 0?`GPU ${Math.round(M)}°`:"-",de=ys(a,"workload.role","role","lane")||($u(n,"aiAssist")?"Agent worker":$u(n,"taskDispatch")?"Task worker":"Local machine"),Z=ys(n.latestTask,"status")||ys(a,"workload.status")||"idle",z=ys(n.latestTask,"title","instructionPreview")||ys(a,"workload.title"),se=ys(n.latestTask,"resultSummary","error","instructionPreview")||ys(a,"workload.summary"),W=[wf(a,"ollama","Ollama"),wf(a,"lmStudio","LM Studio"),wf(a,"comfyui","ComfyUI"),wf(a,"stableDiffusion","Stable Diffusion")],O=W.some(fe=>fe.status!=="unknown"),le=Date.parse(n.lastSeenAt||n.connectedAt||""),ce=Number.isFinite(le)?Date.now()-le:0;let Q="online";n.connected?ce>5*6e4?Q="stale":(b??0)>=86||(M??0)>=88||(c??0)>=.94||(w??0)>=.96||(N??0)>=.96||(T??0)>=.96||(h??0)>=.94||(x??0)>=.94||(L??0)>=200||Z==="failed"?Q="critical":(b??0)>=78||(M??0)>=80||(c??0)>=.82||(w??0)>=.86||(N??0)>=.88||(T??0)>=.86||(h??0)>=.82||(x??0)>=.86||(L??0)>=80?Q="warn":(["queued","running","targeted"].includes(Z)||W.some(fe=>fe.status==="busy"))&&(Q="busy"):Q="offline";const be=W.filter(fe=>fe.status==="online"||fe.status==="busy").length,he=[{id:"cpu",label:"CPU",value:pc(c),detail:i?`${i} cores`:l!==void 0?`load ${l.toFixed(1)}`:"not reported",ratio:c,state:ro(c,.92,.78)},{id:"memory",label:"RAM",value:pc(h),detail:qh(d,m),ratio:h,state:ro(h,.92,.78)},{id:"disk",label:"DISK",value:pc(x),detail:qh(g,y),ratio:x,state:ro(x,.92,.82)},{id:"gpu",label:"GPU",value:pc(w),detail:A||(j&&k!==void 0?`${Lu(k)} VRAM free`:M!==void 0?`${Math.round(M)}C`:"not reported"),ratio:w,state:M!==void 0&&M>=88?"critical":M!==void 0&&M>=80?"warn":ro(w,.96,.86)},{id:"vram",label:"VRAM",value:pc(N),detail:qh(j,k),ratio:N,state:ro(N,.96,.88)},{id:"npu",label:"NPU",value:T!==void 0?pc(T):F!==void 0?`${Math.round(F)} TOPS`:"-",detail:D||(F!==void 0?"neural engine":"not reported"),ratio:T,state:ro(T,.96,.86)},{id:"temp",label:"TEMP",value:ye,detail:be>0?`${be} local tools`:`uptime ${vR(xn(a,"uptimeSec"))}`,ratio:H,state:K===void 0?"unknown":K>=86?"critical":K>=78?"warn":"good"},{id:"network",label:"NET",value:Vh($)||(L!==void 0?`${Math.round(L)}ms`:G||"-"),detail:Vh(q)?`${Vh(q)} up`:G||"not reported",ratio:Y,state:L!==void 0&&L>=200?"critical":L!==void 0&&L>=80?"warn":ro(Y,.9,.75)}];return{state:Q,label:pR(Q,he,Z),role:de,taskLabel:z||(Z==="idle"?"idle":Z),taskStatus:Z,taskSummary:se,tools:O?W:W.map(fe=>({...fe,detail:"not reported"})),metrics:he}}const yR=[{id:"list",label:"List"},{id:"medium",label:"Small"},{id:"large",label:"Large"}],bR=[{id:"sync-server",label:"Hub",icon:zr,accent:"blue",tooltip:"hub"},{id:"wall",label:"Wall",icon:I0,accent:"blue",tooltip:"wall"},{id:"control",label:"Control",icon:Xh,accent:"red",tooltip:"control"},{id:"share-files",label:"Share Files",icon:Sf,accent:"green",tooltip:"share-files"},{id:"agents",label:"Agents",icon:Zh,accent:"violet",tooltip:"agents"}],xR=[{id:"doc",label:"Doc",icon:Tf,accent:"amber"},{id:"support",label:"Support",icon:_u,accent:"violet"},{id:"pricing",label:"Pricing",icon:Iu,accent:"green"}];function wR(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 hn(n){return wR(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 io(n){return n.map(a=>hn(a))}function ja(n){return{languageName:n.languageName,languageLabel:n.languageLabel,eyebrow:n.eyebrow,title:hn(n.title),intro:hn(n.intro),sections:[{title:hn(n.managerTitle),body:hn(n.managerBody),points:io(n.managerPoints)},{title:hn(n.clientTitle),body:hn(n.clientBody),points:io(n.clientPoints)},{title:hn(n.syncTitle),body:hn(n.syncBody),points:io(n.syncPoints)},...n.agentTitle&&n.agentBody&&n.agentPoints?[{title:hn(n.agentTitle),body:hn(n.agentBody),points:io(n.agentPoints)}]:[],{title:hn(n.platformTitle),body:hn(n.platformBody),points:io(n.platformPoints)}],sync:{title:hn(n.syncTitle),body:hn(n.syncBody),points:io(n.syncPoints)},firewall:{title:hn(n.firewallTitle),body:hn(n.firewallBody),points:io(n.firewallPoints)},commands:{title:hn(n.commandsTitle),body:hn(n.commandsBody),manager:hn(n.managerCommandLabel),primary:hn(n.clientCommandLabel),slot:hn(n.slotCommandLabel),manual:hn(n.manualCommandLabel)}}}const wc={ko:ja({languageName:"한국어",languageLabel:"문서 언어",eyebrow:"LiveDesk Manual",title:"한 줄로 여는 로컬 Screen Wall",intro:"LiveDesk는 매니저 PC 한 대에서 여러 작업 PC, AI 박스, 맥미니, 개발 장비를 한 화면에 모니터링하고 필요한 제어를 실행하는 npm-first 원격 작업 데크입니다.",managerTitle:"1. 매니저 실행",managerBody:"화면을 모아 볼 컴퓨터에서 LiveDesk 매니저를 실행합니다. 매니저는 UI와 로컬 서버를 같이 열고 브라우저를 http://127.0.0.1:5179 로 띄웁니다.",managerPoints:["명령은 npx -y livedesk 입니다.","매니저는 Screen Wall/API 포트 5179와 클라이언트 접속 포트 5197을 사용합니다.","기존 LiveDesk 포트가 남아 있으면 기본적으로 정리하고 새로 시작합니다. 필요하면 --no-clean 을 붙입니다."],clientTitle:"2. 워크스테이션 연결",clientBody:"모니터링할 PC에서는 Google 로그인 또는 Hub 화면의 6자리 PIN으로 연결합니다. Hub가 꺼져 있으면 실시간 온라인 알림을 기다리고 적응형 간격으로 다시 확인합니다.",clientPoints:["빈 자리에 자동 배치하려면 npx -y livedesk client 를 실행합니다.","자리 번호를 고정하려면 npx -y livedesk client 3 처럼 번호를 붙입니다.","브라우저 연결 페이지에서 Google 버튼 또는 6자리 PIN 입력 중 하나를 선택합니다."],syncTitle:"3. Sync Server와 자동 발견",syncBody:"Sync Server는 이 매니저를 현재 계정의 활성 Screen Wall로 Supabase에 등록합니다. 클라이언트는 같은 Google 계정으로 로그인한 뒤 그 기록을 읽고 접속 후보들을 순서대로 시도합니다.",syncPoints:["등록 정보에는 host instance, LAN/private 주소, public 후보 주소, pair token, 짧은 lease가 포함됩니다.","같은 LAN 후보를 먼저 쓰고, 필요하면 외부 주소 후보를 시도합니다.","매니저 위치, VPN, 방화벽, 공유기 설정이 바뀌었거나 개발 중 활성 매니저를 바꿀 때 Sync Server를 누릅니다.","이제 livedesk.pages.dev의 Chrome Local Network Access 허용은 기본 실행 경로가 아닙니다. npm 매니저 앱이 실제 서버입니다."],agentTitle:"4. Agent로 여러 장비 작업하기",agentBody:"Agents 화면은 Hub에서 실행되는 Codex 기반 Agent가 연결된 장비를 확인하고, 선택한 권한 범위 안에서 작업을 실행하는 공간입니다. 클라이언트 PC에 Codex 앱이나 Codex SDK를 설치할 필요는 없습니다.",agentPoints:["Suggested tasks에는 현재 72개의 읽기·운영 작업 템플릿이 있으며, 검색과 권한·플랫폼·capability 조건으로 실행 가능 항목을 안내합니다.","Ask, Safe Auto, Full Access, Custom 권한 모드를 선택할 수 있습니다. 위험한 변경 작업은 승인 카드와 장비 capability 검사를 거칩니다.","All connected 또는 Selected로 대상 장비를 제한하고, 결과는 장비별 상태 칩과 실제 RAM·디스크·GPU·프로세스 요약으로 확인합니다.","Agent 실행은 Hub의 격리된 runtime과 LiveDesk MCP 도구를 통해서만 장비에 전달되며, 모든 작업은 timeout·취소·tool limit·감사 로그 경계를 가집니다."],platformTitle:"5. 현재 플랫폼과 스트림 상태",platformBody:"Windows의 Wall, Control, 파일 전송, 원격 오디오와 RemoteFast 경로를 현재 기준으로 확인했습니다. macOS와 Linux는 같은 npm 명령 경로를 유지하면서 권한과 캡처 백엔드를 확장하고 있습니다.",platformPoints:["자동 Wall과 Control은 모든 Client에서 직접 H.264를 사용합니다. RGB565/LZO Atlas는 내부 진단 실험에만 남고 자동 전송 경로에는 사용되지 않습니다.","원격 오디오는 선택한 장비가 capability를 광고할 때 사용할 수 있으며, 브라우저는 queue·drop·resync·automatic restart 상태를 진단합니다.","macOS: 화면 캡처와 제어에는 Screen Recording/Accessibility 권한이 필요합니다. RemoteFast 로그는 필요한 상태 중심으로 제한됩니다.","Linux: linux-x64 runtime, X11/XTEST 입력과 PipeWire/PulseAudio 기본 출력 오디오 캡처를 지원합니다."],firewallTitle:"방화벽과 외부 장소 연결",firewallBody:"같은 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:ja({languageName:"English",languageLabel:"Document language",eyebrow:"LiveDesk Manual",title:"Open a local Screen Wall with one command",intro:"LiveDesk is an npm-first remote work deck for monitoring many Clients, AI boxes, Mac minis, and dev machines from one manager PC.",managerTitle:"1. Run the manager",managerBody:"Run LiveDesk on the computer that will watch the screens. The manager starts the UI and local server together, then opens http://127.0.0.1:5179.",managerPoints:["The command is npx -y livedesk.","The manager uses port 5179 for the Screen Wall/API and port 5197 for client connections.","If an old LiveDesk process still owns those ports, startup cleans it by default. Add --no-clean when you want to keep it."],clientTitle:"2. Connect a Client",clientBody:"On each monitored computer, connect with Google sign-in or the 6-digit PIN shown on the Hub screen. If no manager is online yet, the client waits for a live online signal and falls back to adaptive retries.",clientPoints:["Run npx -y livedesk client for first available placement.","Run npx -y livedesk client 3 to pin the machine to slot 3.","The browser connection page lets you choose Google or a 6-digit PIN."],syncTitle:"3. Sync Server and discovery",syncBody:"Sync Server publishes this manager as the active Screen Wall for the signed-in account. Clients read that Supabase record after Google sign-in and try the endpoint candidates in order.",syncPoints:["The record includes host instance, LAN/private addresses, public endpoint candidates, pair token, and a short lease.","LAN candidates are preferred first, then public candidates if needed.","Press Sync Server after manager moves, VPN/firewall/router changes, or when this development machine should take over as active manager.","Chrome Local Network Access on livedesk.pages.dev is no longer the default runtime path. The npm manager app is the real server."],agentTitle:"4. Run multi-Client tasks with Agent",agentBody:"The Agents page runs a Codex-based Agent in the Hub to inspect connected Clients and perform actions within the selected permission scope. Client PCs do not need the Codex app or Codex SDK installed.",agentPoints:["Suggested tasks currently contains 72 read-only and operational templates with search plus permission, platform, and capability availability checks.","Choose Ask, Safe Auto, Full Access, or Custom. Risky changes go through approval cards and explicit client capability checks.","Limit targets with All connected or Selected. Results use compact per-device status chips and show real RAM, disk, GPU, and process summaries.","Runs stay inside the Hub-isolated runtime and LiveDesk MCP tools, with timeout, cancellation, tool-call limits, and audit-log boundaries."],platformTitle:"5. Current platform and stream state",platformBody:"Windows Wall, Control, file transfer, remote audio, and the RemoteFast path are verified against the current implementation. macOS and Linux keep the same npm command path while capture and permission backends expand.",platformPoints:["Automatic Wall and Control use direct H.264 for every Client. The RGB565/LZO Atlas remains only for internal diagnostic experiments and is never selected automatically.","Remote audio is available when the selected Client advertises the capability, with queue, drop, resync, and automatic-restart diagnostics in the browser.","macOS requires Screen Recording and Accessibility permissions for capture and control. RemoteFast logs focus on actionable state.","Linux includes the linux-x64 runtime, X11/XTEST input, and default-output audio capture through PipeWire or PulseAudio."],firewallTitle:"Firewall and remote locations",firewallBody:"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 Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ja:ja({languageName:"日本語",languageLabel:"ドキュメント言語",eyebrow:"LiveDesk Manual",title:"1行でローカル Screen Wall を開く",intro:"LiveDesk は、複数の作業 PC、AI マシン、Mac mini、開発機を1台の manager PC から監視する npm-first のリモート作業デッキです。",managerTitle:"1. manager を実行",managerBody:"画面を集めて見るコンピューターで LiveDesk manager を実行します。UI とローカルサーバーが同時に起動し、http://127.0.0.1:5179 が開きます。",managerPoints:["コマンドは npx -y livedesk です。","Screen Wall/API は 5179、client 接続は 5197 を使います。","古い LiveDesk プロセスがポートを使っている場合は、基本的に自動で整理して起動します。"],clientTitle:"2. Client を接続",clientBody:"監視される PC で同じ Google アカウントにログインします。manager がまだ無い場合、client はオンライン通知を待ち、適応型の間隔で再確認します。",clientPoints:["空きスロットに入れるには npx -y livedesk client を実行します。","スロットを固定するには npx -y livedesk client 3 のように番号を付けます。","大量の PC でも再ログインなしで待ち続けます。"],syncTitle:"3. Sync Server と自動検出",syncBody:"Sync Server はこの manager を現在の Google アカウントの active Screen Wall として Supabase に登録します。",syncPoints:["host instance、LAN/private アドレス、public 候補、pair token、短い lease を登録します。","client は LAN 候補を優先し、必要なら public 候補も試します。","VPN、firewall、router、manager の場所が変わったら Sync Server を押します。","livedesk.pages.dev の Chrome Local Network Access は標準実行経路ではありません。npm manager アプリが実際のサーバーです。"],platformTitle:"4. 現在のプラットフォーム状態",platformBody:"Windows は live screen transfer まで確認済みです。macOS と Linux も同じ npm コマンド経路を目標に対応を広げています。",platformPoints:["Windows: 動作確認済み。","macOS: 画面取得と制御には Screen Recording/Accessibility 権限が必要です。","Linux: linux-x64 runtime、grim/gnome-screenshot/import/scrot capture、X11/XTEST input backend を追加済み。audio は未対応です。"],firewallTitle:"Firewall と外部拠点",firewallBody:"同じ 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:"Client 接続",slotCommandLabel:"slot 3 に固定",manualCommandLabel:"高度な手動接続"}),"zh-CN":ja({languageName:"简体中文",languageLabel:"文档语言",eyebrow:"LiveDesk Manual",title:"用一条命令打开本地 Screen Wall",intro:"LiveDesk 是 npm-first 的远程工作台,用一台 manager PC 监控多台工作站、AI 主机、Mac mini 和开发机器。",managerTitle:"1. 运行 manager",managerBody:"在负责查看屏幕的电脑上运行 LiveDesk manager。它会同时启动 UI 和本地服务器,并打开 http://127.0.0.1:5179。",managerPoints:["命令是 npx -y livedesk。","Screen Wall/API 使用 5179,client 连接使用 5197。","如果旧的 LiveDesk 进程占用端口,默认会清理后重新启动。"],clientTitle:"2. 连接 Client",clientBody:"在被监控的电脑上使用同一个 Google 账号登录。如果 manager 尚未在线,client 会等待上线通知,并以自适应间隔重新检查。",clientPoints:["自动放入空位: npx -y livedesk client。","固定到 3 号位置: npx -y livedesk client 3。","大量电脑也可以持续等待,不需要反复登录。"],syncTitle:"3. Sync Server 和自动发现",syncBody:"Sync Server 会把当前 manager 作为该账号的 active Screen Wall 写入 Supabase。client 登录后读取记录并依次尝试连接候选地址。",syncPoints:["记录包括 host instance、LAN/private 地址、public 候选、pair token 和短 lease。","优先尝试同一 LAN 地址,需要时再尝试外部地址。","manager 位置、VPN、防火墙或路由变化后请点击 Sync Server。","livedesk.pages.dev 的 Chrome Local Network Access 不再是默认运行方式。npm manager app 才是真正服务器。"],platformTitle:"4. 当前平台状态",platformBody:"Windows 已确认可传输实时画面。macOS 和 Linux 正按同一 npm 命令路径扩展支持。",platformPoints:["Windows: 已确认可用。","macOS: 画面捕获和控制需要 Screen Recording/Accessibility 权限。","Linux: 已加入 linux-x64 runtime、grim/gnome-screenshot/import/scrot 捕获、X11/XTEST 输入后端。音频尚未启用。"],firewallTitle:"防火墙和外部地点",firewallBody:"同一 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:"连接 Client",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"高级手动连接"}),"zh-TW":ja({languageName:"繁體中文",languageLabel:"文件語言",eyebrow:"LiveDesk Manual",title:"用一行指令開啟本機 Screen Wall",intro:"LiveDesk 是 npm-first 的遠端工作台,用一台 manager PC 監看多台工作站、AI 主機、Mac mini 與開發機。",managerTitle:"1. 執行 manager",managerBody:"在負責看畫面的電腦上執行 LiveDesk manager。它會同時啟動 UI 與本機伺服器,並開啟 http://127.0.0.1:5179。",managerPoints:["指令是 npx -y livedesk。","Screen Wall/API 使用 5179,client 連線使用 5197。","若舊的 LiveDesk 程序占用連接埠,預設會清理後重新啟動。"],clientTitle:"2. 連接 Client",clientBody:"在被監看的電腦上使用同一個 Google 帳號登入。如果 manager 尚未上線,client 會等待上線通知,並以自適應間隔重新檢查。",clientPoints:["自動放入空位: npx -y livedesk client。","固定到 3 號位置: npx -y livedesk client 3。","大量電腦也能持續等待,不需要反覆登入。"],syncTitle:"3. Sync Server 與自動探索",syncBody:"Sync Server 會把目前 manager 登錄為此帳號的 active Screen Wall。client 登入後讀取 Supabase 記錄並依序嘗試連線候選地址。",syncPoints:["記錄包含 host instance、LAN/private 位址、public 候選、pair token 與短 lease。","優先嘗試 LAN 位址,需要時再嘗試外部位址。","manager 位置、VPN、防火牆或路由設定改變後請按 Sync Server。","livedesk.pages.dev 的 Chrome Local Network Access 不再是預設執行路徑。npm manager app 才是真正伺服器。"],platformTitle:"4. 目前平台狀態",platformBody:"Windows 已確認可傳輸即時畫面。macOS 與 Linux 也沿用相同 npm 指令路徑擴充支援。",platformPoints:["Windows: 已確認可用。","macOS: 畫面擷取與控制需要 Screen Recording/Accessibility 權限。","Linux: 已加入 linux-x64 runtime、grim/gnome-screenshot/import/scrot capture、X11/XTEST input backend。音訊尚未啟用。"],firewallTitle:"防火牆與外部地點",firewallBody:"同一 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:"連接 Client",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"進階手動連線"}),es:ja({languageName:"Español",languageLabel:"Idioma del documento",eyebrow:"LiveDesk Manual",title:"Abre un Screen Wall local con un comando",intro:"LiveDesk es una consola npm-first para vigilar muchas estaciones, cajas de IA, Mac mini y equipos de desarrollo desde un PC manager.",managerTitle:"1. Ejecuta el manager",managerBody:"Ejecuta LiveDesk en el equipo que verá las pantallas. El manager inicia la UI y el servidor local juntos y abre http://127.0.0.1:5179.",managerPoints:["El comando es npx -y livedesk.","El manager usa 5179 para Screen Wall/API y 5197 para conexiones client.","Si un proceso antiguo ocupa los puertos, el arranque lo limpia por defecto."],clientTitle:"2. Conecta una Client",clientBody:"En cada equipo monitoreado, inicia sesión con la misma cuenta Google. Si el manager aún no está activo, el client espera una señal en tiempo real y vuelve a comprobar con intervalos adaptativos.",clientPoints:["Usa npx -y livedesk client para el primer slot libre.","Usa npx -y livedesk client 3 para fijar el equipo al slot 3.","Los clients siguen esperando para no repetir login en muchas máquinas."],syncTitle:"3. Sync Server y descubrimiento",syncBody:"Sync Server publica este manager como Screen Wall activo para la cuenta. Los clients leen el registro en Supabase y prueban los endpoints.",syncPoints:["Incluye host instance, direcciones LAN/private, candidatos public, pair token y lease corto.","Primero se prueban candidatos LAN, luego públicos si hace falta.","Pulsa Sync Server después de cambios de manager, VPN, firewall o router.","Chrome Local Network Access en livedesk.pages.dev ya no es el flujo principal. La app npm manager es el servidor real."],platformTitle:"4. Estado de plataformas",platformBody:"Windows ya fue verificado con transferencia de pantalla. macOS y Linux siguen el mismo camino npm.",platformPoints:["Windows: verificado.","macOS: captura y control requieren permisos Screen Recording/Accessibility.","Linux: runtime linux-x64, entrada X11/XTEST y audio de salida mediante PipeWire o PulseAudio."],firewallTitle:"Firewall y sedes remotas",firewallBody:"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 Client",slotCommandLabel:"Fijar al slot 3",manualCommandLabel:"Conexión manual avanzada"}),fr:ja({languageName:"Français",languageLabel:"Langue du document",eyebrow:"LiveDesk Manual",title:"Ouvrir un Screen Wall local en une commande",intro:"LiveDesk est un deck npm-first pour surveiller plusieurs postes, machines IA, Mac mini et machines dev depuis un PC manager.",managerTitle:"1. Lancer le manager",managerBody:"Lancez LiveDesk sur l’ordinateur qui observe les écrans. Le manager démarre l’UI et le serveur local, puis ouvre http://127.0.0.1:5179.",managerPoints:["La commande est npx -y livedesk.","Le manager utilise 5179 pour Screen Wall/API et 5197 pour les connexions client.","Si un ancien processus utilise les ports, le démarrage le nettoie par défaut."],clientTitle:"2. Connecter une Client",clientBody:"Sur chaque ordinateur surveillé, connectez-vous avec le même compte Google. Si le manager n’est pas encore actif, le client réessaie toutes les 5 secondes.",clientPoints:["Utilisez npx -y livedesk client pour le premier slot libre.","Utilisez npx -y livedesk client 3 pour fixer la machine au slot 3.","Les clients continuent d’attendre pour éviter les reconnexions répétées."],syncTitle:"3. Sync Server et découverte",syncBody:"Sync Server publie ce manager comme Screen Wall actif du compte. Les clients lisent l’enregistrement Supabase et testent les endpoints.",syncPoints:["Il contient host instance, adresses LAN/private, candidats public, pair token et lease court.","Les candidats LAN sont essayés en premier, puis les candidats publics si besoin.","Cliquez Sync Server après un changement de manager, VPN, firewall ou routeur.","Chrome Local Network Access sur livedesk.pages.dev n’est plus le chemin par défaut. L’app npm manager est le vrai serveur."],platformTitle:"4. État des plateformes",platformBody:"Windows est vérifié avec transfert d’écran live. macOS et Linux suivent le même chemin npm.",platformPoints:["Windows: vérifié.","macOS: capture et contrôle nécessitent Screen Recording/Accessibility.","Linux: runtime linux-x64, entrée X11/XTEST et audio de sortie via PipeWire ou PulseAudio."],firewallTitle:"Firewall et sites distants",firewallBody:"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 Client",slotCommandLabel:"Fixer au slot 3",manualCommandLabel:"Connexion manuelle avancée"}),de:ja({languageName:"Deutsch",languageLabel:"Dokumentsprache",eyebrow:"LiveDesk Manual",title:"Lokale Screen Wall mit einem Befehl öffnen",intro:"LiveDesk ist ein npm-first Arbeitsdeck, um viele Clients, AI-Boxen, Mac minis und Dev-Rechner von einem Manager-PC zu überwachen.",managerTitle:"1. Manager starten",managerBody:"Starte LiveDesk auf dem Computer, der die Screens sieht. Der Manager startet UI und lokalen Server zusammen und öffnet http://127.0.0.1:5179.",managerPoints:["Der Befehl ist npx -y livedesk.","Der Manager nutzt 5179 für Screen Wall/API und 5197 für Client-Verbindungen.","Wenn alte LiveDesk-Prozesse Ports belegen, werden sie beim Start standardmäßig bereinigt."],clientTitle:"2. Client verbinden",clientBody:"Melde dich auf jedem überwachten Computer mit demselben Google-Konto an. Wenn kein Manager online ist, wartet der Client auf ein Live-Signal und prüft mit adaptiven Intervallen erneut.",clientPoints:["npx -y livedesk client nutzt den ersten freien Slot.","npx -y livedesk client 3 fixiert den Rechner auf Slot 3.","Clients warten weiter, damit große Setups kein wiederholtes Login brauchen."],syncTitle:"3. Sync Server und Discovery",syncBody:"Sync Server veröffentlicht diesen Manager als aktive Screen Wall des Kontos. Clients lesen den Supabase-Eintrag und testen Endpoints der Reihe nach.",syncPoints:["Enthält host instance, LAN/private Adressen, public Kandidaten, pair token und kurze lease.","LAN-Kandidaten werden zuerst versucht, danach public Kandidaten.","Nach Änderungen an Manager, VPN, Firewall oder Router Sync Server drücken.","Chrome Local Network Access auf livedesk.pages.dev ist nicht mehr der Standardpfad. Die npm Manager App ist der echte Server."],platformTitle:"4. Plattformstatus",platformBody:"Windows wurde mit Live-Screen-Transfer geprüft. macOS und Linux folgen demselben npm-Pfad.",platformPoints:["Windows: verifiziert.","macOS: Capture und Control brauchen Screen Recording/Accessibility Rechte.","Linux: linux-x64 Runtime, X11/XTEST Eingabe und Ausgangsaudio über PipeWire oder PulseAudio."],firewallTitle:"Firewall und entfernte Standorte",firewallBody:"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:"Client verbinden",slotCommandLabel:"An Slot 3 fixieren",manualCommandLabel:"Erweiterte manuelle Verbindung"}),"pt-BR":ja({languageName:"Português",languageLabel:"Idioma do documento",eyebrow:"LiveDesk Manual",title:"Abra um Screen Wall local com um comando",intro:"LiveDesk é um deck npm-first para monitorar várias estações, caixas de IA, Mac minis e máquinas dev a partir de um PC manager.",managerTitle:"1. Execute o manager",managerBody:"Rode LiveDesk no computador que verá as telas. O manager inicia a UI e o servidor local juntos e abre http://127.0.0.1:5179.",managerPoints:["O comando é npx -y livedesk.","O manager usa 5179 para Screen Wall/API e 5197 para conexões client.","Se um processo antigo ocupa as portas, a inicialização limpa por padrão."],clientTitle:"2. Conecte uma Client",clientBody:"Em cada computador monitorado, entre com a mesma conta Google. Se o manager ainda não estiver online, o client aguarda um sinal em tempo real e verifica novamente em intervalos adaptativos.",clientPoints:["Use npx -y livedesk client para o primeiro slot livre.","Use npx -y livedesk client 3 para fixar no slot 3.","Clients continuam tentando para evitar login repetido em muitos PCs."],syncTitle:"3. Sync Server e descoberta",syncBody:"Sync Server publica este manager como Screen Wall ativo da conta. Clients leem o registro no Supabase e testam endpoints.",syncPoints:["Inclui host instance, endereços LAN/private, candidatos public, pair token e lease curto.","Candidatos LAN vêm primeiro; public depois se necessário.","Clique Sync Server após mudanças de manager, VPN, firewall ou roteador.","Chrome Local Network Access em livedesk.pages.dev não é mais o caminho padrão. O app npm manager é o servidor real."],platformTitle:"4. Estado das plataformas",platformBody:"Windows foi verificado com transferência de tela. macOS e Linux seguem o mesmo caminho npm.",platformPoints:["Windows: verificado.","macOS: captura e controle precisam de permissões Screen Recording/Accessibility.","Linux: runtime linux-x64, captura grim/gnome-screenshot/import/scrot e entrada X11/XTEST adicionados. Áudio ainda desativado."],firewallTitle:"Firewall e locais remotos",firewallBody:"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 Client",slotCommandLabel:"Fixar no slot 3",manualCommandLabel:"Conexão manual avançada"}),it:ja({languageName:"Italiano",languageLabel:"Lingua documento",eyebrow:"LiveDesk Manual",title:"Apri uno Screen Wall locale con un comando",intro:"LiveDesk è un deck npm-first per monitorare Client, box AI, Mac mini e macchine dev da un solo PC manager.",managerTitle:"1. Avvia il manager",managerBody:"Esegui LiveDesk sul computer che guarderà gli schermi. Il manager avvia UI e server locale e apre http://127.0.0.1:5179.",managerPoints:["Il comando è npx -y livedesk.","Il manager usa 5179 per Screen Wall/API e 5197 per connessioni client.","Se vecchi processi occupano le porte, l’avvio le pulisce di default."],clientTitle:"2. Connetti una Client",clientBody:"Su ogni computer monitorato, accedi con lo stesso account Google. Se il manager non è online, il client riprova ogni 5 secondi.",clientPoints:["npx -y livedesk client usa il primo slot libero.","npx -y livedesk client 3 fissa la macchina allo slot 3.","I client continuano a provare per evitare login ripetuti."],syncTitle:"3. Sync Server e discovery",syncBody:"Sync Server pubblica questo manager come Screen Wall attivo dell’account. I client leggono Supabase e provano gli endpoint.",syncPoints:["Include host instance, indirizzi LAN/private, candidati public, pair token e lease breve.","Prima LAN, poi public se necessario.","Premi Sync Server dopo cambi di manager, VPN, firewall o router.","Chrome Local Network Access su livedesk.pages.dev non è più il percorso principale. L’app npm manager è il server reale."],platformTitle:"4. Stato piattaforme",platformBody:"Windows è verificato con trasferimento schermo live. macOS e Linux seguono lo stesso percorso npm.",platformPoints:["Windows: verificato.","macOS: capture e control richiedono permessi Screen Recording/Accessibility.","Linux: aggiunti runtime linux-x64, capture grim/gnome-screenshot/import/scrot e input X11/XTEST. Audio disattivato."],firewallTitle:"Firewall e sedi remote",firewallBody:"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 Client",slotCommandLabel:"Fissa allo slot 3",manualCommandLabel:"Connessione manuale avanzata"}),id:ja({languageName:"Bahasa Indonesia",languageLabel:"Bahasa dokumen",eyebrow:"LiveDesk Manual",title:"Buka Screen Wall lokal dengan satu perintah",intro:"LiveDesk adalah deck npm-first untuk memantau banyak Client, AI box, Mac mini, dan mesin dev dari satu PC manager.",managerTitle:"1. Jalankan manager",managerBody:"Jalankan LiveDesk di komputer yang melihat layar. Manager membuka UI dan server lokal bersama, lalu membuka http://127.0.0.1:5179.",managerPoints:["Perintahnya npx -y livedesk.","Manager memakai 5179 untuk Screen Wall/API dan 5197 untuk koneksi client.","Jika proses lama memakai port itu, startup membersihkannya secara default."],clientTitle:"2. Hubungkan Client",clientBody:"Di komputer yang dipantau, masuk dengan akun Google yang sama. Jika manager belum online, client tetap mencoba tiap 5 detik.",clientPoints:["npx -y livedesk client memakai slot kosong pertama.","npx -y livedesk client 3 mengunci mesin ke slot 3.","Client terus mencoba agar banyak PC tidak perlu login berulang."],syncTitle:"3. Sync Server dan discovery",syncBody:"Sync Server menerbitkan manager ini sebagai Screen Wall aktif untuk akun. Client membaca Supabase dan mencoba endpoint.",syncPoints:["Berisi host instance, alamat LAN/private, kandidat public, pair token, dan lease pendek.","Kandidat LAN dicoba lebih dulu, lalu public jika perlu.","Tekan Sync Server setelah perubahan manager, VPN, firewall, atau router.","Chrome Local Network Access di livedesk.pages.dev bukan jalur utama lagi. App npm manager adalah server sebenarnya."],platformTitle:"4. Status platform",platformBody:"Windows sudah diverifikasi dengan live screen transfer. macOS dan Linux mengikuti jalur npm yang sama.",platformPoints:["Windows: terverifikasi.","macOS: capture dan control perlu izin Screen Recording/Accessibility.","Linux: runtime linux-x64, capture grim/gnome-screenshot/import/scrot, dan input X11/XTEST sudah ditambahkan. Audio belum aktif."],firewallTitle:"Firewall dan lokasi luar",firewallBody:"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 Client",slotCommandLabel:"Kunci ke slot 3",manualCommandLabel:"Koneksi manual lanjutan"}),vi:ja({languageName:"Tiếng Việt",languageLabel:"Ngôn ngữ tài liệu",eyebrow:"LiveDesk Manual",title:"Mở Screen Wall cục bộ bằng một lệnh",intro:"LiveDesk là deck npm-first để giám sát nhiều Client, máy AI, Mac mini và máy dev từ một PC manager.",managerTitle:"1. Chạy manager",managerBody:"Chạy LiveDesk trên máy dùng để xem màn hình. Manager khởi động UI và server cục bộ cùng lúc, rồi mở http://127.0.0.1:5179.",managerPoints:["Lệnh là npx -y livedesk.","Manager dùng 5179 cho Screen Wall/API và 5197 cho kết nối client.","Nếu tiến trình cũ giữ port, startup mặc định sẽ dọn và khởi động lại."],clientTitle:"2. Kết nối Client",clientBody:"Trên mỗi máy được giám sát, đăng nhập cùng tài khoản Google. Nếu manager chưa online, client tiếp tục thử mỗi 5 giây.",clientPoints:["npx -y livedesk client dùng slot trống đầu tiên.","npx -y livedesk client 3 ghim máy vào slot 3.","Client tiếp tục chờ để nhiều máy không cần đăng nhập lại."],syncTitle:"3. Sync Server và tự phát hiện",syncBody:"Sync Server đăng manager này là Screen Wall đang hoạt động của tài khoản. Client đọc Supabase và thử các endpoint.",syncPoints:["Bao gồm host instance, địa chỉ LAN/private, public candidate, pair token và lease ngắn.","Ưu tiên LAN trước, sau đó thử public nếu cần.","Bấm Sync Server sau thay đổi manager, VPN, firewall hoặc router.","Chrome Local Network Access trên livedesk.pages.dev không còn là đường chạy chính. App npm manager mới là server thật."],platformTitle:"4. Trạng thái nền tảng",platformBody:"Windows đã được kiểm chứng với truyền màn hình live. macOS và Linux đi theo cùng đường npm.",platformPoints:["Windows: đã kiểm chứng.","macOS: capture và control cần quyền Screen Recording/Accessibility.","Linux: đã thêm runtime linux-x64, capture grim/gnome-screenshot/import/scrot và input X11/XTEST. Audio chưa bật."],firewallTitle:"Firewall và địa điểm ngoài",firewallBody:"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 Client",slotCommandLabel:"Ghim vào slot 3",manualCommandLabel:"Kết nối thủ công nâng cao"}),th:ja({languageName:"ไทย",languageLabel:"ภาษาของเอกสาร",eyebrow:"LiveDesk Manual",title:"เปิด Screen Wall ภายในด้วยคำสั่งเดียว",intro:"LiveDesk คือ deck แบบ npm-first สำหรับดู Client, กล่อง AI, Mac mini และเครื่อง dev หลายเครื่องจาก manager PC เครื่องเดียว",managerTitle:"1. รัน manager",managerBody:"รัน LiveDesk บนเครื่องที่ใช้ดูหน้าจอ Manager จะเปิด UI และ local server พร้อมกัน แล้วเปิด http://127.0.0.1:5179",managerPoints:["คำสั่งคือ npx -y livedesk","Manager ใช้ 5179 สำหรับ Screen Wall/API และ 5197 สำหรับ client connection","ถ้า process เก่ายังใช้ port อยู่ startup จะล้างให้โดย default"],clientTitle:"2. เชื่อม Client",clientBody:"บนเครื่องที่ต้อง monitor ให้ login ด้วย Google account เดียวกัน ถ้า manager ยังไม่ออนไลน์ client จะลองใหม่ทุก 5 วินาที",clientPoints:["npx -y livedesk client จะใช้ slot ว่างแรก","npx -y livedesk client 3 จะตรึงเครื่องไว้ที่ slot 3","Client จะรอต่อเนื่องเพื่อไม่ต้อง login ซ้ำเมื่อมีหลายเครื่อง"],syncTitle:"3. Sync Server และ discovery",syncBody:"Sync Server จะ publish manager นี้เป็น active Screen Wall ของ account แล้ว client อ่านข้อมูลจาก Supabase และลอง endpoint ต่างๆ",syncPoints:["มี host instance, LAN/private address, public candidate, pair token และ short lease","ลอง LAN ก่อน แล้วค่อยลอง public ถ้าจำเป็น","กด Sync Server หลังเปลี่ยน manager, VPN, firewall หรือ router","Chrome Local Network Access บน livedesk.pages.dev ไม่ใช่ runtime หลักแล้ว app npm manager คือ server จริง"],platformTitle:"4. สถานะ platform",platformBody:"Windows ตรวจสอบแล้วว่าส่งภาพ live ได้ macOS และ Linux ใช้เส้นทาง npm เดียวกัน",platformPoints:["Windows: verified","macOS: capture/control ต้องใช้สิทธิ์ Screen Recording/Accessibility","Linux: เพิ่ม linux-x64 runtime, grim/gnome-screenshot/import/scrot capture และ X11/XTEST input แล้ว audio ยังปิดอยู่"],firewallTitle:"Firewall และเครื่องต่างสถานที่",firewallBody:"ใน 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:"เชื่อม Client",slotCommandLabel:"ตรึง slot 3",manualCommandLabel:"manual connection ขั้นสูง"}),hi:ja({languageName:"हिन्दी",languageLabel:"दस्तावेज़ भाषा",eyebrow:"LiveDesk Manual",title:"एक कमांड से local Screen Wall खोलें",intro:"LiveDesk एक npm-first remote work deck है जिससे एक manager PC से कई Client, AI box, Mac mini और dev machines देखे जा सकते हैं।",managerTitle:"1. manager चलाएं",managerBody:"जिस computer से screens देखनी हैं उस पर LiveDesk manager चलाएं। यह UI और local server साथ में शुरू करता है और http://127.0.0.1:5179 खोलता है।",managerPoints:["कमांड है npx -y livedesk।","Manager Screen Wall/API के लिए 5179 और client connections के लिए 5197 इस्तेमाल करता है।","अगर पुराने LiveDesk ports बचे हों तो startup default रूप से साफ करता है।"],clientTitle:"2. Client जोड़ें",clientBody:"हर monitored computer पर उसी Google account से sign in करें। Manager online न हो तब भी client बंद नहीं होता और हर 5 सेकंड retry करता है।",clientPoints:["npx -y livedesk client पहला खाली slot लेता है।","npx -y livedesk client 3 machine को slot 3 पर pin करता है।","बहुत सी machines हों तब भी बार-बार login की जरूरत नहीं रहती।"],syncTitle:"3. Sync Server और discovery",syncBody:"Sync Server इस manager को account का active Screen Wall बनाकर Supabase में publish करता है। Clients record पढ़कर endpoints try करते हैं।",syncPoints:["इसमें host instance, LAN/private addresses, public candidates, pair token और short lease होता है।","LAN candidates पहले try होते हैं, जरूरत हो तो public candidates।","Manager, VPN, firewall या router बदलने के बाद Sync Server दबाएं।","livedesk.pages.dev का Chrome Local Network Access अब default runtime नहीं है। npm manager app ही real server है।"],platformTitle:"4. Platform status",platformBody:"Windows live screen transfer के साथ verified है। macOS और Linux भी इसी npm path पर आगे बढ़ रहे हैं।",platformPoints:["Windows: verified.","macOS: capture/control के लिए Screen Recording/Accessibility permissions चाहिए।","Linux: linux-x64 runtime, X11/XTEST input और PipeWire/PulseAudio output audio capture उपलब्ध हैं।"],firewallTitle:"Firewall और remote locations",firewallBody:"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 Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ar:ja({languageName:"العربية",languageLabel:"لغة المستند",eyebrow:"LiveDesk Manual",title:"افتح Screen Wall محلي بأمر واحد",intro:"LiveDesk هو deck بنمط npm-first لمراقبة عدة Clients وأجهزة AI وMac mini وأجهزة تطوير من كمبيوتر manager واحد.",managerTitle:"1. شغل manager",managerBody:"شغل LiveDesk على الكمبيوتر الذي سيعرض الشاشات. يبدأ manager الواجهة والخادم المحلي معا ويفتح http://127.0.0.1:5179.",managerPoints:["الأمر هو npx -y livedesk.","يستخدم manager المنفذ 5179 للواجهة/API والمنفذ 5197 لاتصالات client.","إذا بقيت عملية LiveDesk قديمة على المنافذ، يتم تنظيفها افتراضيا عند التشغيل."],clientTitle:"2. وصل Client",clientBody:"على كل كمبيوتر تتم مراقبته، سجل الدخول بنفس حساب Google. إذا لم يكن manager متاحا، يبقى client يعمل ويحاول كل 5 ثوان.",clientPoints:["npx -y livedesk client يختار أول slot فارغ.","npx -y livedesk client 3 يثبت الجهاز في slot 3.","clients تستمر بالمحاولة لتجنب تكرار تسجيل الدخول عند كثرة الأجهزة."],syncTitle:"3. Sync Server والاكتشاف",syncBody:"Sync Server ينشر هذا manager كـ active Screen Wall للحساب. يقرأ clients سجل Supabase ويجربون endpoints بالترتيب.",syncPoints:["السجل يتضمن host instance وعناوين LAN/private وpublic candidates وpair token وlease قصير.","يتم تفضيل LAN أولا، ثم public عند الحاجة.","اضغط Sync Server بعد تغيير manager أو VPN أو firewall أو router.","Chrome Local Network Access على livedesk.pages.dev لم يعد مسار التشغيل الافتراضي. تطبيق npm manager هو الخادم الحقيقي."],platformTitle:"4. حالة المنصات",platformBody:"Windows تم التحقق منه مع نقل شاشة live. macOS وLinux يتبعان نفس مسار npm.",platformPoints:["Windows: تم التحقق.","macOS: capture/control يحتاجان أذونات Screen Recording/Accessibility.","Linux: تمت إضافة linux-x64 runtime وgrim/gnome-screenshot/import/scrot capture وX11/XTEST input. الصوت ما زال معطلا."],firewallTitle:"Firewall والمواقع البعيدة",firewallBody:"داخل نفس 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 Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),tr:ja({languageName:"Türkçe",languageLabel:"Belge dili",eyebrow:"LiveDesk Manual",title:"Yerel Screen Wall tek komutla açılsın",intro:"LiveDesk, tek bir manager PC üzerinden birçok Client, AI box, Mac mini ve dev machine izlemek için npm-first bir çalışma deckidir.",managerTitle:"1. Manager çalıştır",managerBody:"Ekranları izleyecek bilgisayarda LiveDesk manager çalıştır. Manager UI ve local server birlikte başlar ve http://127.0.0.1:5179 açılır.",managerPoints:["Komut: npx -y livedesk.","Manager Screen Wall/API için 5179, client bağlantıları için 5197 kullanır.","Eski LiveDesk process portları tutuyorsa başlangıç varsayılan olarak temizler."],clientTitle:"2. Client bağla",clientBody:"İzlenecek bilgisayarda aynı Google hesabıyla giriş yap. Manager henüz online değilse client kapanmaz ve her 5 saniyede tekrar dener.",clientPoints:["npx -y livedesk client ilk boş slota yerleşir.","npx -y livedesk client 3 makineyi slot 3’e sabitler.","Çok makinede tekrar tekrar login gerekmesin diye client beklemeye devam eder."],syncTitle:"3. Sync Server ve discovery",syncBody:"Sync Server bu managerı hesabın active Screen Wall kaydı olarak Supabase’e yazar. Clients bu kaydı okuyup endpoint adaylarını dener.",syncPoints:["Host instance, LAN/private adresler, public adaylar, pair token ve kısa lease içerir.","Önce LAN adayları, gerekirse public adaylar denenir.","Manager, VPN, firewall veya router değişince Sync Server’a bas.","livedesk.pages.dev üzerindeki Chrome Local Network Access artık default runtime yolu değil. Gerçek server npm manager app."],platformTitle:"4. Platform durumu",platformBody:"Windows live screen transfer ile doğrulandı. macOS ve Linux aynı npm yolunu takip ediyor.",platformPoints:["Windows: doğrulandı.","macOS: capture/control için Screen Recording/Accessibility izinleri gerekir.","Linux: linux-x64 runtime, grim/gnome-screenshot/import/scrot capture ve X11/XTEST input backend eklendi. Audio kapalı."],firewallTitle:"Firewall ve uzak konumlar",firewallBody:"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:"Client bağla",slotCommandLabel:"Slot 3’e sabitle",manualCommandLabel:"Gelişmiş manuel bağlantı"})},SR=Object.entries(wc).map(([n,a])=>({id:n,label:a.languageName}));function CR(){if(typeof navigator>"u")return"en";const n=navigator.languages?.length?navigator.languages:[navigator.language];for(const a of n){const i=a.toLowerCase();if(wc[a])return a;if(i.startsWith("zh-tw")||i.startsWith("zh-hk"))return"zh-TW";if(i.startsWith("pt"))return"pt-BR";const l=i.split("-")[0];if(wc[l])return l}return"en"}function ix({index:n}){const a=n+1;return r.jsx("article",{className:"device-tile placeholder-tile","aria-label":`Empty slot ${a}`,children:r.jsxs("div",{className:"tile-screen","aria-hidden":"true",children:[r.jsx("span",{className:"slot-grid","aria-hidden":"true"}),r.jsxs("span",{className:"empty-screen",children:[r.jsx(Ta,{size:24}),r.jsxs("strong",{children:["Slot ",String(a).padStart(3,"0")]})]})]})})}const kR=["cpu","gpu","memory","vram","network","disk","temp"];function jR({device:n,slotNumber:a,selected:i,updateIndicator:l,onSelect:c,onOpenControl:d}){const m=Xw(n),h=new Map(m.metrics.map(y=>[y.id,y])),g=l?.label||m.label;return r.jsxs("div",{className:`wall-device-list-row state-${m.state} ${i?"selected":""}`,role:"row","aria-selected":i,tabIndex:0,onClick:c,onDoubleClick:y=>{y.preventDefault(),d()},onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),c())},children:[r.jsxs("span",{className:"wall-device-name",role:"gridcell",children:[r.jsx("span",{className:"wall-device-icon","aria-hidden":"true",children:r.jsx(Ta,{size:17})}),r.jsxs("span",{children:[r.jsx("strong",{children:ha(n)}),r.jsxs("small",{children:["Slot ",String(a).padStart(3,"0"),n.platform?` · ${n.platform}`:"",n.arch?` · ${n.arch}`:""]})]}),i&&r.jsx(Ir,{size:16,strokeWidth:3,"aria-label":"Selected"})]}),r.jsxs("span",{className:`wall-device-list-status state-${m.state} ${l?`update-${l.state}`:""}`,role:"gridcell",title:l?.error||g,children:[r.jsx("i",{"aria-hidden":"true"}),r.jsx("strong",{children:g})]}),kR.map(y=>{const x=h.get(y);return r.jsxs("span",{className:`wall-device-list-metric state-${x?.state||"unknown"}`,role:"gridcell",title:x?`${x.label}: ${x.value} · ${x.detail}`:"Not reported",children:[r.jsx("strong",{children:x?.value||"-"}),r.jsx("small",{children:x?.detail||"not reported"}),x?.ratio!==void 0&&r.jsx("i",{style:{width:`${Math.round(x.ratio*100)}%`},"aria-hidden":"true"})]},y)})]})}function AR(n){if(!n)return!1;const a=String(n.platform||"").trim().toLowerCase();return Ni(a)&&n.capabilities?.screenRecordingPermission===!1}function Ni(n){const a=String(n||"").trim().toLowerCase();return a==="macos"||a==="darwin"||a==="mac"||a==="macosx"}function MR(n){const a=String(n||"").trim().toLowerCase();return a==="linux"||a.startsWith("linux ")}function Wh({device:n,frame:a,selected:i,controlEnabled:l,showStatus:c,monitorIndex:d,monitorCount:m,onSelect:h,onFocusDevice:g,onOpenControl:y,onCycleMonitor:x,onCanvasReady:b,sendInput:w,remoteModifierState:A,updateIndicator:j,presentationReady:k,showPresentationSpinner:N=!1,remoteDiagnostics:M,diagnosticsMode:T="remote"}){const D=u.useRef(null),F=u.useRef(null),$=u.useRef(0),q=u.useRef(null),L=Xw(n),Y=["cpu","gpu","memory","vram"].map(ee=>L.metrics.find(Se=>Se.id===ee)).filter(ee=>!!ee),G=Gn(d,m),P=m>1,K=k??!!a,H=AR(n)&&!K,ye=N&&n.connected&&!K&&!H,de=tR(n,a,G),Z=de>=xf?100:de/xf*100,z=de>=xf?xf/de*100:100,se={"--screen-aspect":de.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,Z)).toFixed(3)}%`,"--screen-content-height":`${Math.max(1,Math.min(100,z)).toFixed(3)}%`},W=u.useCallback(ee=>{D.current=ee,b(n.deviceId,ee)},[n.deviceId,b]),O=ee=>{const Se=ee.currentTarget.getBoundingClientRect();return J1(ee.clientX,ee.clientY,Se)},le=ee=>tk(ee,A),ce=u.useCallback(()=>{q.current!==null&&(window.cancelAnimationFrame(q.current),q.current=null)},[]),Q=u.useCallback(()=>{const ee=F.current;if(!ee)return;F.current=null;const Se=Number(ee.input.normalizedX),Ne=Number(ee.input.normalizedY);if(!Number.isFinite(Se)||!Number.isFinite(Ne))return;w(n.deviceId,{...ee.input,normalizedX:Se,normalizedY:Ne})&&($.current=performance.now())},[n.deviceId,w]),be=u.useCallback(()=>{q.current===null&&(q.current=window.requestAnimationFrame(()=>{q.current=null,Q()}))},[Q]);u.useEffect(()=>()=>{ce(),F.current=null},[ce]);const he=(ee,Se)=>{if(!l)return;const Ne={type:Se,monitorIndex:G,...O(ee),button:mR(ee.button),...le(ee)};if(Se==="pointermove"){const Fe=performance.now();F.current={input:Ne},Fe-$.current>=CT&&(ce(),Q()),be();return}F.current&&(ce(),Q()),w(n.deviceId,Ne)},fe=u.useCallback(ee=>{const Se=document.activeElement;Se instanceof HTMLElement&&ee.contains(Se)&&Se.classList.contains("monitor-cycle-button")&&Se.blur()},[]);return r.jsx("article",{className:`device-tile ${i?"selected":""} ${n.connected?"online":"offline"}`,"data-live-device-id":n.deviceId,style:se,children:r.jsxs("div",{className:`tile-screen ${K?"has-frame":"is-empty"}`,role:"button",tabIndex:l?-1:0,"aria-pressed":i,onClick:ee=>{ee.target instanceof Element&&ee.target.closest(".monitor-cycle")||l||h()},onKeyDown:ee=>{ee.target instanceof Element&&ee.target.closest(".monitor-cycle")||l||(ee.key==="Enter"||ee.key===" ")&&(ee.preventDefault(),h())},onDoubleClick:ee=>{ee.target instanceof Element&&ee.target.closest(".monitor-cycle")||(ee.preventDefault(),y())},onPointerLeave:ee=>fe(ee.currentTarget),children:[r.jsx("span",{className:`screen-content ${K?"has-frame":"is-empty"}`,children:r.jsx("canvas",{ref:W,className:`remote-canvas ${K?"has-frame":"is-empty"}`,"data-monitor-index":G,tabIndex:l?0:-1,onPointerDown:ee=>{l&&(ee.preventDefault(),ee.stopPropagation(),g(),ee.currentTarget.focus(),ee.currentTarget.setPointerCapture(ee.pointerId),he(ee,"pointerdown"))},onPointerMove:ee=>{l&&ee.preventDefault(),he(ee,"pointermove")},onPointerLeave:ee=>{l&&(he(ee,"pointermove"),ce(),Q())},onPointerUp:ee=>{l&&(ee.preventDefault(),ee.stopPropagation(),he(ee,"pointerup"),ee.currentTarget.hasPointerCapture(ee.pointerId)&&ee.currentTarget.releasePointerCapture(ee.pointerId))},onPointerCancel:ee=>{ee.currentTarget.hasPointerCapture(ee.pointerId)&&ee.currentTarget.releasePointerCapture(ee.pointerId)},onWheel:ee=>{l&&(ee.preventDefault(),w(n.deviceId,{type:"wheel",monitorIndex:G,...O(ee),deltaX:ee.deltaX,deltaY:ee.deltaY,...le(ee)}))},onContextMenu:ee=>l&&ee.preventDefault()},`${n.deviceId}:monitor:${G}`)}),!K&&r.jsx("span",{className:"empty-screen",children:r.jsx(Ta,{size:26})}),r.jsx("span",{className:"wall-device-title",title:ha(n),children:ha(n)}),ye&&r.jsxs("span",{className:"wall-presentation-loading",role:"status","aria-live":"polite",children:[r.jsx("span",{className:"wall-presentation-spinner","aria-hidden":"true"}),r.jsx("strong",{children:"Preparing video"})]}),H&&r.jsxs("span",{className:"wall-presentation-loading permission-required",role:"status","aria-live":"polite",children:[r.jsx(Vn,{size:24,"aria-hidden":"true"}),r.jsx("strong",{children:"Screen Recording permission required"}),r.jsx("small",{children:"Allow the terminal app on this Mac, then restart LiveDesk."})]}),j&&r.jsxs("span",{className:`wall-update-status state-${j.state}`,role:"status","aria-live":"polite",title:j.error||j.label,children:[j.state==="updated"?r.jsx(Xn,{size:20,"aria-hidden":"true"}):j.state==="failed"?r.jsx(Na,{size:22,"aria-hidden":"true"}):j.state==="offline"?r.jsx($f,{size:22,"aria-hidden":"true"}):r.jsx("span",{className:"wall-update-spinner","aria-hidden":"true"}),r.jsx("strong",{children:j.label}),j.error?r.jsx("small",{children:j.error}):null]}),c&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:`tile-health-pill state-${L.state}`,children:L.label}),r.jsx("span",{className:"tile-metrics","aria-label":`${ha(n)} status`,children:Y.map(ee=>r.jsxs("span",{className:`tile-metric state-${ee.state}`,children:[r.jsx("b",{children:ee.label}),r.jsx("em",{children:ee.value}),ee.ratio!==void 0&&r.jsx("i",{style:{width:`${Math.round(ee.ratio*100)}%`}})]},ee.id))})]}),M&&r.jsx(WN,{items:M,mode:T}),P&&r.jsxs("span",{className:"monitor-cycle","aria-label":`${ha(n)} display ${G+1} of ${m}`,onPointerDown:ee=>ee.stopPropagation(),onClick:ee=>ee.stopPropagation(),onDoubleClick:ee=>ee.stopPropagation(),children:[r.jsx("button",{className:"monitor-cycle-button previous",onClick:ee=>{ee.preventDefault(),ee.stopPropagation(),x(-1),ee.currentTarget.blur()},title:"Previous display",type:"button",children:r.jsx(yx,{size:18})}),r.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",G+1,"/",m]}),r.jsx("button",{className:"monitor-cycle-button next",onClick:ee=>{ee.preventDefault(),ee.stopPropagation(),x(1),ee.currentTarget.blur()},title:"Next display",type:"button",children:r.jsx(Ap,{size:18})})]}),i&&r.jsx("span",{className:"device-selection-check","aria-hidden":"true",children:r.jsx(Ir,{size:23,strokeWidth:3.5})})]})})}function NR({visible:n}){return u.useEffect(()=>{if(!n||!Fh)return;if(!document.getElementById(Pb)){const i=document.createElement("script");i.id=Pb,i.async=!0,i.crossOrigin="anonymous",i.src=`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${encodeURIComponent(bp)}`,document.head.appendChild(i)}const a=window.setTimeout(()=>{try{window.adsbygoogle=window.adsbygoogle||[],window.adsbygoogle.push({})}catch{}},120);return()=>window.clearTimeout(a)},[n]),n?r.jsxs("aside",{className:`free-ad-banner ${Fh?"adsense-ready":"house-ad"}`,"aria-label":"Advertisement",children:[r.jsx("span",{className:"ad-label",children:"Advertisement"}),Fh?r.jsx("ins",{className:"adsbygoogle livedesk-ad-unit",style:{display:"block"},"data-ad-client":bp,"data-ad-slot":qw,"data-ad-format":"auto","data-full-width-responsive":"true"}):r.jsxs("div",{className:"house-ad-copy",children:[r.jsx("strong",{children:"Sponsored placement"}),r.jsx("span",{children:"Local AI gear, mini PCs, GPUs, NAS, and developer tools."})]})]}):null}function TR(){const{session:n,loading:a}=R1(),{target:i,error:l,refresh:c}=D1(n),d=u.useMemo(()=>{if(!i?.active)return null;const v=i.expires_at?Date.parse(i.expires_at):Number.POSITIVE_INFINITY;return Number.isFinite(v)&&v<=Date.now()?null:i},[i]),m=u.useMemo(()=>Ty(d),[d]),h=u.useMemo(()=>m.length>0?[...new Set([...m,Mn])]:[Mn],[m]),[g,y]=u.useState(XT),x=u.useMemo(()=>h.some(v=>!!Ou(v)),[h]),b=!x||g,{status:w,devices:A,error:j,refresh:k,hubBaseUrl:N}=E1(h,b),{entitlement:M,licensed:T,loading:D,error:F,refresh:$}=L1(n),[q,L]=u.useState([]),[Y,G]=u.useState(""),[P,K]=u.useState(""),[H,ye]=u.useState(""),[de,Z]=u.useState(""),[z,se]=u.useState(""),[W,O]=u.useState("idle"),[le,ce]=u.useState(!1),[Q,be]=u.useState(null),he=u.useRef(null),[fe,ee]=u.useState(""),Se=u.useRef("");Se.current=de;const[Ne,Fe]=u.useState(!1),[ne,Pe]=u.useState([]),mt=u.useRef(null),[J,ke]=u.useState(!1),Le=u.useRef(""),Be=u.useRef(new Map),_e=u.useRef(0),[Qe,Ye]=u.useState({}),Ze=u.useRef({}),ut=u.useRef(new Map),U=u.useRef(new Map),[ve,je]=u.useState({}),$e=u.useMemo(()=>new Set(Object.keys(Qe)),[Qe]),dt=u.useCallback((v,C)=>{if(!v)return;const E={...Ze.current};C?E[v]=C:delete E[v],Ze.current=E,Ye(E)},[]),it=u.useCallback((v,C)=>{v&&je(E=>{if(!!E[v]===C)return E;const I={...E};return C?I[v]=!0:delete I[v],I})},[]),pt=u.useCallback((v,C)=>{v&&U.current.set(v,{paused:C,expiresAt:Date.now()+LT})},[]),[ct,kt]=u.useState(""),[pe,De]=u.useState(""),[Oe,Ae]=u.useState(!1),ft=u.useRef(null),xt=u.useRef(null);u.useEffect(()=>{ct==="auth"&&n?.access_token&&kt("")},[ct,n?.access_token]);const[Ie,na]=u.useState(""),[wn,at]=u.useState(null),Ot=u.useRef(null),aa=u.useRef(0),pa=u.useCallback((v,C,E)=>{const I=String(v||"").trim();if(na(I),Ot.current!==null&&(window.clearTimeout(Ot.current),Ot.current=null),!I){at(null);return}const _=++aa.current;if(at({id:_,message:I,tone:C}),!E)return;const te=window.setTimeout(()=>{at(ie=>ie?.id===_?null:ie),Ot.current===te&&(Ot.current=null)},5e3);Ot.current=te},[]),He=u.useCallback((v,C="info")=>{pa(v,C,!0)},[pa]),Sn=u.useCallback(v=>{pa(v,"progress",!1)},[pa]);u.useEffect(()=>()=>{Ot.current!==null&&window.clearTimeout(Ot.current)},[]);const[zn,ws]=u.useState(()=>typeof window<"u"&&window.location.pathname.startsWith("/support")?"support":"wall");u.useEffect(()=>{const v=()=>{ws(window.location.pathname.startsWith("/support")?"support":C=>C==="support"?"wall":C)};return window.addEventListener("popstate",v),()=>window.removeEventListener("popstate",v)},[]);const[pn,qs]=u.useState("large"),[Wn,Gs]=u.useState(!1),[B,Ke]=u.useState(!1),[ht,fn]=u.useState(!1),[Fa,Di]=u.useState(!1),[Ss,re]=u.useState(Date.now),Te=u.useRef(null);u.useEffect(()=>()=>{Te.current!==null&&window.clearTimeout(Te.current)},[]);const[Ue,yt]=u.useState(CR),[qt,Yt]=u.useState(!1),[st,Mt]=u.useState(!1),[sa,On]=u.useState(!1),[gn,nn]=u.useState(QT),[We]=u.useState(sR),[At]=u.useState(iR),[Vs]=u.useState(nR),[zt,Cn]=u.useState(Vs.selections),Tn=u.useRef({...Vs.topologyFingerprints}),go=u.useRef({...Vs.selections}),[Nt,ga]=u.useState(null),[Mc,Fr]=u.useState([]),[Hn,$a]=u.useState(We.fps),[Yn,Qu]=u.useState(""),[Qf,Nc]=u.useState(0),[Xu,Sl]=u.useState(0),[Xf,Ba]=u.useState(0),[vo,Li]=u.useState(()=>new Set),Fn=u.useRef(new Map),Ra=u.useRef(new Map),Ws=u.useRef(new Map),$r=u.useRef(new Map),kn=u.useRef(new Map),Cl=u.useRef(new Map),Ys=u.useRef(new Set),kl=u.useRef(new Map),Br=u.useRef(""),os=u.useRef(null),Zu=u.useRef(Promise.resolve()),Pr=u.useRef(0),ra=u.useRef(null),Cs=u.useRef(new Map),_i=u.useRef(null),vr=u.useRef(0),Ks=u.useRef(new Map),[jl,yo]=u.useState({}),Al=u.useRef(new Map),[yr,ks]=u.useState({}),[bo,ia]=u.useState(!1),js=u.useRef(null),Pa=u.useRef(null),va=u.useRef(0),la=u.useRef(""),Ml=u.useRef(Promise.resolve()),Nl=u.useRef(""),Tt=u.useRef(null),Zt=u.useRef(""),Ea=u.useRef(null),Qs=u.useRef(0),Xs=u.useRef(""),br=u.useRef(new Map),Zs=u.useRef(new Map),Ii=u.useRef(performance.now()),As=u.useRef(new Map),Ms=u.useRef(new Map),xr=u.useRef(new Map),zi=u.useRef(new Map),xo=u.useRef(new Map),Tl=u.useRef(0),Oi=u.useRef(0),wo=u.useRef(0),So=u.useRef(0),Tc=u.useRef(0),Ju=u.useRef(new Map),Js=u.useRef(new Map),cs=u.useCallback((v,C)=>{const E=rs(v,C),I=performance.now();br.current.delete(E),Zs.current.delete(E),As.current.delete(E),xo.current.delete(E),Js.current.delete(E),Al.current.delete(E),Ks.current.delete(E),ks(_=>{if(!Object.prototype.hasOwnProperty.call(_,E))return _;const te={..._};return delete te[E],te}),yo(_=>{if(!Object.prototype.hasOwnProperty.call(_,E))return _;const te={..._};return delete te[E],te}),v==="control"?(Ms.current.delete(E),xr.current.set(E,I)):zi.current.set(E,I)},[]),[Ur,wr]=u.useState(null),[Zf,Rc]=u.useState(!1),[ed,Jf]=u.useState([]),[Hi,em]=u.useState("all"),[qr,Ec]=u.useState([]),[Wp,Yp]=u.useState(!1),[Kp,tm]=u.useState(!0),td=u.useRef(null),nd=u.useRef(null),nm=u.useRef(null),am=u.useRef(null),Dc=u.useRef(!1),Gr=u.useRef(!1),Lc=u.useRef(!1),Fi=u.useRef(0),er=u.useRef(0),Rl=zn==="settings",_c=zn==="pricing",Ic=zn==="doc",Vr=zn==="support",El=zn==="share-files",zc=zn==="agents",Dl=!Rl&&!_c&&!Ic&&!Vr&&!El&&!zc,gt=zn==="control";u.useEffect(()=>{Dl||(Gs(!1),Ke(!1),fn(!1))},[Dl]);const Rt=We.frameMode==="mode4-h264-atlas",$n=z||At.frameMode,tr=$n!=="mode3-h264-hw"?Math.min(30,At.fps):At.fps,sm=A.find(v=>v.deviceId===P)?.platform,Ll=MR(sm)?{maxWidth:1280,maxHeight:720}:{maxWidth:3840,maxHeight:2160},Wr={maxWidth:Math.min($n!=="mode3-h264-hw"?1920:3840,Ll.maxWidth,At.maxWidth),maxHeight:Math.min($n!=="mode3-h264-hw"?1080:2160,Ll.maxHeight,At.maxHeight)};u.useEffect(()=>{if(w?.started){if(!n?.access_token){Ve("/api/remote/license",{method:"DELETE"},N).catch(()=>{});return}Ve("/api/remote/license/sync",{method:"POST",headers:{Authorization:`Bearer ${n.access_token}`}},N).catch(v=>{console.warn("[LiveDesk] Hub license sync failed",v)})}},[M?.updated_at,N,n?.access_token,w?.started]),u.useEffect(()=>{!n?.access_token||!w?.started||w.runtimeRole!=="hub"||!w.deviceId||(async()=>{try{const{data:v,error:C}=await Ct.rpc("register_livedesk_device",{p_device_id:w.deviceId,p_device_name:w.deviceName||w.deviceId,p_role:"hub",p_assigned_hub_id:null,p_platform:navigator.platform||navigator.userAgent,p_os_version:navigator.userAgent,p_app_version:w.managerVersion||w.managerPackage||""}),E=Array.isArray(v)?v[0]:v;(C||E?.ok===!1)&&console.warn("[LiveDesk] Hub device role registration failed",C||E?.reason||"unknown-error")}catch(v){console.warn("[LiveDesk] Hub device role registration failed",v)}})()},[n?.access_token,w?.deviceId,w?.deviceName,w?.managerPackage,w?.managerVersion,w?.runtimeRole,w?.started]),u.useEffect(()=>{!n?.access_token||!n.refresh_token||!w?.started||w.runtimeRole!=="hub"||Lc.current||(Lc.current=!0,Ve("/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}})},N||Mn).then(v=>{v.hostTarget?.ok===!1&&console.warn("[LiveDesk] Hub host target publish is waiting for a valid Hub role:",v.hostTarget.error||"unknown-error"),k()}).catch(v=>{console.warn("[LiveDesk] Hub session sync failed:",v)}).finally(()=>{Lc.current=!1}))},[N,k,n?.access_token,n?.expires_at,n?.refresh_token,n?.user?.email,n?.user?.id,w?.runtimeRole,w?.started]);const lt=u.useMemo(()=>A.filter(v=>v.connected),[A]);u.useEffect(()=>{const v={...Ze.current},C=Date.now();let E=!1;je(I=>{const _={...I};let te=!1;for(const ie of A){const Me=String(ie.liveCapturePause?.token||"").trim(),Re=U.current.get(ie.deviceId);if(Re)if((Re.paused?!!Me:!Me)||Re.expiresAt<=C)U.current.delete(ie.deviceId);else continue;const qe=!!Me&&(ie.liveCapturePause?.captureStopConfirmed!==!0||ie.liveCapturePause?.phase==="stop-unconfirmed");!!_[ie.deviceId]!==qe&&(te=!0,qe?_[ie.deviceId]=!0:delete _[ie.deviceId])}return te?_:I});for(const I of A){const _=String(I.liveCapturePause?.token||"").trim(),te=String(v[I.deviceId]||""),ie=U.current.get(I.deviceId);if(ie)if((ie.paused?!!_:!_)||ie.expiresAt<=C)U.current.delete(I.deviceId);else continue;_&&_!==te?(v[I.deviceId]=_,E=!0):!_&&te&&(delete v[I.deviceId],ut.current.delete(I.deviceId),E=!0)}E&&(Ze.current=v,Ye(v))},[A]);const Co=Hi==="all"?lt.length:qr.filter(v=>lt.some(C=>C.deviceId===v)).length,Oc=u.useMemo(()=>lt.reduce((v,C)=>Math.max(v,rx(C.slotNumber)),0),[lt]),ko=Math.max(pT,lt.length,Oc),Sr=u.useMemo(()=>{const v=Array(ko).fill(null),C=[];for(const E of lt){const I=rx(E.slotNumber);I>0&&I<=ko&&!v[I-1]?v[I-1]=E:C.push(E)}for(const E of C){const I=v.findIndex(_=>!_);I<0?v.push(E):v[I]=E}return v},[lt]),Hc=u.useMemo(()=>Sr.flatMap((v,C)=>v?[{device:v,slotNumber:C+1}]:[]),[Sr]),Fc=u.useMemo(()=>lt.map(v=>v.deviceId),[lt]),Yr=u.useMemo(()=>new Set(q),[q]),Da=u.useMemo(()=>lt.filter(v=>Yr.has(v.deviceId)),[lt,Yr]),$i=u.useMemo(()=>A.find(v=>v.deviceId===Y)||Da[0]||null,[A,Y,Da]),oa=u.useMemo(()=>A.find(v=>v.deviceId===P)||null,[P,A]),an=oa?Gn(zt[oa.deviceId],qn(oa)):0,Ee=gt?oa:$i,$c=u.useMemo(()=>new Set(qr),[qr]),ad=u.useMemo(()=>Hi==="all"?lt.map(v=>v.deviceId):lt.filter(v=>$c.has(v.deviceId)).map(v=>v.deviceId),[lt,$c,Hi]),sd=Ee?$u(Ee,"control"):!1,jo=Ni(Ee?.platform)&&(Ee?.capabilities?.controlPermission===!1||Ee?.capabilities?.accessibilityPermission===!1),Kr=Ee?$u(Ee,"audio")||$u(Ee,"remoteAudio"):!1,Qr=(Array.isArray(Ee?.capabilities?.agentTools)?Ee.capabilities.agentTools.map(String):[]).includes("system.power"),un=T?M?.plan==="pro"?"pro":"ltd":"free",Bi=so[un],Pi=Bi.limit,Xr=u.useMemo(()=>{if(!Number.isFinite(Pi))return new Set(lt.map(C=>C.deviceId));const v=Ee?[Ee,...lt.filter(C=>C.deviceId!==Ee.deviceId)]:lt;return new Set(v.slice(0,Pi).map(C=>C.deviceId))},[Pi,lt,Ee]),Zr=!Ee||Xr.has(Ee.deviceId),Ui=un==="free",Kt=Zr,Jr=un==="ltd"?`Plus includes up to ${Du} Clients. Upgrade to Pro for commercial use and larger walls.`:`Free includes up to ${Eu} Clients. Upgrade to Plus for ${Du} devices and no ads.`,ei=un==="free",Ns=Kt&&!!Ee&&sd,Bc=Kt&&!!Ee&&Kr,qi=!!Ee&&$e.has(Ee.deviceId),Pc=!!Ee&&ve[Ee.deviceId]===!0,Ao=u.useMemo(()=>Sr.filter(v=>!!v?.connected).slice(0,oR(pn)).map(v=>v.deviceId),[Sr,pn]),Mo=u.useMemo(()=>pn==="list"?[]:Rt?Fc:We.visibleOnlyLive?Mc.length>0?Mc:Ao:Fc,[Ao,Rt,Mc,We.visibleOnlyLive,Fc,pn]),Ua=u.useMemo(()=>Uh(Mo.filter(v=>Xr.has(v))),[Xr,Mo]),nr=u.useMemo(()=>Ua.filter(v=>v!==Yn&&!$e.has(v)),[$e,Ua,Yn]),Gi=u.useMemo(()=>new Map(lt.map(v=>[v.deviceId,v.platform])),[lt]),vn=sk(Rt,Ua.length),Bn=u.useMemo(()=>Rt?nr.filter(v=>Mu({mode4Enabled:Rt,directMode4WallEnabled:vn,isMac:Ni(Gi.get(v))})==="atlas"):[],[vn,Rt,Gi,nr]),sn=u.useMemo(()=>nr.filter(v=>Mu({mode4Enabled:Rt,directMode4WallEnabled:vn,isMac:Ni(Gi.get(v))})==="direct"),[vn,Rt,Gi,nr]);u.useEffect(()=>{const v=new Set(Ua);Li(C=>{let E=!1;const I=new Set;for(const _ of C)v.has(_)?I.add(_):E=!0;return E?I:C})},[Ua]);const Vi=u.useMemo(()=>{const v=_=>lt.find(te=>te.deviceId===_)||null,C=_=>Gn(zt[_],v(_)?qn(v(_)):0),E=(_,te=C(_))=>_===H&&(W==="connecting"||W==="active"||W==="warm")?kn.current.get(_)||Ra.current.get(_)||null:Rt?Cs.current.get(_)||Fn.current.get(_)||null:Fn.current.get(_)||null,I=(_,te=C(_))=>{const ie=v(_);return`${ie?ha(ie):_} · Monitor ${te+1}`};return{resolveCurrentTarget(){if(gt&&oa){const Re=an;return{type:"control",deviceIds:[oa.deviceId],monitorIndex:Re,label:`${ha(oa)} · Monitor ${Re+1}`,sourceCanvas:E(oa.deviceId,Re),signature:`control:${oa.deviceId}:${Re}:${At.frameMode}`}}const _=Da.map(Re=>Re.deviceId).filter(Re=>nr.includes(Re)),te=$i&&nr.includes($i.deviceId)?$i.deviceId:"",ie=_.length>0?_:te?[te]:nr,Me=_.length===0&&!te;if(ie.length===0)return null;if(ie.length===1){const Re=ie[0],qe=C(Re);return{type:Me?"wall":_.length>1?"selection":"device",deviceIds:ie,monitorIndex:qe,label:Me?"Wall":I(Re,qe),sourceCanvas:Me?null:E(Re,qe),signature:`${Me?"wall":"device"}:${Re}:${qe}:${Rt?"atlas":"direct"}`}}return{type:_.length>1?"selection":"wall",deviceIds:ie,label:_.length>1?`${ie.length} selected Clients`:"Wall",sourceCanvas:null,signature:`${_.length>1?"selection":"wall"}:${ie.join(",")}:${pn}`}},getDeviceCanvas:E,composeWall(_,te={}){return aT(_.map(ie=>{const Me=C(ie);return{deviceId:ie,label:I(ie,Me),canvas:E(ie,Me)}}),te)}}},[lt,oa,H,W,At.frameMode,Fn,Rt,zt,an,Da,gt,nr,$i,pn]),No=hT({hubUrl:N,sourceRegistry:Vi,onToast:He}),ar=u.useMemo(()=>Kt&&H&&Xr.has(H)&&(W==="connecting"||W==="active"||W==="warm")?[H]:[],[H,W,Kt,Xr]),To=u.useMemo(()=>Uh([...Ua,...ar]),[ar,Ua]),La=u.useMemo(()=>cR(We,pn),[We,pn]),_a=rk({mode4Enabled:Rt,directMode4WallEnabled:vn,adaptiveFps:Hn,directDeviceCount:sn.length,adaptive:We.adaptiveLoadShedding}),Ro=ik({deviceCount:Bn.length,targetFps:Hn,adaptive:We.adaptiveLoadShedding});Rt&&Bn.length>0;const Rn=u.useCallback((v,C,E)=>{if(v.width<=0||v.height<=0)return!1;const I=E?Math.min(1,E.maxWidth/v.width,E.maxHeight/v.height):1,_=Math.max(1,Math.round(v.width*I)),te=Math.max(1,Math.round(v.height*I));(C.width!==_||C.height!==te)&&(C.width=_,C.height=te);const ie=C.getContext("2d",{alpha:!1});return ie?(ie.imageSmoothingEnabled=!0,ie.imageSmoothingQuality="high",ie.drawImage(v,0,0,v.width,v.height,0,0,C.width,C.height),!0):!1},[]),ca=u.useCallback(v=>{v&&Li(C=>{if(C.has(v))return C;const E=new Set(C);return E.add(v),E})},[]),Eo=u.useCallback(v=>{v&&Li(C=>{if(!C.has(v))return C;const E=new Set(C);return E.delete(v),E})},[]),En=u.useCallback((v,C)=>{if(!C||C.width<=0||C.height<=0)return!1;const E=document.createElement("canvas");return E.width=C.width,E.height=C.height,Rn(C,E)?(Ws.current.set(v,E),ca(v),!0):!1},[ca,Rn]),Ts=u.useCallback(v=>{const C=$r.current.get(v);C!==void 0&&(window.cancelAnimationFrame(C),$r.current.delete(v))},[]),ya=u.useCallback(v=>{Ts(v),Ws.current.delete(v)},[Ts]),_l=u.useCallback((v,C)=>{Ts(v);const E=()=>{const I=Ws.current.get(v),_=Fn.current.get(v)===C||Cs.current.get(v)===C;if(!I||!_){$r.current.delete(v);return}Rn(I,C),$r.current.set(v,window.requestAnimationFrame(E))};E()},[Rn,Ts]);u.useEffect(()=>()=>{for(const v of $r.current.values())window.cancelAnimationFrame(v);$r.current.clear()},[]);const qa=u.useCallback((v,C=!1)=>{if(!Ys.current.has(v))return!1;const E=performance.now(),I=kl.current.get(v)||0,_=Math.max(1,Math.min(bs.controlWallReuseMaxFps,tr)),te=tr>_?Math.max(0,1e3/_-2):0;if(!C&&E-I<te)return!1;const ie=kn.current.get(v)||Ra.current.get(v),Me=Fn.current.get(v)||Cs.current.get(v);return!ie||!Me||!Rn(ie,Me,La)?!1:(kl.current.set(v,E),ca(v),ya(v),!0)},[tr,La,ca,Rn,ya]);u.useEffect(()=>{Br.current=Yn},[Yn]);const Cr=u.useCallback((v,C)=>{const E=Fn.current.get(v);if(E&&E!==C&&(Ts(v),En(v,E),dc(E)),C){Fn.current.set(v,C);const I=Ws.current.get(v);I&&Rn(I,C)&&(ca(v),_l(v,C)),qa(v,!0);return}Fn.current.delete(v),Ws.current.has(v)||Eo(v)},[Eo,_l,ca,Rn,qa,En,Ts]),Uc=u.useCallback((v,C)=>{const E=Ra.current.get(v);if(E&&E!==C&&dc(E),C){Ra.current.set(v,C);const I=H===v&&le?kn.current.get(v):null;I&&Rn(I,C)&&v===P&&ia(!0);return}Ra.current.delete(v)},[P,H,le,Rn]),Il=u.useCallback((v,C,E)=>{const I=performance.now(),_=rs(v,E.deviceId);let te=E;if(v==="control"&&E.visualChanged){const Me=F1(E.deviceId),Re=Ju.current.get(E.deviceId)||0,qe=Me?I-Me.sentAt:Number.POSITIVE_INFINITY;Me&&Me.inputSeq>Re&&qe<=Ub&&(te={...E,inputFeedbackSeq:Me.inputSeq,inputFeedbackMs:Math.max(0,qe),inputFeedbackAt:I},Ju.current.set(E.deviceId,Me.inputSeq))}Zs.current.set(_,I);const ie=Ks.current.get(_)||{totalFrames:0,totalChangedFrames:0,sampleFrames:0,sampleChangedFrames:0,sampleStartedAt:I,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleDecoderInputBase:0,sampleDecoderOutputBase:0};v==="control"&&te.inputFeedbackMs===void 0&&ie.lastInfo?.inputFeedbackMs!==void 0&&ie.lastInfo.inputFeedbackAt!==void 0&&I-ie.lastInfo.inputFeedbackAt<=Ub&&(te={...te,inputFeedbackSeq:ie.lastInfo.inputFeedbackSeq,inputFeedbackMs:ie.lastInfo.inputFeedbackMs,inputFeedbackAt:ie.lastInfo.inputFeedbackAt}),ie.totalFrames+=1,ie.sampleFrames+=1,Kb(ie,I,te.frameSeq),te.visualChanged&&(ie.totalChangedFrames+=1,ie.sampleChangedFrames+=1),ie.lastInfo=te,Ks.current.set(_,ie)},[]),Wi=u.useCallback((v,C)=>{Il("wall",v,C),v.kind==="live"&&(ca(v.deviceId),ya(v.deviceId));const E=le&&H===v.deviceId;Br.current!==v.deviceId&&!E&&(Ys.current.delete(v.deviceId),kl.current.delete(v.deviceId))},[H,le,ca,Il,ya]),qc=u.useCallback((v,C)=>{if(Ze.current[v.deviceId]||!Ky(v,Tt.current))return;Il("control",v,C),ee(te=>te&&"");const E=kn.current.get(v.deviceId),I=Ra.current.get(v.deviceId);E&&E.width>0&&E.height>0&&(I&&Rn(E,I),Cl.current.set(v.deviceId,{...v,payload:new Uint8Array(0),byteLength:0}),Ys.current.add(v.deviceId),v.deviceId===H&&(ce(!0),O(te=>te==="connecting"?"active":te)),qa(v.deviceId));const _=js.current;!_||!_T(_,v)||ia(!0)},[H,Rn,qa,Il]);u.useEffect(()=>{const v=window.setInterval(()=>{const C=performance.now(),E={};for(const[I,_]of Ks.current.entries()){const te=Math.max(1,C-_.sampleStartedAt);E[I]={totalFrames:_.totalFrames,totalChangedFrames:_.totalChangedFrames,framesPerSecond:_.sampleFrames*1e3/te,changedFramesPerSecond:_.sampleChangedFrames*1e3/te,averageIntervalMs:_.intervalCount>0?_.intervalSumMs/_.intervalCount:0,minIntervalMs:Number.isFinite(_.minIntervalMs)?_.minIntervalMs:0,maxIntervalMs:_.maxIntervalMs,p95IntervalMs:Bh(_.intervalSamplesMs,.95),intervalCount:_.intervalCount,seqGapCount:_.seqGapCount,maxSeqGap:_.maxSeqGap,decoderInputFps:Math.max(0,(Number(_.lastInfo?.decoderInputCount||0)-_.sampleDecoderInputBase)*1e3/te),decoderOutputFps:Math.max(0,(Number(_.lastInfo?.decoderOutputCount||0)-_.sampleDecoderOutputBase)*1e3/te),sampleMs:te,lastInfo:_.lastInfo},_.sampleDecoderInputBase=Number(_.lastInfo?.decoderInputCount||0),_.sampleDecoderOutputBase=Number(_.lastInfo?.decoderOutputCount||0),_.sampleChangedFrames=0,Yb(_,C)}yo(E)},1e3);return()=>window.clearInterval(v)},[]);const Pn=u.useCallback((v,C)=>{const E=performance.now(),I=rs(v,C.deviceId);br.current.set(I,E),Js.current.delete(I),v==="control"?Ms.current.delete(I):zi.current.delete(I);const _=Al.current.get(I)||{totalFrames:0,sampleFrames:0,sampleStartedAt:E,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleBytes:0,sampleH264Frames:0,sampleTinyFrames:0,sampleRepeatedFrames:0,sourceSendIntervalsMs:[]};if(_.totalFrames+=1,_.sampleFrames+=1,_.sampleBytes+=Math.max(0,Number(C.byteLength||0)),String(C.frameMode||C.mode||C.codec||C.mimeType||"").toLowerCase().includes("h264")){_.sampleH264Frames+=1,Number(C.byteLength||0)<=TT&&(_.sampleTinyFrames+=1);const Re=String(C.contentHash||"");Re&&_.lastContentHash===Re&&(_.sampleRepeatedFrames+=1),_.lastContentHash=Re}const Me=Number(C.agentSendGapMs||0);Me>0&&Me<1e3&&Gw(_.sourceSendIntervalsMs,Me),_.lastFrame=C,Kb(_,E,C.frameSeq),Al.current.set(I,_)},[]);u.useEffect(()=>{const v=window.setInterval(()=>{const C=performance.now(),E={};for(const[I,_]of Al.current.entries()){const te=Math.max(1,C-_.sampleStartedAt);E[I]={totalFrames:_.totalFrames,framesPerSecond:_.sampleFrames*1e3/te,averageIntervalMs:_.intervalCount>0?_.intervalSumMs/_.intervalCount:0,minIntervalMs:Number.isFinite(_.minIntervalMs)?_.minIntervalMs:0,maxIntervalMs:_.maxIntervalMs,p95IntervalMs:Bh(_.intervalSamplesMs,.95),intervalCount:_.intervalCount,seqGapCount:_.seqGapCount,maxSeqGap:_.maxSeqGap,averageFrameBytes:_.sampleFrames>0?_.sampleBytes/_.sampleFrames:0,tinyFrameRatio:_.sampleH264Frames>0?_.sampleTinyFrames/_.sampleH264Frames:0,repeatedFrameRatio:_.sampleH264Frames>0?_.sampleRepeatedFrames/_.sampleH264Frames:0,sourceSendAverageMs:_.sourceSendIntervalsMs.length>0?_.sourceSendIntervalsMs.reduce((ie,Me)=>ie+Me,0)/_.sourceSendIntervalsMs.length:0,sourceSendP95Ms:Bh(_.sourceSendIntervalsMs,.95),sourceSendSampleCount:_.sourceSendIntervalsMs.length,sampleMs:te,lastFrame:_.lastFrame},_.sampleBytes=0,_.sampleH264Frames=0,_.sampleTinyFrames=0,_.sampleRepeatedFrames=0,_.sourceSendIntervalsMs.length=0,Yb(_,C)}ks(E)},1e3);return()=>window.clearInterval(v)},[]);const ti=u.useCallback(v=>{if(Br.current===v.deviceId)return;Pn("wall",v);const C=Fn.current.get(v.deviceId);if(!C)return;const E=lk(Rt,We.h264DecodeAcceleration);jh(C,v,()=>Fn.current.get(v.deviceId)!==C,Wi,E.acceleration,E.latencyMode).catch(()=>{})},[Wi,Rt,Pn,We.h264DecodeAcceleration]),ni=u.useCallback(v=>{if(Ze.current[v.deviceId]||!Ky(v,Tt.current))return;Pn("control",v);let C=kn.current.get(v.deviceId);C||(C=document.createElement("canvas"),C.setAttribute("aria-hidden","true"),kn.current.set(v.deviceId,C));const E=C,I=Se.current;jh(E,v,()=>kn.current.get(v.deviceId)!==E,qc,At.h264DecodeAcceleration,"interactive").catch(_=>{Se.current!==I||kn.current.get(v.deviceId)!==E||H!==v.deviceId||ee(_ instanceof Error?_.message:String(_||"Control H.264 decode failed"))})},[H,At.h264DecodeAcceleration,qc,Pn]),Do=u.useCallback(v=>{const C=ra.current;C&&C!==v&&dc(C),ra.current=v,Tl.current=0,Oi.current=0,wo.current=0,So.current=0,Tc.current=0,vr.current=0},[]),Rs=u.useCallback(()=>{const v=new Set,C=ra.current,E=_i.current;if(!C||!E||C.width<=0||C.height<=0||vr.current!==E.layoutVersion)return v;for(const I of E.tiles){const _=Cs.current.get(I.deviceId);if(!_||I.width<=0||I.height<=0)continue;const te=Math.max(1,Math.round(I.width)),ie=Math.max(1,Math.round(I.height)),Me=RT,Re=ET;(_.width!==Me||_.height!==Re)&&(_.width=Me,_.height=Re);const qe=_.getContext("2d",{alpha:!1});if(qe){qe.imageSmoothingEnabled=!0,qe.imageSmoothingQuality="high";try{qe.drawImage(C,Math.round(I.x),Math.round(I.y),te,ie,0,0,Me,Re),v.add(I.deviceId)}catch{}}}return v},[]),Ga=u.useCallback((v,C)=>{if(C){Cs.current.set(v,C);const I=Ws.current.get(v);I&&Rn(I,C)&&(ca(v),_l(v,C)),window.requestAnimationFrame(()=>{Rs().has(v)&&ya(v)}),window.requestAnimationFrame(()=>qa(v,!0));return}const E=Cs.current.get(v);Ts(v),En(v,E),Cs.current.delete(v),Ws.current.has(v)||Eo(v)},[Eo,_l,ca,Rs,Rn,qa,En,ya,Ts]),Ia=u.useCallback((v,C)=>{wo.current=performance.now(),vr.current=Number(v.layoutVersion||0),Rs();const E=_i.current?.tiles||[],I=E.length>0?Math.round(v.byteLength/E.length):v.byteLength;for(const _ of E){const te={...v,deviceId:_.deviceId,width:_.width,height:_.height,sourceWidth:_.width,sourceHeight:_.height,byteLength:I};Wi(te,{...C,deviceId:_.deviceId,width:_.width,height:_.height,byteLength:I}),Br.current===_.deviceId&&qa(_.deviceId,!0)}},[Wi,Rs,qa]),kr=u.useCallback(v=>{const C=performance.now();Tl.current<=0&&(Tl.current=C),Oi.current=C;const E=ra.current;if(!E)return;const I=_i.current?.tiles||[],_=I.length>0?Math.round(v.byteLength/I.length):v.byteLength;for(const te of I)Pn("wall",{...v,deviceId:te.deviceId,width:te.width,height:te.height,sourceWidth:te.width,sourceHeight:te.height,byteLength:_});jh(E,v,()=>ra.current!==E,Ia).catch(()=>{})},[Ia,Pn]),Es=u.useMemo(()=>({fps:_a,maxWidth:La.maxWidth,maxHeight:La.maxHeight,quality:We.quality,mode:Rt?"mode3-h264-hw":We.frameMode,frameMode:Rt?"mode3-h264-hw":We.frameMode,streamPurpose:"wall",monitorSelections:zt,onFrame:ti}),[_a,ti,La,Rt,zt,We]),us=u.useCallback(v=>{const C=Tt.current;if(Ze.current[v.deviceId]||!C||C.deviceId!==v.deviceId||v.deviceId!==H||v.streamPurpose!=="control"||v.monitorIndex!==an)return;const E=lt.find(I=>I.deviceId===v.deviceId);!E?.sessionId||E.sessionId!==v.sessionId||(Tt.current=af(C.deviceId,C.transitionGeneration,v),he.current=v,be(v),O(I=>I==="connecting"?"active":I))},[lt,H,an]);u.useEffect(()=>{he.current=null;const v=Tt.current;v&&v.deviceId===H&&(Tt.current=af(v.deviceId,v.transitionGeneration,{sessionId:v.sessionId,monitorIndex:an})),be(null)},[H,de,$n,an]);const Va=de?`${de}-monitor-${an}`:"",rd=u.useMemo(()=>({fps:tr,maxWidth:Wr.maxWidth,maxHeight:Wr.maxHeight,quality:At.quality,mode:$n,frameMode:$n,streamPurpose:"control",forceRestart:Va!=="",forceRestartToken:Va,restartReason:Va?"control-session-or-monitor-change":"",monitorSelections:zt,onFrame:ni,onStreamReady:us}),[Va,At.quality,ni,tr,$n,Wr.maxHeight,Wr.maxWidth,us,zt]),{frames:Lo,state:ai,error:Gc,stats:rn,restartLive:Gt}=Py(sn,We.autoStartLive&&sn.length>0,N,Es),{frame:wt,layout:ba,state:xa,stats:Vc,refreshInputs:sr}=B1(Bn,Rt&&We.autoStartLive&&Bn.length>0,N,{fps:bs.atlasOutputFps,inputFps:Ro,width:1920,height:1080,tileWidth:La.maxWidth,tileHeight:La.maxHeight,captureDeviceIds:Bn,monitorSelections:zt,onFrame:kr});u.useEffect(()=>{_i.current=ba,ba&&window.requestAnimationFrame(Rs)},[ba,Rs]),u.useEffect(()=>{if(!Rt||xa!=="open"){Tl.current=0,Oi.current=0,wo.current=0;return}const v=window.setInterval(()=>{const C=ra.current,E=performance.now();if(!C||document.visibilityState!=="visible"||E-Ii.current<$h)return;const I=Oi.current,_=Tl.current;if(I<=0||_<=0||E-I>500)return;const te=wo.current||_,ie=E-te;if(ie>=jT&&E-Tc.current>=MT){ju(C)&&(Tc.current=E,So.current=E);return}ie>=kT&&E-So.current>=AT&&k1(C)&&(So.current=E)},250);return()=>window.clearInterval(v)},[xa,Rt]);const{frames:zl,state:_o,error:Ds,stats:si,restartLive:Yi,reconnectLive:Ki}=Py(ar,ar.length>0,N,rd);u.useEffect(()=>{const v=go.current,C=new Set([...Object.keys(v),...Object.keys(zt)]);for(const E of C){const I=Math.max(0,Math.floor(Number(v[E])||0)),_=Math.max(0,Math.floor(Number(zt[E])||0));I!==_&&(cs("wall",E),cs("control",E),ju(Fn.current.get(E)||null),ju(kn.current.get(E)||null))}go.current={...zt}},[zt,cs]);const ri=u.useMemo(()=>{const v=(E,I)=>{const _=lt.find(ie=>ie.deviceId===E),te=Gn(zt[E],_?qn(_):1);return!Number.isFinite(Number(I.monitorIndex))||Number(I.monitorIndex)===te},C=new Map;for(const[E,I]of Lo.entries())v(E,I)&&C.set(E,I);if(Rt&&wt&&Bn.length>0){const E=new Map((ba?.tiles||[]).map(_=>[_.deviceId,_])),I=Math.max(1,E.size);for(const _ of Bn){const te=E.get(_);te&&C.set(_,{...wt,deviceId:_,width:te.width,height:te.height,sourceWidth:te.width,sourceHeight:te.height,byteLength:Math.round(wt.byteLength/I)})}}for(const[E,I]of zl.entries())v(E,I)&&C.set(E,I);for(const E of Mo){if(!Ys.current.has(E)||C.has(E))continue;const I=Cl.current.get(E);I&&v(E,I)&&C.set(E,I)}return C},[wt,ba,lt,zl,Bn,Rt,zt,Lo,Mo,Xf]),rr=gt&&ar.length>0?_o:Bn.length>0?xa:ai,Wa=gt&&ar.length>0?si:Bn.length>0?Vc:rn;u.useCallback((v,C="browser-stale")=>{const E=Gt(v,C),I=Yi(v,C);return E||I},[Yi,Gt]),u.useEffect(()=>{Rt&&Bn.length>0&&!gt&&sr()},[Bn.length,Rt,sr,gt]);const ds=u.useCallback((v,C,E)=>{const I=C==="control"?kn.current.get(v)||null:Fn.current.get(v)||null;if(!I||!ju(I))return!1;const _=performance.now();return xo.current.set(rs(C,v),_),!0},[]),Ya=u.useCallback(v=>{if($n!=="mode3-h264-hw"||!H||z)return!1;const C=lt.find(Me=>Me.deviceId===H)||oa,E=String(C?.platform||"").toLowerCase();if(!["win32","windows","win32nt"].includes(E))return!1;const I="mode5-lzo-delta",_=rs("control",H),te=performance.now();xr.current.set(_,te),br.current.delete(_),Zs.current.delete(_),As.current.delete(_),Ms.current.delete(_),Js.current.delete(_),ju(kn.current.get(H)||null),Ki([H],"control-decode-fallback"),se(I),Z(`control-${I}-fallback-${H}-${Date.now()}`),ce(!1),ia(!1);const ie=v==="no first frame"||v==="control-first-frame-timeout";return ee(Me=>Me||(ie?`Control frame transport timeout; retrying Control with Mode 5 (${v})`:`H.264 decode failed; retrying Control with Mode 5 (${v})`)),O("connecting"),!0},[lt,oa,H,z,$n,Ki]);u.useEffect(()=>{const v=gt?oa:null;if(v){js.current={deviceId:v.deviceId,monitorIndex:an,frameMode:$n,startedAtEpochMs:Date.now()},ia(H===v.deviceId&&le);return}js.current=null,ia(!1)},[oa?.sessionId,P,H,le,$n,an,gt]);const ir=u.useCallback(async v=>{if(Ze.current[v])throw new Error("LIVE_CAPTURE_PAUSED");const C=A.find(te=>te.deviceId===v);Mu({mode4Enabled:Rt,directMode4WallEnabled:vn,isMac:Ni(C?.platform)});const E=Gn(zt[v],C?qn(C):1),I={fps:Rt?_a:Hn,maxWidth:La.maxWidth,maxHeight:La.maxHeight,quality:We.quality,mode:Rt?"mode3-h264-hw":We.frameMode,frameMode:Rt?"mode3-h264-hw":We.frameMode,streamPurpose:"wall",monitorIndex:E},_=await Ve(`/api/remote/devices/${encodeURIComponent(v)}/live/start`,{method:"POST",body:JSON.stringify(I)},N);if(_?.ok===!1)throw new Error(_.error||"wall-stream-start-failed");return _},[Hn,Ro,A,vn,_a,La.maxHeight,La.maxWidth,N,Rt,zt,We.frameMode,We.quality]),Io=u.useCallback(async v=>{const C=A.find(I=>I.deviceId===v);Mu({mode4Enabled:Rt,directMode4WallEnabled:vn,isMac:Ni(C?.platform)});const E=await Ve(`/api/remote/devices/${encodeURIComponent(v)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"wall",reason:"control-active"})},N);if(E?.ok===!1)throw new Error(E.error||"wall-stream-stop-failed");return E},[A,vn,N,Rt]),ii=u.useCallback(async(v,C="control-session-stop")=>{const E=await Ve(`/api/remote/devices/${encodeURIComponent(v)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"control",reason:C})},N);if(E?.ok===!1)throw new Error(E.error||"control-stream-stop-failed");return E},[N]),lr=u.useCallback(v=>{const C=kn.current.get(v);C&&(Ws.current.has(v)||Fn.current.has(v)||Cs.current.has(v)||En(v,C),dc(C),kn.current.delete(v));const E=Ra.current.get(v);E&&dc(E),Cl.current.delete(v),Ys.current.delete(v),kl.current.delete(v)},[En]),Ka=u.useCallback(v=>{const C=Yy(Zu.current,v);return Zu.current=C.tail,C.result},[]),ln=u.useCallback(v=>{const C=Yy(Ml.current,v);return Ml.current=C.tail,C.result},[]),za=u.useCallback(v=>{os.current=v,Pr.current=0;const C=v?.deviceId||"";Br.current=C,Qu(C),C&&Ys.current.add(C)},[]),li=u.useCallback(v=>Ka(async()=>{if(Ze.current[v.deviceId])return!1;const C=os.current;return!gs(C,v)||!sf(v.deviceId,v,Tt.current)?!1:(await ir(v.deviceId),gs(os.current,v)&&za(null),!0)}),[za,Ka,ir]),id=u.useCallback((v,C,E)=>Ka(async()=>{const I=os.current;if(gs(I,v))return E.stoppedWallDeviceId=v.deviceId,!0;if(I)if(Ze.current[I.deviceId])gs(os.current,I)&&za(null);else{if(!sf(I.deviceId,I,Tt.current))return!1;await ir(I.deviceId),gs(os.current,I)&&za(null)}if(!C())return!1;if(await Io(v.deviceId),E.stoppedWallDeviceId=v.deviceId,!C()){if(sf(E.stoppedWallDeviceId,v,Tt.current))try{await ir(E.stoppedWallDeviceId)}catch(_){throw za(v),_}finally{E.stoppedWallDeviceId=""}return!1}return dc(Fn.current.get(v.deviceId)||null),za(v),!0}),[za,Ka,ir,Io]),zo=u.useCallback(async(v,C)=>{if(C.stoppedWallDeviceId){if(gs(os.current,v)){try{await li(v)}catch(E){He(E instanceof Error?E.message:String(E))}finally{C.stoppedWallDeviceId=""}return}await Ka(async()=>{if(!C.stoppedWallDeviceId||!sf(C.stoppedWallDeviceId,v,Tt.current))return;const E=C.stoppedWallDeviceId;try{await ir(E)}catch(I){za(v),He(I instanceof Error?I.message:String(I))}finally{C.stoppedWallDeviceId=""}})}},[za,Ka,li,He,ir]),jr=u.useCallback(async(v,C,E=!1)=>{try{await ii(v.deviceId,C)}catch(I){if(!E)throw I}if(!gs(Tt.current,v))return!1;Tt.current=null,he.current=null,be(null),lr(v.deviceId),ce(!1),Z(""),se(""),ee(""),ye(I=>I===v.deviceId?"":I);try{await li(v)}catch(I){He(I instanceof Error?I.message:String(I))}return!0},[lr,li,He,ii]),Oo=(gt&&Kt&&P&&!$e.has(P)&&lt.find(v=>v.deviceId===P)||null)?.deviceId||"";u.useEffect(()=>{Nl.current=Oo},[Oo]),u.useEffect(()=>{const v=P&&lt.find(te=>te.deviceId===P)||null;if(!gt||!Kt||!v){la.current&&(++va.current,la.current="");return}if(Ze.current[v.deviceId]){la.current&&(++va.current,la.current=""),H===v.deviceId&&O("paused");return}if(Zt.current){if(Zt.current===v.deviceId)return;Zt.current=""}if(H===v.deviceId&&(W==="active"||W==="warm"||W==="connecting")){O(te=>te==="warm"?"active":te);return}if(la.current===v.deviceId)return;const C=++va.current,E=af(v.deviceId,C,{sessionId:v.sessionId,monitorIndex:an});la.current=v.deviceId;const I={stoppedWallDeviceId:""},_=()=>C===va.current&&Nl.current===E.deviceId;ln(async()=>{if(!_())return;const te=Tt.current;if(te){O("stopping");try{await jr(te,"control-session-switch")}catch(Re){_()&&(O("error"),He(Re instanceof Error?Re.message:String(Re)));return}if(!_()){Tt.current||O("idle");return}}try{if(!await id(E,_,I)||!_()){await zo(E,I),Tt.current||O("idle");return}}catch(Re){await zo(E,I),_()&&(O("error"),He(Re instanceof Error?Re.message:String(Re)));return}if(!_()){await zo(E,I);return}Tt.current=E,Zt.current="",Ea.current=null,Qs.current=0,Xs.current="",I.stoppedWallDeviceId="";const ie=rs("control",E.deviceId),Me=`control-session-${C}-${E.deviceId}`;xr.current.set(ie,performance.now()),br.current.delete(ie),Zs.current.delete(ie),Js.current.delete(ie),Ms.current.delete(ie),se(""),ee(""),Z(Me),ye(E.deviceId),ce(!1),O("connecting")}).catch(te=>{_()&&(O("error"),He(te instanceof Error?te.message:String(te)))}).finally(()=>{va.current===C&&la.current===E.deviceId&&(la.current="")})},[lt,P,H,W,ln,Kt,id,zo,an,He,gt,jr,Qe]),u.useEffect(()=>{if(!H||lt.some(E=>E.deviceId===H))return;const v=H;++va.current,la.current="";const C=Tt.current;O("stopping"),ln(async()=>{C&&C.deviceId===v?await jr(C,"control-device-disconnected",!0):(lr(v),ye(E=>E===v?"":E)),Tt.current||O("idle")})},[lt,H,ln,lr,jr]),u.useEffect(()=>{if(Pa.current!==null&&(window.clearTimeout(Pa.current),Pa.current=null),!H||W==="idle"||W==="paused"||W==="stopping"||W==="error"||gt||zn==="wall"){H&&!gt&&zn==="wall"&&O(C=>C==="warm"||C==="active"?"active":C);return}O(C=>C==="idle"||C==="stopping"?C:"warm");const v=H;return Pa.current=window.setTimeout(()=>{Pa.current=null,++va.current,la.current="";const C=Tt.current;O("stopping"),ln(async()=>{if(C&&C.deviceId===v)try{await jr(C,"control-session-warm-timeout")}catch(E){O("error"),He(E instanceof Error?E.message:String(E));return}else lr(v),ye(E=>E===v?"":E);Tt.current||O("idle")})},NT),()=>{Pa.current!==null&&(window.clearTimeout(Pa.current),Pa.current=null)}},[zn,H,W,ln,lr,He,gt,jr]),u.useEffect(()=>()=>{Pa.current!==null&&window.clearTimeout(Pa.current)},[]),u.useEffect(()=>{const v=os.current,C=Tt.current;if(!v||Ze.current[v.deviceId]||C&&C.deviceId===v.deviceId){Pr.current=0;return}const E=Pr.current,I=Math.min(5e3,500*2**Math.min(E,4)),_=window.setTimeout(()=>{const te=os.current;!te||Ze.current[te.deviceId]||!gs(te,v)||(Pr.current=E+1,li(te).catch(ie=>{He(ie instanceof Error?ie.message:String(ie)),gs(os.current,te)&&!Tt.current&&Nc(Me=>Me+1)}))},I);return()=>window.clearTimeout(_)},[W,li,He,Qf,Yn]);const or=H&&lt.find(v=>v.deviceId===H)||null,Ar=!!(gt&&Ne&&W==="active"&&le&&or?.sessionId&&Q?.deviceId===or.deviceId&&Q.sessionId===or.sessionId&&Q.streamPurpose==="control"&&Q.commandId&&Q.captureGeneration>0&&Q.monitorIndex===an),{state:Ol,sendInput:oi,stats:ua,error:ld}=P1(Ns&&Ar,N),Ho=or?.deviceId||"",Wc=or?.sessionId||"",Fo=Q?.commandId||"",cr=Number(Q?.captureGeneration||0),$o=Number(Q?.monitorIndex||0),Mr=u.useCallback((v,C)=>!Ar||!Ho||!Wc||!Fo||cr<=0||v!==Ho?!1:oi(v,{...C,monitorIndex:$o,controlSessionId:Wc,controlCommandId:Fo,captureGeneration:cr}),[Ar,cr,Fo,Ho,$o,Wc,oi]),Ls=Ar&&Ol==="open",Nr={shiftKey:ne.includes("ShiftLeft"),ctrlKey:ne.includes("ControlLeft"),altKey:ne.includes("AltLeft"),metaKey:ne.includes("MetaLeft")},{state:Yc,lastFrame:Hl,stats:Dn,error:Kc}=X1(Ee?.deviceId||"",Bc&&J,N),Fl=u.useRef(new Map);u.useEffect(()=>{const v=[["hub",j],["registry",l],["license",F],["wall-stream",Gc],["control-stream",Ds],["control-decode",fe],["remote-input",ld],["remote-audio",Kc]];for(const[C,E]of v){const I=String(E||"").trim();if(C==="hub"&&Nt?.requiresHubRestart&&Nt.stage==="updating"){Fl.current.delete(C);continue}if(!I){Fl.current.delete(C);continue}Fl.current.get(C)!==I&&(Fl.current.set(C,I),He(I))}},[Kc,fe,Ds,j,ld,F,l,He,Gc,Nt]);const _s=Ee?.deviceId||"",Tr=Ee?Gn(zt[_s],qn(Ee)):0;u.useEffect(()=>{if(!Ne||!Ns||!Ls||!_s)return;const v=ak(),C=_s,E=Tr,I=bt=>bt?Mr(C,{...bt,monitorIndex:E}):!1,_=(bt,en)=>{const Ca=bt.target,Kn=Ca?.tagName?.toLowerCase(),Za=Ca?.isContentEditable||Kn==="input"||Kn==="textarea"||Kn==="select",vi=v.snapshot().pressedCodes.includes(bt.code);if(Za&&(en==="keydown"||!vi))return;const el=v.event(bt,en);el&&(bt.preventDefault(),bt.stopPropagation(),I(el))},te=bt=>_(bt,"keydown"),ie=bt=>_(bt,"keyup"),Me=(bt,en=!1)=>{const Ca=v.reset(bt,en);Ca&&(I(Ca),Pe([]))};mt.current=bt=>{const en=v.snapshot().latchedCodes.includes(bt),Ca=v.modifier(bt,!en);Ca&&(I(Ca),Pe(Kn=>en?Kn.filter(Za=>Za!==bt):[...Kn.filter(Za=>Za!==bt),bt]))};const Re=()=>Me("browser-window-blur"),qe=()=>Me("browser-page-hidden"),Bt=()=>{document.visibilityState==="hidden"&&Me("browser-document-hidden")};return window.addEventListener("keydown",te),window.addEventListener("keyup",ie),window.addEventListener("blur",Re),window.addEventListener("pagehide",qe),document.addEventListener("visibilitychange",Bt),()=>{window.removeEventListener("keydown",te),window.removeEventListener("keyup",ie),window.removeEventListener("blur",Re),window.removeEventListener("pagehide",qe),document.removeEventListener("visibilitychange",Bt),mt.current=null,Me("control-keyboard-owner-changed",!0)}},[Ns,Ls,_s,Tr,Ne,Mr]),u.useEffect(()=>{const v=()=>{document.visibilityState==="visible"&&(Ii.current=performance.now())};return document.addEventListener("visibilitychange",v),window.addEventListener("pageshow",v),()=>{document.removeEventListener("visibilitychange",v),window.removeEventListener("pageshow",v)}},[]),u.useEffect(()=>{if(!H||W!=="connecting"&&W!=="active"&&W!=="warm"||_o!=="open")return;const v=H,C=rs("control",v),E=window.setInterval(()=>{const I=performance.now();if(document.visibilityState!=="visible"||I-Ii.current<$h)return;const _=br.current.get(C)||0,te=Zs.current.get(C)||0,ie=As.current.get(C)||0,Me=xr.current.get(C)||I;xr.current.has(C)||xr.current.set(C,Me);const Re=_<=0,qe=Re?I-Me>FT:I-_>Jb,Bt=_>0&&(te<=0||I-te>Jb);if(!qe&&Bt){const Kn=xo.current.get(C)||0;I-Kn>=ex&&ds(v,"control","decoder-paint-stale");return}if(!qe)return;const bt=Ms.current.get(C)||0;if(bt>0){if(I-bt<BT)return;Ms.current.delete(C)}const en=Js.current.get(C)||0;if(en>=PT){if(Ya(Re?"no first frame":"stale stream"))return;ce(!1),ia(!1),Zt.current=v,O("error");return}if(I-ie<tx($T,en))return;Yi([v],Re?"control-first-frame-timeout":"control-receive-stale")&&(As.current.set(C,I),Ms.current.set(C,I),xr.current.set(C,I),Js.current.set(C,en+1))},650);return()=>window.clearInterval(E)},[_o,H,W,Ya,ds,Yi]),u.useEffect(()=>{!fe||H&&Ze.current[H]||$n!=="mode3-h264-hw"||Ya(fe)||(ce(!1),ia(!1),Zt.current=Tt.current?.deviceId||"",O("error"))},[fe,H,$n,Ya]),u.useEffect(()=>{!gt||!H||Ze.current[H]||!Ds||(Zt.current=H,O(v=>v==="error"?v:"error"))},[Ds,H,gt]),u.useEffect(()=>{if(W!=="error")return;const v=Tt.current;if(!v)return;Zt.current=v.deviceId,gs(Ea.current,v)||(Ea.current=v,Qs.current=0);const C=Qs.current,E=C===0?0:Math.min(5e3,500*2**Math.min(C-1,4)),I=window.setTimeout(()=>{gs(Tt.current,v)&&(++va.current,la.current="",O("stopping"),ln(async()=>{if(gs(Tt.current,v))try{if(!await jr(v,"control-session-terminal-error"))return;Ea.current=null,Qs.current=0,Xs.current===v.deviceId?(Xs.current="",Zt.current="",O("idle")):O("error")}catch(_){if(!gs(Tt.current,v))return;Qs.current+=1,He(_ instanceof Error?_.message:String(_)),O("error"),Sl(te=>te+1)}}))},E);return()=>window.clearTimeout(I)},[W,Xu,ln,He,jr]);const Qi=u.useCallback(v=>{if(!v||Zt.current!==v)return!1;const C=Tt.current;return++va.current,la.current="",Qs.current=0,C&&C.deviceId===v?(Xs.current=v,Ea.current=null,O("error"),Sl(E=>E+1),!0):(Xs.current="",Zt.current="",Ea.current=null,O("idle"),!0)},[]);u.useEffect(()=>{if(ai!=="open"||!We.autoStartLive||sn.length===0)return;const v=window.setInterval(()=>{const C=performance.now();if(document.visibilityState!=="visible"||C-Ii.current<$h)return;const E=1e3/Math.max(1,_a||We.fps||1),I=Math.max(qT,Math.ceil(E*4)),_=[];for(const te of sn){if(_.length>=WT)break;const ie=rs("wall",te),Me=br.current.get(ie)||0,Re=Me<=0,qe=zi.current.get(ie)||C;if(zi.current.has(ie)||zi.current.set(ie,qe),Re&&C-qe<=UT)continue;const Bt=As.current.get(ie)||0,bt=Zs.current.get(ie)||0,en=Re||C-Me>I,Ca=!Re&&(bt<=0||C-bt>I);if(!en&&Ca){const Za=xo.current.get(ie)||0;C-Za>=ex&&ds(te,"wall","decoder-paint-stale");continue}if(!en)continue;const Kn=Js.current.get(ie)||0;C-Bt>=tx(GT,Kn)&&_.push(te)}if(_.length>0&&Gt(_,_.some(te=>(br.current.get(rs("wall",te))||0)<=0)?"wall-first-frame-timeout":"wall-frame-stale"))for(const te of _){const ie=rs("wall",te);As.current.set(ie,C),zi.current.set(ie,C),br.current.delete(ie),Zs.current.delete(ie),Js.current.set(ie,(Js.current.get(ie)||0)+1)}},VT);return()=>window.clearInterval(v)},[_a,sn,ds,Gt,We.autoStartLive,We.fps,ai]),u.useEffect(()=>{$a(We.fps),Fi.current=Date.now(),er.current=0},[We.fps,We.frameMode,We.adaptiveLoadShedding]),u.useEffect(()=>{h1({h264DecodeAcceleration:We.h264DecodeAcceleration})},[We.h264DecodeAcceleration]),u.useEffect(()=>{if(!Kt||gt||pn==="list"||!We.visibleOnlyLive){Fr([]);return}const v=td.current;if(!v||typeof IntersectionObserver>"u"){Fr(Ao);return}const C=Array.from(v.querySelectorAll("[data-live-device-id]"));if(C.length===0){Fr([]);return}const E=new Map,I=()=>{const te=Uh(C.map(ie=>String(ie.dataset.liveDeviceId||"")).filter(ie=>(E.get(ie)||0)>0));Fr(ie=>Ph(ie,te)?ie:te)},_=new IntersectionObserver(te=>{for(const ie of te){const Me=String(ie.target.dataset.liveDeviceId||"");Me&&E.set(Me,ie.isIntersecting?ie.intersectionRatio||.01:0)}I()},{root:null,rootMargin:Ma.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return C.forEach(te=>_.observe(te)),I(),()=>_.disconnect()},[Ao,Kt,gt,Sr,We.visibleOnlyLive,pn]),u.useEffect(()=>{if(!We.adaptiveLoadShedding||!We.autoStartLive||sn.length===0)return;const v=We.fps;if(sn.length<=Ma.preserveConfiguredFpsDeviceCount){Hn!==v&&($a(v),Fi.current=Date.now(),er.current=0);return}if(ai!=="open"||rn.sampleMs<500)return;const C=Date.now(),E=sn.length*Hn,I=rn.framesPerSecond,_=rn.bytesPerSecond,te=Math.max(0,...sn.map(Bt=>yr[rs("wall",Bt)]?.maxIntervalMs||0)),ie=Math.max(0,...sn.map(Bt=>jl[rs("wall",Bt)]?.maxIntervalMs||0)),Me=E>8&&I>0&&I<E*.72;if(I>Ma.maxWallFramesPerSecond||_>Ma.maxWallBytesPerSecond||te>Ma.maxFrameGapMs||ie>Ma.maxFrameGapMs||Me){er.current=0;const Bt=Ma.minFps;if(C-Fi.current>=Ma.downshiftCooldownMs&&Hn>Bt){const bt=Math.max(Bt,uR(Hn,Bt));bt<Hn&&($a(bt),Fi.current=C)}return}const qe=I<Ma.maxWallFramesPerSecond*Ma.lowLoadFrameRatio&&_<Ma.maxWallBytesPerSecond*Ma.lowLoadByteRatio;if(!qe||Hn>=v){qe||(er.current=0);return}if(!er.current){er.current=C;return}if(C-er.current>=Ma.recoveryCooldownMs){const Bt=Math.min(v,dR(Hn,v));Bt>Hn&&($a(Bt),Fi.current=C,er.current=0)}},[Hn,sn.length,sn,jl,yr,ai,rn.bytesPerSecond,rn.framesPerSecond,rn.lastUpdatedAt,rn.sampleMs,We.adaptiveLoadShedding,We.autoStartLive,We.frameMode,We.fps]),u.useEffect(()=>{const v=new URLSearchParams(window.location.search).get("checkout");if(v==="success"){He("Checkout returned. Waiting for Dodo confirmation."),$();const C=window.setInterval(()=>{$()},4e3),E=window.setTimeout(()=>{window.clearInterval(C)},45e3);return()=>{window.clearInterval(C),window.clearTimeout(E)}}v==="cancelled"&&He("Checkout cancelled.")},[$]),u.useEffect(()=>{!Kt&&Ne&&Fe(!1),!Kt&&J&&ke(!1)},[J,Ne,Kt]),u.useEffect(()=>{const v=Ee?.deviceId||"",C=Le.current;if(Le.current=v,!C||C===v)return;const E=++_e.current,I=v?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";v&&J&&Be.current.set(v,I);let _=!0;return(async()=>{try{const ie=Be.current.get(C);if(Be.current.delete(C),await Ve(`/api/remote/devices/${encodeURIComponent(C)}/audio/stop`,{method:"POST",body:JSON.stringify(ie?{streamId:ie}:{})},N),!_||E!==_e.current||!J||!v||!Kt||!Kr)return;const Me=await Ve(`/api/remote/devices/${encodeURIComponent(v)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:I,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},N);if(Me.ok===!1)throw new Error(Me.error||"Remote audio start failed.")}catch(ie){_&&(Be.current.delete(v),ke(!1),He(ie instanceof Error?ie.message:String(ie)))}})(),()=>{_=!1}},[J,Kt,N,Kr,Ee?.deviceId]),u.useEffect(()=>{const v=lt.map(I=>I.deviceId),C=new Set(v),E=new Map(lt.map(I=>[I.deviceId,I]));for(const I of lt){const _=JT(I);_&&(Tn.current[I.deviceId]=_)}L(I=>{const _=I.filter(te=>C.has(te));return Ph(I,_)?I:_}),G(I=>I&&C.has(I)?I:""),K(I=>I&&C.has(I)?I:""),Cn(I=>{let _=!1;const te={};for(const[ie,Me]of Object.entries(I)){const Re=E.get(ie);if(!Re){te[ie]=Me;continue}const qe=Gn(Me,qn(Re));te[ie]=qe,qe!==Me&&(_=!0)}return _?te:I}),Ec(I=>{const _=I.filter(te=>C.has(te));return Ph(I,_)?I:_})},[lt,ko]),u.useEffect(()=>{Jf([]),tm(!1)},[qa]),u.useEffect(()=>{!El||Hi!=="selected"||qr.length>0||Da.length===0||Ec(Da.map(v=>v.deviceId))},[Da,qr.length,Hi,El]),u.useEffect(()=>{try{localStorage.setItem(Bw,gn)}catch{}},[gn]),u.useEffect(()=>{rR(We)},[We]),u.useEffect(()=>{lR(At)},[At]),u.useEffect(()=>{aR(zt,Tn.current)},[lt,zt]);const Bo=u.useCallback(async()=>{const v=new Set(h);v.add(Mn);try{const te=await Ve("/api/remote/status",void 0,Mn);Ty({endpoint:te.agentEndpoint,endpoint_candidates:[...te.agentEndpointCandidates||[],...te.hostTargetEndpointCandidates||[]]}).forEach(ie=>v.add(ie))}catch{}const C=[...v].sort((te,ie)=>{const Me=Re=>{const qe=Ou(Re);return qe==="local"?0:qe==="loopback"?1:2};return Me(te)-Me(ie)||te.localeCompare(ie)});let E=!1,I="",_=!1;try{for(const te of C){const ie=Ou(te);try{if(await Ve("/api/health",void 0,te),ie==="local")return y(!0),hc(!0),te;ie==="loopback"&&(E=!0,I=te)}catch{ie==="local"&&(_=!0)}}return E?(_&&He("LiveDesk Hub is reachable on this PC, but not through the LAN address yet. Restart LiveDesk Hub to bind 5179 on the network."),y(!0),hc(!0),I||Mn):(y(!1),hc(!1),"")}catch{return y(!1),hc(!1),""}},[h]),Is=async()=>{if(kt("auth"),Mt(!1),await Bo(),window.liveDesk?.auth?.signInWithGoogle){const E=await window.liveDesk.auth.signInWithGoogle();E?.ok===!1&&(He(E.error||"LiveDesk could not open the system browser for Google sign-in."),kt(""));return}const{data:v,error:C}=await Ct.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}/callback`}});C&&(He(C.message),kt(""))},$l=async()=>{kt("auth"),Mt(!1),await Ct.auth.signOut(),(await window.liveDesk?.auth?.persistSession?.(null))?.runtimeCleared===!1?He("Signed out locally. The LiveDesk runtime could not be reached to clear its session."):window.liveDesk?.auth?.persistSession||await Ve("/api/auth/session",{method:"DELETE"},Mn).catch(()=>{}),kt("")};u.useEffect(()=>{if(!st)return;const v=E=>{E.target instanceof Element&&(E.target.closest(".account-popover, .rail-account")||Mt(!1))},C=E=>{E.key==="Escape"&&Mt(!1)};return window.addEventListener("pointerdown",v),window.addEventListener("keydown",C),()=>{window.removeEventListener("pointerdown",v),window.removeEventListener("keydown",C)}},[st]);const Bl=u.useCallback(async(v={})=>{const C=v.silent===!0,E=v.takeover===!0,I=v.requestLocalAccess===!0;if(!n?.user){C||He("Sign in before publishing this host.","error");return}if(!Gr.current){Gr.current=!0,C||(kt("host"),Sn("Hub · 1/4 · Checking the local runtime…"));try{const te=(I?await Bo():"")||N||Mn;if(!(w||await Ve("/api/remote/status",void 0,te)).started)throw new Error("Start LiveDesk on this computer before syncing the server.");C||Sn("Hub · 2/4 · Sending the signed-in session to the Hub…");const Me=await Ve("/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}})},te);if(!Me.ok||!Me.authenticated)throw new Error(Me.error||"hub-session-sync-failed");C||Sn("Hub · 3/4 · Claiming the Hub role and publishing its endpoint…");const Re=await Ve("/api/hub/sync",{method:"POST",body:JSON.stringify({takeover:E})},te);if(!Re.ok)throw new Error(Re.error||"host-target-failed");if(!C){Sn("Hub · 4/4 · Verifying the endpoint and lease renewal…");const qe=await Ve("/api/hub/status",void 0,te);if(!qe.hostTargetActive)throw new Error(qe.hostTargetLease?.lastError||"host-target-not-active-after-sync");const Bt=qe.hostTargetEndpoint||qe.agentEndpoint||"endpoint ready",bt=Number(qe.connectedDeviceCount||0),en=bt>0?`${bt} client${bt===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";He(`Hub ready · ${Bt} · lease auto-renewal active. ${en}`,"success"),(I||x)&&(y(!0),hc(!0)),k()}c()}catch(_){if(!C){const te=_ instanceof Error?_.message:String(_);te.includes("local network access")&&(y(!1),hc(!1)),He(`Hub setup failed · ${te}`,"error")}}finally{Gr.current=!1,C||kt("")}}},[N,x,k,c,Bo,n,He,Sn,w]),ur=u.useCallback((v=!0)=>{ct!=="host"&&(Ae(!1),v&&window.requestAnimationFrame(()=>xt.current?.focus()))},[ct]),Po=u.useCallback(()=>{ct!=="host"&&(xt.current=document.activeElement instanceof HTMLElement?document.activeElement:null,Mt(!1),Ae(!0))},[ct]),od=u.useCallback(()=>{Ae(!1),Bl({takeover:!0,requestLocalAccess:!0})},[Bl]);u.useEffect(()=>{if(!Oe)return;const v=window.requestAnimationFrame(()=>ft.current?.focus()),C=I=>{I.target instanceof Element&&I.target.closest(".client-hub-switch-popover, .hub-sync-trigger")||ur(!1)},E=I=>{I.key==="Escape"&&ur()};return window.addEventListener("pointerdown",C),window.addEventListener("keydown",E),()=>{window.cancelAnimationFrame(v),window.removeEventListener("pointerdown",C),window.removeEventListener("keydown",E)}},[ur,Oe]);const ci=u.useCallback(async()=>{if(!(!w?.update?.canApply||ct==="update")){kt("update");try{const v=await Ve("/api/update/apply",{method:"POST",body:JSON.stringify({})},N||Mn);if(!v.ok)throw new Error(v.error||"LiveDesk update could not be started.");const C=[...new Set((v.targets||[]).map(_=>String(_.deviceId||"").trim()).filter(Boolean))],E=!!(v.managerUpdateAvailable||v.clientPackageUpdateAvailable),I=v.state==="hub-restart-requested"?Date.now():void 0;(C.length>0||E)&&ga({operationId:String(v.operationId||`wall-update-${Date.now()}`),targetIds:C,stage:v.state==="clients-updated"?"updated":"updating",requiresHubRestart:E,initialHostInstanceId:String(w.hostInstanceId||""),targetManagerVersion:String(v.latestVersion||w.update?.latestVersion||""),targetClientVersion:String(v.latestClientVersion||w.update?.latestClientVersion||""),restartRequestedAt:I,restartDeadlineAt:I?I+bf:void 0}),Sn(v.state==="hub-restart-requested"?yf:Vb),k()}catch(v){He(v instanceof Error?v.message:String(v),"error")}finally{kt("")}}},[ct,N,k,He,Sn,w]);u.useEffect(()=>{const v=Nt,C=w?.update;if(!v||v.stage!=="updating"||!C)return;const E=C.restartResult?.operationId===v.operationId?C.restartResult:null;if(E?.outcome==="restored"){const Re=E.error||`The requested Hub ${E.targetVersion||v.targetManagerVersion||"version"} failed verification.`;ga(qe=>qe?.operationId===v.operationId?{...qe,stage:"restored",error:Re}:qe),He(`LiveDesk update did not complete. Hub ${E.fallbackVersion||E.appVersion||"the previous version"} was restored. ${Re}`,"error");return}if(E?.outcome==="failed"){const Re=E.error||"No verified LiveDesk Hub replacement could be started.";ga(qe=>qe?.operationId===v.operationId?{...qe,stage:"failed",error:Re}:qe),He(`LiveDesk Hub update failed. ${Re}`,"error");return}if(C.operationId===v.operationId&&C.state==="failed"){const Re=C.error||"LiveDesk update failed before the Hub replacement completed.";ga(qe=>qe?.operationId===v.operationId?{...qe,stage:"failed",error:Re}:qe),He(Re,"error");return}if(C.operationId===v.operationId){if(C.state==="hub-restart-requested"&&!v.restartDeadlineAt){const Re=Date.now();ga(qe=>qe?.operationId===v.operationId?{...qe,restartRequestedAt:Re,restartDeadlineAt:Re+bf}:qe),Sn(yf)}!v.requiresHubRestart&&C.state==="clients-updated"&&(ga(Re=>Re?.operationId===v.operationId?{...Re,stage:"updated"}:Re),He("LiveDesk clients updated and reconnected successfully.","success"));return}if(!v.requiresHubRestart)return;const I=w.started===!0&&(!v.initialHostInstanceId||w.hostInstanceId&&w.hostInstanceId!==v.initialHostInstanceId),_=!!C.checkedAt,te=Wb(C.currentVersion,v.targetManagerVersion),ie=!v.targetClientVersion||Wb(C.currentClientVersion,v.targetClientVersion),Me=_&&C.state==="idle"&&C.updateAvailable===!1&&te&&ie;I&&Me&&(ga(Re=>Re?.operationId===v.operationId?{...Re,stage:"updated"}:Re),He(`LiveDesk Hub ${C.currentVersion||E?.appVersion||v.targetManagerVersion} restarted and passed version verification.`,"success"))},[He,Sn,w,Nt]),u.useEffect(()=>{const v=Nt;if(!v||v.stage!=="updating"||!v.requiresHubRestart||v.restartDeadlineAt)return;const C=()=>{const I=Date.now();ga(_=>_?.operationId===v.operationId&&_.stage==="updating"&&!_.restartDeadlineAt?{..._,restartRequestedAt:I,restartDeadlineAt:I+bf}:_),Sn(yf)};if(w?.update?.state==="hub-restart-requested"){C();return}if(!j)return;const E=window.setTimeout(C,DT);return()=>window.clearTimeout(E)},[j,Sn,w?.update?.state,Nt]),u.useEffect(()=>{const v=Nt;if(!v||v.stage!=="updating"||!v.requiresHubRestart||!v.restartDeadlineAt)return;const C=Math.max(0,v.restartDeadlineAt-Date.now()),E=v.operationId,I=window.setTimeout(()=>{const _=`LiveDesk Hub did not return and verify ${v.targetManagerVersion||"the requested version"} within ${Math.round(bf/6e4)} minutes. Check the Hub terminal or restart log, then run livedesk@latest manually if the Hub is still offline.`;ga(te=>te?.operationId===E&&te.stage==="updating"?{...te,stage:"failed",error:_}:te),He(_,"error")},C);return()=>window.clearTimeout(I)},[He,Nt]),u.useEffect(()=>{if(!Nt||Nt.stage!=="updated")return;const v=Nt.operationId,C=window.setTimeout(()=>{ga(E=>E?.operationId===v?null:E)},8e3);return()=>window.clearTimeout(C)},[Nt]),u.useEffect(()=>{if(Ie!==Vb&&Ie!==yf)return;const v=w?.update;if(String(v?.state||"")==="failed"){He(v?.error||"LiveDesk update failed.","error");return}Nt?.stage==="updated"&&He("")},[Ie,He,w?.update?.error,w?.update?.state,Nt?.stage]);const cd=u.useCallback(async()=>{if(!ct){kt("pin");try{const C=await Ve("/api/remote/pairing-pin",{method:"POST"},N||Mn);if(!C.ok)throw new Error(C.error||"pin-rotation-failed");await k(),He("New PIN published.")}catch(v){He(v instanceof Error?v.message:String(v))}finally{kt("")}}},[ct,N,k]),zs=u.useCallback(v=>{v&&(G(v),L(C=>C.includes(v)?C:[...C,v]))},[]),Pl=u.useCallback(v=>{if(!v)return;const C=Yr.has(v);G(E=>C?E===v?"":E:v),L(E=>C?E.filter(I=>I!==v):E.includes(v)?E:[...E,v])},[Yr]),ui=u.useCallback(()=>{L([]),G("")},[Rn]),dr=u.useCallback(()=>{L(lt.map(v=>v.deviceId)),G("")},[lt]),Os=u.useCallback((v,C)=>{const E=lt.find(_=>_.deviceId===v);if(!E)return;const I=qn(E);if(!(I<=1)&&(Cn(_=>{const te=Gn(_[v],I),ie=(te+C+I)%I;return ie===te?_:{..._,[v]:ie}}),cs("wall",v),cs("control",v),Li(_=>{if(!_.has(v))return _;const te=new Set(_);return te.delete(v),te}),Cl.current.delete(v),Ys.current.delete(v),gt)){const _=Qi(v);ce(!1),_||O("connecting"),ia(!1),K(v)}},[lt,cs,Qi,gt]);u.useEffect(()=>{const v=C=>{if(Ne&&Ns&&Ls)return;const E=C.target,I=E?.tagName?.toLowerCase();E?.isContentEditable||I==="input"||I==="textarea"||I==="select"||((C.ctrlKey||C.metaKey)&&C.key.toLowerCase()==="a"&&(C.preventDefault(),dr()),C.key==="Escape"&&ui())};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[Ns,ui,Ls,Ne,dr]);const Ul=(v,C)=>{const E=lt.find(ie=>ie.deviceId===v),I=E?qn(E):1,_=Gn(zt[v],I),te=Gn(C,I);if(_!==te&&(Cn(ie=>({...ie,[v]:te})),Li(ie=>{if(!ie.has(v))return ie;const Me=new Set(ie);return Me.delete(v),Me}),Cl.current.delete(v),Ys.current.delete(v),cs("wall",v),cs("control",v)),gt){const ie=Qi(v);_!==te&&(ce(!1),ie||O("connecting")),ia(!1),K(v)}else zs(v)},di=async v=>{if(Qi(v),ia(!1),K(v),ws("control"),!Xr.has(v)){Fe(!1),He(Jr);return}const C=lt.find(I=>I.deviceId===v);if(Ni(C?.platform)&&(C?.capabilities?.controlPermission===!1||C?.capabilities?.accessibilityPermission===!1)){Fe(!1),He("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts LiveDesk, then restart the Mac client.","error");return}Fe(!0),He(`Opening remote control${C?` for ${ha(C)}`:""}.`,"success")},Qc=async()=>{if(!Ee){He("Select a Client before playing audio.");return}if(!Kt){He(Jr);return}if(!Kr){He("Selected Client does not report remote audio support yet.");return}if(pe)return;const v=!J,C=v?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:Be.current.get(Ee.deviceId);v&&C?Be.current.set(Ee.deviceId,C):v||Be.current.delete(Ee.deviceId),De("audio"),ke(v);try{await Ve(`/api/remote/devices/${encodeURIComponent(Ee.deviceId)}/audio/${v?"start":"stop"}`,{method:"POST",body:JSON.stringify({...C?{streamId:C}:{},mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},N),He(`${v?"Audio started":"Audio stopped"} for ${ha(Ee)}.`,"success")}catch(E){v&&Be.current.delete(Ee.deviceId),ke(!1),He(E instanceof Error?E.message:String(E),"error")}finally{De("")}},ql=async()=>{if(!Ee){He("Select a Client before pausing video.");return}if(!Kt){He(Jr);return}if(pe)return;const v=Ee,C=v.deviceId,E=String(Ze.current[C]||""),I=!!E&&ve[C]===!0,_=!E||I;if(De("video"),_){const te=E||`pending:${Date.now()}:${C}`,ie=Tt.current?.deviceId===C?Tt.current:null,Me=ut.current.get(C);ut.current.set(C,{deviceId:C,monitorIndex:Gn(zt[C]??Me?.monitorIndex,qn(v)),previousControlOwner:ie||Me?.previousControlOwner||null}),pt(C,!0),it(C,!1),dt(C,te),(ie||H===C)&&(++va.current,la.current="",O("paused"));try{const Re=await Ve(`/api/remote/devices/${encodeURIComponent(C)}/live/pause`,{method:"POST",body:JSON.stringify({reason:"user-video-pause"})},N);if(!Re?.pauseToken){U.current.delete(C),dt(C,""),it(C,!1),ut.current.delete(C),(ie||H===C)&&(he.current=null,be(null),ce(!1),Z(`control-pause-rollback-${Date.now()}-${C}`),O("connecting")),He(Re?.error||"video-capture-pause-failed","error");return}const qe=Tt.current?.deviceId===C?Tt.current:ie,Bt=ut.current.get(C);Bt&&(Bt.previousControlOwner=qe),Tt.current?.deviceId===C&&(Tt.current=null),he.current=null,be(null),dt(C,Re.pauseToken),(qe||H===C)&&O("paused"),Re.ok===!1||Re.captureStopConfirmed!==!0?(it(C,!0),He(`Video restart is blocked for ${ha(v)}, but Client capture shutdown was not confirmed: ${Re.stopError||Re.error||"unknown stop error"}. Press Retry pause to check again.`,"error")):(it(C,!1),He(`Video paused for ${ha(v)}. Client capture and FFmpeg shutdown were confirmed.`,"success")),k()}catch(Re){it(C,!0),k(),He(`Video pause could not be confirmed: ${Re instanceof Error?Re.message:String(Re)}. LiveDesk will reconcile Hub status before allowing restart.`,"error")}finally{De("")}return}if(E.startsWith("pending:")){De("");return}try{pt(C,!1);const te=await Ve(`/api/remote/devices/${encodeURIComponent(C)}/live/resume`,{method:"POST",body:JSON.stringify({pauseToken:E})},N);if(te?.ok===!1)throw new Error(te.error||"video-capture-resume-failed");const ie=ut.current.get(C),Me=ie?.previousControlOwner||null,Re=H===C&&(Me!==null||os.current?.deviceId===C||W==="paused");if(dt(C,""),it(C,!1),ut.current.delete(C),Re){const qe=++va.current;la.current="";const Bt=af(C,qe,{sessionId:v.sessionId||Me?.sessionId,monitorIndex:Gn(zt[C]??ie?.monitorIndex,qn(v))});Tt.current=Bt,za(Bt),Zt.current="",Ea.current=null,he.current=null,be(null),se(""),ee(""),ce(!1),cs("control",C);const bt=`control-video-resume-${qe}-${C}`;Z(bt),ye(C),O("connecting")}else cs("wall",C);k(),He(`Video resumed for ${ha(v)}.`,"success")}catch(te){U.current.delete(C),k(),He(te instanceof Error?te.message:String(te),"error")}finally{De("")}},Gl=v=>{const C=v instanceof Error?v.message:String(v);return/remote-actions-disabled|allowAgent-blocked-by-settings/i.test(C)?"Remote actions are off. Turn on Settings > Agent > Enable AI Agent first.":/power-actions-disabled/i.test(C)?"Power actions are off. Turn on Settings > Agent > Allow power actions first.":/agent-tool-capability-unavailable|unsupported-agent-operation/i.test(C)?"This Client needs a newer LiveDesk Client for power actions.":/device-not-connected|404 device-not-found/i.test(C)?"The Client disconnected before the action could be sent.":C},Uo=async v=>{if(!Ee||pe)return;const C=Ee,I={sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[v];if(window.confirm(`${I} ${ha(C)}? Unsaved work on that computer may be lost.`)){De(v),He(`Sending ${I.toLowerCase()} request to ${ha(C)}...`);try{const _=await Ve(`/api/remote/devices/${encodeURIComponent(C.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:v})},N);if(!_.ok)throw new Error(_.error||"The remote action could not be sent.");He(`${I} request sent to ${ha(C)}.`,"success"),k()}catch(_){He(Gl(_),"error")}finally{De("")}}},Xc=async(v,C,E="files")=>{const I=v.filter(Me=>Me.file.size>=0);if(I.length===0)return{files:0,bytes:0};if(!Kt)throw new Error(Jr);if(C.length===0)throw new Error("Select at least one connected Client.");const _=crypto.randomUUID(),te=I.reduce((Me,Re)=>Me+Re.file.size,0);let ie=0;wr({id:_,status:"reading",progress:1,message:`Preparing ${I.length} ${E}`});try{for(let Me=0;Me<I.length;Me+=1){const Re=I[Me],qe=Re.file,Bt=Math.max(1,Math.ceil(qe.size/Hh));for(let bt=0;bt<Bt;bt+=1){const en=bt*Hh,Ca=Math.min(qe.size,en+Hh),Kn=qe.size===0?new ArrayBuffer(0):await qe.slice(en,Ca).arrayBuffer(),Za=bt===Bt-1;wr({id:_,status:"sending",progress:Math.max(2,Math.min(98,Math.round(ie/Math.max(1,te)*96))),message:`${Me+1}/${I.length} ${Re.relativePath}`});const vi=await Ve("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:_,deviceIds:C,remoteDirectory:gn.trim(),name:qe.name,relativePath:Re.relativePath,size:qe.size,type:qe.type,lastModified:qe.lastModified,offset:en,totalBytes:qe.size,final:Za,dataBase64:fR(Kn)})},N);if(!vi.ok||vi.queued!==C.length)throw new Error(vi.error||`file-chunk-not-queued-${vi.queued}/${C.length}`);ie+=Kn.byteLength,await new Promise(el=>window.setTimeout(el,0))}}return wr({id:_,status:"queued",progress:100,message:`Sent ${I.length} file${I.length===1?"":"s"} to ${C.length} Client${C.length===1?"":"s"}`}),window.setTimeout(()=>{wr(Me=>Me?.id===_&&Me.status==="queued"?null:Me)},4500),{files:I.length,bytes:te}}catch(Me){throw wr({id:_,status:"failed",progress:100,message:Me instanceof Error?Me.message:String(Me)}),Me}},fi=async v=>{const C=Da.length>0?Da.map(E=>E.deviceId):Ee?[Ee.deviceId]:[];try{await Xc(ax(v),C)}catch(E){He(E instanceof Error?E.message:String(E))}},Vl=async v=>{try{await Xc(ax(v),ad)}catch(C){He(C instanceof Error?C.message:String(C))}};u.useEffect(()=>{Dc.current=!1},[]);const ud=v=>{v.preventDefault(),v.stopPropagation(),Rc(!1),fi(v.dataTransfer.files)},Wl=async(v="ltd")=>{if(!n){He("Sign in with Google before checkout.");return}if(T&&v===un){He("LiveDesk license is already active.");return}if(T&&un==="pro"){He("LiveDesk Pro is already active.");return}kt("checkout");try{const{data:C,error:E}=await Ct.functions.invoke("dodo-checkout",{body:{plan:v}});if(E)throw E;if(!C?.checkout_url)throw new Error("Checkout function did not return a checkout URL.");window.location.assign(C.checkout_url)}catch(C){He(C instanceof Error?C.message:String(C)),kt("")}},Xi=YT(),wa=KT(),Sa=To.filter(v=>ri.has(v)).length,Hs=rr==="open"&&Wa.sampleMs>0?`${Wa.framesPerSecond.toFixed(1)} fps`:rr,ze=Ee?gt?zl.get(Ee.deviceId):ri.get(Ee.deviceId):void 0,Yl=Ee?Gn(zt[Ee.deviceId],qn(Ee)):0,fr=Ee?ZT(Ee):[],Oa=typeof ze?.monitorIndex=="number"?Gn(ze.monitorIndex,Math.max(1,ze.monitorCount||1)):Yl,Zi=(ze&&Oa===Yl?Qw(ze):null)||(Ee?Kw(Ee,Yl):null);Zi&&`${Zi.width}${Zi.height}`;const Qa=Ee?rs(gt?"control":"wall",Ee.deviceId):"",et=Qa?yr[Qa]:void 0,St=Qa?jl[Qa]:void 0,nt=St?.lastInfo,qo=et&&et.sampleMs>0?`${et.framesPerSecond.toFixed(1)} fps`:"waiting";et&&`${et.totalFrames}${qo}`,St&&St.sampleMs>0&&`${St.framesPerSecond.toFixed(1)}`,St&&St.sampleMs>0&&`${St.changedFramesPerSecond.toFixed(1)}`,nt&&(`${nt.frameSeq}${nt.decoderLabel}${nt.queueSize}${nt.renderQueueSize}${nt.droppedForLatency}${nt.decoderFlushCount}${nt.decoderTimestampFallbacks}${nt.decoderInputCount}${nt.decoderOutputCount}`,nt.visualChanged),nt&&`${Math.round(nt.queuedForMs)}${Math.round(nt.decodedForMs)}${Math.round(nt.scheduledForMs)}${nt.drawMs.toFixed(1)}`,nt?.targetPaintIntervalMs&&`${nt.targetPaintIntervalMs.toFixed(1)}${(1e3/nt.targetPaintIntervalMs).toFixed(1)}`,St&&`${St.decoderInputFps.toFixed(1)}${St.decoderOutputFps.toFixed(1)}`,nt?.canvasPresentation,nt&&`${nt.interactiveBufferWaitCount}${Math.round(nt.interactiveBufferWaitMs)}${nt.interactiveQueueDrainCount}`,et&&(ze?.frameMode==="mode5-lzo-delta"?`${Lu(et.averageFrameBytes)}${ze.deltaVisualTileCount||0}${ze.deltaRefreshTileCount||0}${ze.deltaTotalTiles||0}`:`${Lu(et.averageFrameBytes)}${Math.round(et.tinyFrameRatio*100)}${Math.round(et.repeatedFrameRatio*100)}`),et&&et.sourceSendSampleCount>0&&`${et.sourceSendAverageMs.toFixed(1)}${et.sourceSendP95Ms.toFixed(1)}`,Qb(et),Qb(St),et&&St&&`${Xb(et)}${Xb(St)}`,ze?ze.frameMode||ze.mode||ze.codec||ze.mimeType:gt?At.frameMode:We.frameMode,gt?At.frameMode:We.frameMode,ze?`${ze.width}${ze.height}${Lu(ze.byteLength)}`:gt?`${Wr.maxWidth}${Wr.maxHeight}`:`${We.maxWidth}${We.maxHeight}`,ze&&`${ze.isKeyFrame?"key":String(ze.chunkType||"delta")}`,ze&&ze.monitorCount&&((ze.monitorIndex??0)+1,`${ze.monitorCount}`),ze&&[`src ${Math.round(ze.sourceGapMs||0)}ms`,`gap ${Math.round(ze.agentSendGapMs||0)}ms`,`tx ${Math.round(ze.agentSendDurationMs||0)}ms`,`pace ${Math.round(ze.agentPaceMs||0)}ms`,`queue ${Math.round(ze.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(ze.agentFrameAgeMs||0)}ms`,ze.hubPacketTransitAgeMs!==void 0?`sock ${Math.max(0,Math.round(ze.hubPacketTransitAgeMs))}ms`:"",ze.droppedByAgent?`drop ${ze.droppedByAgent}`:"",ze.hubIngressDropped?`ingress-drop ${ze.hubIngressDropped}`:"",ze.hubClientDropped?`ws-drop ${ze.hubClientDropped}`:"",ze.captureStageMs?`capture ${Math.round(ze.captureStageMs)}ms`:"",ze.requestedFps?`req ${Math.round(ze.requestedFps)}fps`:"",ze.effectiveFps?`eff ${Math.round(ze.effectiveFps)}fps`:"",ze.captureAverageMs?`avg ${Math.round(ze.captureAverageMs)}ms`:"",ze.captureP95Ms?`p95 ${Math.round(ze.captureP95Ms)}ms`:"",ze.slowFrameCount?`slow ${Math.round(ze.slowFrameCount)}`:"",ze.captureHelperRestarts?`helper ${Math.round(ze.captureHelperRestarts)}`:"",ze.convertMs?`rgb565 ${Math.round(ze.convertMs)}ms`:"",ze.compressMs?`lzo ${Math.round(ze.compressMs)}ms`:"",ze.captureSourceSerial?`cap #${ze.captureSourceSerial}`:"",ze.captureSourceSkipped?`cap skip ${ze.captureSourceSkipped}`:"",ze.frameMode==="mode5-lzo-delta"?`tiles ${ze.deltaVisualTileCount||0}+${ze.deltaRefreshTileCount||0}/${ze.deltaTotalTiles||0}@${ze.deltaTileSize||0}`:"",ze.platformProfile||ze.hardwareEncoder||"-",ze.atlasComposeMs?`atlas ${ze.atlasComposeMs.toFixed(1)}ms`:"",ze.atlasPoolStarved?`pool ${ze.atlasPoolStarved}`:"",ze.atlasTileCount?`tiles ${ze.atlasReadyTiles||0}/${ze.atlasTileCount}`:"",ze.atlasInputRevision?`input #${ze.atlasInputRevision}`:"",ze.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(ze.atlasSourceMaxAgeMs)}ms`:"",nt?.inputFeedbackMs!==void 0&&nt.inputFeedbackAt!==void 0&&performance.now()-nt.inputFeedbackAt<=qb?`feedback ${Math.round(nt.inputFeedbackMs)}ms`:"",ze.contentHash?`enc ${ze.contentHash.slice(0,6)}`:"",nt?.visualHash?`pix ${nt.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "),Ol==="open"&&[`${ua.sentPerSecond.toFixed(1)} hz`,ua.lastInputSeq>0?`rtt ${Math.round(ua.lastRoundTripMs)}ms`:"",ua.lastInputSeq>0?`apply ${ua.lastAgentApplyMs.toFixed(1)}ms`:"",ua.droppedPerSecond>0?`drop ${ua.droppedPerSecond.toFixed(1)}/s`:"",ua.bufferedAmount>0?`buf ${Lu(ua.bufferedAmount)}`:"",ua.lastInputType||"ready"].filter(Boolean).join(" / "),nt?.inputFeedbackMs!==void 0&&nt.inputFeedbackAt!==void 0&&performance.now()-nt.inputFeedbackAt<=qb&&`${Math.round(nt.inputFeedbackMs)}${nt.inputFeedbackSeq||0}`,J&&[Yc,`context ${Dn.audioContextState}`,`queue ${Math.round(Dn.queuedMs)}ms`,`last ${Math.round(Dn.lastPacketAgeMs)}ms`,`accepted ${Math.round(Dn.lastAcceptedAgeMs)}ms`,`process ${Math.round(Dn.localProcessingAgeMs)}ms`,`remote ${Math.round(Dn.browserAgeMs)}/${Math.round(Dn.captureAgeMs)}ms`,`heartbeat ${Math.round(Dn.captureStatusAgeMs)}ms`,`capture ${Dn.captureAlive&&Dn.helperAlive?"alive":"down"}`,`drop ${Dn.drops}`,`resync ${Dn.resyncs}`,`restart ${Dn.automaticRestarts}`,Dn.pendingDecodes>0?`decode ${Dn.pendingDecodes}`:"",Hl?`#${Hl.frameSeq}`:"waiting"].filter(Boolean).join(" / "),ze&&`${ze.frameSeq}${Cx(ze.receivedAt||ze.capturedAt)}`;const fs=Math.max(0,Wa.bytesPerSecond*8/1e6),Xa=u.useCallback(()=>{Di(!0),re(Date.now()),k(),Te.current!==null&&window.clearTimeout(Te.current),Te.current=window.setTimeout(()=>{Te.current=null,re(Date.now()),Di(!1)},650)},[k]),Kl=u.useCallback(()=>{if(Wn){Gs(!1);return}Ke(!1),Gs(!0),Xa()},[Xa,Wn]),Ji=u.useCallback(()=>{if(B){Ke(!1);return}Gs(!1),Ke(!0),Xa()},[B,Xa]),mi=u.useCallback(()=>{if(ht){fn(!1);return}fn(!0),Xa()},[ht,Xa]),Ql=new Map,Jt=new Map;if(Wn||B||ht)for(const v of lt){const C=v.deviceId,E=gt&&H===C,_=rs(E?"control":"wall",C),te=E?zl.get(C):ri.get(C),ie=E?kn.current.get(C)||Ra.current.get(C)||null:Fn.current.get(C)||(Rt?ra.current:null),Me={device:v,frame:te,receiveStat:yr[_],paintStat:jl[_],codec:ie?Hy(ie):{},selectedMonitorIndex:Gn(zt[C],qn(v)),control:E,controlInputReady:E&&Ls,controlBinding:E&&Q?.deviceId===C?Q:void 0,capturePaused:$e.has(C),capturePauseConfirmed:v.liveCapturePause?.captureStopConfirmed===!0,capturePauseError:v.liveCapturePause?.stopError||"",clientHeartbeatMs:Number(w?.heartbeatMs||5e3),now:Date.now()};(Wn||ht)&&Ql.set(C,eT(Me)),B&&Jt.set(C,tT(Me))}const Zc=ht?nT({status:w||{},deviceDiagnostics:[...Ql.values()],codec:Hy(),browser:{hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:Number(navigator.deviceMemory||0)},frameStats:Wa}):[],Go=wt?.atlasReadyTiles??Sa,Vo=wt?.atlasTileCount??Sa,dd=Go===Vo?`${Vo} tiles`:`${Go}/${Vo} tiles`,rm=Bn.length>0;gt?`${Hs}${fs.toFixed(fs>=10?0:1)}`:rm?`${dd}${Hs}${fs.toFixed(fs>=10?0:1)}`:`${Sa}${Hs}${fs.toFixed(fs>=10?0:1)}`;const Xl=Da.length,Jc=gt?Ee?ha(Ee):"No Client":Xl===0?"No Client":Xl>1?`${Xl} selected`:Ee?ha(Ee):"No Client",eu=gt?[Ee?.deviceId].filter(v=>!!v):Da.map(v=>v.deviceId),$t=wc[Ue]||wc.en,on=$t.sync||wc.en.sync,Wo=a||D?"checking":T?un==="pro"?"Pro LTD active":`Plus LTD ${lt.length}/${Du}`:Ui?`Free ${lt.length}/${Eu}`:`Upgrade ${lt.length}/${Eu}`,Ko=T?un==="pro"?"Pro active":"Upgrade to Pro LTD":n?ct==="checkout"?"Opening checkout":un==="ltd"?"Buy Pro LTD":"Buy Plus LTD":ct==="auth"?"Opening Google":"Sign in to buy",tu=un==="pro"||ct==="checkout"||ct==="auth"||a||D,Fs=n?.user?.user_metadata,hi=sx(Fs,"avatar_url","picture"),pi=sx(Fs,"full_name","name")||n?.user?.email||"Google",Qo=pi.slice(0,1).toUpperCase(),fd=w?.started?"Local app ready":"Start LiveDesk",md=i?.active?"Published":n?"Not published":"Sign in required",hd=/^\d{6}$/.test(w?.pairingPin||"")?w?.pairingPin:"------",Xo=v=>{if(typeof window<"u"&&(v==="support"?window.history.pushState({},"","/support"):zn==="support"&&window.history.pushState({},"","/")),v==="control"){const C=oa||$i;if(C&&(Qi(C.deviceId),ia(!1),K(C.deviceId)),ws(v),!Kt){Fe(!1),He(Jr);return}Fe(!0);return}v==="wall"&&Ba(C=>C+1),ws(v),Fe(!1)},gi=ct==="update"||Nt?.stage==="updating"||["dispatching","waiting-for-clients","hub-restart-requested"].includes(w?.update?.state||""),pd=!!(w?.update?.updateAvailable&&w.update.canApply||gi||Nt?.error||!w&&Nt),mr=FC(Ue),Zo=u.useCallback(v=>{if(!Nt?.targetIds.includes(v))return;const C=w?.update?.operationId===Nt.operationId?w.update.targets?.find(E=>E.deviceId===v):void 0;switch(C?.state){case"completed":return{state:"updated",label:"Updated"};case"failed":return{state:"failed",label:"Update failed",error:C.error};case"pending-offline":return{state:"offline",label:"Waiting for reconnect"};case"queued":return Nt.stage==="updating"?{state:"queued",label:"Queued"}:void 0;case"waiting":return Nt.stage==="updating"?C.candidateSince?{state:"updating",label:"Verifying restart..."}:{state:"updating",label:"Restarting..."}:void 0;default:return Nt.stage==="updated"?{state:"updated",label:"Updated"}:Nt.stage==="updating"?{state:"updating",label:"Verifying..."}:void 0}},[w?.update,Nt]);return r.jsxs("main",{className:"app-shell",children:[r.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk tools",children:[r.jsx("div",{className:"rail-brand",title:"LiveDesk",children:r.jsx(kx,{size:25})}),r.jsx("nav",{className:"rail-tools",children:bR.map(v=>{const C=v.icon,E=Rf(v.tooltip,Ue);return r.jsxs("button",{className:`rail-tool ${v.id==="sync-server"?"sync-server hub-sync-trigger":""} ${zn===v.id?"active":""} accent-${v.accent}`,onClick:()=>v.id==="sync-server"?Po():Xo(v.id),"data-tooltip":v.id==="sync-server"&&Oe?void 0:tp(v.label,v.tooltip,Ue),"aria-label":`${v.label}. ${E}`,type:"button",disabled:v.id==="sync-server"&&ct==="host","aria-busy":v.id==="sync-server"&&ct==="host","aria-expanded":v.id==="sync-server"?Oe:void 0,"aria-haspopup":v.id==="sync-server"?"dialog":void 0,"aria-controls":v.id==="sync-server"&&Oe?"hub-sync-popover":void 0,children:[v.id==="sync-server"&&ct==="host"?r.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):r.jsx(C,{size:19}),r.jsx("span",{children:v.id==="sync-server"&&ct==="host"?"Syncing…":v.label})]},v.id)})}),r.jsxs("div",{className:"rail-footer",children:[xR.map(v=>{const C=v.icon;return r.jsxs("button",{className:`rail-tool compact ${zn===v.id?"active":""} accent-${v.accent}`,onClick:()=>Xo(v.id),title:v.label,type:"button",children:[r.jsx(C,{size:18}),r.jsx("span",{children:v.label})]},v.id)}),r.jsxs("button",{className:`rail-tool compact local-settings ${Rl?"active":""}`,onClick:()=>{ws("settings"),typeof window<"u"&&window.history.pushState({},"","/"),Mt(!1),Fe(!1),Yt(!1)},title:"Settings",type:"button",children:[r.jsx(wp,{size:18}),r.jsx("span",{children:"Settings"})]}),r.jsxs("button",{className:`rail-account ${n?"signed-in":""}`,onClick:()=>{Mt(v=>!v)},disabled:a||ct==="auth","aria-expanded":st,title:n?`Account: ${n.user?.email||pi}`:"Sign in with Google",type:"button",children:[n?hi?r.jsx("img",{src:hi,alt:pi,referrerPolicy:"no-referrer"}):r.jsx("span",{className:"avatar-fallback",children:Qo}):r.jsx(mo,{size:18}),r.jsx("span",{children:n?"Account":"Google"})]}),st&&r.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[r.jsxs("div",{className:"account-popover-head",children:[r.jsx("div",{className:"account-popover-avatar",children:n&&hi?r.jsx("img",{src:hi,alt:pi,referrerPolicy:"no-referrer"}):n?r.jsx("span",{children:Qo}):r.jsx(mo,{size:18})}),r.jsxs("div",{children:[r.jsx("strong",{children:n?pi:"Account"}),r.jsx("p",{children:n?.user?.email||"Not signed in"})]})]}),r.jsxs("dl",{className:"account-popover-facts",children:[r.jsx("dt",{children:"User"}),r.jsx("dd",{children:n?.user?.email||"Not signed in"}),r.jsx("dt",{children:"Network"}),r.jsx("dd",{children:fd}),r.jsx("dt",{children:"Access"}),r.jsx("dd",{children:md}),r.jsx("dt",{children:"Plan"}),r.jsx("dd",{children:Wo}),r.jsx("dt",{children:"Ads"}),r.jsx("dd",{children:un==="free"?"Standard banner":"Removed"})]}),n?r.jsxs("button",{className:"account-popover-action",onClick:$l,disabled:ct==="auth",type:"button",children:[r.jsx(cx,{size:16}),"Logout"]}):r.jsxs("button",{className:"account-popover-action primary",onClick:Is,disabled:ct==="auth",type:"button",children:[r.jsx(mo,{size:16}),"Sign in with Google"]})]})]})]}),Oe&&r.jsxs("section",{id:"hub-sync-popover",className:"client-hub-switch-popover hub-sync-popover",role:"dialog","aria-modal":"false","aria-labelledby":"hub-sync-title","aria-describedby":"hub-sync-description hub-sync-notice",children:[r.jsxs("header",{className:"client-hub-switch-head",children:[r.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:r.jsx(zr,{size:19})}),r.jsx("span",{className:"client-hub-switch-eyebrow",children:mr.eyebrow}),r.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>ur(),"aria-label":mr.closeLabel,children:r.jsx(Na,{size:17})})]}),r.jsx("h2",{id:"hub-sync-title",children:mr.title}),r.jsx("p",{id:"hub-sync-description",children:mr.description}),r.jsxs("p",{id:"hub-sync-notice",className:"client-hub-switch-notice",children:[r.jsx(Vn,{size:16,"aria-hidden":"true"}),r.jsx("span",{children:mr.restartNotice})]}),r.jsxs("div",{className:"client-hub-switch-actions",children:[r.jsx("button",{type:"button",onClick:()=>ur(),children:mr.cancel}),r.jsxs("button",{ref:ft,className:"primary",type:"button",onClick:od,disabled:ct==="host",children:[r.jsx(zr,{size:16}),mr.confirm]})]})]}),r.jsxs("section",{className:`desk-stage ${Dl&&!qt?"dock-open":""} ${gt?"control-stage":""} ${zc?"agents-stage":""}`,children:[r.jsxs("header",{className:"topbar",children:[r.jsxs("div",{className:"brand",children:[r.jsx("span",{className:"brand-mark",children:r.jsx(ho,{size:18})}),r.jsxs("div",{className:"brand-copy",children:[r.jsx("h1",{children:"LiveDesk"}),r.jsx("p",{children:"Control wall for local machines"})]}),pd?r.jsxs("button",{className:"topbar-update-button",onClick:()=>{ci()},title:Nt?.error?`LiveDesk Hub update failed: ${Nt.error}`:`Update LiveDesk to ${w?.update?.latestVersion||Nt?.targetManagerVersion||"latest"}`,"aria-label":Nt?.error?`LiveDesk Hub update failed: ${Nt.error}`:gi?"LiveDesk update in progress":`Update LiveDesk to ${w?.update?.latestVersion||Nt?.targetManagerVersion||"latest"}`,type:"button",disabled:gi||!w?.update?.canApply,"aria-busy":gi,children:[gi?r.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):r.jsx(xp,{size:19,"aria-hidden":"true"}),gi&&w?.update?.targetCount?r.jsxs("span",{className:"topbar-update-count","aria-hidden":"true",children:[w.update.completedCount||0,"/",w.update.targetCount]}):null]}):null]}),r.jsxs("div",{className:"topbar-tray",children:[El&&!gt&&r.jsxs("div",{className:"file-share-top-route","aria-label":"File distribution route",children:[r.jsxs("div",{children:[r.jsx(co,{size:17}),r.jsxs("span",{children:[r.jsx("small",{children:"Source"}),r.jsx("strong",{children:"LiveDesk Hub"})]})]}),r.jsx(jp,{size:15}),r.jsx(z0,{size:16}),r.jsxs("div",{children:[r.jsx("span",{className:"file-share-top-route-laptops",children:"▣ ▣ ▣"}),r.jsxs("span",{children:[r.jsx("small",{children:"Destination"}),r.jsxs("strong",{children:[Co," Client",Co===1?"":"s"]}),r.jsx("em",{children:gn.trim()||"Desktop/LiveDeskFiles"})]})]})]}),Dl&&!gt&&r.jsxs("div",{className:"top-actions",children:[r.jsx(Fb,{active:ht,refreshing:ht&&Fa,onClick:mi}),r.jsx(Ob,{active:Wn,refreshing:Wn&&Fa,onClick:Kl}),r.jsx(Hb,{active:B,refreshing:B&&Fa,onClick:Ji}),r.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),r.jsx(zb,{controller:No,onError:He}),r.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),r.jsx("div",{className:"segmented-control","aria-label":"Wall view",children:yR.map(v=>r.jsx("button",{className:pn===v.id?"active":"",onClick:()=>qs(v.id),type:"button",children:v.label},v.id))})]}),gt&&r.jsxs("div",{className:"top-actions",children:[r.jsx(Fb,{active:ht,refreshing:ht&&Fa,onClick:mi}),r.jsx(Ob,{active:Wn,refreshing:Wn&&Fa,onClick:Kl}),r.jsx(Hb,{active:B,refreshing:B&&Fa,onClick:Ji}),r.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),r.jsx(zb,{controller:No,onError:He})]})]})]}),ht&&Dl&&r.jsx(YN,{items:Zc,collectedAt:Ss,onClose:()=>fn(!1)}),Ic?r.jsxs("section",{className:"doc-page",lang:Ue,dir:Ue==="ar"?"rtl":"ltr",children:[r.jsxs("section",{className:"doc-hero",children:[r.jsxs("div",{className:"doc-hero-copy",children:[r.jsxs("span",{className:"pricing-eyebrow",children:[r.jsx(Tf,{size:16}),$t.eyebrow]}),r.jsx("h2",{children:$t.title}),r.jsx("p",{children:$t.intro})]}),r.jsxs("label",{className:"doc-language-picker",children:[r.jsxs("span",{children:[r.jsx(O0,{size:17}),$t.languageLabel]}),r.jsx("select",{value:Ue,onChange:v=>yt(v.target.value),children:SR.map(v=>r.jsx("option",{value:v.id,children:v.label},v.id))})]})]}),r.jsx("section",{className:"doc-grid",children:$t.sections.map((v,C)=>{const I=[zr,Zh,gy,Vn,$f][C]||Tf;return r.jsxs("article",{className:"doc-card",children:[r.jsx("div",{className:"doc-card-icon",children:r.jsx(I,{size:19})}),r.jsxs("div",{children:[r.jsx("h3",{children:v.title}),r.jsx("p",{children:v.body}),r.jsx("ul",{children:v.points.map(_=>r.jsx("li",{children:_},_))})]})]},v.title)})}),on&&r.jsxs("section",{className:"doc-sync",children:[r.jsxs("div",{className:"doc-sync-head",children:[r.jsx(gy,{size:20}),r.jsxs("div",{children:[r.jsx("h3",{children:on.title}),r.jsx("p",{children:on.body})]})]}),r.jsx("ul",{children:on.points.map(v=>r.jsx("li",{children:v},v))})]}),r.jsxs("section",{className:"doc-firewall",children:[r.jsxs("div",{className:"doc-firewall-head",children:[r.jsx(Vn,{size:20}),r.jsxs("div",{children:[r.jsx("h3",{children:$t.firewall.title}),r.jsx("p",{children:$t.firewall.body})]})]}),r.jsx("ul",{children:$t.firewall.points.map(v=>r.jsx("li",{children:v},v))})]}),r.jsxs("section",{className:"doc-command-panel",children:[r.jsxs("div",{className:"doc-command-head",children:[r.jsx(Zh,{size:20}),r.jsxs("div",{children:[r.jsx("h3",{children:$t.commands.title}),r.jsx("p",{children:$t.commands.body})]})]}),r.jsxs("div",{className:"doc-command-list",children:[$t.commands.manager&&r.jsxs("div",{className:"doc-command-row",children:[r.jsx("span",{children:$t.commands.manager}),r.jsx("code",{children:wa}),r.jsx("button",{className:"icon-button",onClick:()=>Cf(wa),title:"Copy command",type:"button",children:r.jsx(mh,{size:16})})]}),r.jsxs("div",{className:"doc-command-row",children:[r.jsx("span",{children:$t.commands.primary}),r.jsx("code",{children:Xi}),r.jsx("button",{className:"icon-button",onClick:()=>Cf(Xi),title:"Copy command",type:"button",children:r.jsx(mh,{size:16})})]}),r.jsxs("div",{className:"doc-command-row",children:[r.jsx("span",{children:$t.commands.slot}),r.jsx("code",{children:`${Xi} 3`}),r.jsx("button",{className:"icon-button",onClick:()=>Cf(`${Xi} 3`),title:"Copy command",type:"button",children:r.jsx(mh,{size:16})})]})]})]})]}):zc?r.jsx(Lb,{hubUrl:N,devices:A}):El?r.jsx(GM,{hubUrl:N,devices:lt,localFeatureAccess:Kt,upgradeNotice:Jr,remoteDirectory:gn,onRemoteDirectoryChange:nn,targetMode:Hi,selectedTargetIds:qr,onTargetModeChange:em,onTargetToggle:v=>Ec(C=>C.includes(v)?C.filter(E=>E!==v):[...C,v]),filePickerRef:nm,folderPickerRef:am,onBrowserFileImport:v=>{Vl(v)},onBrowserFolderImport:v=>{Vl(v)},onNotice:He,onTransferChange:v=>{if(!v){wr(null);return}const C=v.state==="failed"||v.state==="partially-failed"||v.state==="cancelled"?"failed":v.state==="completed"?"queued":v.state==="sending"?"sending":"reading";wr({id:v.id,status:C,progress:v.progress,message:v.message}),["completed","partially-failed","failed","cancelled"].includes(v.state)&&window.setTimeout(()=>wr(E=>E?.id===v.id?null:E),4500)}}):Vr?r.jsx(xx,{session:n,currentProductKey:"livedesk",appVersion:"",onSignIn:Is}):Rl?r.jsx(ck,{hubUrl:N,runtimeRole:w?.runtimeRole||"hub",runtimeDeviceId:w?.deviceId||"",sessionAccessToken:n?.access_token||"",pin:r.jsxs(uk,{children:[r.jsx("div",{className:"settings-section-grid",children:r.jsxs("section",{className:"settings-section-card settings-pairing-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Pair a Client"}),r.jsx("h3",{children:"Connect another local PC"})]}),r.jsx(Ta,{size:20})]}),r.jsxs("div",{className:"settings-pin-display",children:[r.jsx("span",{children:"Hub PIN"}),r.jsx("strong",{children:hd}),r.jsxs("button",{className:"text-button ghost compact",onClick:cd,disabled:!w?.started||ct==="pin",type:"button",children:[r.jsx(Ti,{size:15}),ct==="pin"?"Creating":"New PIN"]})]})]})}),r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"File transfer"}),r.jsx("h3",{children:"Client destination folder"})]}),r.jsx(gc,{size:20})]}),r.jsxs("label",{className:"settings-field",children:[r.jsx("span",{children:"Remote folder"}),r.jsx("input",{value:gn,onChange:v=>nn(v.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),r.jsx("p",{className:"settings-help",children:"Blank uses Desktop/LiveDeskFiles on each Client."})]})]}),agent:r.jsx(fk,{hubUrl:N}),captureGallery:r.jsx(VN,{hubUrl:N,onToast:He})}):_c?r.jsxs("section",{className:"pricing-page",children:[r.jsxs("header",{className:"pricing-header",children:[r.jsxs("div",{children:[r.jsxs("span",{className:"pricing-eyebrow",children:[r.jsx(Qh,{size:15})," LiveDesk plans"]}),r.jsx("h2",{children:"Choose the plan that fits your wall"}),r.jsx("p",{children:"Start free with a local screen wall. Upgrade when you need ad-free monitoring, more Clients, or commercial controls."})]}),r.jsx("button",{className:"pricing-close",onClick:()=>Xo("wall"),title:"Close pricing",type:"button",children:r.jsx(Na,{size:18})})]}),r.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[r.jsx("span",{children:"Current plan"}),r.jsx("strong",{children:Bi.name}),r.jsxs("small",{children:[lt.length,"/",HT(Pi)," connected devices"]})]}),r.jsxs("div",{className:"pricing-cards","aria-label":"LiveDesk plans",children:[r.jsxs("article",{className:`pricing-plan-card ${un==="free"?"current":""}`,children:[r.jsxs("div",{className:"pricing-plan-topline",children:[r.jsx("span",{className:"pricing-plan-badge free",children:"Free"}),r.jsx("strong",{children:"$0"})]}),r.jsx("p",{className:"pricing-plan-audience",children:so.free.audience}),r.jsx("h3",{children:"Monitor your local wall"}),r.jsx("p",{children:so.free.note}),r.jsxs("ul",{children:[r.jsxs("li",{children:[r.jsx(Xn,{size:16})," Up to ",Eu," devices"]}),r.jsxs("li",{children:[r.jsx(Xn,{size:16})," Live view and local control"]}),r.jsxs("li",{children:[r.jsx(Xn,{size:16})," Standard ad-supported banner"]})]}),r.jsx("span",{className:"pricing-current-label",children:un==="free"?"Current plan":"Included for everyone"})]}),r.jsxs("article",{className:`pricing-plan-card featured ${un==="ltd"?"current":""}`,children:[r.jsxs("div",{className:"pricing-plan-topline",children:[r.jsxs("span",{className:"pricing-plan-badge plus",children:[r.jsx(H0,{size:14})," Plus"]}),r.jsx("strong",{children:"$5"})]}),r.jsx("p",{className:"pricing-plan-audience",children:so.ltd.audience}),r.jsx("h3",{children:"Ad-free monitoring"}),r.jsx("p",{children:"More room for personal AI Clients without the standard banner."}),r.jsxs("ul",{children:[r.jsxs("li",{children:[r.jsx(Xn,{size:16})," Up to ",Du," devices"]}),r.jsxs("li",{children:[r.jsx(Xn,{size:16})," No standard ad banner"]}),r.jsxs("li",{children:[r.jsx(Xn,{size:16})," ",so.ltd.ltd]})]}),r.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>Wl("ltd"):Is,disabled:un!=="free"||ct==="checkout"||ct==="auth"||a||D,type:"button",children:[r.jsx(Iu,{size:16}),un==="free"?n?"Choose Plus":"Sign in for Plus":"Plus active"]})]}),r.jsxs("article",{className:`pricing-plan-card pro ${un==="pro"?"current":""}`,children:[r.jsxs("div",{className:"pricing-plan-topline",children:[r.jsxs("span",{className:"pricing-plan-badge pro",children:[r.jsx(Vn,{size:14})," Pro"]}),r.jsx("strong",{children:"$15"})]}),r.jsx("p",{className:"pricing-plan-audience",children:so.pro.audience}),r.jsx("h3",{children:"For serious operations"}),r.jsx("p",{children:"Commercial-ready monitoring for larger AI labs, studios, and teams."}),r.jsxs("ul",{children:[r.jsxs("li",{children:[r.jsx(Xn,{size:16})," 30+ Client walls"]}),r.jsxs("li",{children:[r.jsx(Xn,{size:16})," Commercial use included"]}),r.jsxs("li",{children:[r.jsx(Xn,{size:16})," ",so.pro.ltd]})]}),r.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>Wl("pro"):Is,disabled:un==="pro"||ct==="checkout"||ct==="auth"||a||D,type:"button",children:[r.jsx(Iu,{size:16}),un==="pro"?"Pro active":n?"Choose Pro":"Sign in for Pro"]})]})]}),r.jsxs("section",{className:"pricing-includes",children:[r.jsxs("div",{children:[r.jsx(Ta,{size:17}),r.jsx("span",{children:"Screen wall"}),r.jsx("strong",{children:"120+ slots"})]}),r.jsxs("div",{children:[r.jsx(Xh,{size:17}),r.jsx("span",{children:"Focused control"}),r.jsx("strong",{children:"Local-first"})]}),r.jsxs("div",{children:[r.jsx(vy,{size:17}),r.jsx("span",{children:"Remote audio"}),r.jsx("strong",{children:"Available"})]}),r.jsxs("div",{children:[r.jsx(gc,{size:17}),r.jsx("span",{children:"File transfer"}),r.jsx("strong",{children:"Included"})]})]}),r.jsxs("p",{className:"pricing-note",children:[r.jsx(Xn,{size:15})," Commercial use requires Pro. Plus LTD is for personal, creator, and homelab use."]}),r.jsxs("button",{className:"pricing-primary-cta",onClick:n?()=>Wl(un==="ltd"?"pro":"ltd"):Is,disabled:tu,type:"button",children:[r.jsx(Iu,{size:18}),Ko]})]}):r.jsx(r.Fragment,{children:r.jsxs("section",{className:`monitor-layout ${qt?"dock-collapsed":""}`,children:[r.jsxs("section",{ref:td,className:`screen-wall-panel ${Zf?"drop-active":""}`,onClick:v=>{v.currentTarget===v.target&&ui()},onDragEnter:v=>{v.preventDefault(),Rc(!0)},onDragOver:v=>{v.preventDefault(),v.dataTransfer.dropEffect="copy"},onDragLeave:v=>{v.currentTarget===v.target&&Rc(!1)},onDrop:ud,children:[Bn.length>0&&r.jsx("canvas",{ref:Do,className:"atlas-source-canvas",width:ba?.width||1920,height:ba?.height||1080,"aria-hidden":"true"}),gt?r.jsx("section",{className:"control-focus",children:r.jsxs("div",{className:"control-wall",children:[Ee&&fr.length>1&&r.jsx("div",{className:"control-monitor-tabs","aria-label":"Select monitor",children:fr.map(v=>r.jsxs("button",{className:v.index===Yl?"active":"",onClick:()=>Ul(Ee.deviceId,v.index),title:eR(v),type:"button",children:[r.jsx("span",{children:v.name||`Display ${v.index+1}`}),v.width>0&&v.height>0&&r.jsxs("small",{children:[v.width,"x",v.height]})]},v.index))}),Ee&&Ls&&r.jsx("div",{className:"control-modifier-bar","aria-label":"Hold remote modifier keys",children:ST.map(v=>{const C=v.code==="MetaLeft"&&Ni(Ee.platform)?"Cmd":v.label,E=ne.includes(v.code);return r.jsx("button",{className:E?"active":"",type:"button","aria-pressed":E,title:`Hold ${C} on the remote computer`,onClick:()=>mt.current?.(v.code),children:C},v.code)})}),Ee?r.jsx(Wh,{device:Ee,frame:ze,selected:!1,controlEnabled:Ns&&Ne&&Ls,showStatus:At.showScreenStatus,monitorIndex:Gn(zt[Ee.deviceId],qn(Ee)),monitorCount:qn(Ee),onSelect:()=>{},onFocusDevice:()=>K(Ee.deviceId),onOpenControl:()=>di(Ee.deviceId),onCycleMonitor:v=>Os(Ee.deviceId,v),onCanvasReady:Uc,sendInput:Mr,remoteModifierState:Nr,presentationReady:bo,remoteDiagnostics:B?Jt.get(Ee.deviceId):Wn?Ql.get(Ee.deviceId):void 0,diagnosticsMode:B?"debug":"remote"},Ee.deviceId):r.jsxs("div",{className:"control-empty",children:[r.jsx(Ta,{size:30}),r.jsx("strong",{children:"No Client"}),r.jsx("span",{children:"Open a Client from the Wall."})]}),Ee&&jo&&r.jsxs("div",{className:"control-connection-overlay",role:"alert",children:[r.jsx(Vn,{size:22,"aria-hidden":"true"}),r.jsx("strong",{children:"Accessibility permission required"}),r.jsx("small",{children:"On the Mac, allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client."})]}),Ee&&!jo&&!bo&&r.jsxs("div",{className:"control-connection-overlay",role:"status","aria-live":"polite",children:[W!=="error"&&r.jsx("span",{className:"control-connection-spinner","aria-hidden":"true"}),r.jsx("strong",{children:W==="error"?"Connection failed":"Connecting"}),r.jsx("small",{children:W==="error"?"See the notification for details. Reopen Control to retry.":Ds||fe?"Control stream is recovering. See the notification for details.":rr==="open"?"Preparing the first control frame":"Opening the Control stream"})]})]})}):pn==="list"?r.jsxs("div",{className:"wall-device-list",role:"grid","aria-label":"Computer status list",children:[r.jsxs("div",{className:"wall-device-list-head",role:"row",children:[r.jsx("span",{role:"columnheader",children:"Computer"}),r.jsx("span",{role:"columnheader",children:"Status"}),r.jsx("span",{role:"columnheader",children:"CPU"}),r.jsx("span",{role:"columnheader",children:"GPU"}),r.jsx("span",{role:"columnheader",children:"RAM"}),r.jsx("span",{role:"columnheader",children:"VRAM"}),r.jsx("span",{role:"columnheader",children:"Network"}),r.jsx("span",{role:"columnheader",children:"HDD"}),r.jsx("span",{role:"columnheader",children:"Temp"})]}),Hc.length>0?Hc.map(({device:v,slotNumber:C})=>r.jsx(jR,{device:v,slotNumber:C,selected:Yr.has(v.deviceId),updateIndicator:Zo(v.deviceId),onSelect:()=>Pl(v.deviceId),onOpenControl:()=>di(v.deviceId)},v.deviceId)):r.jsxs("div",{className:"wall-device-list-empty",children:[r.jsx(Ta,{size:24,"aria-hidden":"true"}),r.jsx("strong",{children:"No connected computers"})]})]}):Rt?r.jsx("div",{className:`screen-wall atlas-slot-wall size-${pn}`,onClick:v=>{v.currentTarget===v.target&&ui()},children:Sr.map((v,C)=>v?r.jsx(Wh,{device:v,frame:ri.get(v.deviceId),selected:Yr.has(v.deviceId),controlEnabled:!1,showStatus:We.showScreenStatus,monitorIndex:Gn(zt[v.deviceId],qn(v)),monitorCount:qn(v),onSelect:()=>Pl(v.deviceId),onFocusDevice:()=>zs(v.deviceId),onOpenControl:()=>di(v.deviceId),onCycleMonitor:E=>Os(v.deviceId,E),onCanvasReady:Mu({mode4Enabled:Rt,directMode4WallEnabled:vn,isMac:Ni(v.platform)})==="direct"?Cr:Ga,sendInput:Mr,remoteModifierState:Nr,updateIndicator:Zo(v.deviceId),presentationReady:We.autoStartLive&&Ua.includes(v.deviceId)?vo.has(v.deviceId):void 0,showPresentationSpinner:We.autoStartLive&&Ua.includes(v.deviceId),remoteDiagnostics:B?Jt.get(v.deviceId):Wn?Ql.get(v.deviceId):void 0,diagnosticsMode:B?"debug":"remote"},v.deviceId):r.jsx(ix,{index:C},`slot-${C}`))}):r.jsx("div",{className:`screen-wall size-${pn}`,onClick:v=>{v.currentTarget===v.target&&ui()},children:Sr.map((v,C)=>v?r.jsx(Wh,{device:v,frame:ri.get(v.deviceId),selected:Yr.has(v.deviceId),controlEnabled:Ns&&Ne&&Ls&&Ee?.deviceId===v.deviceId,showStatus:We.showScreenStatus,monitorIndex:Gn(zt[v.deviceId],qn(v)),monitorCount:qn(v),onSelect:()=>Pl(v.deviceId),onFocusDevice:()=>zs(v.deviceId),onOpenControl:()=>di(v.deviceId),onCycleMonitor:E=>Os(v.deviceId,E),onCanvasReady:Cr,sendInput:Mr,remoteModifierState:Nr,updateIndicator:Zo(v.deviceId),presentationReady:We.autoStartLive&&Ua.includes(v.deviceId)?vo.has(v.deviceId):void 0,showPresentationSpinner:We.autoStartLive&&Ua.includes(v.deviceId),remoteDiagnostics:B?Jt.get(v.deviceId):Wn?Ql.get(v.deviceId):void 0,diagnosticsMode:B?"debug":"remote"},v.deviceId):r.jsx(ix,{index:C},`slot-${C}`))}),r.jsx(NR,{visible:ei&&!gt})]}),!Rl&&r.jsxs("aside",{className:`right-dock actions-mode ${qt?"collapsed":""}`,"aria-label":"LiveDesk tools",children:[r.jsx("button",{className:"dock-toggle",onClick:()=>Yt(v=>!v),"aria-label":qt?"Show control panel":"Hide control panel",title:qt?"Show control panel":"Hide control panel",type:"button",children:qt?r.jsx(yx,{size:18}):r.jsx(Ap,{size:18})}),!qt&&r.jsxs(r.Fragment,{children:[r.jsxs("section",{className:"action-dock",children:[r.jsx("input",{ref:nd,className:"hidden-file-input",type:"file",multiple:!0,onChange:v=>{v.currentTarget.files&&fi(v.currentTarget.files),v.currentTarget.value=""}}),r.jsxs("div",{className:"manual-action-bar",role:"toolbar","aria-label":"Manual Client controls",children:[r.jsx(ao,{label:"Control",tooltip:Ee?jo?"Allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client.":Ns?Ls?"Keyboard and mouse control is ready":"Waiting for the current Control capture session":"Remote control is not available on this Client":"Select a Client to use Control",onClick:()=>{if(Ee){if(gt&&Ne){Fe(!1),He("Remote control paused. Screen viewing stays on.");return}di(Ee.deviceId)}},disabled:!Ns||!!pe,active:Ne,pressed:gt&&Ne,children:r.jsx(Xh,{size:17})}),r.jsx(ao,{label:"Audio",tooltip:Ee?Kr?J?"Stop hearing this Client":"Hear this Client":"Audio is not available on this Client":"Select a Client to use Audio",onClick:()=>{Qc()},disabled:!Bc||!!pe,active:J,pressed:J,children:pe==="audio"?r.jsx(Lr,{className:"spin",size:17}):r.jsx(vy,{size:17})}),r.jsx(ao,{label:Pc?"Retry pause":qi?"Resume video":"Pause video",tooltip:Ee?Pc?"Retry stopping Client screen capture and wait for FFmpeg shutdown confirmation":qi?"Resume Client screen capture and video encoding":"Pause Client screen capture and stop FFmpeg encoding":"Select a Client to pause video",onClick:()=>{ql()},disabled:!Ee||!Kt||!!pe,active:qi,pressed:qi,children:pe==="video"?r.jsx(Lr,{className:"spin",size:17}):qi&&!Pc?r.jsx(F0,{size:17}):r.jsx($0,{size:17})}),r.jsx(ao,{label:"Send files",tooltip:Da.length===0&&!gt?"Select one or more Clients to send files":Ee?"Choose files and send them to the selected Client":"Select a Client to send files",onClick:()=>{He(`Choose files to send to ${Jc}.`),nd.current?.click()},disabled:!!pe||!Kt||(gt?!Ee:Da.length===0),children:r.jsx(gc,{size:17})}),r.jsx(ao,{label:"Restart",tooltip:Ee?Qr?"Restart Client":"Restart is not available on this Client":"Select a Client to restart",onClick:()=>{Uo("restart")},disabled:!Ee||!Kt||!!pe||!Qr,children:pe==="restart"?r.jsx(Lr,{className:"spin",size:17}):r.jsx(Cp,{size:17})}),r.jsx(ao,{label:"Sleep",tooltip:Ee?"Put Client to sleep":"Select a Client to put to sleep",onClick:()=>{Uo("sleep")},disabled:!Ee||!Kt||!!pe,children:pe==="sleep"?r.jsx(Lr,{className:"spin",size:17}):r.jsx(B0,{size:17})}),r.jsx(ao,{label:"Shut down",tooltip:Ee?"Shut down Client":"Select a Client to shut down",onClick:()=>{Uo("shutdown")},disabled:!Ee||!Kt||!!pe,danger:!0,children:pe==="shutdown"?r.jsx(Lr,{className:"spin",size:17}):r.jsx(P0,{size:17})})]})]}),r.jsx(Lb,{hubUrl:N,devices:A,variant:"dock",selectedDeviceIds:eu})]})]})]})})]}),Ur&&r.jsxs("aside",{className:`transfer-bar state-${Ur.status}`,"aria-live":"polite",children:[r.jsx("span",{className:"transfer-bar-icon","aria-hidden":"true",children:Ur.status==="queued"?r.jsx(Xn,{size:18}):Ur.status==="failed"?r.jsx(Na,{size:18}):r.jsx(hx,{size:18})}),r.jsxs("div",{className:"transfer-bar-copy",children:[r.jsx("p",{children:Ur.message}),r.jsx("div",{className:"transfer-bar-track",children:r.jsx("span",{style:{width:`${Math.max(0,Math.min(100,Ur.progress))}%`}})})]}),r.jsxs("strong",{children:[Math.max(0,Math.min(100,Ur.progress)),"%"]})]}),wn&&r.jsxs("aside",{className:`livedesk-toast tone-${wn.tone}`,role:wn.tone==="error"?"alert":"status","aria-live":wn.tone==="error"?"assertive":"polite","aria-busy":wn.tone==="progress",children:[wn.tone==="progress"&&r.jsx("span",{className:"livedesk-toast-spinner","aria-hidden":"true"}),r.jsx("span",{children:wn.message}),r.jsx("button",{className:"livedesk-toast-close",onClick:()=>He(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:r.jsx(Na,{size:15})})]})]})}function RR(){if(typeof window>"u")return[];const n=window.location.origin;return window.location.port==="5179"?[n]:["http://127.0.0.1:5179"]}function ER(){const[a,i]=u.useState(null);return u.useEffect(()=>{let l=!1,c=!1;const d=async()=>{for(const g of RR())try{const y=await fetch(`${g}/api/runtime`,{cache:"no-store"});if(!y.ok)continue;const b=(await y.json()).role==="hub"?"hub":"client";c=!0,l||i(b);return}catch{}};d();const m=window.setInterval(()=>{d()},1e3),h=window.setTimeout(()=>{!l&&!c&&i("client")},2500);return()=>{l=!0,window.clearInterval(m),window.clearTimeout(h)}},[null]),a?a==="client"?r.jsx(KC,{}):r.jsx(TR,{}):r.jsxs("main",{className:"runtime-role-boot","aria-busy":"true","aria-label":"Starting LiveDesk",children:[r.jsx("span",{className:"runtime-role-boot-mark","aria-hidden":"true"}),r.jsx("strong",{children:"Starting LiveDesk"}),r.jsx("p",{children:"Loading this computer's assigned role..."})]})}Q0.createRoot(document.getElementById("root")).render(r.jsx(u.StrictMode,{children:r.jsx(ER,{})}));