livedesk 0.1.429 → 0.1.430

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,25 @@
1
+ import{r as zS,a as u,M as Gc,S as jn,R as Ho,B as OS,P as Lm,X as la,b as Qc,C as fr,F as Yv,L as Zr,A as Hb,c as HS,d as Kv,E as Xv,T as FS,D as Bh,e as Dn,f as BS,g as PS,h as $S,i as US,j as mr,k as oa,l as qd,m as Do,n as Ph,o as Ol,p as Fb,q as Hl,s as Bb,t as Pb,u as gh,v as qS,w as GS,H as _l,W as ef,x as VS,y as WS,z as Lo,K as $b,G as vh,I as Gi,J as Ub,N as YS,O as KS,Q as XS,U as $h,V as Uh,Y as QS,Z as qh,_ as ZS,$ as Gh,a0 as qb,a1 as JS,a2 as Jr,a3 as Qv,a4 as Vh,a5 as tf,a6 as Zc,a7 as Od,a8 as e0,a9 as Gb,aa as t0,ab as Vb,ac as n0,ad as a0,ae as yh,af as Wb,ag as s0,ah as r0,ai as i0,aj as l0,ak as o0,al as c0,am as Zv,an as u0,ao as d0,ap as f0,aq as m0,ar as bh,as as xh,at as h0,au as p0,av as _m,aw as Im,ax as g0,ay as Jv,az as Yb,aA as v0,aB as y0}from"./icons-VU9ZIqNm.js";import{r as Kb}from"./react-JoD2dl9B.js";import{c as b0}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 zm={exports:{}},zc={};var ey;function x0(){if(ey)return zc;ey=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 p in c)p!=="key"&&(d[p]=c[p])}else d=c;return c=d.ref,{$$typeof:n,type:l,key:m,ref:c!==void 0?c:null,props:d}}return zc.Fragment=a,zc.jsx=i,zc.jsxs=i,zc}var ty;function w0(){return ty||(ty=1,zm.exports=x0()),zm.exports}var r=w0(),Om={exports:{}},Oc={},Hm={exports:{}},Fm={};var ny;function S0(){return ny||(ny=1,(function(n){function a(I,ee){var V=I.length;I.push(ee);e:for(;0<V;){var P=V-1>>>1,re=I[P];if(0<c(re,ee))I[P]=ee,I[V]=re,V=P;else break e}}function i(I){return I.length===0?null:I[0]}function l(I){if(I.length===0)return null;var ee=I[0],V=I.pop();if(V!==ee){I[0]=V;e:for(var P=0,re=I.length,ue=re>>>1;P<ue;){var K=2*(P+1)-1,xe=I[K],z=K+1,le=I[z];if(0>c(xe,V))z<re&&0>c(le,xe)?(I[P]=le,I[z]=V,P=z):(I[P]=xe,I[K]=V,P=K);else if(z<re&&0>c(le,V))I[P]=le,I[z]=V,P=z;else break e}}return ee}function c(I,ee){var V=I.sortIndex-ee.sortIndex;return V!==0?V:I.id-ee.id}if(n.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var d=performance;n.unstable_now=function(){return d.now()}}else{var m=Date,p=m.now();n.unstable_now=function(){return m.now()-p}}var g=[],v=[],x=1,b=null,w=3,C=!1,j=!1,k=!1,M=!1,A=typeof setTimeout=="function"?setTimeout:null,T=typeof clearTimeout=="function"?clearTimeout:null,D=typeof setImmediate<"u"?setImmediate:null;function B(I){for(var ee=i(v);ee!==null;){if(ee.callback===null)l(v);else if(ee.startTime<=I)l(v),ee.sortIndex=ee.expirationTime,a(g,ee);else break;ee=i(v)}}function H(I){if(k=!1,B(I),!j)if(i(g)!==null)j=!0,W||(W=!0,O());else{var ee=i(v);ee!==null&&X(H,ee.startTime-I)}}var W=!1,_=-1,Z=5,G=-1;function q(){return M?!0:!(n.unstable_now()-G<Z)}function Q(){if(M=!1,W){var I=n.unstable_now();G=I;var ee=!0;try{e:{j=!1,k&&(k=!1,T(_),_=-1),C=!0;var V=w;try{t:{for(B(I),b=i(g);b!==null&&!(b.expirationTime>I&&q());){var P=b.callback;if(typeof P=="function"){b.callback=null,w=b.priorityLevel;var re=P(b.expirationTime<=I);if(I=n.unstable_now(),typeof re=="function"){b.callback=re,B(I),ee=!0;break t}b===i(g)&&l(g),B(I)}else l(g);b=i(g)}if(b!==null)ee=!0;else{var ue=i(v);ue!==null&&X(H,ue.startTime-I),ee=!1}}break e}finally{b=null,w=V,C=!1}ee=void 0}}finally{ee?O():W=!1}}}var O;if(typeof D=="function")O=function(){D(Q)};else if(typeof MessageChannel<"u"){var ye=new MessageChannel,me=ye.port2;ye.port1.onmessage=Q,O=function(){me.postMessage(null)}}else O=function(){A(Q,0)};function X(I,ee){_=A(function(){I(n.unstable_now())},ee)}n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(I){I.callback=null},n.unstable_forceFrameRate=function(I){0>I||125<I?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):Z=0<I?Math.floor(1e3/I):5},n.unstable_getCurrentPriorityLevel=function(){return w},n.unstable_next=function(I){switch(w){case 1:case 2:case 3:var ee=3;break;default:ee=w}var V=w;w=ee;try{return I()}finally{w=V}},n.unstable_requestPaint=function(){M=!0},n.unstable_runWithPriority=function(I,ee){switch(I){case 1:case 2:case 3:case 4:case 5:break;default:I=3}var V=w;w=I;try{return ee()}finally{w=V}},n.unstable_scheduleCallback=function(I,ee,V){var P=n.unstable_now();switch(typeof V=="object"&&V!==null?(V=V.delay,V=typeof V=="number"&&0<V?P+V:P):V=P,I){case 1:var re=-1;break;case 2:re=250;break;case 5:re=1073741823;break;case 4:re=1e4;break;default:re=5e3}return re=V+re,I={id:x++,callback:ee,priorityLevel:I,startTime:V,expirationTime:re,sortIndex:-1},V>P?(I.sortIndex=V,a(v,I),i(g)===null&&I===i(v)&&(k?(T(_),_=-1):k=!0,X(H,V-P))):(I.sortIndex=re,a(g,I),j||C||(j=!0,W||(W=!0,O()))),I},n.unstable_shouldYield=q,n.unstable_wrapCallback=function(I){var ee=w;return function(){var V=w;w=ee;try{return I.apply(this,arguments)}finally{w=V}}}})(Fm)),Fm}var ay;function C0(){return ay||(ay=1,Hm.exports=S0()),Hm.exports}var sy;function k0(){if(sy)return Oc;sy=1;var n=C0(),a=zS(),i=Kb();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 p(e){if(e.tag===31){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function g(e){if(d(e)!==e)throw Error(l(188))}function v(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 h=f.alternate;if(h===null){if(o=f.return,o!==null){s=o;continue}break}if(f.child===h.child){for(h=f.child;h;){if(h===s)return g(f),e;if(h===o)return g(f),t;h=h.sibling}throw Error(l(188))}if(s.return!==o.return)s=f,o=h;else{for(var S=!1,E=f.child;E;){if(E===s){S=!0,s=f,o=h;break}if(E===o){S=!0,o=f,s=h;break}E=E.sibling}if(!S){for(E=h.child;E;){if(E===s){S=!0,s=h,o=f;break}if(E===o){S=!0,o=h,s=f;break}E=E.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"),C=Symbol.for("react.transitional.element"),j=Symbol.for("react.portal"),k=Symbol.for("react.fragment"),M=Symbol.for("react.strict_mode"),A=Symbol.for("react.profiler"),T=Symbol.for("react.consumer"),D=Symbol.for("react.context"),B=Symbol.for("react.forward_ref"),H=Symbol.for("react.suspense"),W=Symbol.for("react.suspense_list"),_=Symbol.for("react.memo"),Z=Symbol.for("react.lazy"),G=Symbol.for("react.activity"),q=Symbol.for("react.memo_cache_sentinel"),Q=Symbol.iterator;function O(e){return e===null||typeof e!="object"?null:(e=Q&&e[Q]||e["@@iterator"],typeof e=="function"?e:null)}var ye=Symbol.for("react.client.reference");function me(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 A:return"Profiler";case M:return"StrictMode";case H:return"Suspense";case W: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 B:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case _:return t=e.displayName||null,t!==null?t:me(e.type)||"Memo";case Z:t=e._payload,e=e._init;try{return me(e(t))}catch{}}return null}var X=Array.isArray,I=a.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ee=i.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,V={pending:!1,data:null,method:null,action:null},P=[],re=-1;function ue(e){return{current:e}}function K(e){0>re||(e.current=P[re],P[re]=null,re--)}function xe(e,t){re++,P[re]=e.current,e.current=t}var z=ue(null),le=ue(null),ke=ue(null),Ce=ue(null);function Ue(e,t){switch(xe(ke,t),xe(le,e),xe(z,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?vv(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=vv(t),e=yv(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}K(z),xe(z,e)}function Be(){K(z),K(le),K(ke)}function he(e){e.memoizedState!==null&&xe(Ce,e);var t=z.current,s=yv(t,e.type);t!==s&&(xe(le,e),xe(z,s))}function Xe(e){le.current===e&&(K(z),K(le)),Ce.current===e&&(K(Ce),Dc._currentValue=V)}var et,ce;function ge(e){if(et===void 0)try{throw Error()}catch(s){var t=s.stack.trim().match(/\n( *(at )?)/);et=t&&t[1]||"",ce=-1<s.stack.indexOf(`
2
+ at`)?" (<anonymous>)":-1<s.stack.indexOf("@")?"@unknown:0:0":""}return`
3
+ `+et+e+ce}var Ae=!1;function Le(e,t){if(!e||Ae)return"";Ae=!0;var s=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var o={DetermineComponentFrameRoot:function(){try{if(t){var Se=function(){throw Error()};if(Object.defineProperty(Se.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Se,[])}catch(pe){var oe=pe}Reflect.construct(e,[],Se)}else{try{Se.call()}catch(pe){oe=pe}e.call(Se.prototype)}}else{try{throw Error()}catch(pe){oe=pe}(Se=e())&&typeof Se.catch=="function"&&Se.catch(function(){})}}catch(pe){if(pe&&oe&&typeof pe.stack=="string")return[pe.stack,oe.stack]}return[null,null]}};o.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var f=Object.getOwnPropertyDescriptor(o.DetermineComponentFrameRoot,"name");f&&f.configurable&&Object.defineProperty(o.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var h=o.DetermineComponentFrameRoot(),S=h[0],E=h[1];if(S&&E){var U=S.split(`
4
+ `),ie=E.split(`
5
+ `);for(f=o=0;o<U.length&&!U[o].includes("DetermineComponentFrameRoot");)o++;for(;f<ie.length&&!ie[f].includes("DetermineComponentFrameRoot");)f++;if(o===U.length||f===ie.length)for(o=U.length-1,f=ie.length-1;1<=o&&0<=f&&U[o]!==ie[f];)f--;for(;1<=o&&0<=f;o--,f--)if(U[o]!==ie[f]){if(o!==1||f!==1)do if(o--,f--,0>f||U[o]!==ie[f]){var be=`
6
+ `+U[o].replace(" at new "," at ");return e.displayName&&be.includes("<anonymous>")&&(be=be.replace("<anonymous>",e.displayName)),be}while(1<=o&&0<=f);break}}}finally{Ae=!1,Error.prepareStackTrace=s}return(s=e?e.displayName||e.name:"")?ge(s):""}function Pe(e,t){switch(e.tag){case 26:case 27:case 5:return ge(e.type);case 16:return ge("Lazy");case 13:return e.child!==t&&t!==null?ge("Suspense Fallback"):ge("Suspense");case 19:return ge("SuspenseList");case 0:case 15:return Le(e.type,!1);case 11:return Le(e.type.render,!1);case 1:return Le(e.type,!0);case 31:return ge("Activity");default:return""}}function Ve(e){try{var t="",s=null;do t+=Pe(e,s),s=e,e=e.return;while(e);return t}catch(o){return`
7
+ Error generating stack: `+o.message+`
8
+ `+o.stack}}var Ke=Object.prototype.hasOwnProperty,de=n.unstable_scheduleCallback,je=n.unstable_cancelCallback,fe=n.unstable_shouldYield,_e=n.unstable_requestPaint,Ee=n.unstable_now,mt=n.unstable_getCurrentPriorityLevel,Ht=n.unstable_ImmediatePriority,Dt=n.unstable_UserBlockingPriority,yt=n.unstable_NormalPriority,Ge=n.unstable_LowPriority,At=n.unstable_IdlePriority,ve=n.log,Fe=n.unstable_setDisableYieldValue,He=null,Me=null;function rt(e){if(typeof ve=="function"&&Fe(e),Me&&typeof Me.setStrictMode=="function")try{Me.setStrictMode(He,e)}catch{}}var dt=Math.clz32?Math.clz32:pa,Re=Math.log,An=Math.LN2;function pa(e){return e>>>=0,e===0?32:31-(Re(e)/An|0)|0}var it=256,Xt=262144,Nn=4194304;function Mn(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 wn(e,t,s){var o=e.pendingLanes;if(o===0)return 0;var f=0,h=e.suspendedLanes,S=e.pingedLanes;e=e.warmLanes;var E=o&134217727;return E!==0?(o=E&~h,o!==0?f=Mn(o):(S&=E,S!==0?f=Mn(S):s||(s=E&~e,s!==0&&(f=Mn(s))))):(E=o&~h,E!==0?f=Mn(E):S!==0?f=Mn(S):s||(s=o&~e,s!==0&&(f=Mn(s)))),f===0?0:t!==0&&t!==f&&(t&h)===0&&(h=f&-f,s=t&-t,h>=s||h===32&&(s&4194048)!==0)?t:f}function Cs(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function Ha(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 gr(){var e=Nn;return Nn<<=1,(Nn&62914560)===0&&(Nn=4194304),e}function rs(e){for(var t=[],s=0;31>s;s++)t.push(e);return t}function zn(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function Xi(e,t,s,o,f,h){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 E=e.entanglements,U=e.expirationTimes,ie=e.hiddenUpdates;for(s=S&~s;0<s;){var be=31-dt(s),Se=1<<be;E[be]=0,U[be]=-1;var oe=ie[be];if(oe!==null)for(ie[be]=null,be=0;be<oe.length;be++){var pe=oe[be];pe!==null&&(pe.lane&=-536870913)}s&=~Se}o!==0&&Qi(e,o,0),h!==0&&f===0&&e.tag!==0&&(e.suspendedLanes|=h&~(S&~t))}function Qi(e,t,s){e.pendingLanes|=t,e.suspendedLanes&=~t;var o=31-dt(t);e.entangledLanes|=t,e.entanglements[o]=e.entanglements[o]|1073741824|s&261930}function F(e,t){var s=e.entangledLanes|=t;for(e=e.entanglements;s;){var o=31-dt(s),f=1<<o;f&t|e[o]&t&&(e[o]|=t),s&=~f}}function Je(e,t){var s=t&-t;return s=(s&42)!==0?1:ze(s),(s&(e.suspendedLanes|t))!==0?0:s}function ze(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 kt(e){return e&=-e,2<e?8<e?(e&134217727)!==0?32:268435456:8:2}function ks(){var e=ee.p;return e!==0?e:(e=window.event,e===void 0?32:Pv(e.type))}function Mt(e,t){var s=ee.p;try{return ee.p=e,t()}finally{ee.p=s}}var ga=Math.random().toString(36).slice(2),ne="__reactFiber$"+ga,Te="__reactProps$"+ga,De="__reactContainer$"+ga,st="__reactEvents$"+ga,Gt="__reactListeners$"+ga,It="__reactHandles$"+ga,Qe="__reactResources$"+ga,jt="__reactMarker$"+ga;function cn(e){delete e[ne],delete e[Te],delete e[st],delete e[Gt],delete e[It]}function Jt(e){var t=e[ne];if(t)return t;for(var s=e.parentNode;s;){if(t=s[De]||s[ne]){if(s=t.alternate,t.child!==null||s!==null&&s.child!==null)for(e=jv(e);e!==null;){if(s=e[ne])return s;e=jv(e)}return t}e=s,s=e.parentNode}return null}function On(e){if(e=e[ne]||e[De]){var t=e.tag;if(t===5||t===6||t===13||t===31||t===26||t===27||t===3)return e}return null}function Wt(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e.stateNode;throw Error(l(33))}function mn(e){var t=e[Qe];return t||(t=e[Qe]={hoistableStyles:new Map,hoistableScripts:new Map}),t}function Yt(e){e[jt]=!0}var Gs=new Set,Fa={};function Nt(e,t){Vt(e,t),Vt(e+"Capture",t)}function Vt(e,t){for(Fa[e]=t,e=0;e<t.length;e++)Gs.add(t[e])}var is=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]*$"),Ba={},hn={};function ni(e){return Ke.call(hn,e)?!0:Ke.call(Ba,e)?!1:is.test(e)?hn[e]=!0:(Ba[e]=!0,!1)}function ca(e,t,s){if(ni(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 vr(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 en(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 Hn(e){switch(typeof e){case"bigint":case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Zi(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function yr(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,h=o.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return f.call(this)},set:function(S){s=""+S,h.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 ls(e){if(!e._valueTracker){var t=Zi(e)?"checked":"value";e._valueTracker=yr(e,t,""+e[t])}}function Ji(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var s=t.getValue(),o="";return e&&(o=Zi(e)?e.checked?"true":"false":e.value),e=o,e!==s?(t.setValue(e),!0):!1}function ai(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 Bl=/[\n"\\]/g;function Fn(e){return e.replace(Bl,function(t){return"\\"+t.charCodeAt(0).toString(16)+" "})}function Pl(e,t,s,o,f,h,S,E){e.name="",S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"?e.type=S:e.removeAttribute("type"),t!=null?S==="number"?(t===0&&e.value===""||e.value!=t)&&(e.value=""+Hn(t)):e.value!==""+Hn(t)&&(e.value=""+Hn(t)):S!=="submit"&&S!=="reset"||e.removeAttribute("value"),t!=null?si(e,S,Hn(t)):s!=null?si(e,S,Hn(s)):o!=null&&e.removeAttribute("value"),f==null&&h!=null&&(e.defaultChecked=!!h),f!=null&&(e.checked=f&&typeof f!="function"&&typeof f!="symbol"),E!=null&&typeof E!="function"&&typeof E!="symbol"&&typeof E!="boolean"?e.name=""+Hn(E):e.removeAttribute("name")}function el(e,t,s,o,f,h,S,E){if(h!=null&&typeof h!="function"&&typeof h!="symbol"&&typeof h!="boolean"&&(e.type=h),t!=null||s!=null){if(!(h!=="submit"&&h!=="reset"||t!=null)){ls(e);return}s=s!=null?""+Hn(s):"",t=t!=null?""+Hn(t):s,E||t===e.value||(e.value=t),e.defaultValue=t}o=o??f,o=typeof o!="function"&&typeof o!="symbol"&&!!o,e.checked=E?e.checked:!!o,e.defaultChecked=!!o,S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"&&(e.name=S),ls(e)}function si(e,t,s){t==="number"&&ai(e.ownerDocument)===e||e.defaultValue===""+s||(e.defaultValue=""+s)}function br(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=""+Hn(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 $o(e,t,s){if(t!=null&&(t=""+Hn(t),t!==e.value&&(e.value=t),s==null)){e.defaultValue!==t&&(e.defaultValue=t);return}e.defaultValue=s!=null?""+Hn(s):""}function va(e,t,s,o){if(t==null){if(o!=null){if(s!=null)throw Error(l(92));if(X(o)){if(1<o.length)throw Error(l(93));o=o[0]}s=o}s==null&&(s=""),t=s}s=Hn(t),e.defaultValue=s,o=e.textContent,o===s&&o!==""&&o!==null&&(e.value=o),ls(e)}function Vs(e,t){if(t){var s=e.firstChild;if(s&&s===e.lastChild&&s.nodeType===3){s.nodeValue=t;return}}e.textContent=t}var os=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 ua(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||os.has(t)?t==="float"?e.cssFloat=s:e[t]=(""+s).trim():e[t]=s+"px"}function Ws(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&&ua(e,f,o)}else for(var h in t)t.hasOwnProperty(h)&&ua(e,h,t[h])}function cs(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 xr=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"]]),$l=/^[\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 js(e){return $l.test(""+e)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":e}function Bn(){}var As=null;function Ys(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Ns=null,us=null;function tl(e){var t=On(e);if(t&&(e=t.stateNode)){var s=e[Te]||null;e:switch(e=t.stateNode,t.type){case"input":if(Pl(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="'+Fn(""+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));Pl(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&&Ji(o)}break e;case"textarea":$o(e,s.value,s.defaultValue);break e;case"select":t=s.value,t!=null&&br(e,!!s.multiple,t,!1)}}}var ri=!1;function nl(e,t,s){if(ri)return e(t,s);ri=!0;try{var o=e(t);return o}finally{if(ri=!1,(Ns!==null||us!==null)&&(Gu(),Ns&&(t=Ns,e=us,us=Ns=null,tl(t),e)))for(t=0;t<e.length;t++)tl(e[t])}}function wr(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 ds=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Pa=!1;if(ds)try{var Pn={};Object.defineProperty(Pn,"passive",{get:function(){Pa=!0}}),window.addEventListener("test",Pn,Pn),window.removeEventListener("test",Pn,Pn)}catch{Pa=!1}var Jn=null,fs=null,Ul=null;function ql(){if(Ul)return Ul;var e,t=fs,s=t.length,o,f="value"in Jn?Jn.value:Jn.textContent,h=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[h-o];o++);return Ul=f.slice(e,1<o?1-o:void 0)}function Uo(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 Gl(){return!0}function Sr(){return!1}function ea(e){function t(s,o,f,h,S){this._reactName=s,this._targetInst=f,this.type=o,this.nativeEvent=h,this.target=S,this.currentTarget=null;for(var E in e)e.hasOwnProperty(E)&&(s=e[E],this[E]=s?s(h):h[E]);return this.isDefaultPrevented=(h.defaultPrevented!=null?h.defaultPrevented:h.returnValue===!1)?Gl:Sr,this.isPropagationStopped=Sr,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=Gl)},stopPropagation:function(){var s=this.nativeEvent;s&&(s.stopPropagation?s.stopPropagation():typeof s.cancelBubble!="unknown"&&(s.cancelBubble=!0),this.isPropagationStopped=Gl)},persist:function(){},isPersistent:Gl}),t}var ya={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},ii=ea(ya),Vl=b({},ya,{view:0,detail:0}),fp=ea(Vl),iu,qo,li,al=b({},Vl,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:pt,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!==li&&(li&&e.type==="mousemove"?(iu=e.screenX-li.screenX,qo=e.screenY-li.screenY):qo=iu=0,li=e),iu)},movementY:function(e){return"movementY"in e?e.movementY:qo}}),lu=ea(al),df=b({},al,{dataTransfer:0}),ff=ea(df),Go=b({},Vl,{relatedTarget:0}),sl=ea(Go),rl=b({},ya,{animationName:0,elapsedTime:0,pseudoElement:0}),Ks=ea(rl),Wl=b({},ya,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),ou=ea(Wl),cu=b({},ya,{data:0}),Vo=ea(cu),il={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Wo={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"},ll={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function ct(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):(e=ll[e])?!!t[e]:!1}function pt(){return ct}var da=b({},Vl,{key:function(e){if(e.key){var t=il[e.key]||e.key;if(t!=="Unidentified")return t}return e.type==="keypress"?(e=Uo(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?Wo[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:pt,charCode:function(e){return e.type==="keypress"?Uo(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?Uo(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),ol=ea(da),mf=b({},al,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Yo=ea(mf),oi=b({},Vl,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:pt}),at=ea(oi),uu=b({},ya,{propertyName:0,elapsedTime:0,pseudoElement:0}),hf=ea(uu),Yl=b({},al,{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}),Cr=ea(Yl),du=b({},ya,{newState:0,oldState:0}),Ko=ea(du),kr=[9,13,27,32],$n=ds&&"CompositionEvent"in window,ms=null;ds&&"documentMode"in document&&(ms=document.documentMode);var Un=ds&&"TextEvent"in window&&!ms,hs=ds&&(!$n||ms&&8<ms&&11>=ms),$e=" ",Xo=!1;function fu(e,t){switch(e){case"keyup":return kr.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function mu(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Xs=!1;function cl(e,t){switch(e){case"compositionend":return mu(t);case"keypress":return t.which!==32?null:(Xo=!0,$e);case"textInput":return e=t.data,e===$e&&Xo?null:e;default:return null}}function mp(e,t){if(Xs)return e==="compositionend"||!$n&&fu(e,t)?(e=ql(),Ul=fs=Jn=null,Xs=!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 hs&&t.locale!=="ko"?null:t.data;default:return null}}var hu={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 $t(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t==="input"?!!hu[e.type]:t==="textarea"}function Qo(e,t,s,o){Ns?us?us.push(o):us=[o]:Ns=o,t=Zu(t,"onChange"),0<t.length&&(s=new ii("onChange","change",null,s,o),e.push({event:s,listeners:t}))}var Qs=null,ps=null;function pf(e){dv(e,0)}function Kl(e){var t=Wt(e);if(Ji(t))return e}function Qt(e,t){if(e==="change")return t}var ci=!1;if(ds){var Zo;if(ds){var $a="oninput"in document;if(!$a){var Jo=document.createElement("div");Jo.setAttribute("oninput","return;"),$a=typeof Jo.oninput=="function"}Zo=$a}else Zo=!1;ci=Zo&&(!document.documentMode||9<document.documentMode)}function ul(){Qs&&(Qs.detachEvent("onpropertychange",dl),ps=Qs=null)}function dl(e){if(e.propertyName==="value"&&Kl(ps)){var t=[];Qo(t,ps,e,Ys(e)),nl(pf,t)}}function Ua(e,t,s){e==="focusin"?(ul(),Qs=t,ps=s,Qs.attachEvent("onpropertychange",dl)):e==="focusout"&&ul()}function Zs(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return Kl(ps)}function Xl(e,t){if(e==="click")return Kl(t)}function gs(e,t){if(e==="input"||e==="change")return Kl(t)}function ta(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Ut=typeof Object.is=="function"?Object.is:ta;function fl(e,t){if(Ut(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(!Ke.call(t,f)||!Ut(e[f],t[f]))return!1}return!0}function ec(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function jr(e,t){var s=ec(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=ec(s)}}function pu(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?pu(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function ba(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=ai(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=ai(e.document)}return t}function Ms(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 tc=ds&&"documentMode"in document&&11>=document.documentMode,an=null,xa=null,Js=null,er=!1;function Ts(e,t,s){var o=s.window===s?s.document:s.nodeType===9?s:s.ownerDocument;er||an==null||an!==ai(o)||(o=an,"selectionStart"in o&&Ms(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}),Js&&fl(Js,o)||(Js=o,o=Zu(xa,"onSelect"),0<o.length&&(t=new ii("onSelect","select",null,t,s),e.push({event:t,listeners:o}),t.target=an)))}function wa(e,t){var s={};return s[e.toLowerCase()]=t.toLowerCase(),s["Webkit"+e]="webkit"+t,s["Moz"+e]="moz"+t,s}var Es={animationend:wa("Animation","AnimationEnd"),animationiteration:wa("Animation","AnimationIteration"),animationstart:wa("Animation","AnimationStart"),transitionrun:wa("Transition","TransitionRun"),transitionstart:wa("Transition","TransitionStart"),transitioncancel:wa("Transition","TransitionCancel"),transitionend:wa("Transition","TransitionEnd")},qa={},nc={};ds&&(nc=document.createElement("div").style,"AnimationEvent"in window||(delete Es.animationend.animation,delete Es.animationiteration.animation,delete Es.animationstart.animation),"TransitionEvent"in window||delete Es.transitionend.transition);function Ar(e){if(qa[e])return qa[e];if(!Es[e])return e;var t=Es[e],s;for(s in t)if(t.hasOwnProperty(s)&&s in nc)return qa[e]=t[s];return e}var ml=Ar("animationend"),hl=Ar("animationiteration"),ac=Ar("animationstart"),ui=Ar("transitionrun"),gu=Ar("transitionstart"),vu=Ar("transitioncancel"),yu=Ar("transitionend"),Nr=new Map,sc="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(" ");sc.push("scrollEnd");function Sa(e,t){Nr.set(e,t),Nt(t,[e])}var Ql=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)},Ca=[],Mr=0,di=0;function Zl(){for(var e=Mr,t=di=Mr=0;t<e;){var s=Ca[t];Ca[t++]=null;var o=Ca[t];Ca[t++]=null;var f=Ca[t];Ca[t++]=null;var h=Ca[t];if(Ca[t++]=null,o!==null&&f!==null){var S=o.pending;S===null?f.next=f:(f.next=S.next,S.next=f),o.pending=f}h!==0&&Rs(s,f,h)}}function pl(e,t,s,o){Ca[Mr++]=e,Ca[Mr++]=t,Ca[Mr++]=s,Ca[Mr++]=o,di|=o,e.lanes|=o,e=e.alternate,e!==null&&(e.lanes|=o)}function Tr(e,t,s,o){return pl(e,t,s,o),Er(e)}function tr(e,t){return pl(e,null,null,t),Er(e)}function Rs(e,t,s){e.lanes|=s;var o=e.alternate;o!==null&&(o.lanes|=s);for(var f=!1,h=e.return;h!==null;)h.childLanes|=s,o=h.alternate,o!==null&&(o.childLanes|=s),h.tag===22&&(e=h.stateNode,e===null||e._visibility&1||(f=!0)),e=h,h=h.return;return e.tag===3?(h=e.stateNode,f&&t!==null&&(f=31-dt(s),e=h.hiddenUpdates,o=e[f],o===null?e[f]=[t]:o.push(t),t.lane=s|536870912),h):null}function Er(e){if(50<jc)throw jc=0,am=null,Error(l(185));for(var t=e.return;t!==null;)e=t,t=e.return;return e.tag===3?e.stateNode:null}var Ga={};function Rr(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 qn(e,t,s,o){return new Rr(e,t,s,o)}function rc(e){return e=e.prototype,!(!e||!e.isReactComponent)}function vs(e,t){var s=e.alternate;return s===null?(s=qn(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 gl(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 fi(e,t,s,o,f,h){var S=0;if(o=e,typeof e=="function")rc(e)&&(S=1);else if(typeof e=="string")S=kS(e,s,z.current)?26:e==="html"||e==="head"||e==="body"?27:5;else e:switch(e){case G:return e=qn(31,s,t,f),e.elementType=G,e.lanes=h,e;case k:return Va(s.children,f,h,t);case M:S=8,f|=24;break;case A:return e=qn(12,s,t,f|2),e.elementType=A,e.lanes=h,e;case H:return e=qn(13,s,t,f),e.elementType=H,e.lanes=h,e;case W:return e=qn(19,s,t,f),e.elementType=W,e.lanes=h,e;default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case D:S=10;break e;case T:S=9;break e;case B:S=11;break e;case _:S=14;break e;case Z:S=16,o=null;break e}S=29,s=Error(l(130,e===null?"null":typeof e,"")),o=null}return t=qn(S,s,t,f),t.elementType=e,t.type=o,t.lanes=h,t}function Va(e,t,s,o){return e=qn(7,e,o,t),e.lanes=s,e}function ic(e,t,s){return e=qn(6,e,null,t),e.lanes=s,e}function vl(e){var t=qn(18,null,null,0);return t.stateNode=e,t}function Jl(e,t,s){return t=qn(4,e.children!==null?e.children:[],e.key,t),t.lanes=s,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}var mi=new WeakMap;function na(e,t){if(typeof e=="object"&&e!==null){var s=mi.get(e);return s!==void 0?s:(t={value:e,source:t,stack:Ve(t)},mi.set(e,t),t)}return{value:e,source:t,stack:Ve(t)}}var Ds=[],Ls=0,Dr=null,_s=0,Gn=[],Sn=0,fa=null,Wa=1,Tn="";function ka(e,t){Ds[Ls++]=_s,Ds[Ls++]=Dr,Dr=e,_s=t}function eo(e,t,s){Gn[Sn++]=Wa,Gn[Sn++]=Tn,Gn[Sn++]=fa,fa=e;var o=Wa;e=Tn;var f=32-dt(o)-1;o&=~(1<<f),s+=1;var h=32-dt(t)+f;if(30<h){var S=f-f%5;h=(o&(1<<S)-1).toString(32),o>>=S,f-=S,Wa=1<<32-dt(t)+f|s<<f|o,Tn=h+e}else Wa=1<<h|s<<f|o,Tn=e}function to(e){e.return!==null&&(ka(e,1),eo(e,1,0))}function ja(e){for(;e===Dr;)Dr=Ds[--Ls],Ds[Ls]=null,_s=Ds[--Ls],Ds[Ls]=null;for(;e===fa;)fa=Gn[--Sn],Gn[Sn]=null,Tn=Gn[--Sn],Gn[Sn]=null,Wa=Gn[--Sn],Gn[Sn]=null}function lc(e,t){Gn[Sn++]=Wa,Gn[Sn++]=Tn,Gn[Sn++]=fa,Wa=t.id,Tn=t.overflow,fa=e}var tn=null,Tt=null,bt=!1,Is=null,Ft=!1,no=Error(l(519));function Ya(e){var t=Error(l(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw yl(na(t,e)),no}function ao(e){var t=e.stateNode,s=e.type,o=e.memoizedProps;switch(t[ne]=e,t[Te]=o,s){case"dialog":wt("cancel",t),wt("close",t);break;case"iframe":case"object":case"embed":wt("load",t);break;case"video":case"audio":for(s=0;s<Nc.length;s++)wt(Nc[s],t);break;case"source":wt("error",t);break;case"img":case"image":case"link":wt("error",t),wt("load",t);break;case"details":wt("toggle",t);break;case"input":wt("invalid",t),el(t,o.value,o.defaultValue,o.checked,o.defaultChecked,o.type,o.name,!0);break;case"select":wt("invalid",t);break;case"textarea":wt("invalid",t),va(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||pv(t.textContent,s)?(o.popover!=null&&(wt("beforetoggle",t),wt("toggle",t)),o.onScroll!=null&&wt("scroll",t),o.onScrollEnd!=null&&wt("scrollend",t),o.onClick!=null&&(t.onclick=Bn),t=!0):t=!1,t||Ya(e,!0)}function hi(e){for(tn=e.return;tn;)switch(tn.tag){case 5:case 31:case 13:Ft=!1;return;case 27:case 3:Ft=!0;return;default:tn=tn.return}}function pi(e){if(e!==tn)return!1;if(!bt)return hi(e),bt=!0,!1;var t=e.tag,s;if((s=t!==3&&t!==27)&&((s=t===5)&&(s=e.type,s=!(s!=="form"&&s!=="button")||ym(e.type,e.memoizedProps)),s=!s),s&&Tt&&Ya(e),hi(e),t===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(l(317));Tt=kv(e)}else if(t===31){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(l(317));Tt=kv(e)}else t===27?(t=Tt,_i(e.type)?(e=Cm,Cm=null,Tt=e):Tt=t):Tt=tn?bs(e.stateNode.nextSibling):null;return!0}function zs(){Tt=tn=null,bt=!1}function Lr(){var e=Is;return e!==null&&(Ea===null?Ea=e:Ea.push.apply(Ea,e),Is=null),e}function yl(e){Is===null?Is=[e]:Is.push(e)}var oc=ue(null),_r=null,Os=null;function ys(e,t,s){xe(oc,t._currentValue),t._currentValue=s}function Ka(e){e._currentValue=oc.current,K(oc)}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 so(e,t,s,o){var f=e.child;for(f!==null&&(f.return=e);f!==null;){var h=f.dependencies;if(h!==null){var S=f.child;h=h.firstContext;e:for(;h!==null;){var E=h;h=f;for(var U=0;U<t.length;U++)if(E.context===t[U]){h.lanes|=s,E=h.alternate,E!==null&&(E.lanes|=s),Ir(h.return,s,e),o||(S=null);break e}h=E.next}}else if(f.tag===18){if(S=f.return,S===null)throw Error(l(341));S.lanes|=s,h=S.alternate,h!==null&&(h.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 nr(e,t,s,o){e=null;for(var f=t,h=!1;f!==null;){if(!h){if((f.flags&524288)!==0)h=!0;else if((f.flags&262144)!==0)break}if(f.tag===10){var S=f.alternate;if(S===null)throw Error(l(387));if(S=S.memoizedProps,S!==null){var E=f.type;Ut(f.pendingProps.value,S.value)||(e!==null?e.push(E):e=[E])}}else if(f===Ce.current){if(S=f.alternate,S===null)throw Error(l(387));S.memoizedState.memoizedState!==f.memoizedState.memoizedState&&(e!==null?e.push(Dc):e=[Dc])}f=f.return}e!==null&&so(t,e,s,o),t.flags|=262144}function ro(e){for(e=e.firstContext;e!==null;){if(!Ut(e.context._currentValue,e.memoizedValue))return!0;e=e.next}return!1}function Xa(e){_r=e,Os=null,e=e.dependencies,e!==null&&(e.firstContext=null)}function Cn(e){return lo(_r,e)}function io(e,t){return _r===null&&Xa(e),lo(e,t)}function lo(e,t){var s=t._currentValue;if(t={context:t,memoizedValue:s,next:null},Os===null){if(e===null)throw Error(l(308));Os=t,e.dependencies={lanes:0,firstContext:t},e.flags|=524288}else Os=Os.next=t;return s}var bu=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()})}},xu=n.unstable_scheduleCallback,wu=n.unstable_NormalPriority,sn={$$typeof:D,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function gi(){return{controller:new bu,data:new Map,refCount:0}}function ar(e){e.refCount--,e.refCount===0&&xu(wu,function(){e.controller.abort()})}var vi=null,cc=0,sr=0,rr=null;function Oe(e,t){if(vi===null){var s=vi=[];cc=0,sr=cm(),rr={status:"pending",value:void 0,then:function(o){s.push(o)}}}return cc++,t.then(bl,bl),t}function bl(){if(--cc===0&&vi!==null){rr!==null&&(rr.status="fulfilled");var e=vi;vi=null,sr=0,rr=null;for(var t=0;t<e.length;t++)(0,e[t])()}}function Su(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 Cu=I.S;I.S=function(e,t){Fg=Ee(),typeof t=="object"&&t!==null&&typeof t.then=="function"&&Oe(e,t),Cu!==null&&Cu(e,t)};var yi=ue(null);function xl(){var e=yi.current;return e!==null?e:qt.pooledCache}function zr(e,t){t===null?xe(yi,yi.current):xe(yi,t.pool)}function pn(){var e=xl();return e===null?null:{parent:sn._currentValue,pool:e}}var gn=Error(l(460)),gt=Error(l(474)),oo=Error(l(542)),Hs={then:function(){}};function wl(e){return e=e.status,e==="fulfilled"||e==="rejected"}function uc(e,t,s){switch(s=e[s],s===void 0?e.push(t):s!==t&&(t.then(Bn,Bn),t=s),t.status){case"fulfilled":return t.value;case"rejected":throw e=t.reason,dc(e),e;default:if(typeof t.status=="string")t.then(Bn,Bn);else{if(e=qt,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,dc(e),e}throw Qa=t,gn}}function ir(e){try{var t=e._init;return t(e._payload)}catch(s){throw s!==null&&typeof s=="object"&&typeof s.then=="function"?(Qa=s,gn):s}}var Qa=null;function ku(){if(Qa===null)throw Error(l(459));var e=Qa;return Qa=null,e}function dc(e){if(e===gn||e===oo)throw Error(l(483))}var lr=null,Sl=0;function co(e){var t=Sl;return Sl+=1,lr===null&&(lr=[]),uc(lr,e,t)}function bi(e,t){t=t.props.ref,e.ref=t!==void 0?t:null}function xi(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 ju(e){function t(J,Y){if(e){var se=J.deletions;se===null?(J.deletions=[Y],J.flags|=16):se.push(Y)}}function s(J,Y){if(!e)return null;for(;Y!==null;)t(J,Y),Y=Y.sibling;return null}function o(J){for(var Y=new Map;J!==null;)J.key!==null?Y.set(J.key,J):Y.set(J.index,J),J=J.sibling;return Y}function f(J,Y){return J=vs(J,Y),J.index=0,J.sibling=null,J}function h(J,Y,se){return J.index=se,e?(se=J.alternate,se!==null?(se=se.index,se<Y?(J.flags|=67108866,Y):se):(J.flags|=67108866,Y)):(J.flags|=1048576,Y)}function S(J){return e&&J.alternate===null&&(J.flags|=67108866),J}function E(J,Y,se,we){return Y===null||Y.tag!==6?(Y=ic(se,J.mode,we),Y.return=J,Y):(Y=f(Y,se),Y.return=J,Y)}function U(J,Y,se,we){var nt=se.type;return nt===k?be(J,Y,se.props.children,we,se.key):Y!==null&&(Y.elementType===nt||typeof nt=="object"&&nt!==null&&nt.$$typeof===Z&&ir(nt)===Y.type)?(Y=f(Y,se.props),bi(Y,se),Y.return=J,Y):(Y=fi(se.type,se.key,se.props,null,J.mode,we),bi(Y,se),Y.return=J,Y)}function ie(J,Y,se,we){return Y===null||Y.tag!==4||Y.stateNode.containerInfo!==se.containerInfo||Y.stateNode.implementation!==se.implementation?(Y=Jl(se,J.mode,we),Y.return=J,Y):(Y=f(Y,se.children||[]),Y.return=J,Y)}function be(J,Y,se,we,nt){return Y===null||Y.tag!==7?(Y=Va(se,J.mode,we,nt),Y.return=J,Y):(Y=f(Y,se),Y.return=J,Y)}function Se(J,Y,se){if(typeof Y=="string"&&Y!==""||typeof Y=="number"||typeof Y=="bigint")return Y=ic(""+Y,J.mode,se),Y.return=J,Y;if(typeof Y=="object"&&Y!==null){switch(Y.$$typeof){case C:return se=fi(Y.type,Y.key,Y.props,null,J.mode,se),bi(se,Y),se.return=J,se;case j:return Y=Jl(Y,J.mode,se),Y.return=J,Y;case Z:return Y=ir(Y),Se(J,Y,se)}if(X(Y)||O(Y))return Y=Va(Y,J.mode,se,null),Y.return=J,Y;if(typeof Y.then=="function")return Se(J,co(Y),se);if(Y.$$typeof===D)return Se(J,io(J,Y),se);xi(J,Y)}return null}function oe(J,Y,se,we){var nt=Y!==null?Y.key:null;if(typeof se=="string"&&se!==""||typeof se=="number"||typeof se=="bigint")return nt!==null?null:E(J,Y,""+se,we);if(typeof se=="object"&&se!==null){switch(se.$$typeof){case C:return se.key===nt?U(J,Y,se,we):null;case j:return se.key===nt?ie(J,Y,se,we):null;case Z:return se=ir(se),oe(J,Y,se,we)}if(X(se)||O(se))return nt!==null?null:be(J,Y,se,we,null);if(typeof se.then=="function")return oe(J,Y,co(se),we);if(se.$$typeof===D)return oe(J,Y,io(J,se),we);xi(J,se)}return null}function pe(J,Y,se,we,nt){if(typeof we=="string"&&we!==""||typeof we=="number"||typeof we=="bigint")return J=J.get(se)||null,E(Y,J,""+we,nt);if(typeof we=="object"&&we!==null){switch(we.$$typeof){case C:return J=J.get(we.key===null?se:we.key)||null,U(Y,J,we,nt);case j:return J=J.get(we.key===null?se:we.key)||null,ie(Y,J,we,nt);case Z:return we=ir(we),pe(J,Y,se,we,nt)}if(X(we)||O(we))return J=J.get(se)||null,be(Y,J,we,nt,null);if(typeof we.then=="function")return pe(J,Y,se,co(we),nt);if(we.$$typeof===D)return pe(J,Y,se,io(Y,we),nt);xi(Y,we)}return null}function Ze(J,Y,se,we){for(var nt=null,Et=null,tt=Y,ht=Y=0,Ct=null;tt!==null&&ht<se.length;ht++){tt.index>ht?(Ct=tt,tt=null):Ct=tt.sibling;var Rt=oe(J,tt,se[ht],we);if(Rt===null){tt===null&&(tt=Ct);break}e&&tt&&Rt.alternate===null&&t(J,tt),Y=h(Rt,Y,ht),Et===null?nt=Rt:Et.sibling=Rt,Et=Rt,tt=Ct}if(ht===se.length)return s(J,tt),bt&&ka(J,ht),nt;if(tt===null){for(;ht<se.length;ht++)tt=Se(J,se[ht],we),tt!==null&&(Y=h(tt,Y,ht),Et===null?nt=tt:Et.sibling=tt,Et=tt);return bt&&ka(J,ht),nt}for(tt=o(tt);ht<se.length;ht++)Ct=pe(tt,J,ht,se[ht],we),Ct!==null&&(e&&Ct.alternate!==null&&tt.delete(Ct.key===null?ht:Ct.key),Y=h(Ct,Y,ht),Et===null?nt=Ct:Et.sibling=Ct,Et=Ct);return e&&tt.forEach(function(Fi){return t(J,Fi)}),bt&&ka(J,ht),nt}function ot(J,Y,se,we){if(se==null)throw Error(l(151));for(var nt=null,Et=null,tt=Y,ht=Y=0,Ct=null,Rt=se.next();tt!==null&&!Rt.done;ht++,Rt=se.next()){tt.index>ht?(Ct=tt,tt=null):Ct=tt.sibling;var Fi=oe(J,tt,Rt.value,we);if(Fi===null){tt===null&&(tt=Ct);break}e&&tt&&Fi.alternate===null&&t(J,tt),Y=h(Fi,Y,ht),Et===null?nt=Fi:Et.sibling=Fi,Et=Fi,tt=Ct}if(Rt.done)return s(J,tt),bt&&ka(J,ht),nt;if(tt===null){for(;!Rt.done;ht++,Rt=se.next())Rt=Se(J,Rt.value,we),Rt!==null&&(Y=h(Rt,Y,ht),Et===null?nt=Rt:Et.sibling=Rt,Et=Rt);return bt&&ka(J,ht),nt}for(tt=o(tt);!Rt.done;ht++,Rt=se.next())Rt=pe(tt,J,ht,Rt.value,we),Rt!==null&&(e&&Rt.alternate!==null&&tt.delete(Rt.key===null?ht:Rt.key),Y=h(Rt,Y,ht),Et===null?nt=Rt:Et.sibling=Rt,Et=Rt);return e&&tt.forEach(function(IS){return t(J,IS)}),bt&&ka(J,ht),nt}function Pt(J,Y,se,we){if(typeof se=="object"&&se!==null&&se.type===k&&se.key===null&&(se=se.props.children),typeof se=="object"&&se!==null){switch(se.$$typeof){case C:e:{for(var nt=se.key;Y!==null;){if(Y.key===nt){if(nt=se.type,nt===k){if(Y.tag===7){s(J,Y.sibling),we=f(Y,se.props.children),we.return=J,J=we;break e}}else if(Y.elementType===nt||typeof nt=="object"&&nt!==null&&nt.$$typeof===Z&&ir(nt)===Y.type){s(J,Y.sibling),we=f(Y,se.props),bi(we,se),we.return=J,J=we;break e}s(J,Y);break}else t(J,Y);Y=Y.sibling}se.type===k?(we=Va(se.props.children,J.mode,we,se.key),we.return=J,J=we):(we=fi(se.type,se.key,se.props,null,J.mode,we),bi(we,se),we.return=J,J=we)}return S(J);case j:e:{for(nt=se.key;Y!==null;){if(Y.key===nt)if(Y.tag===4&&Y.stateNode.containerInfo===se.containerInfo&&Y.stateNode.implementation===se.implementation){s(J,Y.sibling),we=f(Y,se.children||[]),we.return=J,J=we;break e}else{s(J,Y);break}else t(J,Y);Y=Y.sibling}we=Jl(se,J.mode,we),we.return=J,J=we}return S(J);case Z:return se=ir(se),Pt(J,Y,se,we)}if(X(se))return Ze(J,Y,se,we);if(O(se)){if(nt=O(se),typeof nt!="function")throw Error(l(150));return se=nt.call(se),ot(J,Y,se,we)}if(typeof se.then=="function")return Pt(J,Y,co(se),we);if(se.$$typeof===D)return Pt(J,Y,io(J,se),we);xi(J,se)}return typeof se=="string"&&se!==""||typeof se=="number"||typeof se=="bigint"?(se=""+se,Y!==null&&Y.tag===6?(s(J,Y.sibling),we=f(Y,se),we.return=J,J=we):(s(J,Y),we=ic(se,J.mode,we),we.return=J,J=we),S(J)):s(J,Y)}return function(J,Y,se,we){try{Sl=0;var nt=Pt(J,Y,se,we);return lr=null,nt}catch(tt){if(tt===gn||tt===oo)throw tt;var Et=qn(29,tt,null,J.mode);return Et.lanes=we,Et.return=J,Et}}}var Or=ju(!0),En=ju(!1),Za=!1;function uo(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function fc(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 Hr(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function or(e,t,s){var o=e.updateQueue;if(o===null)return null;if(o=o.shared,(Lt&2)!==0){var f=o.pending;return f===null?t.next=t:(t.next=f.next,f.next=t),o.pending=t,t=Er(e),Rs(e,null,s),t}return pl(e,o,t,s),Er(e)}function Cl(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,F(e,s)}}function fo(e,t){var s=e.updateQueue,o=e.alternate;if(o!==null&&(o=o.updateQueue,s===o)){var f=null,h=null;if(s=s.firstBaseUpdate,s!==null){do{var S={lane:s.lane,tag:s.tag,payload:s.payload,callback:null,next:null};h===null?f=h=S:h=h.next=S,s=s.next}while(s!==null);h===null?f=h=t:h=h.next=t}else f=h=t;s={baseState:o.baseState,firstBaseUpdate:f,lastBaseUpdate:h,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 wi=!1;function Fs(){if(wi){var e=rr;if(e!==null)throw e}}function Si(e,t,s,o){wi=!1;var f=e.updateQueue;Za=!1;var h=f.firstBaseUpdate,S=f.lastBaseUpdate,E=f.shared.pending;if(E!==null){f.shared.pending=null;var U=E,ie=U.next;U.next=null,S===null?h=ie:S.next=ie,S=U;var be=e.alternate;be!==null&&(be=be.updateQueue,E=be.lastBaseUpdate,E!==S&&(E===null?be.firstBaseUpdate=ie:E.next=ie,be.lastBaseUpdate=U))}if(h!==null){var Se=f.baseState;S=0,be=ie=U=null,E=h;do{var oe=E.lane&-536870913,pe=oe!==E.lane;if(pe?(St&oe)===oe:(o&oe)===oe){oe!==0&&oe===sr&&(wi=!0),be!==null&&(be=be.next={lane:0,tag:E.tag,payload:E.payload,callback:null,next:null});e:{var Ze=e,ot=E;oe=t;var Pt=s;switch(ot.tag){case 1:if(Ze=ot.payload,typeof Ze=="function"){Se=Ze.call(Pt,Se,oe);break e}Se=Ze;break e;case 3:Ze.flags=Ze.flags&-65537|128;case 0:if(Ze=ot.payload,oe=typeof Ze=="function"?Ze.call(Pt,Se,oe):Ze,oe==null)break e;Se=b({},Se,oe);break e;case 2:Za=!0}}oe=E.callback,oe!==null&&(e.flags|=64,pe&&(e.flags|=8192),pe=f.callbacks,pe===null?f.callbacks=[oe]:pe.push(oe))}else pe={lane:oe,tag:E.tag,payload:E.payload,callback:E.callback,next:null},be===null?(ie=be=pe,U=Se):be=be.next=pe,S|=oe;if(E=E.next,E===null){if(E=f.shared.pending,E===null)break;pe=E,E=pe.next,pe.next=null,f.lastBaseUpdate=pe,f.shared.pending=null}}while(!0);be===null&&(U=Se),f.baseState=U,f.firstBaseUpdate=ie,f.lastBaseUpdate=be,h===null&&(f.shared.lanes=0),Ti|=S,e.lanes=S,e.memoizedState=Se}}function Au(e,t){if(typeof e!="function")throw Error(l(191,e));e.call(t)}function Nu(e,t){var s=e.callbacks;if(s!==null)for(e.callbacks=null,e=0;e<s.length;e++)Au(s[e],t)}var Ci=ue(null),ki=ue(0);function Fr(e,t){e=Wr,xe(ki,e),xe(Ci,t),Wr=e|t.baseLanes}function mc(){xe(ki,Wr),xe(Ci,Ci.current)}function Bs(){Wr=ki.current,K(Ci),K(ki)}var Vn=ue(null),y=null;function N(e){var t=e.alternate;xe(te,te.current&1),xe(Vn,e),y===null&&(t===null||Ci.current!==null||t.memoizedState!==null)&&(y=e)}function L(e){xe(te,te.current),xe(Vn,e),y===null&&(y=e)}function $(e){e.tag===22?(xe(te,te.current),xe(Vn,e),y===null&&(y=e)):R()}function R(){xe(te,te.current),xe(Vn,Vn.current)}function ae(e){K(Vn),y===e&&(y=null),K(te)}var te=ue(0);function Ie(e){for(var t=e;t!==null;){if(t.tag===13){var s=t.memoizedState;if(s!==null&&(s=s.dehydrated,s===null||wm(s)||Sm(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 qe=0,Ne=null,lt=null,vt=null,Wn=!1,Ps=!1,Aa=!1,ji=0,cr=0,Ai=null,jw=0;function rn(){throw Error(l(321))}function gf(e,t){if(t===null)return!1;for(var s=0;s<t.length&&s<e.length;s++)if(!Ut(e[s],t[s]))return!1;return!0}function vf(e,t,s,o,f,h){return qe=h,Ne=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,I.H=e===null||e.memoizedState===null?Xp:Df,Aa=!1,h=s(o,f),Aa=!1,Ps&&(h=pp(t,s,o,f)),hp(e),h}function hp(e){I.H=gc;var t=lt!==null&&lt.next!==null;if(qe=0,vt=lt=Ne=null,Wn=!1,cr=0,Ai=null,t)throw Error(l(300));e===null||vn||(e=e.dependencies,e!==null&&ro(e)&&(vn=!0))}function pp(e,t,s,o){Ne=e;var f=0;do{if(Ps&&(Ai=null),cr=0,Ps=!1,25<=f)throw Error(l(301));if(f+=1,vt=lt=null,e.updateQueue!=null){var h=e.updateQueue;h.lastEffect=null,h.events=null,h.stores=null,h.memoCache!=null&&(h.memoCache.index=0)}I.H=Qp,h=t(s,o)}while(Ps);return h}function Aw(){var e=I.H,t=e.useState()[0];return t=typeof t.then=="function"?hc(t):t,e=e.useState()[0],(lt!==null?lt.memoizedState:null)!==e&&(Ne.flags|=1024),t}function yf(){var e=ji!==0;return ji=0,e}function bf(e,t,s){t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~s}function xf(e){if(Wn){for(e=e.memoizedState;e!==null;){var t=e.queue;t!==null&&(t.pending=null),e=e.next}Wn=!1}qe=0,vt=lt=Ne=null,Ps=!1,cr=ji=0,Ai=null}function ma(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return vt===null?Ne.memoizedState=vt=e:vt=vt.next=e,vt}function un(){if(lt===null){var e=Ne.alternate;e=e!==null?e.memoizedState:null}else e=lt.next;var t=vt===null?Ne.memoizedState:vt.next;if(t!==null)vt=t,lt=e;else{if(e===null)throw Ne.alternate===null?Error(l(467)):Error(l(310));lt=e,e={memoizedState:lt.memoizedState,baseState:lt.baseState,baseQueue:lt.baseQueue,queue:lt.queue,next:null},vt===null?Ne.memoizedState=vt=e:vt=vt.next=e}return vt}function Mu(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function hc(e){var t=cr;return cr+=1,Ai===null&&(Ai=[]),e=uc(Ai,e,t),t=Ne,(vt===null?t.memoizedState:vt.next)===null&&(t=t.alternate,I.H=t===null||t.memoizedState===null?Xp:Df),e}function Tu(e){if(e!==null&&typeof e=="object"){if(typeof e.then=="function")return hc(e);if(e.$$typeof===D)return Cn(e)}throw Error(l(438,String(e)))}function wf(e){var t=null,s=Ne.updateQueue;if(s!==null&&(t=s.memoCache),t==null){var o=Ne.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=Mu(),Ne.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]=q;return t.index++,s}function Br(e,t){return typeof t=="function"?t(e):t}function Eu(e){var t=un();return Sf(t,lt,e)}function Sf(e,t,s){var o=e.queue;if(o===null)throw Error(l(311));o.lastRenderedReducer=s;var f=e.baseQueue,h=o.pending;if(h!==null){if(f!==null){var S=f.next;f.next=h.next,h.next=S}t.baseQueue=f=h,o.pending=null}if(h=e.baseState,f===null)e.memoizedState=h;else{t=f.next;var E=S=null,U=null,ie=t,be=!1;do{var Se=ie.lane&-536870913;if(Se!==ie.lane?(St&Se)===Se:(qe&Se)===Se){var oe=ie.revertLane;if(oe===0)U!==null&&(U=U.next={lane:0,revertLane:0,gesture:null,action:ie.action,hasEagerState:ie.hasEagerState,eagerState:ie.eagerState,next:null}),Se===sr&&(be=!0);else if((qe&oe)===oe){ie=ie.next,oe===sr&&(be=!0);continue}else Se={lane:0,revertLane:ie.revertLane,gesture:null,action:ie.action,hasEagerState:ie.hasEagerState,eagerState:ie.eagerState,next:null},U===null?(E=U=Se,S=h):U=U.next=Se,Ne.lanes|=oe,Ti|=oe;Se=ie.action,Aa&&s(h,Se),h=ie.hasEagerState?ie.eagerState:s(h,Se)}else oe={lane:Se,revertLane:ie.revertLane,gesture:ie.gesture,action:ie.action,hasEagerState:ie.hasEagerState,eagerState:ie.eagerState,next:null},U===null?(E=U=oe,S=h):U=U.next=oe,Ne.lanes|=Se,Ti|=Se;ie=ie.next}while(ie!==null&&ie!==t);if(U===null?S=h:U.next=E,!Ut(h,e.memoizedState)&&(vn=!0,be&&(s=rr,s!==null)))throw s;e.memoizedState=h,e.baseState=S,e.baseQueue=U,o.lastRenderedState=h}return f===null&&(o.lanes=0),[e.memoizedState,o.dispatch]}function Cf(e){var t=un(),s=t.queue;if(s===null)throw Error(l(311));s.lastRenderedReducer=e;var o=s.dispatch,f=s.pending,h=t.memoizedState;if(f!==null){s.pending=null;var S=f=f.next;do h=e(h,S.action),S=S.next;while(S!==f);Ut(h,t.memoizedState)||(vn=!0),t.memoizedState=h,t.baseQueue===null&&(t.baseState=h),s.lastRenderedState=h}return[h,o]}function gp(e,t,s){var o=Ne,f=un(),h=bt;if(h){if(s===void 0)throw Error(l(407));s=s()}else s=t();var S=!Ut((lt||f).memoizedState,s);if(S&&(f.memoizedState=s,vn=!0),f=f.queue,Af(bp.bind(null,o,f,e),[e]),f.getSnapshot!==t||S||vt!==null&&vt.memoizedState.tag&1){if(o.flags|=2048,mo(9,{destroy:void 0},yp.bind(null,o,f,s,t),null),qt===null)throw Error(l(349));h||(qe&127)!==0||vp(o,t,s)}return s}function vp(e,t,s){e.flags|=16384,e={getSnapshot:t,value:s},t=Ne.updateQueue,t===null?(t=Mu(),Ne.updateQueue=t,t.stores=[e]):(s=t.stores,s===null?t.stores=[e]:s.push(e))}function yp(e,t,s,o){t.value=s,t.getSnapshot=o,xp(t)&&wp(e)}function bp(e,t,s){return s(function(){xp(t)&&wp(e)})}function xp(e){var t=e.getSnapshot;e=e.value;try{var s=t();return!Ut(e,s)}catch{return!0}}function wp(e){var t=tr(e,2);t!==null&&Ra(t,e,2)}function kf(e){var t=ma();if(typeof e=="function"){var s=e;if(e=s(),Aa){rt(!0);try{s()}finally{rt(!1)}}}return t.memoizedState=t.baseState=e,t.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Br,lastRenderedState:e},t}function Sp(e,t,s,o){return e.baseState=s,Sf(e,lt,typeof o=="function"?o:Br)}function Nw(e,t,s,o,f){if(Lu(e))throw Error(l(485));if(e=t.action,e!==null){var h={payload:f,action:e,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(S){h.listeners.push(S)}};I.T!==null?s(!0):h.isTransition=!1,o(h),s=t.pending,s===null?(h.next=t.pending=h,Cp(t,h)):(h.next=s.next,t.pending=s.next=h)}}function Cp(e,t){var s=t.action,o=t.payload,f=e.state;if(t.isTransition){var h=I.T,S={};I.T=S;try{var E=s(f,o),U=I.S;U!==null&&U(S,E),kp(e,t,E)}catch(ie){jf(e,t,ie)}finally{h!==null&&S.types!==null&&(h.types=S.types),I.T=h}}else try{h=s(f,o),kp(e,t,h)}catch(ie){jf(e,t,ie)}}function kp(e,t,s){s!==null&&typeof s=="object"&&typeof s.then=="function"?s.then(function(o){jp(e,t,o)},function(o){return jf(e,t,o)}):jp(e,t,s)}function jp(e,t,s){t.status="fulfilled",t.value=s,Ap(t),e.state=s,t=e.pending,t!==null&&(s=t.next,s===t?e.pending=null:(s=s.next,t.next=s,Cp(e,s)))}function jf(e,t,s){var o=e.pending;if(e.pending=null,o!==null){o=o.next;do t.status="rejected",t.reason=s,Ap(t),t=t.next;while(t!==o)}e.action=null}function Ap(e){e=e.listeners;for(var t=0;t<e.length;t++)(0,e[t])()}function Np(e,t){return t}function Mp(e,t){if(bt){var s=qt.formState;if(s!==null){e:{var o=Ne;if(bt){if(Tt){t:{for(var f=Tt,h=Ft;f.nodeType!==8;){if(!h){f=null;break t}if(f=bs(f.nextSibling),f===null){f=null;break t}}h=f.data,f=h==="F!"||h==="F"?f:null}if(f){Tt=bs(f.nextSibling),o=f.data==="F!";break e}}Ya(o)}o=!1}o&&(t=s[0])}}return s=ma(),s.memoizedState=s.baseState=t,o={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Np,lastRenderedState:t},s.queue=o,s=Wp.bind(null,Ne,o),o.dispatch=s,o=kf(!1),h=Rf.bind(null,Ne,!1,o.queue),o=ma(),f={state:t,dispatch:null,action:e,pending:null},o.queue=f,s=Nw.bind(null,Ne,f,h,s),f.dispatch=s,o.memoizedState=e,[t,s,!1]}function Tp(e){var t=un();return Ep(t,lt,e)}function Ep(e,t,s){if(t=Sf(e,t,Np)[0],e=Eu(Br)[0],typeof t=="object"&&t!==null&&typeof t.then=="function")try{var o=hc(t)}catch(S){throw S===gn?oo:S}else o=t;t=un();var f=t.queue,h=f.dispatch;return s!==t.memoizedState&&(Ne.flags|=2048,mo(9,{destroy:void 0},Mw.bind(null,f,s),null)),[o,h,e]}function Mw(e,t){e.action=t}function Rp(e){var t=un(),s=lt;if(s!==null)return Ep(t,s,e);un(),t=t.memoizedState,s=un();var o=s.queue.dispatch;return s.memoizedState=e,[t,o,!1]}function mo(e,t,s,o){return e={tag:e,create:s,deps:o,inst:t,next:null},t=Ne.updateQueue,t===null&&(t=Mu(),Ne.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 Dp(){return un().memoizedState}function Ru(e,t,s,o){var f=ma();Ne.flags|=e,f.memoizedState=mo(1|t,{destroy:void 0},s,o===void 0?null:o)}function Du(e,t,s,o){var f=un();o=o===void 0?null:o;var h=f.memoizedState.inst;lt!==null&&o!==null&&gf(o,lt.memoizedState.deps)?f.memoizedState=mo(t,h,s,o):(Ne.flags|=e,f.memoizedState=mo(1|t,h,s,o))}function Lp(e,t){Ru(8390656,8,e,t)}function Af(e,t){Du(2048,8,e,t)}function Tw(e){Ne.flags|=4;var t=Ne.updateQueue;if(t===null)t=Mu(),Ne.updateQueue=t,t.events=[e];else{var s=t.events;s===null?t.events=[e]:s.push(e)}}function _p(e){var t=un().memoizedState;return Tw({ref:t,nextImpl:e}),function(){if((Lt&2)!==0)throw Error(l(440));return t.impl.apply(void 0,arguments)}}function Ip(e,t){return Du(4,2,e,t)}function zp(e,t){return Du(4,4,e,t)}function Op(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 Hp(e,t,s){s=s!=null?s.concat([e]):null,Du(4,4,Op.bind(null,t,e),s)}function Nf(){}function Fp(e,t){var s=un();t=t===void 0?null:t;var o=s.memoizedState;return t!==null&&gf(t,o[1])?o[0]:(s.memoizedState=[e,t],e)}function Bp(e,t){var s=un();t=t===void 0?null:t;var o=s.memoizedState;if(t!==null&&gf(t,o[1]))return o[0];if(o=e(),Aa){rt(!0);try{e()}finally{rt(!1)}}return s.memoizedState=[o,t],o}function Mf(e,t,s){return s===void 0||(qe&1073741824)!==0&&(St&261930)===0?e.memoizedState=t:(e.memoizedState=s,e=Pg(),Ne.lanes|=e,Ti|=e,s)}function Pp(e,t,s,o){return Ut(s,t)?s:Ci.current!==null?(e=Mf(e,s,o),Ut(e,t)||(vn=!0),e):(qe&42)===0||(qe&1073741824)!==0&&(St&261930)===0?(vn=!0,e.memoizedState=s):(e=Pg(),Ne.lanes|=e,Ti|=e,t)}function $p(e,t,s,o,f){var h=ee.p;ee.p=h!==0&&8>h?h:8;var S=I.T,E={};I.T=E,Rf(e,!1,t,s);try{var U=f(),ie=I.S;if(ie!==null&&ie(E,U),U!==null&&typeof U=="object"&&typeof U.then=="function"){var be=Su(U,o);pc(e,t,be,ts(e))}else pc(e,t,o,ts(e))}catch(Se){pc(e,t,{then:function(){},status:"rejected",reason:Se},ts())}finally{ee.p=h,S!==null&&E.types!==null&&(S.types=E.types),I.T=S}}function Ew(){}function Tf(e,t,s,o){if(e.tag!==5)throw Error(l(476));var f=Up(e).queue;$p(e,f,t,V,s===null?Ew:function(){return qp(e),s(o)})}function Up(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:V,baseState:V,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Br,lastRenderedState:V},next:null};var s={};return t.next={memoizedState:s,baseState:s,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Br,lastRenderedState:s},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function qp(e){var t=Up(e);t.next===null&&(t=e.alternate.memoizedState),pc(e,t.next.queue,{},ts())}function Ef(){return Cn(Dc)}function Gp(){return un().memoizedState}function Vp(){return un().memoizedState}function Rw(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var s=ts();e=Hr(s);var o=or(t,e,s);o!==null&&(Ra(o,t,s),Cl(o,t,s)),t={cache:gi()},e.payload=t;return}t=t.return}}function Dw(e,t,s){var o=ts();s={lane:o,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null},Lu(e)?Yp(t,s):(s=Tr(e,t,s,o),s!==null&&(Ra(s,e,o),Kp(s,t,o)))}function Wp(e,t,s){var o=ts();pc(e,t,s,o)}function pc(e,t,s,o){var f={lane:o,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null};if(Lu(e))Yp(t,f);else{var h=e.alternate;if(e.lanes===0&&(h===null||h.lanes===0)&&(h=t.lastRenderedReducer,h!==null))try{var S=t.lastRenderedState,E=h(S,s);if(f.hasEagerState=!0,f.eagerState=E,Ut(E,S))return pl(e,t,f,0),qt===null&&Zl(),!1}catch{}if(s=Tr(e,t,f,o),s!==null)return Ra(s,e,o),Kp(s,t,o),!0}return!1}function Rf(e,t,s,o){if(o={lane:2,revertLane:cm(),gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null},Lu(e)){if(t)throw Error(l(479))}else t=Tr(e,s,o,2),t!==null&&Ra(t,e,2)}function Lu(e){var t=e.alternate;return e===Ne||t!==null&&t===Ne}function Yp(e,t){Ps=Wn=!0;var s=e.pending;s===null?t.next=t:(t.next=s.next,s.next=t),e.pending=t}function Kp(e,t,s){if((s&4194048)!==0){var o=t.lanes;o&=e.pendingLanes,s|=o,t.lanes=s,F(e,s)}}var gc={readContext:Cn,use:Tu,useCallback:rn,useContext:rn,useEffect:rn,useImperativeHandle:rn,useLayoutEffect:rn,useInsertionEffect:rn,useMemo:rn,useReducer:rn,useRef:rn,useState:rn,useDebugValue:rn,useDeferredValue:rn,useTransition:rn,useSyncExternalStore:rn,useId:rn,useHostTransitionStatus:rn,useFormState:rn,useActionState:rn,useOptimistic:rn,useMemoCache:rn,useCacheRefresh:rn};gc.useEffectEvent=rn;var Xp={readContext:Cn,use:Tu,useCallback:function(e,t){return ma().memoizedState=[e,t===void 0?null:t],e},useContext:Cn,useEffect:Lp,useImperativeHandle:function(e,t,s){s=s!=null?s.concat([e]):null,Ru(4194308,4,Op.bind(null,t,e),s)},useLayoutEffect:function(e,t){return Ru(4194308,4,e,t)},useInsertionEffect:function(e,t){Ru(4,2,e,t)},useMemo:function(e,t){var s=ma();t=t===void 0?null:t;var o=e();if(Aa){rt(!0);try{e()}finally{rt(!1)}}return s.memoizedState=[o,t],o},useReducer:function(e,t,s){var o=ma();if(s!==void 0){var f=s(t);if(Aa){rt(!0);try{s(t)}finally{rt(!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=Dw.bind(null,Ne,e),[o.memoizedState,e]},useRef:function(e){var t=ma();return e={current:e},t.memoizedState=e},useState:function(e){e=kf(e);var t=e.queue,s=Wp.bind(null,Ne,t);return t.dispatch=s,[e.memoizedState,s]},useDebugValue:Nf,useDeferredValue:function(e,t){var s=ma();return Mf(s,e,t)},useTransition:function(){var e=kf(!1);return e=$p.bind(null,Ne,e.queue,!0,!1),ma().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,s){var o=Ne,f=ma();if(bt){if(s===void 0)throw Error(l(407));s=s()}else{if(s=t(),qt===null)throw Error(l(349));(St&127)!==0||vp(o,t,s)}f.memoizedState=s;var h={value:s,getSnapshot:t};return f.queue=h,Lp(bp.bind(null,o,h,e),[e]),o.flags|=2048,mo(9,{destroy:void 0},yp.bind(null,o,h,s,t),null),s},useId:function(){var e=ma(),t=qt.identifierPrefix;if(bt){var s=Tn,o=Wa;s=(o&~(1<<32-dt(o)-1)).toString(32)+s,t="_"+t+"R_"+s,s=ji++,0<s&&(t+="H"+s.toString(32)),t+="_"}else s=jw++,t="_"+t+"r_"+s.toString(32)+"_";return e.memoizedState=t},useHostTransitionStatus:Ef,useFormState:Mp,useActionState:Mp,useOptimistic:function(e){var t=ma();t.memoizedState=t.baseState=e;var s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return t.queue=s,t=Rf.bind(null,Ne,!0,s),s.dispatch=t,[e,t]},useMemoCache:wf,useCacheRefresh:function(){return ma().memoizedState=Rw.bind(null,Ne)},useEffectEvent:function(e){var t=ma(),s={impl:e};return t.memoizedState=s,function(){if((Lt&2)!==0)throw Error(l(440));return s.impl.apply(void 0,arguments)}}},Df={readContext:Cn,use:Tu,useCallback:Fp,useContext:Cn,useEffect:Af,useImperativeHandle:Hp,useInsertionEffect:Ip,useLayoutEffect:zp,useMemo:Bp,useReducer:Eu,useRef:Dp,useState:function(){return Eu(Br)},useDebugValue:Nf,useDeferredValue:function(e,t){var s=un();return Pp(s,lt.memoizedState,e,t)},useTransition:function(){var e=Eu(Br)[0],t=un().memoizedState;return[typeof e=="boolean"?e:hc(e),t]},useSyncExternalStore:gp,useId:Gp,useHostTransitionStatus:Ef,useFormState:Tp,useActionState:Tp,useOptimistic:function(e,t){var s=un();return Sp(s,lt,e,t)},useMemoCache:wf,useCacheRefresh:Vp};Df.useEffectEvent=_p;var Qp={readContext:Cn,use:Tu,useCallback:Fp,useContext:Cn,useEffect:Af,useImperativeHandle:Hp,useInsertionEffect:Ip,useLayoutEffect:zp,useMemo:Bp,useReducer:Cf,useRef:Dp,useState:function(){return Cf(Br)},useDebugValue:Nf,useDeferredValue:function(e,t){var s=un();return lt===null?Mf(s,e,t):Pp(s,lt.memoizedState,e,t)},useTransition:function(){var e=Cf(Br)[0],t=un().memoizedState;return[typeof e=="boolean"?e:hc(e),t]},useSyncExternalStore:gp,useId:Gp,useHostTransitionStatus:Ef,useFormState:Rp,useActionState:Rp,useOptimistic:function(e,t){var s=un();return lt!==null?Sp(s,lt,e,t):(s.baseState=e,[e,s.queue.dispatch])},useMemoCache:wf,useCacheRefresh:Vp};Qp.useEffectEvent=_p;function Lf(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 _f={enqueueSetState:function(e,t,s){e=e._reactInternals;var o=ts(),f=Hr(o);f.payload=t,s!=null&&(f.callback=s),t=or(e,f,o),t!==null&&(Ra(t,e,o),Cl(t,e,o))},enqueueReplaceState:function(e,t,s){e=e._reactInternals;var o=ts(),f=Hr(o);f.tag=1,f.payload=t,s!=null&&(f.callback=s),t=or(e,f,o),t!==null&&(Ra(t,e,o),Cl(t,e,o))},enqueueForceUpdate:function(e,t){e=e._reactInternals;var s=ts(),o=Hr(s);o.tag=2,t!=null&&(o.callback=t),t=or(e,o,s),t!==null&&(Ra(t,e,s),Cl(t,e,s))}};function Zp(e,t,s,o,f,h,S){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(o,h,S):t.prototype&&t.prototype.isPureReactComponent?!fl(s,o)||!fl(f,h):!0}function Jp(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&&_f.enqueueReplaceState(t,t.state,null)}function kl(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 eg(e){Ql(e)}function tg(e){console.error(e)}function ng(e){Ql(e)}function _u(e,t){try{var s=e.onUncaughtError;s(t.value,{componentStack:t.stack})}catch(o){setTimeout(function(){throw o})}}function ag(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 If(e,t,s){return s=Hr(s),s.tag=3,s.payload={element:null},s.callback=function(){_u(e,t)},s}function sg(e){return e=Hr(e),e.tag=3,e}function rg(e,t,s,o){var f=s.type.getDerivedStateFromError;if(typeof f=="function"){var h=o.value;e.payload=function(){return f(h)},e.callback=function(){ag(t,s,o)}}var S=s.stateNode;S!==null&&typeof S.componentDidCatch=="function"&&(e.callback=function(){ag(t,s,o),typeof f!="function"&&(Ei===null?Ei=new Set([this]):Ei.add(this));var E=o.stack;this.componentDidCatch(o.value,{componentStack:E!==null?E:""})})}function Lw(e,t,s,o,f){if(s.flags|=32768,o!==null&&typeof o=="object"&&typeof o.then=="function"){if(t=s.alternate,t!==null&&nr(t,s,f,!0),s=Vn.current,s!==null){switch(s.tag){case 31:case 13:return y===null?Vu():s.alternate===null&&ln===0&&(ln=3),s.flags&=-257,s.flags|=65536,s.lanes=f,o===Hs?s.flags|=16384:(t=s.updateQueue,t===null?s.updateQueue=new Set([o]):t.add(o),im(e,o,f)),!1;case 22:return s.flags|=65536,o===Hs?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)),im(e,o,f)),!1}throw Error(l(435,s.tag))}return im(e,o,f),Vu(),!1}if(bt)return t=Vn.current,t!==null?((t.flags&65536)===0&&(t.flags|=256),t.flags|=65536,t.lanes=f,o!==no&&(e=Error(l(422),{cause:o}),yl(na(e,s)))):(o!==no&&(t=Error(l(423),{cause:o}),yl(na(t,s))),e=e.current.alternate,e.flags|=65536,f&=-f,e.lanes|=f,o=na(o,s),f=If(e.stateNode,o,f),fo(e,f),ln!==4&&(ln=2)),!1;var h=Error(l(520),{cause:o});if(h=na(h,s),kc===null?kc=[h]:kc.push(h),ln!==4&&(ln=2),t===null)return!0;o=na(o,s),s=t;do{switch(s.tag){case 3:return s.flags|=65536,e=f&-f,s.lanes|=e,e=If(s.stateNode,o,e),fo(s,e),!1;case 1:if(t=s.type,h=s.stateNode,(s.flags&128)===0&&(typeof t.getDerivedStateFromError=="function"||h!==null&&typeof h.componentDidCatch=="function"&&(Ei===null||!Ei.has(h))))return s.flags|=65536,f&=-f,s.lanes|=f,f=sg(f),rg(f,e,s,o),fo(s,f),!1}s=s.return}while(s!==null);return!1}var zf=Error(l(461)),vn=!1;function Yn(e,t,s,o){t.child=e===null?En(t,null,s,o):Or(t,e.child,s,o)}function ig(e,t,s,o,f){s=s.render;var h=t.ref;if("ref"in o){var S={};for(var E in o)E!=="ref"&&(S[E]=o[E])}else S=o;return Xa(t),o=vf(e,t,s,S,h,f),E=yf(),e!==null&&!vn?(bf(e,t,f),Pr(e,t,f)):(bt&&E&&to(t),t.flags|=1,Yn(e,t,o,f),t.child)}function lg(e,t,s,o,f){if(e===null){var h=s.type;return typeof h=="function"&&!rc(h)&&h.defaultProps===void 0&&s.compare===null?(t.tag=15,t.type=h,og(e,t,h,o,f)):(e=fi(s.type,null,o,t,t.mode,f),e.ref=t.ref,e.return=t,t.child=e)}if(h=e.child,!qf(e,f)){var S=h.memoizedProps;if(s=s.compare,s=s!==null?s:fl,s(S,o)&&e.ref===t.ref)return Pr(e,t,f)}return t.flags|=1,e=vs(h,o),e.ref=t.ref,e.return=t,t.child=e}function og(e,t,s,o,f){if(e!==null){var h=e.memoizedProps;if(fl(h,o)&&e.ref===t.ref)if(vn=!1,t.pendingProps=o=h,qf(e,f))(e.flags&131072)!==0&&(vn=!0);else return t.lanes=e.lanes,Pr(e,t,f)}return Of(e,t,s,o,f)}function cg(e,t,s,o){var f=o.children,h=e!==null?e.memoizedState:null;if(e===null&&t.stateNode===null&&(t.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),o.mode==="hidden"){if((t.flags&128)!==0){if(h=h!==null?h.baseLanes|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&~h}else o=0,t.child=null;return ug(e,t,h,s,o)}if((s&536870912)!==0)t.memoizedState={baseLanes:0,cachePool:null},e!==null&&zr(t,h!==null?h.cachePool:null),h!==null?Fr(t,h):mc(),$(t);else return o=t.lanes=536870912,ug(e,t,h!==null?h.baseLanes|s:s,s,o)}else h!==null?(zr(t,h.cachePool),Fr(t,h),R(),t.memoizedState=null):(e!==null&&zr(t,null),mc(),R());return Yn(e,t,f,s),t.child}function vc(e,t){return e!==null&&e.tag===22||t.stateNode!==null||(t.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),t.sibling}function ug(e,t,s,o,f){var h=xl();return h=h===null?null:{parent:sn._currentValue,pool:h},t.memoizedState={baseLanes:s,cachePool:h},e!==null&&zr(t,null),mc(),$(t),e!==null&&nr(e,t,o,!0),t.childLanes=f,null}function Iu(e,t){return t=Ou({mode:t.mode,children:t.children},e.mode),t.ref=e.ref,e.child=t,t.return=e,t}function dg(e,t,s){return Or(t,e.child,null,s),e=Iu(t,t.pendingProps),e.flags|=2,ae(t),t.memoizedState=null,e}function _w(e,t,s){var o=t.pendingProps,f=(t.flags&128)!==0;if(t.flags&=-129,e===null){if(bt){if(o.mode==="hidden")return e=Iu(t,o),t.lanes=536870912,vc(null,e);if(L(t),(e=Tt)?(e=Cv(e,Ft),e=e!==null&&e.data==="&"?e:null,e!==null&&(t.memoizedState={dehydrated:e,treeContext:fa!==null?{id:Wa,overflow:Tn}:null,retryLane:536870912,hydrationErrors:null},s=vl(e),s.return=t,t.child=s,tn=t,Tt=null)):e=null,e===null)throw Ya(t);return t.lanes=536870912,null}return Iu(t,o)}var h=e.memoizedState;if(h!==null){var S=h.dehydrated;if(L(t),f)if(t.flags&256)t.flags&=-257,t=dg(e,t,s);else if(t.memoizedState!==null)t.child=e.child,t.flags|=128,t=null;else throw Error(l(558));else if(vn||nr(e,t,s,!1),f=(s&e.childLanes)!==0,vn||f){if(o=qt,o!==null&&(S=Je(o,s),S!==0&&S!==h.retryLane))throw h.retryLane=S,tr(e,S),Ra(o,e,S),zf;Vu(),t=dg(e,t,s)}else e=h.treeContext,Tt=bs(S.nextSibling),tn=t,bt=!0,Is=null,Ft=!1,e!==null&&lc(t,e),t=Iu(t,o),t.flags|=4096;return t}return e=vs(e.child,{mode:o.mode,children:o.children}),e.ref=t.ref,t.child=e,e.return=t,e}function zu(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 Of(e,t,s,o,f){return Xa(t),s=vf(e,t,s,o,void 0,f),o=yf(),e!==null&&!vn?(bf(e,t,f),Pr(e,t,f)):(bt&&o&&to(t),t.flags|=1,Yn(e,t,s,f),t.child)}function fg(e,t,s,o,f,h){return Xa(t),t.updateQueue=null,s=pp(t,o,s,f),hp(e),o=yf(),e!==null&&!vn?(bf(e,t,h),Pr(e,t,h)):(bt&&o&&to(t),t.flags|=1,Yn(e,t,s,h),t.child)}function mg(e,t,s,o,f){if(Xa(t),t.stateNode===null){var h=Ga,S=s.contextType;typeof S=="object"&&S!==null&&(h=Cn(S)),h=new s(o,h),t.memoizedState=h.state!==null&&h.state!==void 0?h.state:null,h.updater=_f,t.stateNode=h,h._reactInternals=t,h=t.stateNode,h.props=o,h.state=t.memoizedState,h.refs={},uo(t),S=s.contextType,h.context=typeof S=="object"&&S!==null?Cn(S):Ga,h.state=t.memoizedState,S=s.getDerivedStateFromProps,typeof S=="function"&&(Lf(t,s,S,o),h.state=t.memoizedState),typeof s.getDerivedStateFromProps=="function"||typeof h.getSnapshotBeforeUpdate=="function"||typeof h.UNSAFE_componentWillMount!="function"&&typeof h.componentWillMount!="function"||(S=h.state,typeof h.componentWillMount=="function"&&h.componentWillMount(),typeof h.UNSAFE_componentWillMount=="function"&&h.UNSAFE_componentWillMount(),S!==h.state&&_f.enqueueReplaceState(h,h.state,null),Si(t,o,h,f),Fs(),h.state=t.memoizedState),typeof h.componentDidMount=="function"&&(t.flags|=4194308),o=!0}else if(e===null){h=t.stateNode;var E=t.memoizedProps,U=kl(s,E);h.props=U;var ie=h.context,be=s.contextType;S=Ga,typeof be=="object"&&be!==null&&(S=Cn(be));var Se=s.getDerivedStateFromProps;be=typeof Se=="function"||typeof h.getSnapshotBeforeUpdate=="function",E=t.pendingProps!==E,be||typeof h.UNSAFE_componentWillReceiveProps!="function"&&typeof h.componentWillReceiveProps!="function"||(E||ie!==S)&&Jp(t,h,o,S),Za=!1;var oe=t.memoizedState;h.state=oe,Si(t,o,h,f),Fs(),ie=t.memoizedState,E||oe!==ie||Za?(typeof Se=="function"&&(Lf(t,s,Se,o),ie=t.memoizedState),(U=Za||Zp(t,s,U,o,oe,ie,S))?(be||typeof h.UNSAFE_componentWillMount!="function"&&typeof h.componentWillMount!="function"||(typeof h.componentWillMount=="function"&&h.componentWillMount(),typeof h.UNSAFE_componentWillMount=="function"&&h.UNSAFE_componentWillMount()),typeof h.componentDidMount=="function"&&(t.flags|=4194308)):(typeof h.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=o,t.memoizedState=ie),h.props=o,h.state=ie,h.context=S,o=U):(typeof h.componentDidMount=="function"&&(t.flags|=4194308),o=!1)}else{h=t.stateNode,fc(e,t),S=t.memoizedProps,be=kl(s,S),h.props=be,Se=t.pendingProps,oe=h.context,ie=s.contextType,U=Ga,typeof ie=="object"&&ie!==null&&(U=Cn(ie)),E=s.getDerivedStateFromProps,(ie=typeof E=="function"||typeof h.getSnapshotBeforeUpdate=="function")||typeof h.UNSAFE_componentWillReceiveProps!="function"&&typeof h.componentWillReceiveProps!="function"||(S!==Se||oe!==U)&&Jp(t,h,o,U),Za=!1,oe=t.memoizedState,h.state=oe,Si(t,o,h,f),Fs();var pe=t.memoizedState;S!==Se||oe!==pe||Za||e!==null&&e.dependencies!==null&&ro(e.dependencies)?(typeof E=="function"&&(Lf(t,s,E,o),pe=t.memoizedState),(be=Za||Zp(t,s,be,o,oe,pe,U)||e!==null&&e.dependencies!==null&&ro(e.dependencies))?(ie||typeof h.UNSAFE_componentWillUpdate!="function"&&typeof h.componentWillUpdate!="function"||(typeof h.componentWillUpdate=="function"&&h.componentWillUpdate(o,pe,U),typeof h.UNSAFE_componentWillUpdate=="function"&&h.UNSAFE_componentWillUpdate(o,pe,U)),typeof h.componentDidUpdate=="function"&&(t.flags|=4),typeof h.getSnapshotBeforeUpdate=="function"&&(t.flags|=1024)):(typeof h.componentDidUpdate!="function"||S===e.memoizedProps&&oe===e.memoizedState||(t.flags|=4),typeof h.getSnapshotBeforeUpdate!="function"||S===e.memoizedProps&&oe===e.memoizedState||(t.flags|=1024),t.memoizedProps=o,t.memoizedState=pe),h.props=o,h.state=pe,h.context=U,o=be):(typeof h.componentDidUpdate!="function"||S===e.memoizedProps&&oe===e.memoizedState||(t.flags|=4),typeof h.getSnapshotBeforeUpdate!="function"||S===e.memoizedProps&&oe===e.memoizedState||(t.flags|=1024),o=!1)}return h=o,zu(e,t),o=(t.flags&128)!==0,h||o?(h=t.stateNode,s=o&&typeof s.getDerivedStateFromError!="function"?null:h.render(),t.flags|=1,e!==null&&o?(t.child=Or(t,e.child,null,f),t.child=Or(t,null,s,f)):Yn(e,t,s,f),t.memoizedState=h.state,e=t.child):e=Pr(e,t,f),e}function hg(e,t,s,o){return zs(),t.flags|=256,Yn(e,t,s,o),t.child}var Hf={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function Ff(e){return{baseLanes:e,cachePool:pn()}}function Bf(e,t,s){return e=e!==null?e.childLanes&~s:0,t&&(e|=es),e}function pg(e,t,s){var o=t.pendingProps,f=!1,h=(t.flags&128)!==0,S;if((S=h)||(S=e!==null&&e.memoizedState===null?!1:(te.current&2)!==0),S&&(f=!0,t.flags&=-129),S=(t.flags&32)!==0,t.flags&=-33,e===null){if(bt){if(f?N(t):R(),(e=Tt)?(e=Cv(e,Ft),e=e!==null&&e.data!=="&"?e:null,e!==null&&(t.memoizedState={dehydrated:e,treeContext:fa!==null?{id:Wa,overflow:Tn}:null,retryLane:536870912,hydrationErrors:null},s=vl(e),s.return=t,t.child=s,tn=t,Tt=null)):e=null,e===null)throw Ya(t);return Sm(e)?t.lanes=32:t.lanes=536870912,null}var E=o.children;return o=o.fallback,f?(R(),f=t.mode,E=Ou({mode:"hidden",children:E},f),o=Va(o,f,s,null),E.return=t,o.return=t,E.sibling=o,t.child=E,o=t.child,o.memoizedState=Ff(s),o.childLanes=Bf(e,S,s),t.memoizedState=Hf,vc(null,o)):(N(t),Pf(t,E))}var U=e.memoizedState;if(U!==null&&(E=U.dehydrated,E!==null)){if(h)t.flags&256?(N(t),t.flags&=-257,t=$f(e,t,s)):t.memoizedState!==null?(R(),t.child=e.child,t.flags|=128,t=null):(R(),E=o.fallback,f=t.mode,o=Ou({mode:"visible",children:o.children},f),E=Va(E,f,s,null),E.flags|=2,o.return=t,E.return=t,o.sibling=E,t.child=o,Or(t,e.child,null,s),o=t.child,o.memoizedState=Ff(s),o.childLanes=Bf(e,S,s),t.memoizedState=Hf,t=vc(null,o));else if(N(t),Sm(E)){if(S=E.nextSibling&&E.nextSibling.dataset,S)var ie=S.dgst;S=ie,o=Error(l(419)),o.stack="",o.digest=S,yl({value:o,source:null,stack:null}),t=$f(e,t,s)}else if(vn||nr(e,t,s,!1),S=(s&e.childLanes)!==0,vn||S){if(S=qt,S!==null&&(o=Je(S,s),o!==0&&o!==U.retryLane))throw U.retryLane=o,tr(e,o),Ra(S,e,o),zf;wm(E)||Vu(),t=$f(e,t,s)}else wm(E)?(t.flags|=192,t.child=e.child,t=null):(e=U.treeContext,Tt=bs(E.nextSibling),tn=t,bt=!0,Is=null,Ft=!1,e!==null&&lc(t,e),t=Pf(t,o.children),t.flags|=4096);return t}return f?(R(),E=o.fallback,f=t.mode,U=e.child,ie=U.sibling,o=vs(U,{mode:"hidden",children:o.children}),o.subtreeFlags=U.subtreeFlags&65011712,ie!==null?E=vs(ie,E):(E=Va(E,f,s,null),E.flags|=2),E.return=t,o.return=t,o.sibling=E,t.child=o,vc(null,o),o=t.child,E=e.child.memoizedState,E===null?E=Ff(s):(f=E.cachePool,f!==null?(U=sn._currentValue,f=f.parent!==U?{parent:U,pool:U}:f):f=pn(),E={baseLanes:E.baseLanes|s,cachePool:f}),o.memoizedState=E,o.childLanes=Bf(e,S,s),t.memoizedState=Hf,vc(e.child,o)):(N(t),s=e.child,e=s.sibling,s=vs(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 Pf(e,t){return t=Ou({mode:"visible",children:t},e.mode),t.return=e,e.child=t}function Ou(e,t){return e=qn(22,e,null,t),e.lanes=0,e}function $f(e,t,s){return Or(t,e.child,null,s),e=Pf(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function gg(e,t,s){e.lanes|=t;var o=e.alternate;o!==null&&(o.lanes|=t),Ir(e.return,t,s)}function Uf(e,t,s,o,f,h){var S=e.memoizedState;S===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:o,tail:s,tailMode:f,treeForkCount:h}:(S.isBackwards=t,S.rendering=null,S.renderingStartTime=0,S.last=o,S.tail=s,S.tailMode=f,S.treeForkCount=h)}function vg(e,t,s){var o=t.pendingProps,f=o.revealOrder,h=o.tail;o=o.children;var S=te.current,E=(S&2)!==0;if(E?(S=S&1|2,t.flags|=128):S&=1,xe(te,S),Yn(e,t,o,s),o=bt?_s:0,!E&&e!==null&&(e.flags&128)!==0)e:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&gg(e,s,t);else if(e.tag===19)gg(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&&Ie(e)===null&&(f=s),s=s.sibling;s=f,s===null?(f=t.child,t.child=null):(f=s.sibling,s.sibling=null),Uf(t,!1,f,s,h,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&&Ie(e)===null){t.child=f;break}e=f.sibling,f.sibling=s,s=f,f=e}Uf(t,!0,s,null,h,o);break;case"together":Uf(t,!1,null,null,void 0,o);break;default:t.memoizedState=null}return t.child}function Pr(e,t,s){if(e!==null&&(t.dependencies=e.dependencies),Ti|=t.lanes,(s&t.childLanes)===0)if(e!==null){if(nr(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=vs(e,e.pendingProps),t.child=s,s.return=t;e.sibling!==null;)e=e.sibling,s=s.sibling=vs(e,e.pendingProps),s.return=t;s.sibling=null}return t.child}function qf(e,t){return(e.lanes&t)!==0?!0:(e=e.dependencies,!!(e!==null&&ro(e)))}function Iw(e,t,s){switch(t.tag){case 3:Ue(t,t.stateNode.containerInfo),ys(t,sn,e.memoizedState.cache),zs();break;case 27:case 5:he(t);break;case 4:Ue(t,t.stateNode.containerInfo);break;case 10:ys(t,t.type,t.memoizedProps.value);break;case 31:if(t.memoizedState!==null)return t.flags|=128,L(t),null;break;case 13:var o=t.memoizedState;if(o!==null)return o.dehydrated!==null?(N(t),t.flags|=128,null):(s&t.child.childLanes)!==0?pg(e,t,s):(N(t),e=Pr(e,t,s),e!==null?e.sibling:null);N(t);break;case 19:var f=(e.flags&128)!==0;if(o=(s&t.childLanes)!==0,o||(nr(e,t,s,!1),o=(s&t.childLanes)!==0),f){if(o)return vg(e,t,s);t.flags|=128}if(f=t.memoizedState,f!==null&&(f.rendering=null,f.tail=null,f.lastEffect=null),xe(te,te.current),o)break;return null;case 22:return t.lanes=0,cg(e,t,s,t.pendingProps);case 24:ys(t,sn,e.memoizedState.cache)}return Pr(e,t,s)}function yg(e,t,s){if(e!==null)if(e.memoizedProps!==t.pendingProps)vn=!0;else{if(!qf(e,s)&&(t.flags&128)===0)return vn=!1,Iw(e,t,s);vn=(e.flags&131072)!==0}else vn=!1,bt&&(t.flags&1048576)!==0&&eo(t,_s,t.index);switch(t.lanes=0,t.tag){case 16:e:{var o=t.pendingProps;if(e=ir(t.elementType),t.type=e,typeof e=="function")rc(e)?(o=kl(e,o),t.tag=1,t=mg(null,t,e,o,s)):(t.tag=0,t=Of(null,t,e,o,s));else{if(e!=null){var f=e.$$typeof;if(f===B){t.tag=11,t=ig(null,t,e,o,s);break e}else if(f===_){t.tag=14,t=lg(null,t,e,o,s);break e}}throw t=me(e)||e,Error(l(306,t,""))}}return t;case 0:return Of(e,t,t.type,t.pendingProps,s);case 1:return o=t.type,f=kl(o,t.pendingProps),mg(e,t,o,f,s);case 3:e:{if(Ue(t,t.stateNode.containerInfo),e===null)throw Error(l(387));o=t.pendingProps;var h=t.memoizedState;f=h.element,fc(e,t),Si(t,o,null,s);var S=t.memoizedState;if(o=S.cache,ys(t,sn,o),o!==h.cache&&so(t,[sn],s,!0),Fs(),o=S.element,h.isDehydrated)if(h={element:o,isDehydrated:!1,cache:S.cache},t.updateQueue.baseState=h,t.memoizedState=h,t.flags&256){t=hg(e,t,o,s);break e}else if(o!==f){f=na(Error(l(424)),t),yl(f),t=hg(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,Tt=bs(e.firstChild),tn=t,bt=!0,Is=null,Ft=!0,s=En(t,null,o,s),t.child=s;s;)s.flags=s.flags&-3|4096,s=s.sibling;else{if(zs(),o===f){t=Pr(e,t,s);break e}Yn(e,t,o,s)}t=t.child}return t;case 26:return zu(e,t),e===null?(s=Tv(t.type,null,t.pendingProps,null))?t.memoizedState=s:bt||(s=t.type,e=t.pendingProps,o=Ju(ke.current).createElement(s),o[ne]=t,o[Te]=e,Kn(o,s,e),Yt(o),t.stateNode=o):t.memoizedState=Tv(t.type,e.memoizedProps,t.pendingProps,e.memoizedState),null;case 27:return he(t),e===null&&bt&&(o=t.stateNode=Av(t.type,t.pendingProps,ke.current),tn=t,Ft=!0,f=Tt,_i(t.type)?(Cm=f,Tt=bs(o.firstChild)):Tt=f),Yn(e,t,t.pendingProps.children,s),zu(e,t),e===null&&(t.flags|=4194304),t.child;case 5:return e===null&&bt&&((f=o=Tt)&&(o=dS(o,t.type,t.pendingProps,Ft),o!==null?(t.stateNode=o,tn=t,Tt=bs(o.firstChild),Ft=!1,f=!0):f=!1),f||Ya(t)),he(t),f=t.type,h=t.pendingProps,S=e!==null?e.memoizedProps:null,o=h.children,ym(f,h)?o=null:S!==null&&ym(f,S)&&(t.flags|=32),t.memoizedState!==null&&(f=vf(e,t,Aw,null,null,s),Dc._currentValue=f),zu(e,t),Yn(e,t,o,s),t.child;case 6:return e===null&&bt&&((e=s=Tt)&&(s=fS(s,t.pendingProps,Ft),s!==null?(t.stateNode=s,tn=t,Tt=null,e=!0):e=!1),e||Ya(t)),null;case 13:return pg(e,t,s);case 4:return Ue(t,t.stateNode.containerInfo),o=t.pendingProps,e===null?t.child=Or(t,null,o,s):Yn(e,t,o,s),t.child;case 11:return ig(e,t,t.type,t.pendingProps,s);case 7:return Yn(e,t,t.pendingProps,s),t.child;case 8:return Yn(e,t,t.pendingProps.children,s),t.child;case 12:return Yn(e,t,t.pendingProps.children,s),t.child;case 10:return o=t.pendingProps,ys(t,t.type,o.value),Yn(e,t,o.children,s),t.child;case 9:return f=t.type._context,o=t.pendingProps.children,Xa(t),f=Cn(f),o=o(f),t.flags|=1,Yn(e,t,o,s),t.child;case 14:return lg(e,t,t.type,t.pendingProps,s);case 15:return og(e,t,t.type,t.pendingProps,s);case 19:return vg(e,t,s);case 31:return _w(e,t,s);case 22:return cg(e,t,s,t.pendingProps);case 24:return Xa(t),o=Cn(sn),e===null?(f=xl(),f===null&&(f=qt,h=gi(),f.pooledCache=h,h.refCount++,h!==null&&(f.pooledCacheLanes|=s),f=h),t.memoizedState={parent:o,cache:f},uo(t),ys(t,sn,f)):((e.lanes&s)!==0&&(fc(e,t),Si(t,null,null,s),Fs()),f=e.memoizedState,h=t.memoizedState,f.parent!==o?(f={parent:o,cache:o},t.memoizedState=f,t.lanes===0&&(t.memoizedState=t.updateQueue.baseState=f),ys(t,sn,o)):(o=h.cache,ys(t,sn,o),o!==f.cache&&so(t,[sn],s,!0))),Yn(e,t,t.pendingProps.children,s),t.child;case 29:throw t.pendingProps}throw Error(l(156,t.tag))}function $r(e){e.flags|=4}function Gf(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(Gg())e.flags|=8192;else throw Qa=Hs,gt}else e.flags&=-16777217}function bg(e,t){if(t.type!=="stylesheet"||(t.state.loading&4)!==0)e.flags&=-16777217;else if(e.flags|=16777216,!_v(t))if(Gg())e.flags|=8192;else throw Qa=Hs,gt}function Hu(e,t){t!==null&&(e.flags|=4),e.flags&16384&&(t=e.tag!==22?gr():536870912,e.lanes|=t,vo|=t)}function yc(e,t){if(!bt)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 Kt(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 zw(e,t,s){var o=t.pendingProps;switch(ja(t),t.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Kt(t),null;case 1:return Kt(t),null;case 3:return s=t.stateNode,o=null,e!==null&&(o=e.memoizedState.cache),t.memoizedState.cache!==o&&(t.flags|=2048),Ka(sn),Be(),s.pendingContext&&(s.context=s.pendingContext,s.pendingContext=null),(e===null||e.child===null)&&(pi(t)?$r(t):e===null||e.memoizedState.isDehydrated&&(t.flags&256)===0||(t.flags|=1024,Lr())),Kt(t),null;case 26:var f=t.type,h=t.memoizedState;return e===null?($r(t),h!==null?(Kt(t),bg(t,h)):(Kt(t),Gf(t,f,null,o,s))):h?h!==e.memoizedState?($r(t),Kt(t),bg(t,h)):(Kt(t),t.flags&=-16777217):(e=e.memoizedProps,e!==o&&$r(t),Kt(t),Gf(t,f,e,o,s)),null;case 27:if(Xe(t),s=ke.current,f=t.type,e!==null&&t.stateNode!=null)e.memoizedProps!==o&&$r(t);else{if(!o){if(t.stateNode===null)throw Error(l(166));return Kt(t),null}e=z.current,pi(t)?ao(t):(e=Av(f,o,s),t.stateNode=e,$r(t))}return Kt(t),null;case 5:if(Xe(t),f=t.type,e!==null&&t.stateNode!=null)e.memoizedProps!==o&&$r(t);else{if(!o){if(t.stateNode===null)throw Error(l(166));return Kt(t),null}if(h=z.current,pi(t))ao(t);else{var S=Ju(ke.current);switch(h){case 1:h=S.createElementNS("http://www.w3.org/2000/svg",f);break;case 2:h=S.createElementNS("http://www.w3.org/1998/Math/MathML",f);break;default:switch(f){case"svg":h=S.createElementNS("http://www.w3.org/2000/svg",f);break;case"math":h=S.createElementNS("http://www.w3.org/1998/Math/MathML",f);break;case"script":h=S.createElement("div"),h.innerHTML="<script><\/script>",h=h.removeChild(h.firstChild);break;case"select":h=typeof o.is=="string"?S.createElement("select",{is:o.is}):S.createElement("select"),o.multiple?h.multiple=!0:o.size&&(h.size=o.size);break;default:h=typeof o.is=="string"?S.createElement(f,{is:o.is}):S.createElement(f)}}h[ne]=t,h[Te]=o;e:for(S=t.child;S!==null;){if(S.tag===5||S.tag===6)h.appendChild(S.stateNode);else if(S.tag!==4&&S.tag!==27&&S.child!==null){S.child.return=S,S=S.child;continue}if(S===t)break e;for(;S.sibling===null;){if(S.return===null||S.return===t)break e;S=S.return}S.sibling.return=S.return,S=S.sibling}t.stateNode=h;e:switch(Kn(h,f,o),f){case"button":case"input":case"select":case"textarea":o=!!o.autoFocus;break e;case"img":o=!0;break e;default:o=!1}o&&$r(t)}}return Kt(t),Gf(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,s),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==o&&$r(t);else{if(typeof o!="string"&&t.stateNode===null)throw Error(l(166));if(e=ke.current,pi(t)){if(e=t.stateNode,s=t.memoizedProps,o=null,f=tn,f!==null)switch(f.tag){case 27:case 5:o=f.memoizedProps}e[ne]=t,e=!!(e.nodeValue===s||o!==null&&o.suppressHydrationWarning===!0||pv(e.nodeValue,s)),e||Ya(t,!0)}else e=Ju(e).createTextNode(o),e[ne]=t,t.stateNode=e}return Kt(t),null;case 31:if(s=t.memoizedState,e===null||e.memoizedState!==null){if(o=pi(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[ne]=t}else zs(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;Kt(t),e=!1}else s=Lr(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=s),e=!0;if(!e)return t.flags&256?(ae(t),t):(ae(t),null);if((t.flags&128)!==0)throw Error(l(558))}return Kt(t),null;case 13:if(o=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(f=pi(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[ne]=t}else zs(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;Kt(t),f=!1}else f=Lr(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=f),f=!0;if(!f)return t.flags&256?(ae(t),t):(ae(t),null)}return ae(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),h=null,o.memoizedState!==null&&o.memoizedState.cachePool!==null&&(h=o.memoizedState.cachePool.pool),h!==f&&(o.flags|=2048)),s!==e&&s&&(t.child.flags|=8192),Hu(t,t.updateQueue),Kt(t),null);case 4:return Be(),e===null&&mm(t.stateNode.containerInfo),Kt(t),null;case 10:return Ka(t.type),Kt(t),null;case 19:if(K(te),o=t.memoizedState,o===null)return Kt(t),null;if(f=(t.flags&128)!==0,h=o.rendering,h===null)if(f)yc(o,!1);else{if(ln!==0||e!==null&&(e.flags&128)!==0)for(e=t.child;e!==null;){if(h=Ie(e),h!==null){for(t.flags|=128,yc(o,!1),e=h.updateQueue,t.updateQueue=e,Hu(t,e),t.subtreeFlags=0,e=s,s=t.child;s!==null;)gl(s,e),s=s.sibling;return xe(te,te.current&1|2),bt&&ka(t,o.treeForkCount),t.child}e=e.sibling}o.tail!==null&&Ee()>Uu&&(t.flags|=128,f=!0,yc(o,!1),t.lanes=4194304)}else{if(!f)if(e=Ie(h),e!==null){if(t.flags|=128,f=!0,e=e.updateQueue,t.updateQueue=e,Hu(t,e),yc(o,!0),o.tail===null&&o.tailMode==="hidden"&&!h.alternate&&!bt)return Kt(t),null}else 2*Ee()-o.renderingStartTime>Uu&&s!==536870912&&(t.flags|=128,f=!0,yc(o,!1),t.lanes=4194304);o.isBackwards?(h.sibling=t.child,t.child=h):(e=o.last,e!==null?e.sibling=h:t.child=h,o.last=h)}return o.tail!==null?(e=o.tail,o.rendering=e,o.tail=e.sibling,o.renderingStartTime=Ee(),e.sibling=null,s=te.current,xe(te,f?s&1|2:s&1),bt&&ka(t,o.treeForkCount),e):(Kt(t),null);case 22:case 23:return ae(t),Bs(),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&&(Kt(t),t.subtreeFlags&6&&(t.flags|=8192)):Kt(t),s=t.updateQueue,s!==null&&Hu(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(yi),null;case 24:return s=null,e!==null&&(s=e.memoizedState.cache),t.memoizedState.cache!==s&&(t.flags|=2048),Ka(sn),Kt(t),null;case 25:return null;case 30:return null}throw Error(l(156,t.tag))}function Ow(e,t){switch(ja(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ka(sn),Be(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return Xe(t),null;case 31:if(t.memoizedState!==null){if(ae(t),t.alternate===null)throw Error(l(340));zs()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(ae(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(l(340));zs()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return K(te),null;case 4:return Be(),null;case 10:return Ka(t.type),null;case 22:case 23:return ae(t),Bs(),e!==null&&K(yi),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Ka(sn),null;case 25:return null;default:return null}}function xg(e,t){switch(ja(t),t.tag){case 3:Ka(sn),Be();break;case 26:case 27:case 5:Xe(t);break;case 4:Be();break;case 31:t.memoizedState!==null&&ae(t);break;case 13:ae(t);break;case 19:K(te);break;case 10:Ka(t.type);break;case 22:case 23:ae(t),Bs(),e!==null&&K(yi);break;case 24:Ka(sn)}}function bc(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 h=s.create,S=s.inst;o=h(),S.destroy=o}s=s.next}while(s!==f)}}catch(E){Ot(t,t.return,E)}}function Ni(e,t,s){try{var o=t.updateQueue,f=o!==null?o.lastEffect:null;if(f!==null){var h=f.next;o=h;do{if((o.tag&e)===e){var S=o.inst,E=S.destroy;if(E!==void 0){S.destroy=void 0,f=t;var U=s,ie=E;try{ie()}catch(be){Ot(f,U,be)}}}o=o.next}while(o!==h)}}catch(be){Ot(t,t.return,be)}}function wg(e){var t=e.updateQueue;if(t!==null){var s=e.stateNode;try{Nu(t,s)}catch(o){Ot(e,e.return,o)}}}function Sg(e,t,s){s.props=kl(e.type,e.memoizedProps),s.state=e.memoizedState;try{s.componentWillUnmount()}catch(o){Ot(e,t,o)}}function xc(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){Ot(e,t,f)}}function ur(e,t){var s=e.ref,o=e.refCleanup;if(s!==null)if(typeof o=="function")try{o()}catch(f){Ot(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){Ot(e,t,f)}else s.current=null}function Cg(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){Ot(e,e.return,f)}}function Vf(e,t,s){try{var o=e.stateNode;rS(o,e.type,s,t),o[Te]=t}catch(f){Ot(e,e.return,f)}}function kg(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&_i(e.type)||e.tag===4}function Wf(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||kg(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&&_i(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 Yf(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=Bn));else if(o!==4&&(o===27&&_i(e.type)&&(s=e.stateNode,t=null),e=e.child,e!==null))for(Yf(e,t,s),e=e.sibling;e!==null;)Yf(e,t,s),e=e.sibling}function Fu(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&&_i(e.type)&&(s=e.stateNode),e=e.child,e!==null))for(Fu(e,t,s),e=e.sibling;e!==null;)Fu(e,t,s),e=e.sibling}function jg(e){var t=e.stateNode,s=e.memoizedProps;try{for(var o=e.type,f=t.attributes;f.length;)t.removeAttributeNode(f[0]);Kn(t,o,s),t[ne]=e,t[Te]=s}catch(h){Ot(e,e.return,h)}}var Ur=!1,yn=!1,Kf=!1,Ag=typeof WeakSet=="function"?WeakSet:Set,Rn=null;function Hw(e,t){if(e=e.containerInfo,gm=id,e=ba(e),Ms(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,h=o.focusNode;o=o.focusOffset;try{s.nodeType,h.nodeType}catch{s=null;break e}var S=0,E=-1,U=-1,ie=0,be=0,Se=e,oe=null;t:for(;;){for(var pe;Se!==s||f!==0&&Se.nodeType!==3||(E=S+f),Se!==h||o!==0&&Se.nodeType!==3||(U=S+o),Se.nodeType===3&&(S+=Se.nodeValue.length),(pe=Se.firstChild)!==null;)oe=Se,Se=pe;for(;;){if(Se===e)break t;if(oe===s&&++ie===f&&(E=S),oe===h&&++be===o&&(U=S),(pe=Se.nextSibling)!==null)break;Se=oe,oe=Se.parentNode}Se=pe}s=E===-1||U===-1?null:{start:E,end:U}}else s=null}s=s||{start:0,end:0}}else s=null;for(vm={focusedElem:e,selectionRange:s},id=!1,Rn=t;Rn!==null;)if(t=Rn,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Rn=e;else for(;Rn!==null;){switch(t=Rn,h=t.alternate,e=t.flags,t.tag){case 0:if((e&4)!==0&&(e=t.updateQueue,e=e!==null?e.events:null,e!==null))for(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&&h!==null){e=void 0,s=t,f=h.memoizedProps,h=h.memoizedState,o=s.stateNode;try{var Ze=kl(s.type,f);e=o.getSnapshotBeforeUpdate(Ze,h),o.__reactInternalSnapshotBeforeUpdate=e}catch(ot){Ot(s,s.return,ot)}}break;case 3:if((e&1024)!==0){if(e=t.stateNode.containerInfo,s=e.nodeType,s===9)xm(e);else if(s===1)switch(e.nodeName){case"HEAD":case"HTML":case"BODY":xm(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,Rn=e;break}Rn=t.return}}function Ng(e,t,s){var o=s.flags;switch(s.tag){case 0:case 11:case 15:Gr(e,s),o&4&&bc(5,s);break;case 1:if(Gr(e,s),o&4)if(e=s.stateNode,t===null)try{e.componentDidMount()}catch(S){Ot(s,s.return,S)}else{var f=kl(s.type,t.memoizedProps);t=t.memoizedState;try{e.componentDidUpdate(f,t,e.__reactInternalSnapshotBeforeUpdate)}catch(S){Ot(s,s.return,S)}}o&64&&wg(s),o&512&&xc(s,s.return);break;case 3:if(Gr(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{Nu(e,t)}catch(S){Ot(s,s.return,S)}}break;case 27:t===null&&o&4&&jg(s);case 26:case 5:Gr(e,s),t===null&&o&4&&Cg(s),o&512&&xc(s,s.return);break;case 12:Gr(e,s);break;case 31:Gr(e,s),o&4&&Eg(e,s);break;case 13:Gr(e,s),o&4&&Rg(e,s),o&64&&(e=s.memoizedState,e!==null&&(e=e.dehydrated,e!==null&&(s=Ww.bind(null,s),mS(e,s))));break;case 22:if(o=s.memoizedState!==null||Ur,!o){t=t!==null&&t.memoizedState!==null||yn,f=Ur;var h=yn;Ur=o,(yn=t)&&!h?Vr(e,s,(s.subtreeFlags&8772)!==0):Gr(e,s),Ur=f,yn=h}break;case 30:break;default:Gr(e,s)}}function Mg(e){var t=e.alternate;t!==null&&(e.alternate=null,Mg(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&cn(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 Zt=null,Na=!1;function qr(e,t,s){for(s=s.child;s!==null;)Tg(e,t,s),s=s.sibling}function Tg(e,t,s){if(Me&&typeof Me.onCommitFiberUnmount=="function")try{Me.onCommitFiberUnmount(He,s)}catch{}switch(s.tag){case 26:yn||ur(s,t),qr(e,t,s),s.memoizedState?s.memoizedState.count--:s.stateNode&&(s=s.stateNode,s.parentNode.removeChild(s));break;case 27:yn||ur(s,t);var o=Zt,f=Na;_i(s.type)&&(Zt=s.stateNode,Na=!1),qr(e,t,s),Tc(s.stateNode),Zt=o,Na=f;break;case 5:yn||ur(s,t);case 6:if(o=Zt,f=Na,Zt=null,qr(e,t,s),Zt=o,Na=f,Zt!==null)if(Na)try{(Zt.nodeType===9?Zt.body:Zt.nodeName==="HTML"?Zt.ownerDocument.body:Zt).removeChild(s.stateNode)}catch(h){Ot(s,t,h)}else try{Zt.removeChild(s.stateNode)}catch(h){Ot(s,t,h)}break;case 18:Zt!==null&&(Na?(e=Zt,wv(e.nodeType===9?e.body:e.nodeName==="HTML"?e.ownerDocument.body:e,s.stateNode),jo(e)):wv(Zt,s.stateNode));break;case 4:o=Zt,f=Na,Zt=s.stateNode.containerInfo,Na=!0,qr(e,t,s),Zt=o,Na=f;break;case 0:case 11:case 14:case 15:Ni(2,s,t),yn||Ni(4,s,t),qr(e,t,s);break;case 1:yn||(ur(s,t),o=s.stateNode,typeof o.componentWillUnmount=="function"&&Sg(s,t,o)),qr(e,t,s);break;case 21:qr(e,t,s);break;case 22:yn=(o=yn)||s.memoizedState!==null,qr(e,t,s),yn=o;break;default:qr(e,t,s)}}function Eg(e,t){if(t.memoizedState===null&&(e=t.alternate,e!==null&&(e=e.memoizedState,e!==null))){e=e.dehydrated;try{jo(e)}catch(s){Ot(t,t.return,s)}}}function Rg(e,t){if(t.memoizedState===null&&(e=t.alternate,e!==null&&(e=e.memoizedState,e!==null&&(e=e.dehydrated,e!==null))))try{jo(e)}catch(s){Ot(t,t.return,s)}}function Fw(e){switch(e.tag){case 31:case 13:case 19:var t=e.stateNode;return t===null&&(t=e.stateNode=new Ag),t;case 22:return e=e.stateNode,t=e._retryCache,t===null&&(t=e._retryCache=new Ag),t;default:throw Error(l(435,e.tag))}}function Bu(e,t){var s=Fw(e);t.forEach(function(o){if(!s.has(o)){s.add(o);var f=Yw.bind(null,e,o);o.then(f,f)}})}function Ma(e,t){var s=t.deletions;if(s!==null)for(var o=0;o<s.length;o++){var f=s[o],h=e,S=t,E=S;e:for(;E!==null;){switch(E.tag){case 27:if(_i(E.type)){Zt=E.stateNode,Na=!1;break e}break;case 5:Zt=E.stateNode,Na=!1;break e;case 3:case 4:Zt=E.stateNode.containerInfo,Na=!0;break e}E=E.return}if(Zt===null)throw Error(l(160));Tg(h,S,f),Zt=null,Na=!1,h=f.alternate,h!==null&&(h.return=null),f.return=null}if(t.subtreeFlags&13886)for(t=t.child;t!==null;)Dg(t,e),t=t.sibling}var $s=null;function Dg(e,t){var s=e.alternate,o=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:Ma(t,e),Ta(e),o&4&&(Ni(3,e,e.return),bc(3,e),Ni(5,e,e.return));break;case 1:Ma(t,e),Ta(e),o&512&&(yn||s===null||ur(s,s.return)),o&64&&Ur&&(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=$s;if(Ma(t,e),Ta(e),o&512&&(yn||s===null||ur(s,s.return)),o&4){var h=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":h=f.getElementsByTagName("title")[0],(!h||h[jt]||h[ne]||h.namespaceURI==="http://www.w3.org/2000/svg"||h.hasAttribute("itemprop"))&&(h=f.createElement(o),f.head.insertBefore(h,f.querySelector("head > title"))),Kn(h,o,s),h[ne]=e,Yt(h),o=h;break e;case"link":var S=Dv("link","href",f).get(o+(s.href||""));if(S){for(var E=0;E<S.length;E++)if(h=S[E],h.getAttribute("href")===(s.href==null||s.href===""?null:s.href)&&h.getAttribute("rel")===(s.rel==null?null:s.rel)&&h.getAttribute("title")===(s.title==null?null:s.title)&&h.getAttribute("crossorigin")===(s.crossOrigin==null?null:s.crossOrigin)){S.splice(E,1);break t}}h=f.createElement(o),Kn(h,o,s),f.head.appendChild(h);break;case"meta":if(S=Dv("meta","content",f).get(o+(s.content||""))){for(E=0;E<S.length;E++)if(h=S[E],h.getAttribute("content")===(s.content==null?null:""+s.content)&&h.getAttribute("name")===(s.name==null?null:s.name)&&h.getAttribute("property")===(s.property==null?null:s.property)&&h.getAttribute("http-equiv")===(s.httpEquiv==null?null:s.httpEquiv)&&h.getAttribute("charset")===(s.charSet==null?null:s.charSet)){S.splice(E,1);break t}}h=f.createElement(o),Kn(h,o,s),f.head.appendChild(h);break;default:throw Error(l(468,o))}h[ne]=e,Yt(h),o=h}e.stateNode=o}else Lv(f,e.type,e.stateNode);else e.stateNode=Rv(f,o,e.memoizedProps);else h!==o?(h===null?s.stateNode!==null&&(s=s.stateNode,s.parentNode.removeChild(s)):h.count--,o===null?Lv(f,e.type,e.stateNode):Rv(f,o,e.memoizedProps)):o===null&&e.stateNode!==null&&Vf(e,e.memoizedProps,s.memoizedProps)}break;case 27:Ma(t,e),Ta(e),o&512&&(yn||s===null||ur(s,s.return)),s!==null&&o&4&&Vf(e,e.memoizedProps,s.memoizedProps);break;case 5:if(Ma(t,e),Ta(e),o&512&&(yn||s===null||ur(s,s.return)),e.flags&32){f=e.stateNode;try{Vs(f,"")}catch(Ze){Ot(e,e.return,Ze)}}o&4&&e.stateNode!=null&&(f=e.memoizedProps,Vf(e,f,s!==null?s.memoizedProps:f)),o&1024&&(Kf=!0);break;case 6:if(Ma(t,e),Ta(e),o&4){if(e.stateNode===null)throw Error(l(162));o=e.memoizedProps,s=e.stateNode;try{s.nodeValue=o}catch(Ze){Ot(e,e.return,Ze)}}break;case 3:if(nd=null,f=$s,$s=ed(t.containerInfo),Ma(t,e),$s=f,Ta(e),o&4&&s!==null&&s.memoizedState.isDehydrated)try{jo(t.containerInfo)}catch(Ze){Ot(e,e.return,Ze)}Kf&&(Kf=!1,Lg(e));break;case 4:o=$s,$s=ed(e.stateNode.containerInfo),Ma(t,e),Ta(e),$s=o;break;case 12:Ma(t,e),Ta(e);break;case 31:Ma(t,e),Ta(e),o&4&&(o=e.updateQueue,o!==null&&(e.updateQueue=null,Bu(e,o)));break;case 13:Ma(t,e),Ta(e),e.child.flags&8192&&e.memoizedState!==null!=(s!==null&&s.memoizedState!==null)&&($u=Ee()),o&4&&(o=e.updateQueue,o!==null&&(e.updateQueue=null,Bu(e,o)));break;case 22:f=e.memoizedState!==null;var U=s!==null&&s.memoizedState!==null,ie=Ur,be=yn;if(Ur=ie||f,yn=be||U,Ma(t,e),yn=be,Ur=ie,Ta(e),o&8192)e:for(t=e.stateNode,t._visibility=f?t._visibility&-2:t._visibility|1,f&&(s===null||U||Ur||yn||jl(e)),s=null,t=e;;){if(t.tag===5||t.tag===26){if(s===null){U=s=t;try{if(h=U.stateNode,f)S=h.style,typeof S.setProperty=="function"?S.setProperty("display","none","important"):S.display="none";else{E=U.stateNode;var Se=U.memoizedProps.style,oe=Se!=null&&Se.hasOwnProperty("display")?Se.display:null;E.style.display=oe==null||typeof oe=="boolean"?"":(""+oe).trim()}}catch(Ze){Ot(U,U.return,Ze)}}}else if(t.tag===6){if(s===null){U=t;try{U.stateNode.nodeValue=f?"":U.memoizedProps}catch(Ze){Ot(U,U.return,Ze)}}}else if(t.tag===18){if(s===null){U=t;try{var pe=U.stateNode;f?Sv(pe,!0):Sv(U.stateNode,!1)}catch(Ze){Ot(U,U.return,Ze)}}}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,Bu(e,s))));break;case 19:Ma(t,e),Ta(e),o&4&&(o=e.updateQueue,o!==null&&(e.updateQueue=null,Bu(e,o)));break;case 30:break;case 21:break;default:Ma(t,e),Ta(e)}}function Ta(e){var t=e.flags;if(t&2){try{for(var s,o=e.return;o!==null;){if(kg(o)){s=o;break}o=o.return}if(s==null)throw Error(l(160));switch(s.tag){case 27:var f=s.stateNode,h=Wf(e);Fu(e,h,f);break;case 5:var S=s.stateNode;s.flags&32&&(Vs(S,""),s.flags&=-33);var E=Wf(e);Fu(e,E,S);break;case 3:case 4:var U=s.stateNode.containerInfo,ie=Wf(e);Yf(e,ie,U);break;default:throw Error(l(161))}}catch(be){Ot(e,e.return,be)}e.flags&=-3}t&4096&&(e.flags&=-4097)}function Lg(e){if(e.subtreeFlags&1024)for(e=e.child;e!==null;){var t=e;Lg(t),t.tag===5&&t.flags&1024&&t.stateNode.reset(),e=e.sibling}}function Gr(e,t){if(t.subtreeFlags&8772)for(t=t.child;t!==null;)Ng(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:Ni(4,t,t.return),jl(t);break;case 1:ur(t,t.return);var s=t.stateNode;typeof s.componentWillUnmount=="function"&&Sg(t,t.return,s),jl(t);break;case 27:Tc(t.stateNode);case 26:case 5:ur(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 Vr(e,t,s){for(s=s&&(t.subtreeFlags&8772)!==0,t=t.child;t!==null;){var o=t.alternate,f=e,h=t,S=h.flags;switch(h.tag){case 0:case 11:case 15:Vr(f,h,s),bc(4,h);break;case 1:if(Vr(f,h,s),o=h,f=o.stateNode,typeof f.componentDidMount=="function")try{f.componentDidMount()}catch(ie){Ot(o,o.return,ie)}if(o=h,f=o.updateQueue,f!==null){var E=o.stateNode;try{var U=f.shared.hiddenCallbacks;if(U!==null)for(f.shared.hiddenCallbacks=null,f=0;f<U.length;f++)Au(U[f],E)}catch(ie){Ot(o,o.return,ie)}}s&&S&64&&wg(h),xc(h,h.return);break;case 27:jg(h);case 26:case 5:Vr(f,h,s),s&&o===null&&S&4&&Cg(h),xc(h,h.return);break;case 12:Vr(f,h,s);break;case 31:Vr(f,h,s),s&&S&4&&Eg(f,h);break;case 13:Vr(f,h,s),s&&S&4&&Rg(f,h);break;case 22:h.memoizedState===null&&Vr(f,h,s),xc(h,h.return);break;case 30:break;default:Vr(f,h,s)}t=t.sibling}}function Xf(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&&ar(s))}function Qf(e,t){e=null,t.alternate!==null&&(e=t.alternate.memoizedState.cache),t=t.memoizedState.cache,t!==e&&(t.refCount++,e!=null&&ar(e))}function Us(e,t,s,o){if(t.subtreeFlags&10256)for(t=t.child;t!==null;)_g(e,t,s,o),t=t.sibling}function _g(e,t,s,o){var f=t.flags;switch(t.tag){case 0:case 11:case 15:Us(e,t,s,o),f&2048&&bc(9,t);break;case 1:Us(e,t,s,o);break;case 3:Us(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&&ar(e)));break;case 12:if(f&2048){Us(e,t,s,o),e=t.stateNode;try{var h=t.memoizedProps,S=h.id,E=h.onPostCommit;typeof E=="function"&&E(S,t.alternate===null?"mount":"update",e.passiveEffectDuration,-0)}catch(U){Ot(t,t.return,U)}}else Us(e,t,s,o);break;case 31:Us(e,t,s,o);break;case 13:Us(e,t,s,o);break;case 23:break;case 22:h=t.stateNode,S=t.alternate,t.memoizedState!==null?h._visibility&2?Us(e,t,s,o):wc(e,t):h._visibility&2?Us(e,t,s,o):(h._visibility|=2,ho(e,t,s,o,(t.subtreeFlags&10256)!==0||!1)),f&2048&&Xf(S,t);break;case 24:Us(e,t,s,o),f&2048&&Qf(t.alternate,t);break;default:Us(e,t,s,o)}}function ho(e,t,s,o,f){for(f=f&&((t.subtreeFlags&10256)!==0||!1),t=t.child;t!==null;){var h=e,S=t,E=s,U=o,ie=S.flags;switch(S.tag){case 0:case 11:case 15:ho(h,S,E,U,f),bc(8,S);break;case 23:break;case 22:var be=S.stateNode;S.memoizedState!==null?be._visibility&2?ho(h,S,E,U,f):wc(h,S):(be._visibility|=2,ho(h,S,E,U,f)),f&&ie&2048&&Xf(S.alternate,S);break;case 24:ho(h,S,E,U,f),f&&ie&2048&&Qf(S.alternate,S);break;default:ho(h,S,E,U,f)}t=t.sibling}}function wc(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:wc(s,o),f&2048&&Xf(o.alternate,o);break;case 24:wc(s,o),f&2048&&Qf(o.alternate,o);break;default:wc(s,o)}t=t.sibling}}var Sc=8192;function po(e,t,s){if(e.subtreeFlags&Sc)for(e=e.child;e!==null;)Ig(e,t,s),e=e.sibling}function Ig(e,t,s){switch(e.tag){case 26:po(e,t,s),e.flags&Sc&&e.memoizedState!==null&&jS(s,$s,e.memoizedState,e.memoizedProps);break;case 5:po(e,t,s);break;case 3:case 4:var o=$s;$s=ed(e.stateNode.containerInfo),po(e,t,s),$s=o;break;case 22:e.memoizedState===null&&(o=e.alternate,o!==null&&o.memoizedState!==null?(o=Sc,Sc=16777216,po(e,t,s),Sc=o):po(e,t,s));break;default:po(e,t,s)}}function zg(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 Cc(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];Rn=o,Hg(o,e)}zg(e)}if(e.subtreeFlags&10256)for(e=e.child;e!==null;)Og(e),e=e.sibling}function Og(e){switch(e.tag){case 0:case 11:case 15:Cc(e),e.flags&2048&&Ni(9,e,e.return);break;case 3:Cc(e);break;case 12:Cc(e);break;case 22:var t=e.stateNode;e.memoizedState!==null&&t._visibility&2&&(e.return===null||e.return.tag!==13)?(t._visibility&=-3,Pu(e)):Cc(e);break;default:Cc(e)}}function Pu(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];Rn=o,Hg(o,e)}zg(e)}for(e=e.child;e!==null;){switch(t=e,t.tag){case 0:case 11:case 15:Ni(8,t,t.return),Pu(t);break;case 22:s=t.stateNode,s._visibility&2&&(s._visibility&=-3,Pu(t));break;default:Pu(t)}e=e.sibling}}function Hg(e,t){for(;Rn!==null;){var s=Rn;switch(s.tag){case 0:case 11:case 15:Ni(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:ar(s.memoizedState.cache)}if(o=s.child,o!==null)o.return=s,Rn=o;else e:for(s=e;Rn!==null;){o=Rn;var f=o.sibling,h=o.return;if(Mg(o),o===s){Rn=null;break e}if(f!==null){f.return=h,Rn=f;break e}Rn=h}}}var Bw={getCacheForType:function(e){var t=Cn(sn),s=t.data.get(e);return s===void 0&&(s=e(),t.data.set(e,s)),s},cacheSignal:function(){return Cn(sn).controller.signal}},Pw=typeof WeakMap=="function"?WeakMap:Map,Lt=0,qt=null,xt=null,St=0,zt=0,Ja=null,Mi=!1,go=!1,Zf=!1,Wr=0,ln=0,Ti=0,Al=0,Jf=0,es=0,vo=0,kc=null,Ea=null,em=!1,$u=0,Fg=0,Uu=1/0,qu=null,Ei=null,kn=0,Ri=null,yo=null,Yr=0,tm=0,nm=null,Bg=null,jc=0,am=null;function ts(){return(Lt&2)!==0&&St!==0?St&-St:I.T!==null?cm():ks()}function Pg(){if(es===0)if((St&536870912)===0||bt){var e=Xt;Xt<<=1,(Xt&3932160)===0&&(Xt=262144),es=e}else es=536870912;return e=Vn.current,e!==null&&(e.flags|=32),es}function Ra(e,t,s){(e===qt&&(zt===2||zt===9)||e.cancelPendingCommit!==null)&&(bo(e,0),Di(e,St,es,!1)),zn(e,s),((Lt&2)===0||e!==qt)&&(e===qt&&((Lt&2)===0&&(Al|=s),ln===4&&Di(e,St,es,!1)),dr(e))}function $g(e,t,s){if((Lt&6)!==0)throw Error(l(327));var o=!s&&(t&127)===0&&(t&e.expiredLanes)===0||Cs(e,t),f=o?qw(e,t):rm(e,t,!0),h=o;do{if(f===0){go&&!o&&Di(e,t,0,!1);break}else{if(s=e.current.alternate,h&&!$w(s)){f=rm(e,t,!1),h=!1;continue}if(f===2){if(h=t,e.errorRecoveryDisabledLanes&h)var S=0;else S=e.pendingLanes&-536870913,S=S!==0?S:S&536870912?536870912:0;if(S!==0){t=S;e:{var E=e;f=kc;var U=E.current.memoizedState.isDehydrated;if(U&&(bo(E,S).flags|=256),S=rm(E,S,!1),S!==2){if(Zf&&!U){E.errorRecoveryDisabledLanes|=h,Al|=h,f=4;break e}h=Ea,Ea=f,h!==null&&(Ea===null?Ea=h:Ea.push.apply(Ea,h))}f=S}if(h=!1,f!==2)continue}}if(f===1){bo(e,0),Di(e,t,0,!0);break}e:{switch(o=e,h=f,h){case 0:case 1:throw Error(l(345));case 4:if((t&4194048)!==t)break;case 6:Di(o,t,es,!Mi);break e;case 2:Ea=null;break;case 3:case 5:break;default:throw Error(l(329))}if((t&62914560)===t&&(f=$u+300-Ee(),10<f)){if(Di(o,t,es,!Mi),wn(o,0,!0)!==0)break e;Yr=t,o.timeoutHandle=bv(Ug.bind(null,o,s,Ea,qu,em,t,es,Al,vo,Mi,h,"Throttled",-0,0),f);break e}Ug(o,s,Ea,qu,em,t,es,Al,vo,Mi,h,null,-0,0)}}break}while(!0);dr(e)}function Ug(e,t,s,o,f,h,S,E,U,ie,be,Se,oe,pe){if(e.timeoutHandle=-1,Se=t.subtreeFlags,Se&8192||(Se&16785408)===16785408){Se={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:Bn},Ig(t,h,Se);var Ze=(h&62914560)===h?$u-Ee():(h&4194048)===h?Fg-Ee():0;if(Ze=AS(Se,Ze),Ze!==null){Yr=h,e.cancelPendingCommit=Ze(Qg.bind(null,e,t,h,s,o,f,S,E,U,be,Se,null,oe,pe)),Di(e,h,S,!ie);return}}Qg(e,t,h,s,o,f,S,E,U)}function $w(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],h=f.getSnapshot;f=f.value;try{if(!Ut(h(),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 Di(e,t,s,o){t&=~Jf,t&=~Al,e.suspendedLanes|=t,e.pingedLanes&=~t,o&&(e.warmLanes|=t),o=e.expirationTimes;for(var f=t;0<f;){var h=31-dt(f),S=1<<h;o[h]=-1,f&=~S}s!==0&&Qi(e,s,t)}function Gu(){return(Lt&6)===0?(Ac(0),!1):!0}function sm(){if(xt!==null){if(zt===0)var e=xt.return;else e=xt,Os=_r=null,xf(e),lr=null,Sl=0,e=xt;for(;e!==null;)xg(e.alternate,e),e=e.return;xt=null}}function bo(e,t){var s=e.timeoutHandle;s!==-1&&(e.timeoutHandle=-1,oS(s)),s=e.cancelPendingCommit,s!==null&&(e.cancelPendingCommit=null,s()),Yr=0,sm(),qt=e,xt=s=vs(e.current,null),St=t,zt=0,Ja=null,Mi=!1,go=Cs(e,t),Zf=!1,vo=es=Jf=Al=Ti=ln=0,Ea=kc=null,em=!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-dt(o),h=1<<f;t|=e[f],o&=~h}return Wr=t,Zl(),s}function qg(e,t){Ne=null,I.H=gc,t===gn||t===oo?(t=ku(),zt=3):t===gt?(t=ku(),zt=4):zt=t===zf?8:t!==null&&typeof t=="object"&&typeof t.then=="function"?6:1,Ja=t,xt===null&&(ln=1,_u(e,na(t,e.current)))}function Gg(){var e=Vn.current;return e===null?!0:(St&4194048)===St?y===null:(St&62914560)===St||(St&536870912)!==0?e===y:!1}function Vg(){var e=I.H;return I.H=gc,e===null?gc:e}function Wg(){var e=I.A;return I.A=Bw,e}function Vu(){ln=4,Mi||(St&4194048)!==St&&Vn.current!==null||(go=!0),(Ti&134217727)===0&&(Al&134217727)===0||qt===null||Di(qt,St,es,!1)}function rm(e,t,s){var o=Lt;Lt|=2;var f=Vg(),h=Wg();(qt!==e||St!==t)&&(qu=null,bo(e,t)),t=!1;var S=ln;e:do try{if(zt!==0&&xt!==null){var E=xt,U=Ja;switch(zt){case 8:sm(),S=6;break e;case 3:case 2:case 9:case 6:Vn.current===null&&(t=!0);var ie=zt;if(zt=0,Ja=null,xo(e,E,U,ie),s&&go){S=0;break e}break;default:ie=zt,zt=0,Ja=null,xo(e,E,U,ie)}}Uw(),S=ln;break}catch(be){qg(e,be)}while(!0);return t&&e.shellSuspendCounter++,Os=_r=null,Lt=o,I.H=f,I.A=h,xt===null&&(qt=null,St=0,Zl()),S}function Uw(){for(;xt!==null;)Yg(xt)}function qw(e,t){var s=Lt;Lt|=2;var o=Vg(),f=Wg();qt!==e||St!==t?(qu=null,Uu=Ee()+500,bo(e,t)):go=Cs(e,t);e:do try{if(zt!==0&&xt!==null){t=xt;var h=Ja;t:switch(zt){case 1:zt=0,Ja=null,xo(e,t,h,1);break;case 2:case 9:if(wl(h)){zt=0,Ja=null,Kg(t);break}t=function(){zt!==2&&zt!==9||qt!==e||(zt=7),dr(e)},h.then(t,t);break e;case 3:zt=7;break e;case 4:zt=5;break e;case 7:wl(h)?(zt=0,Ja=null,Kg(t)):(zt=0,Ja=null,xo(e,t,h,7));break;case 5:var S=null;switch(xt.tag){case 26:S=xt.memoizedState;case 5:case 27:var E=xt;if(S?_v(S):E.stateNode.complete){zt=0,Ja=null;var U=E.sibling;if(U!==null)xt=U;else{var ie=E.return;ie!==null?(xt=ie,Wu(ie)):xt=null}break t}}zt=0,Ja=null,xo(e,t,h,5);break;case 6:zt=0,Ja=null,xo(e,t,h,6);break;case 8:sm(),ln=6;break e;default:throw Error(l(462))}}Gw();break}catch(be){qg(e,be)}while(!0);return Os=_r=null,I.H=o,I.A=f,Lt=s,xt!==null?0:(qt=null,St=0,Zl(),ln)}function Gw(){for(;xt!==null&&!fe();)Yg(xt)}function Yg(e){var t=yg(e.alternate,e,Wr);e.memoizedProps=e.pendingProps,t===null?Wu(e):xt=t}function Kg(e){var t=e,s=t.alternate;switch(t.tag){case 15:case 0:t=fg(s,t,t.pendingProps,t.type,void 0,St);break;case 11:t=fg(s,t,t.pendingProps,t.type.render,t.ref,St);break;case 5:xf(t);default:xg(s,t),t=xt=gl(t,Wr),t=yg(s,t,Wr)}e.memoizedProps=e.pendingProps,t===null?Wu(e):xt=t}function xo(e,t,s,o){Os=_r=null,xf(t),lr=null,Sl=0;var f=t.return;try{if(Lw(e,f,t,s,St)){ln=1,_u(e,na(s,e.current)),xt=null;return}}catch(h){if(f!==null)throw xt=f,h;ln=1,_u(e,na(s,e.current)),xt=null;return}t.flags&32768?(bt||o===1?e=!0:go||(St&536870912)!==0?e=!1:(Mi=e=!0,(o===2||o===9||o===3||o===6)&&(o=Vn.current,o!==null&&o.tag===13&&(o.flags|=16384))),Xg(t,e)):Wu(t)}function Wu(e){var t=e;do{if((t.flags&32768)!==0){Xg(t,Mi);return}e=t.return;var s=zw(t.alternate,t,Wr);if(s!==null){xt=s;return}if(t=t.sibling,t!==null){xt=t;return}xt=t=e}while(t!==null);ln===0&&(ln=5)}function Xg(e,t){do{var s=Ow(e.alternate,e);if(s!==null){s.flags&=32767,xt=s;return}if(s=e.return,s!==null&&(s.flags|=32768,s.subtreeFlags=0,s.deletions=null),!t&&(e=e.sibling,e!==null)){xt=e;return}xt=e=s}while(e!==null);ln=6,xt=null}function Qg(e,t,s,o,f,h,S,E,U){e.cancelPendingCommit=null;do Yu();while(kn!==0);if((Lt&6)!==0)throw Error(l(327));if(t!==null){if(t===e.current)throw Error(l(177));if(h=t.lanes|t.childLanes,h|=di,Xi(e,s,h,S,E,U),e===qt&&(xt=qt=null,St=0),yo=t,Ri=e,Yr=s,tm=h,nm=f,Bg=o,(t.subtreeFlags&10256)!==0||(t.flags&10256)!==0?(e.callbackNode=null,e.callbackPriority=0,Kw(yt,function(){return nv(),null})):(e.callbackNode=null,e.callbackPriority=0),o=(t.flags&13878)!==0,(t.subtreeFlags&13878)!==0||o){o=I.T,I.T=null,f=ee.p,ee.p=2,S=Lt,Lt|=4;try{Hw(e,t,s)}finally{Lt=S,ee.p=f,I.T=o}}kn=1,Zg(),Jg(),ev()}}function Zg(){if(kn===1){kn=0;var e=Ri,t=yo,s=(t.flags&13878)!==0;if((t.subtreeFlags&13878)!==0||s){s=I.T,I.T=null;var o=ee.p;ee.p=2;var f=Lt;Lt|=4;try{Dg(t,e);var h=vm,S=ba(e.containerInfo),E=h.focusedElem,U=h.selectionRange;if(S!==E&&E&&E.ownerDocument&&pu(E.ownerDocument.documentElement,E)){if(U!==null&&Ms(E)){var ie=U.start,be=U.end;if(be===void 0&&(be=ie),"selectionStart"in E)E.selectionStart=ie,E.selectionEnd=Math.min(be,E.value.length);else{var Se=E.ownerDocument||document,oe=Se&&Se.defaultView||window;if(oe.getSelection){var pe=oe.getSelection(),Ze=E.textContent.length,ot=Math.min(U.start,Ze),Pt=U.end===void 0?ot:Math.min(U.end,Ze);!pe.extend&&ot>Pt&&(S=Pt,Pt=ot,ot=S);var J=jr(E,ot),Y=jr(E,Pt);if(J&&Y&&(pe.rangeCount!==1||pe.anchorNode!==J.node||pe.anchorOffset!==J.offset||pe.focusNode!==Y.node||pe.focusOffset!==Y.offset)){var se=Se.createRange();se.setStart(J.node,J.offset),pe.removeAllRanges(),ot>Pt?(pe.addRange(se),pe.extend(Y.node,Y.offset)):(se.setEnd(Y.node,Y.offset),pe.addRange(se))}}}}for(Se=[],pe=E;pe=pe.parentNode;)pe.nodeType===1&&Se.push({element:pe,left:pe.scrollLeft,top:pe.scrollTop});for(typeof E.focus=="function"&&E.focus(),E=0;E<Se.length;E++){var we=Se[E];we.element.scrollLeft=we.left,we.element.scrollTop=we.top}}id=!!gm,vm=gm=null}finally{Lt=f,ee.p=o,I.T=s}}e.current=t,kn=2}}function Jg(){if(kn===2){kn=0;var e=Ri,t=yo,s=(t.flags&8772)!==0;if((t.subtreeFlags&8772)!==0||s){s=I.T,I.T=null;var o=ee.p;ee.p=2;var f=Lt;Lt|=4;try{Ng(e,t.alternate,t)}finally{Lt=f,ee.p=o,I.T=s}}kn=3}}function ev(){if(kn===4||kn===3){kn=0,_e();var e=Ri,t=yo,s=Yr,o=Bg;(t.subtreeFlags&10256)!==0||(t.flags&10256)!==0?kn=5:(kn=0,yo=Ri=null,tv(e,e.pendingLanes));var f=e.pendingLanes;if(f===0&&(Ei=null),kt(s),t=t.stateNode,Me&&typeof Me.onCommitFiberRoot=="function")try{Me.onCommitFiberRoot(He,t,void 0,(t.current.flags&128)===128)}catch{}if(o!==null){t=I.T,f=ee.p,ee.p=2,I.T=null;try{for(var h=e.onRecoverableError,S=0;S<o.length;S++){var E=o[S];h(E.value,{componentStack:E.stack})}}finally{I.T=t,ee.p=f}}(Yr&3)!==0&&Yu(),dr(e),f=e.pendingLanes,(s&261930)!==0&&(f&42)!==0?e===am?jc++:(jc=0,am=e):jc=0,Ac(0)}}function tv(e,t){(e.pooledCacheLanes&=t)===0&&(t=e.pooledCache,t!=null&&(e.pooledCache=null,ar(t)))}function Yu(){return Zg(),Jg(),ev(),nv()}function nv(){if(kn!==5)return!1;var e=Ri,t=tm;tm=0;var s=kt(Yr),o=I.T,f=ee.p;try{ee.p=32>s?32:s,I.T=null,s=nm,nm=null;var h=Ri,S=Yr;if(kn=0,yo=Ri=null,Yr=0,(Lt&6)!==0)throw Error(l(331));var E=Lt;if(Lt|=4,Og(h.current),_g(h,h.current,S,s),Lt=E,Ac(0,!1),Me&&typeof Me.onPostCommitFiberRoot=="function")try{Me.onPostCommitFiberRoot(He,h)}catch{}return!0}finally{ee.p=f,I.T=o,tv(e,t)}}function av(e,t,s){t=na(s,t),t=If(e.stateNode,t,2),e=or(e,t,2),e!==null&&(zn(e,2),dr(e))}function Ot(e,t,s){if(e.tag===3)av(e,e,s);else for(;t!==null;){if(t.tag===3){av(t,e,s);break}else if(t.tag===1){var o=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof o.componentDidCatch=="function"&&(Ei===null||!Ei.has(o))){e=na(s,e),s=sg(2),o=or(t,s,2),o!==null&&(rg(s,o,t,e),zn(o,2),dr(o));break}}t=t.return}}function im(e,t,s){var o=e.pingCache;if(o===null){o=e.pingCache=new Pw;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)||(Zf=!0,f.add(s),e=Vw.bind(null,e,t,s),t.then(e,e))}function Vw(e,t,s){var o=e.pingCache;o!==null&&o.delete(t),e.pingedLanes|=e.suspendedLanes&s,e.warmLanes&=~s,qt===e&&(St&s)===s&&(ln===4||ln===3&&(St&62914560)===St&&300>Ee()-$u?(Lt&2)===0&&bo(e,0):Jf|=s,vo===St&&(vo=0)),dr(e)}function sv(e,t){t===0&&(t=gr()),e=tr(e,t),e!==null&&(zn(e,t),dr(e))}function Ww(e){var t=e.memoizedState,s=0;t!==null&&(s=t.retryLane),sv(e,s)}function Yw(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),sv(e,s)}function Kw(e,t){return de(e,t)}var Ku=null,wo=null,lm=!1,Xu=!1,om=!1,Li=0;function dr(e){e!==wo&&e.next===null&&(wo===null?Ku=wo=e:wo=wo.next=e),Xu=!0,lm||(lm=!0,Qw())}function Ac(e,t){if(!om&&Xu){om=!0;do for(var s=!1,o=Ku;o!==null;){if(e!==0){var f=o.pendingLanes;if(f===0)var h=0;else{var S=o.suspendedLanes,E=o.pingedLanes;h=(1<<31-dt(42|e)+1)-1,h&=f&~(S&~E),h=h&201326741?h&201326741|1:h?h|2:0}h!==0&&(s=!0,ov(o,h))}else h=St,h=wn(o,o===qt?h:0,o.cancelPendingCommit!==null||o.timeoutHandle!==-1),(h&3)===0||Cs(o,h)||(s=!0,ov(o,h));o=o.next}while(s);om=!1}}function Xw(){rv()}function rv(){Xu=lm=!1;var e=0;Li!==0&&lS()&&(e=Li);for(var t=Ee(),s=null,o=Ku;o!==null;){var f=o.next,h=iv(o,t);h===0?(o.next=null,s===null?Ku=f:s.next=f,f===null&&(wo=s)):(s=o,(e!==0||(h&3)!==0)&&(Xu=!0)),o=f}kn!==0&&kn!==5||Ac(e),Li!==0&&(Li=0)}function iv(e,t){for(var s=e.suspendedLanes,o=e.pingedLanes,f=e.expirationTimes,h=e.pendingLanes&-62914561;0<h;){var S=31-dt(h),E=1<<S,U=f[S];U===-1?((E&s)===0||(E&o)!==0)&&(f[S]=Ha(E,t)):U<=t&&(e.expiredLanes|=E),h&=~E}if(t=qt,s=St,s=wn(e,e===t?s:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),o=e.callbackNode,s===0||e===t&&(zt===2||zt===9)||e.cancelPendingCommit!==null)return o!==null&&o!==null&&je(o),e.callbackNode=null,e.callbackPriority=0;if((s&3)===0||Cs(e,s)){if(t=s&-s,t===e.callbackPriority)return t;switch(o!==null&&je(o),kt(s)){case 2:case 8:s=Dt;break;case 32:s=yt;break;case 268435456:s=At;break;default:s=yt}return o=lv.bind(null,e),s=de(s,o),e.callbackPriority=t,e.callbackNode=s,t}return o!==null&&o!==null&&je(o),e.callbackPriority=2,e.callbackNode=null,2}function lv(e,t){if(kn!==0&&kn!==5)return e.callbackNode=null,e.callbackPriority=0,null;var s=e.callbackNode;if(Yu()&&e.callbackNode!==s)return null;var o=St;return o=wn(e,e===qt?o:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),o===0?null:($g(e,o,t),iv(e,Ee()),e.callbackNode!=null&&e.callbackNode===s?lv.bind(null,e):null)}function ov(e,t){if(Yu())return null;$g(e,t,!0)}function Qw(){cS(function(){(Lt&6)!==0?de(Ht,Xw):rv()})}function cm(){if(Li===0){var e=sr;e===0&&(e=it,it<<=1,(it&261888)===0&&(it=256)),Li=e}return Li}function cv(e){return e==null||typeof e=="symbol"||typeof e=="boolean"?null:typeof e=="function"?e:js(""+e)}function uv(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 Zw(e,t,s,o,f){if(t==="submit"&&s&&s.stateNode===f){var h=cv((f[Te]||null).action),S=o.submitter;S&&(t=(t=S[Te]||null)?cv(t.formAction):S.getAttribute("formAction"),t!==null&&(h=t,S=null));var E=new ii("action","action",null,o,f);e.push({event:E,listeners:[{instance:null,listener:function(){if(o.defaultPrevented){if(Li!==0){var U=S?uv(f,S):new FormData(f);Tf(s,{pending:!0,data:U,method:f.method,action:h},null,U)}}else typeof h=="function"&&(E.preventDefault(),U=S?uv(f,S):new FormData(f),Tf(s,{pending:!0,data:U,method:f.method,action:h},h,U))},currentTarget:f}]})}}for(var um=0;um<sc.length;um++){var dm=sc[um],Jw=dm.toLowerCase(),eS=dm[0].toUpperCase()+dm.slice(1);Sa(Jw,"on"+eS)}Sa(ml,"onAnimationEnd"),Sa(hl,"onAnimationIteration"),Sa(ac,"onAnimationStart"),Sa("dblclick","onDoubleClick"),Sa("focusin","onFocus"),Sa("focusout","onBlur"),Sa(ui,"onTransitionRun"),Sa(gu,"onTransitionStart"),Sa(vu,"onTransitionCancel"),Sa(yu,"onTransitionEnd"),Vt("onMouseEnter",["mouseout","mouseover"]),Vt("onMouseLeave",["mouseout","mouseover"]),Vt("onPointerEnter",["pointerout","pointerover"]),Vt("onPointerLeave",["pointerout","pointerover"]),Nt("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),Nt("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),Nt("onBeforeInput",["compositionend","keypress","textInput","paste"]),Nt("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),Nt("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),Nt("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Nc="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(" "),tS=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(Nc));function dv(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 h=void 0;if(t)for(var S=o.length-1;0<=S;S--){var E=o[S],U=E.instance,ie=E.currentTarget;if(E=E.listener,U!==h&&f.isPropagationStopped())break e;h=E,f.currentTarget=ie;try{h(f)}catch(be){Ql(be)}f.currentTarget=null,h=U}else for(S=0;S<o.length;S++){if(E=o[S],U=E.instance,ie=E.currentTarget,E=E.listener,U!==h&&f.isPropagationStopped())break e;h=E,f.currentTarget=ie;try{h(f)}catch(be){Ql(be)}f.currentTarget=null,h=U}}}}function wt(e,t){var s=t[st];s===void 0&&(s=t[st]=new Set);var o=e+"__bubble";s.has(o)||(fv(t,e,2,!1),s.add(o))}function fm(e,t,s){var o=0;t&&(o|=4),fv(s,e,o,t)}var Qu="_reactListening"+Math.random().toString(36).slice(2);function mm(e){if(!e[Qu]){e[Qu]=!0,Gs.forEach(function(s){s!=="selectionchange"&&(tS.has(s)||fm(s,!1,e),fm(s,!0,e))});var t=e.nodeType===9?e:e.ownerDocument;t===null||t[Qu]||(t[Qu]=!0,fm("selectionchange",!1,t))}}function fv(e,t,s,o){switch(Pv(t)){case 2:var f=TS;break;case 8:f=ES;break;default:f=Mm}s=f.bind(null,t,s,e),f=void 0,!Pa||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 hm(e,t,s,o,f){var h=o;if((t&1)===0&&(t&2)===0&&o!==null)e:for(;;){if(o===null)return;var S=o.tag;if(S===3||S===4){var E=o.stateNode.containerInfo;if(E===f)break;if(S===4)for(S=o.return;S!==null;){var U=S.tag;if((U===3||U===4)&&S.stateNode.containerInfo===f)return;S=S.return}for(;E!==null;){if(S=Jt(E),S===null)return;if(U=S.tag,U===5||U===6||U===26||U===27){o=h=S;continue e}E=E.parentNode}}o=o.return}nl(function(){var ie=h,be=Ys(s),Se=[];e:{var oe=Nr.get(e);if(oe!==void 0){var pe=ii,Ze=e;switch(e){case"keypress":if(Uo(s)===0)break e;case"keydown":case"keyup":pe=ol;break;case"focusin":Ze="focus",pe=sl;break;case"focusout":Ze="blur",pe=sl;break;case"beforeblur":case"afterblur":pe=sl;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":pe=lu;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":pe=ff;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":pe=at;break;case ml:case hl:case ac:pe=Ks;break;case yu:pe=hf;break;case"scroll":case"scrollend":pe=fp;break;case"wheel":pe=Cr;break;case"copy":case"cut":case"paste":pe=ou;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":pe=Yo;break;case"toggle":case"beforetoggle":pe=Ko}var ot=(t&4)!==0,Pt=!ot&&(e==="scroll"||e==="scrollend"),J=ot?oe!==null?oe+"Capture":null:oe;ot=[];for(var Y=ie,se;Y!==null;){var we=Y;if(se=we.stateNode,we=we.tag,we!==5&&we!==26&&we!==27||se===null||J===null||(we=wr(Y,J),we!=null&&ot.push(Mc(Y,we,se))),Pt)break;Y=Y.return}0<ot.length&&(oe=new pe(oe,Ze,null,s,be),Se.push({event:oe,listeners:ot}))}}if((t&7)===0){e:{if(oe=e==="mouseover"||e==="pointerover",pe=e==="mouseout"||e==="pointerout",oe&&s!==As&&(Ze=s.relatedTarget||s.fromElement)&&(Jt(Ze)||Ze[De]))break e;if((pe||oe)&&(oe=be.window===be?be:(oe=be.ownerDocument)?oe.defaultView||oe.parentWindow:window,pe?(Ze=s.relatedTarget||s.toElement,pe=ie,Ze=Ze?Jt(Ze):null,Ze!==null&&(Pt=d(Ze),ot=Ze.tag,Ze!==Pt||ot!==5&&ot!==27&&ot!==6)&&(Ze=null)):(pe=null,Ze=ie),pe!==Ze)){if(ot=lu,we="onMouseLeave",J="onMouseEnter",Y="mouse",(e==="pointerout"||e==="pointerover")&&(ot=Yo,we="onPointerLeave",J="onPointerEnter",Y="pointer"),Pt=pe==null?oe:Wt(pe),se=Ze==null?oe:Wt(Ze),oe=new ot(we,Y+"leave",pe,s,be),oe.target=Pt,oe.relatedTarget=se,we=null,Jt(be)===ie&&(ot=new ot(J,Y+"enter",Ze,s,be),ot.target=se,ot.relatedTarget=Pt,we=ot),Pt=we,pe&&Ze)t:{for(ot=nS,J=pe,Y=Ze,se=0,we=J;we;we=ot(we))se++;we=0;for(var nt=Y;nt;nt=ot(nt))we++;for(;0<se-we;)J=ot(J),se--;for(;0<we-se;)Y=ot(Y),we--;for(;se--;){if(J===Y||Y!==null&&J===Y.alternate){ot=J;break t}J=ot(J),Y=ot(Y)}ot=null}else ot=null;pe!==null&&mv(Se,oe,pe,ot,!1),Ze!==null&&Pt!==null&&mv(Se,Pt,Ze,ot,!0)}}e:{if(oe=ie?Wt(ie):window,pe=oe.nodeName&&oe.nodeName.toLowerCase(),pe==="select"||pe==="input"&&oe.type==="file")var Et=Qt;else if($t(oe))if(ci)Et=gs;else{Et=Zs;var tt=Ua}else pe=oe.nodeName,!pe||pe.toLowerCase()!=="input"||oe.type!=="checkbox"&&oe.type!=="radio"?ie&&cs(ie.elementType)&&(Et=Qt):Et=Xl;if(Et&&(Et=Et(e,ie))){Qo(Se,Et,s,be);break e}tt&&tt(e,oe,ie),e==="focusout"&&ie&&oe.type==="number"&&ie.memoizedProps.value!=null&&si(oe,"number",oe.value)}switch(tt=ie?Wt(ie):window,e){case"focusin":($t(tt)||tt.contentEditable==="true")&&(an=tt,xa=ie,Js=null);break;case"focusout":Js=xa=an=null;break;case"mousedown":er=!0;break;case"contextmenu":case"mouseup":case"dragend":er=!1,Ts(Se,s,be);break;case"selectionchange":if(tc)break;case"keydown":case"keyup":Ts(Se,s,be)}var ht;if($n)e:{switch(e){case"compositionstart":var Ct="onCompositionStart";break e;case"compositionend":Ct="onCompositionEnd";break e;case"compositionupdate":Ct="onCompositionUpdate";break e}Ct=void 0}else Xs?fu(e,s)&&(Ct="onCompositionEnd"):e==="keydown"&&s.keyCode===229&&(Ct="onCompositionStart");Ct&&(hs&&s.locale!=="ko"&&(Xs||Ct!=="onCompositionStart"?Ct==="onCompositionEnd"&&Xs&&(ht=ql()):(Jn=be,fs="value"in Jn?Jn.value:Jn.textContent,Xs=!0)),tt=Zu(ie,Ct),0<tt.length&&(Ct=new Vo(Ct,e,null,s,be),Se.push({event:Ct,listeners:tt}),ht?Ct.data=ht:(ht=mu(s),ht!==null&&(Ct.data=ht)))),(ht=Un?cl(e,s):mp(e,s))&&(Ct=Zu(ie,"onBeforeInput"),0<Ct.length&&(tt=new Vo("onBeforeInput","beforeinput",null,s,be),Se.push({event:tt,listeners:Ct}),tt.data=ht)),Zw(Se,e,ie,s,be)}dv(Se,t)})}function Mc(e,t,s){return{instance:e,listener:t,currentTarget:s}}function Zu(e,t){for(var s=t+"Capture",o=[];e!==null;){var f=e,h=f.stateNode;if(f=f.tag,f!==5&&f!==26&&f!==27||h===null||(f=wr(e,s),f!=null&&o.unshift(Mc(e,f,h)),f=wr(e,t),f!=null&&o.push(Mc(e,f,h))),e.tag===3)return o;e=e.return}return[]}function nS(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5&&e.tag!==27);return e||null}function mv(e,t,s,o,f){for(var h=t._reactName,S=[];s!==null&&s!==o;){var E=s,U=E.alternate,ie=E.stateNode;if(E=E.tag,U!==null&&U===o)break;E!==5&&E!==26&&E!==27||ie===null||(U=ie,f?(ie=wr(s,h),ie!=null&&S.unshift(Mc(s,ie,U))):f||(ie=wr(s,h),ie!=null&&S.push(Mc(s,ie,U)))),s=s.return}S.length!==0&&e.push({event:t,listeners:S})}var aS=/\r\n?/g,sS=/\u0000|\uFFFD/g;function hv(e){return(typeof e=="string"?e:""+e).replace(aS,`
9
+ `).replace(sS,"")}function pv(e,t){return t=hv(t),hv(e)===t}function Bt(e,t,s,o,f,h){switch(s){case"children":typeof o=="string"?t==="body"||t==="textarea"&&o===""||Vs(e,o):(typeof o=="number"||typeof o=="bigint")&&t!=="body"&&Vs(e,""+o);break;case"className":vr(e,"class",o);break;case"tabIndex":vr(e,"tabindex",o);break;case"dir":case"role":case"viewBox":case"width":case"height":vr(e,s,o);break;case"style":Ws(e,o,h);break;case"data":if(t!=="object"){vr(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=js(""+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 h=="function"&&(s==="formAction"?(t!=="input"&&Bt(e,t,"name",f.name,f,null),Bt(e,t,"formEncType",f.formEncType,f,null),Bt(e,t,"formMethod",f.formMethod,f,null),Bt(e,t,"formTarget",f.formTarget,f,null)):(Bt(e,t,"encType",f.encType,f,null),Bt(e,t,"method",f.method,f,null),Bt(e,t,"target",f.target,f,null)));if(o==null||typeof o=="symbol"||typeof o=="boolean"){e.removeAttribute(s);break}o=js(""+o),e.setAttribute(s,o);break;case"onClick":o!=null&&(e.onclick=Bn);break;case"onScroll":o!=null&&wt("scroll",e);break;case"onScrollEnd":o!=null&&wt("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=js(""+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":wt("beforetoggle",e),wt("toggle",e),ca(e,"popover",o);break;case"xlinkActuate":en(e,"http://www.w3.org/1999/xlink","xlink:actuate",o);break;case"xlinkArcrole":en(e,"http://www.w3.org/1999/xlink","xlink:arcrole",o);break;case"xlinkRole":en(e,"http://www.w3.org/1999/xlink","xlink:role",o);break;case"xlinkShow":en(e,"http://www.w3.org/1999/xlink","xlink:show",o);break;case"xlinkTitle":en(e,"http://www.w3.org/1999/xlink","xlink:title",o);break;case"xlinkType":en(e,"http://www.w3.org/1999/xlink","xlink:type",o);break;case"xmlBase":en(e,"http://www.w3.org/XML/1998/namespace","xml:base",o);break;case"xmlLang":en(e,"http://www.w3.org/XML/1998/namespace","xml:lang",o);break;case"xmlSpace":en(e,"http://www.w3.org/XML/1998/namespace","xml:space",o);break;case"is":ca(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=xr.get(s)||s,ca(e,s,o))}}function pm(e,t,s,o,f,h){switch(s){case"style":Ws(e,o,h);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"?Vs(e,o):(typeof o=="number"||typeof o=="bigint")&&Vs(e,""+o);break;case"onScroll":o!=null&&wt("scroll",e);break;case"onScrollEnd":o!=null&&wt("scrollend",e);break;case"onClick":o!=null&&(e.onclick=Bn);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!Fa.hasOwnProperty(s))e:{if(s[0]==="o"&&s[1]==="n"&&(f=s.endsWith("Capture"),t=s.slice(2,f?s.length-7:void 0),h=e[Te]||null,h=h!=null?h[s]:null,typeof h=="function"&&e.removeEventListener(t,h,f),typeof o=="function")){typeof h!="function"&&h!==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,""):ca(e,s,o)}}}function Kn(e,t,s){switch(t){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":wt("error",e),wt("load",e);var o=!1,f=!1,h;for(h in s)if(s.hasOwnProperty(h)){var S=s[h];if(S!=null)switch(h){case"src":o=!0;break;case"srcSet":f=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(l(137,t));default:Bt(e,t,h,S,s,null)}}f&&Bt(e,t,"srcSet",s.srcSet,s,null),o&&Bt(e,t,"src",s.src,s,null);return;case"input":wt("invalid",e);var E=h=S=f=null,U=null,ie=null;for(o in s)if(s.hasOwnProperty(o)){var be=s[o];if(be!=null)switch(o){case"name":f=be;break;case"type":S=be;break;case"checked":U=be;break;case"defaultChecked":ie=be;break;case"value":h=be;break;case"defaultValue":E=be;break;case"children":case"dangerouslySetInnerHTML":if(be!=null)throw Error(l(137,t));break;default:Bt(e,t,o,be,s,null)}}el(e,h,E,U,ie,S,f,!1);return;case"select":wt("invalid",e),o=S=h=null;for(f in s)if(s.hasOwnProperty(f)&&(E=s[f],E!=null))switch(f){case"value":h=E;break;case"defaultValue":S=E;break;case"multiple":o=E;default:Bt(e,t,f,E,s,null)}t=h,s=S,e.multiple=!!o,t!=null?br(e,!!o,t,!1):s!=null&&br(e,!!o,s,!0);return;case"textarea":wt("invalid",e),h=f=o=null;for(S in s)if(s.hasOwnProperty(S)&&(E=s[S],E!=null))switch(S){case"value":o=E;break;case"defaultValue":f=E;break;case"children":h=E;break;case"dangerouslySetInnerHTML":if(E!=null)throw Error(l(91));break;default:Bt(e,t,S,E,s,null)}va(e,o,f,h);return;case"option":for(U in s)s.hasOwnProperty(U)&&(o=s[U],o!=null)&&(U==="selected"?e.selected=o&&typeof o!="function"&&typeof o!="symbol":Bt(e,t,U,o,s,null));return;case"dialog":wt("beforetoggle",e),wt("toggle",e),wt("cancel",e),wt("close",e);break;case"iframe":case"object":wt("load",e);break;case"video":case"audio":for(o=0;o<Nc.length;o++)wt(Nc[o],e);break;case"image":wt("error",e),wt("load",e);break;case"details":wt("toggle",e);break;case"embed":case"source":case"link":wt("error",e),wt("load",e);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(ie in s)if(s.hasOwnProperty(ie)&&(o=s[ie],o!=null))switch(ie){case"children":case"dangerouslySetInnerHTML":throw Error(l(137,t));default:Bt(e,t,ie,o,s,null)}return;default:if(cs(t)){for(be in s)s.hasOwnProperty(be)&&(o=s[be],o!==void 0&&pm(e,t,be,o,s,void 0));return}}for(E in s)s.hasOwnProperty(E)&&(o=s[E],o!=null&&Bt(e,t,E,o,s,null))}function rS(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,h=null,S=null,E=null,U=null,ie=null,be=null;for(pe in s){var Se=s[pe];if(s.hasOwnProperty(pe)&&Se!=null)switch(pe){case"checked":break;case"value":break;case"defaultValue":U=Se;default:o.hasOwnProperty(pe)||Bt(e,t,pe,null,o,Se)}}for(var oe in o){var pe=o[oe];if(Se=s[oe],o.hasOwnProperty(oe)&&(pe!=null||Se!=null))switch(oe){case"type":h=pe;break;case"name":f=pe;break;case"checked":ie=pe;break;case"defaultChecked":be=pe;break;case"value":S=pe;break;case"defaultValue":E=pe;break;case"children":case"dangerouslySetInnerHTML":if(pe!=null)throw Error(l(137,t));break;default:pe!==Se&&Bt(e,t,oe,pe,o,Se)}}Pl(e,S,E,U,ie,be,h,f);return;case"select":pe=S=E=oe=null;for(h in s)if(U=s[h],s.hasOwnProperty(h)&&U!=null)switch(h){case"value":break;case"multiple":pe=U;default:o.hasOwnProperty(h)||Bt(e,t,h,null,o,U)}for(f in o)if(h=o[f],U=s[f],o.hasOwnProperty(f)&&(h!=null||U!=null))switch(f){case"value":oe=h;break;case"defaultValue":E=h;break;case"multiple":S=h;default:h!==U&&Bt(e,t,f,h,o,U)}t=E,s=S,o=pe,oe!=null?br(e,!!s,oe,!1):!!o!=!!s&&(t!=null?br(e,!!s,t,!0):br(e,!!s,s?[]:"",!1));return;case"textarea":pe=oe=null;for(E in s)if(f=s[E],s.hasOwnProperty(E)&&f!=null&&!o.hasOwnProperty(E))switch(E){case"value":break;case"children":break;default:Bt(e,t,E,null,o,f)}for(S in o)if(f=o[S],h=s[S],o.hasOwnProperty(S)&&(f!=null||h!=null))switch(S){case"value":oe=f;break;case"defaultValue":pe=f;break;case"children":break;case"dangerouslySetInnerHTML":if(f!=null)throw Error(l(91));break;default:f!==h&&Bt(e,t,S,f,o,h)}$o(e,oe,pe);return;case"option":for(var Ze in s)oe=s[Ze],s.hasOwnProperty(Ze)&&oe!=null&&!o.hasOwnProperty(Ze)&&(Ze==="selected"?e.selected=!1:Bt(e,t,Ze,null,o,oe));for(U in o)oe=o[U],pe=s[U],o.hasOwnProperty(U)&&oe!==pe&&(oe!=null||pe!=null)&&(U==="selected"?e.selected=oe&&typeof oe!="function"&&typeof oe!="symbol":Bt(e,t,U,oe,o,pe));return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var ot in s)oe=s[ot],s.hasOwnProperty(ot)&&oe!=null&&!o.hasOwnProperty(ot)&&Bt(e,t,ot,null,o,oe);for(ie in o)if(oe=o[ie],pe=s[ie],o.hasOwnProperty(ie)&&oe!==pe&&(oe!=null||pe!=null))switch(ie){case"children":case"dangerouslySetInnerHTML":if(oe!=null)throw Error(l(137,t));break;default:Bt(e,t,ie,oe,o,pe)}return;default:if(cs(t)){for(var Pt in s)oe=s[Pt],s.hasOwnProperty(Pt)&&oe!==void 0&&!o.hasOwnProperty(Pt)&&pm(e,t,Pt,void 0,o,oe);for(be in o)oe=o[be],pe=s[be],!o.hasOwnProperty(be)||oe===pe||oe===void 0&&pe===void 0||pm(e,t,be,oe,o,pe);return}}for(var J in s)oe=s[J],s.hasOwnProperty(J)&&oe!=null&&!o.hasOwnProperty(J)&&Bt(e,t,J,null,o,oe);for(Se in o)oe=o[Se],pe=s[Se],!o.hasOwnProperty(Se)||oe===pe||oe==null&&pe==null||Bt(e,t,Se,oe,o,pe)}function gv(e){switch(e){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function iS(){if(typeof performance.getEntriesByType=="function"){for(var e=0,t=0,s=performance.getEntriesByType("resource"),o=0;o<s.length;o++){var f=s[o],h=f.transferSize,S=f.initiatorType,E=f.duration;if(h&&E&&gv(S)){for(S=0,E=f.responseEnd,o+=1;o<s.length;o++){var U=s[o],ie=U.startTime;if(ie>E)break;var be=U.transferSize,Se=U.initiatorType;be&&gv(Se)&&(U=U.responseEnd,S+=be*(U<E?1:(E-ie)/(U-ie)))}if(--o,t+=8*(h+S)/(f.duration/1e3),e++,10<e)break}}if(0<e)return t/e/1e6}return navigator.connection&&(e=navigator.connection.downlink,typeof e=="number")?e:5}var gm=null,vm=null;function Ju(e){return e.nodeType===9?e:e.ownerDocument}function vv(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 yv(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 ym(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 bm=null;function lS(){var e=window.event;return e&&e.type==="popstate"?e===bm?!1:(bm=e,!0):(bm=null,!1)}var bv=typeof setTimeout=="function"?setTimeout:void 0,oS=typeof clearTimeout=="function"?clearTimeout:void 0,xv=typeof Promise=="function"?Promise:void 0,cS=typeof queueMicrotask=="function"?queueMicrotask:typeof xv<"u"?function(e){return xv.resolve(null).then(e).catch(uS)}:bv;function uS(e){setTimeout(function(){throw e})}function _i(e){return e==="head"}function wv(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),jo(t);return}o--}else if(s==="$"||s==="$?"||s==="$~"||s==="$!"||s==="&")o++;else if(s==="html")Tc(e.ownerDocument.documentElement);else if(s==="head"){s=e.ownerDocument.head,Tc(s);for(var h=s.firstChild;h;){var S=h.nextSibling,E=h.nodeName;h[jt]||E==="SCRIPT"||E==="STYLE"||E==="LINK"&&h.rel.toLowerCase()==="stylesheet"||s.removeChild(h),h=S}}else s==="body"&&Tc(e.ownerDocument.body);s=f}while(s);jo(t)}function Sv(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 xm(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":xm(s),cn(s);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(s.rel.toLowerCase()==="stylesheet")continue}e.removeChild(s)}}function dS(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[jt])switch(t){case"meta":if(!e.hasAttribute("itemprop"))break;return e;case"link":if(h=e.getAttribute("rel"),h==="stylesheet"&&e.hasAttribute("data-precedence"))break;if(h!==f.rel||e.getAttribute("href")!==(f.href==null||f.href===""?null:f.href)||e.getAttribute("crossorigin")!==(f.crossOrigin==null?null:f.crossOrigin)||e.getAttribute("title")!==(f.title==null?null:f.title))break;return e;case"style":if(e.hasAttribute("data-precedence"))break;return e;case"script":if(h=e.getAttribute("src"),(h!==(f.src==null?null:f.src)||e.getAttribute("type")!==(f.type==null?null:f.type)||e.getAttribute("crossorigin")!==(f.crossOrigin==null?null:f.crossOrigin))&&h&&e.hasAttribute("async")&&!e.hasAttribute("itemprop"))break;return e;default:return e}}else if(t==="input"&&e.type==="hidden"){var h=f.name==null?null:""+f.name;if(f.type==="hidden"&&e.getAttribute("name")===h)return e}else return e;if(e=bs(e.nextSibling),e===null)break}return null}function fS(e,t,s){if(t==="")return null;for(;e.nodeType!==3;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!s||(e=bs(e.nextSibling),e===null))return null;return e}function Cv(e,t){for(;e.nodeType!==8;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!t||(e=bs(e.nextSibling),e===null))return null;return e}function wm(e){return e.data==="$?"||e.data==="$~"}function Sm(e){return e.data==="$!"||e.data==="$?"&&e.ownerDocument.readyState!=="loading"}function mS(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 bs(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 Cm=null;function kv(e){e=e.nextSibling;for(var t=0;e;){if(e.nodeType===8){var s=e.data;if(s==="/$"||s==="/&"){if(t===0)return bs(e.nextSibling);t--}else s!=="$"&&s!=="$!"&&s!=="$?"&&s!=="$~"&&s!=="&"||t++}e=e.nextSibling}return null}function jv(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 Av(e,t,s){switch(t=Ju(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 Tc(e){for(var t=e.attributes;t.length;)e.removeAttributeNode(t[0]);cn(e)}var xs=new Map,Nv=new Set;function ed(e){return typeof e.getRootNode=="function"?e.getRootNode():e.nodeType===9?e:e.ownerDocument}var Kr=ee.d;ee.d={f:hS,r:pS,D:gS,C:vS,L:yS,m:bS,X:wS,S:xS,M:SS};function hS(){var e=Kr.f(),t=Gu();return e||t}function pS(e){var t=On(e);t!==null&&t.tag===5&&t.type==="form"?qp(t):Kr.r(e)}var So=typeof document>"u"?null:document;function Mv(e,t,s){var o=So;if(o&&typeof t=="string"&&t){var f=Fn(t);f='link[rel="'+e+'"][href="'+f+'"]',typeof s=="string"&&(f+='[crossorigin="'+s+'"]'),Nv.has(f)||(Nv.add(f),e={rel:e,crossOrigin:s,href:t},o.querySelector(f)===null&&(t=o.createElement("link"),Kn(t,"link",e),Yt(t),o.head.appendChild(t)))}}function gS(e){Kr.D(e),Mv("dns-prefetch",e,null)}function vS(e,t){Kr.C(e,t),Mv("preconnect",e,t)}function yS(e,t,s){Kr.L(e,t,s);var o=So;if(o&&e&&t){var f='link[rel="preload"][as="'+Fn(t)+'"]';t==="image"&&s&&s.imageSrcSet?(f+='[imagesrcset="'+Fn(s.imageSrcSet)+'"]',typeof s.imageSizes=="string"&&(f+='[imagesizes="'+Fn(s.imageSizes)+'"]')):f+='[href="'+Fn(e)+'"]';var h=f;switch(t){case"style":h=Co(e);break;case"script":h=ko(e)}xs.has(h)||(e=b({rel:"preload",href:t==="image"&&s&&s.imageSrcSet?void 0:e,as:t},s),xs.set(h,e),o.querySelector(f)!==null||t==="style"&&o.querySelector(Ec(h))||t==="script"&&o.querySelector(Rc(h))||(t=o.createElement("link"),Kn(t,"link",e),Yt(t),o.head.appendChild(t)))}}function bS(e,t){Kr.m(e,t);var s=So;if(s&&e){var o=t&&typeof t.as=="string"?t.as:"script",f='link[rel="modulepreload"][as="'+Fn(o)+'"][href="'+Fn(e)+'"]',h=f;switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":h=ko(e)}if(!xs.has(h)&&(e=b({rel:"modulepreload",href:e},t),xs.set(h,e),s.querySelector(f)===null)){switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(s.querySelector(Rc(h)))return}o=s.createElement("link"),Kn(o,"link",e),Yt(o),s.head.appendChild(o)}}}function xS(e,t,s){Kr.S(e,t,s);var o=So;if(o&&e){var f=mn(o).hoistableStyles,h=Co(e);t=t||"default";var S=f.get(h);if(!S){var E={loading:0,preload:null};if(S=o.querySelector(Ec(h)))E.loading=5;else{e=b({rel:"stylesheet",href:e,"data-precedence":t},s),(s=xs.get(h))&&km(e,s);var U=S=o.createElement("link");Yt(U),Kn(U,"link",e),U._p=new Promise(function(ie,be){U.onload=ie,U.onerror=be}),U.addEventListener("load",function(){E.loading|=1}),U.addEventListener("error",function(){E.loading|=2}),E.loading|=4,td(S,t,o)}S={type:"stylesheet",instance:S,count:1,state:E},f.set(h,S)}}}function wS(e,t){Kr.X(e,t);var s=So;if(s&&e){var o=mn(s).hoistableScripts,f=ko(e),h=o.get(f);h||(h=s.querySelector(Rc(f)),h||(e=b({src:e,async:!0},t),(t=xs.get(f))&&jm(e,t),h=s.createElement("script"),Yt(h),Kn(h,"link",e),s.head.appendChild(h)),h={type:"script",instance:h,count:1,state:null},o.set(f,h))}}function SS(e,t){Kr.M(e,t);var s=So;if(s&&e){var o=mn(s).hoistableScripts,f=ko(e),h=o.get(f);h||(h=s.querySelector(Rc(f)),h||(e=b({src:e,async:!0,type:"module"},t),(t=xs.get(f))&&jm(e,t),h=s.createElement("script"),Yt(h),Kn(h,"link",e),s.head.appendChild(h)),h={type:"script",instance:h,count:1,state:null},o.set(f,h))}}function Tv(e,t,s,o){var f=(f=ke.current)?ed(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=Co(s.href),s=mn(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=Co(s.href);var h=mn(f).hoistableStyles,S=h.get(e);if(S||(f=f.ownerDocument||f,S={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},h.set(e,S),(h=f.querySelector(Ec(e)))&&!h._p&&(S.instance=h,S.state.loading=5),xs.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},xs.set(e,s),h||CS(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=ko(s),s=mn(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 Co(e){return'href="'+Fn(e)+'"'}function Ec(e){return'link[rel="stylesheet"]['+e+"]"}function Ev(e){return b({},e,{"data-precedence":e.precedence,precedence:null})}function CS(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}),Kn(t,"link",s),Yt(t),e.head.appendChild(t))}function ko(e){return'[src="'+Fn(e)+'"]'}function Rc(e){return"script[async]"+e}function Rv(e,t,s){if(t.count++,t.instance===null)switch(t.type){case"style":var o=e.querySelector('style[data-href~="'+Fn(s.href)+'"]');if(o)return t.instance=o,Yt(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"),Yt(o),Kn(o,"style",f),td(o,s.precedence,e),t.instance=o;case"stylesheet":f=Co(s.href);var h=e.querySelector(Ec(f));if(h)return t.state.loading|=4,t.instance=h,Yt(h),h;o=Ev(s),(f=xs.get(f))&&km(o,f),h=(e.ownerDocument||e).createElement("link"),Yt(h);var S=h;return S._p=new Promise(function(E,U){S.onload=E,S.onerror=U}),Kn(h,"link",o),t.state.loading|=4,td(h,s.precedence,e),t.instance=h;case"script":return h=ko(s.src),(f=e.querySelector(Rc(h)))?(t.instance=f,Yt(f),f):(o=s,(f=xs.get(h))&&(o=b({},s),jm(o,f)),e=e.ownerDocument||e,f=e.createElement("script"),Yt(f),Kn(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,td(o,s.precedence,e));return t.instance}function td(e,t,s){for(var o=s.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),f=o.length?o[o.length-1]:null,h=f,S=0;S<o.length;S++){var E=o[S];if(E.dataset.precedence===t)h=E;else if(h!==f)break}h?h.parentNode.insertBefore(e,h.nextSibling):(t=s.nodeType===9?s.head:s,t.insertBefore(e,t.firstChild))}function km(e,t){e.crossOrigin==null&&(e.crossOrigin=t.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=t.referrerPolicy),e.title==null&&(e.title=t.title)}function jm(e,t){e.crossOrigin==null&&(e.crossOrigin=t.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=t.referrerPolicy),e.integrity==null&&(e.integrity=t.integrity)}var nd=null;function Dv(e,t,s){if(nd===null){var o=new Map,f=nd=new Map;f.set(s,o)}else f=nd,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 h=s[f];if(!(h[jt]||h[ne]||e==="link"&&h.getAttribute("rel")==="stylesheet")&&h.namespaceURI!=="http://www.w3.org/2000/svg"){var S=h.getAttribute(t)||"";S=e+S;var E=o.get(S);E?E.push(h):o.set(S,[h])}}return o}function Lv(e,t,s){e=e.ownerDocument||e,e.head.insertBefore(s,t==="title"?e.querySelector("head > title"):null)}function kS(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 _v(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function jS(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=Co(o.href),h=t.querySelector(Ec(f));if(h){t=h._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(e.count++,e=ad.bind(e),t.then(e,e)),s.state.loading|=4,s.instance=h,Yt(h);return}h=t.ownerDocument||t,o=Ev(o),(f=xs.get(f))&&km(o,f),h=h.createElement("link"),Yt(h);var S=h;S._p=new Promise(function(E,U){S.onload=E,S.onerror=U}),Kn(h,"link",o),s.instance=h}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(s,t),(t=s.state.preload)&&(s.state.loading&3)===0&&(e.count++,s=ad.bind(e),t.addEventListener("load",s),t.addEventListener("error",s))}}var Am=0;function AS(e,t){return e.stylesheets&&e.count===0&&rd(e,e.stylesheets),0<e.count||0<e.imgCount?function(s){var o=setTimeout(function(){if(e.stylesheets&&rd(e,e.stylesheets),e.unsuspend){var h=e.unsuspend;e.unsuspend=null,h()}},6e4+t);0<e.imgBytes&&Am===0&&(Am=62500*iS());var f=setTimeout(function(){if(e.waitingForImages=!1,e.count===0&&(e.stylesheets&&rd(e,e.stylesheets),e.unsuspend)){var h=e.unsuspend;e.unsuspend=null,h()}},(e.imgBytes>Am?50:800)+t);return e.unsuspend=s,function(){e.unsuspend=null,clearTimeout(o),clearTimeout(f)}}:null}function ad(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)rd(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var sd=null;function rd(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,sd=new Map,t.forEach(NS,e),sd=null,ad.call(e))}function NS(e,t){if(!(t.state.loading&4)){var s=sd.get(e);if(s)var o=s.get(null);else{s=new Map,sd.set(e,s);for(var f=e.querySelectorAll("link[data-precedence],style[data-precedence]"),h=0;h<f.length;h++){var S=f[h];(S.nodeName==="LINK"||S.getAttribute("media")!=="not all")&&(s.set(S.dataset.precedence,S),o=S)}o&&s.set(null,o)}f=t.instance,S=f.getAttribute("data-precedence"),h=s.get(S)||o,h===o&&s.set(null,f),s.set(S,f),this.count++,o=ad.bind(this),f.addEventListener("load",o),f.addEventListener("error",o),h?h.parentNode.insertBefore(f,h.nextSibling):(e=e.nodeType===9?e.head:e,e.insertBefore(f,e.firstChild)),t.state.loading|=4}}var Dc={$$typeof:D,Provider:null,Consumer:null,_currentValue:V,_currentValue2:V,_threadCount:0};function MS(e,t,s,o,f,h,S,E,U){this.tag=1,this.containerInfo=e,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=rs(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=rs(0),this.hiddenUpdates=rs(null),this.identifierPrefix=o,this.onUncaughtError=f,this.onCaughtError=h,this.onRecoverableError=S,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=U,this.incompleteTransitions=new Map}function Iv(e,t,s,o,f,h,S,E,U,ie,be,Se){return e=new MS(e,t,s,S,U,ie,be,Se,E),t=1,h===!0&&(t|=24),h=qn(3,null,null,t),e.current=h,h.stateNode=e,t=gi(),t.refCount++,e.pooledCache=t,t.refCount++,h.memoizedState={element:o,isDehydrated:s,cache:t},uo(h),e}function zv(e){return e?(e=Ga,e):Ga}function Ov(e,t,s,o,f,h){f=zv(f),o.context===null?o.context=f:o.pendingContext=f,o=Hr(t),o.payload={element:s},h=h===void 0?null:h,h!==null&&(o.callback=h),s=or(e,o,t),s!==null&&(Ra(s,e,t),Cl(s,e,t))}function Hv(e,t){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var s=e.retryLane;e.retryLane=s!==0&&s<t?s:t}}function Nm(e,t){Hv(e,t),(e=e.alternate)&&Hv(e,t)}function Fv(e){if(e.tag===13||e.tag===31){var t=tr(e,67108864);t!==null&&Ra(t,e,67108864),Nm(e,67108864)}}function Bv(e){if(e.tag===13||e.tag===31){var t=ts();t=ze(t);var s=tr(e,t);s!==null&&Ra(s,e,t),Nm(e,t)}}var id=!0;function TS(e,t,s,o){var f=I.T;I.T=null;var h=ee.p;try{ee.p=2,Mm(e,t,s,o)}finally{ee.p=h,I.T=f}}function ES(e,t,s,o){var f=I.T;I.T=null;var h=ee.p;try{ee.p=8,Mm(e,t,s,o)}finally{ee.p=h,I.T=f}}function Mm(e,t,s,o){if(id){var f=Tm(o);if(f===null)hm(e,t,o,ld,s),$v(e,o);else if(DS(f,e,t,s,o))o.stopPropagation();else if($v(e,o),t&4&&-1<RS.indexOf(e)){for(;f!==null;){var h=On(f);if(h!==null)switch(h.tag){case 3:if(h=h.stateNode,h.current.memoizedState.isDehydrated){var S=Mn(h.pendingLanes);if(S!==0){var E=h;for(E.pendingLanes|=2,E.entangledLanes|=2;S;){var U=1<<31-dt(S);E.entanglements[1]|=U,S&=~U}dr(h),(Lt&6)===0&&(Uu=Ee()+500,Ac(0))}}break;case 31:case 13:E=tr(h,2),E!==null&&Ra(E,h,2),Gu(),Nm(h,2)}if(h=Tm(o),h===null&&hm(e,t,o,ld,s),h===f)break;f=h}f!==null&&o.stopPropagation()}else hm(e,t,o,null,s)}}function Tm(e){return e=Ys(e),Em(e)}var ld=null;function Em(e){if(ld=null,e=Jt(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=p(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 ld=e,null}function Pv(e){switch(e){case"beforetoggle":case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"toggle":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 2;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 8;case"message":switch(mt()){case Ht:return 2;case Dt:return 8;case yt:case Ge:return 32;case At:return 268435456;default:return 32}default:return 32}}var Rm=!1,Ii=null,zi=null,Oi=null,Lc=new Map,_c=new Map,Hi=[],RS="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 $v(e,t){switch(e){case"focusin":case"focusout":Ii=null;break;case"dragenter":case"dragleave":zi=null;break;case"mouseover":case"mouseout":Oi=null;break;case"pointerover":case"pointerout":Lc.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":_c.delete(t.pointerId)}}function Ic(e,t,s,o,f,h){return e===null||e.nativeEvent!==h?(e={blockedOn:t,domEventName:s,eventSystemFlags:o,nativeEvent:h,targetContainers:[f]},t!==null&&(t=On(t),t!==null&&Fv(t)),e):(e.eventSystemFlags|=o,t=e.targetContainers,f!==null&&t.indexOf(f)===-1&&t.push(f),e)}function DS(e,t,s,o,f){switch(t){case"focusin":return Ii=Ic(Ii,e,t,s,o,f),!0;case"dragenter":return zi=Ic(zi,e,t,s,o,f),!0;case"mouseover":return Oi=Ic(Oi,e,t,s,o,f),!0;case"pointerover":var h=f.pointerId;return Lc.set(h,Ic(Lc.get(h)||null,e,t,s,o,f)),!0;case"gotpointercapture":return h=f.pointerId,_c.set(h,Ic(_c.get(h)||null,e,t,s,o,f)),!0}return!1}function Uv(e){var t=Jt(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,Mt(e.priority,function(){Bv(s)});return}}else if(t===31){if(t=p(s),t!==null){e.blockedOn=t,Mt(e.priority,function(){Bv(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 od(e){if(e.blockedOn!==null)return!1;for(var t=e.targetContainers;0<t.length;){var s=Tm(e.nativeEvent);if(s===null){s=e.nativeEvent;var o=new s.constructor(s.type,s);As=o,s.target.dispatchEvent(o),As=null}else return t=On(s),t!==null&&Fv(t),e.blockedOn=s,!1;t.shift()}return!0}function qv(e,t,s){od(e)&&s.delete(t)}function LS(){Rm=!1,Ii!==null&&od(Ii)&&(Ii=null),zi!==null&&od(zi)&&(zi=null),Oi!==null&&od(Oi)&&(Oi=null),Lc.forEach(qv),_c.forEach(qv)}function cd(e,t){e.blockedOn===t&&(e.blockedOn=null,Rm||(Rm=!0,n.unstable_scheduleCallback(n.unstable_NormalPriority,LS)))}var ud=null;function Gv(e){ud!==e&&(ud=e,n.unstable_scheduleCallback(n.unstable_NormalPriority,function(){ud===e&&(ud=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(Em(o||s)===null)continue;break}var h=On(s);h!==null&&(e.splice(t,3),t-=3,Tf(h,{pending:!0,data:f,method:s.method,action:o},o,f))}}))}function jo(e){function t(U){return cd(U,e)}Ii!==null&&cd(Ii,e),zi!==null&&cd(zi,e),Oi!==null&&cd(Oi,e),Lc.forEach(t),_c.forEach(t);for(var s=0;s<Hi.length;s++){var o=Hi[s];o.blockedOn===e&&(o.blockedOn=null)}for(;0<Hi.length&&(s=Hi[0],s.blockedOn===null);)Uv(s),s.blockedOn===null&&Hi.shift();if(s=(e.ownerDocument||e).$$reactFormReplay,s!=null)for(o=0;o<s.length;o+=3){var f=s[o],h=s[o+1],S=f[Te]||null;if(typeof h=="function")S||Gv(s);else if(S){var E=null;if(h&&h.hasAttribute("formAction")){if(f=h,S=h[Te]||null)E=S.formAction;else if(Em(f)!==null)continue}else E=S.action;typeof E=="function"?s[o+1]=E:(s.splice(o,3),o-=3),Gv(s)}}}function Vv(){function e(h){h.canIntercept&&h.info==="react-transition"&&h.intercept({handler:function(){return new Promise(function(S){return f=S})},focusReset:"manual",scroll:"manual"})}function t(){f!==null&&(f(),f=null),o||setTimeout(s,20)}function s(){if(!o&&!navigation.transition){var h=navigation.currentEntry;h&&h.url!=null&&navigation.navigate(h.url,{state:h.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var o=!1,f=null;return navigation.addEventListener("navigate",e),navigation.addEventListener("navigatesuccess",t),navigation.addEventListener("navigateerror",t),setTimeout(s,100),function(){o=!0,navigation.removeEventListener("navigate",e),navigation.removeEventListener("navigatesuccess",t),navigation.removeEventListener("navigateerror",t),f!==null&&(f(),f=null)}}}function Dm(e){this._internalRoot=e}dd.prototype.render=Dm.prototype.render=function(e){var t=this._internalRoot;if(t===null)throw Error(l(409));var s=t.current,o=ts();Ov(s,o,e,t,null,null)},dd.prototype.unmount=Dm.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var t=e.containerInfo;Ov(e.current,2,null,e,null,null),Gu(),t[De]=null}};function dd(e){this._internalRoot=e}dd.prototype.unstable_scheduleHydration=function(e){if(e){var t=ks();e={blockedOn:null,target:e,priority:t};for(var s=0;s<Hi.length&&t!==0&&t<Hi[s].priority;s++);Hi.splice(s,0,e),s===0&&Uv(e)}};var Wv=a.version;if(Wv!=="19.2.7")throw Error(l(527,Wv,"19.2.7"));ee.findDOMNode=function(e){var t=e._reactInternals;if(t===void 0)throw typeof e.render=="function"?Error(l(188)):(e=Object.keys(e).join(","),Error(l(268,e)));return e=v(t),e=e!==null?x(e):null,e=e===null?null:e.stateNode,e};var _S={bundleType:0,version:"19.2.7",rendererPackageName:"react-dom",currentDispatcherRef:I,reconcilerVersion:"19.2.7"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var fd=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!fd.isDisabled&&fd.supportsFiber)try{He=fd.inject(_S),Me=fd}catch{}}return Oc.createRoot=function(e,t){if(!c(e))throw Error(l(299));var s=!1,o="",f=eg,h=tg,S=ng;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&&(h=t.onCaughtError),t.onRecoverableError!==void 0&&(S=t.onRecoverableError)),t=Iv(e,1,!1,null,null,s,o,null,f,h,S,Vv),e[De]=t.current,mm(e),new Dm(t)},Oc.hydrateRoot=function(e,t,s){if(!c(e))throw Error(l(299));var o=!1,f="",h=eg,S=tg,E=ng,U=null;return s!=null&&(s.unstable_strictMode===!0&&(o=!0),s.identifierPrefix!==void 0&&(f=s.identifierPrefix),s.onUncaughtError!==void 0&&(h=s.onUncaughtError),s.onCaughtError!==void 0&&(S=s.onCaughtError),s.onRecoverableError!==void 0&&(E=s.onRecoverableError),s.formState!==void 0&&(U=s.formState)),t=Iv(e,1,!0,t,s??null,o,f,U,h,S,E,Vv),t.context=zv(null),s=t.current,o=ts(),o=ze(o),f=Hr(o),f.callback=null,or(s,f,o),s=o,t.current.lanes=s,zn(t,s),dr(t),e[De]=t.current,mm(e),new dd(t)},Oc.version="19.2.7",Oc}var ry;function j0(){if(ry)return Om.exports;ry=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(),Om.exports=k0(),Om.exports}var A0=j0();const N0="https://otbyfkjxrkngvjziawki.supabase.co",M0="sb_publishable_NpUs0RDJH2YnllsqTKO6TQ_1jTdSsNQ",T0={getItem:()=>null,setItem:()=>{},removeItem:()=>{}},iy=typeof window<"u"&&!!window.liveDesk,ft=b0(N0,M0,{auth:{autoRefreshToken:!0,persistSession:!iy,storage:iy?T0:void 0,detectSessionInUrl:!0,flowType:"pkce",storageKey:"livedesk.mindexec.supabase.auth"}}),E0=new Set(["browserLanguage","platform","online","viewport","timezone","screen"]),R0={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])=>E0.has(a)&&i!==void 0))}};function D0(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 L0(n=R0){return n.collect()}async function _0(n,a="livedesk"){const{data:i,error:l}=await ft.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:C}=await ft.rpc("register_product_access",{p_product_key:a,p_access_type:"free"});if(C)throw C}const[d,m,p]=await Promise.all([ft.from("products").select("id, product_key, name, description, sort_order").order("sort_order"),ft.from("product_admins").select("product_id, role").eq("user_id",n),ft.from("user_products").select("product_id").eq("user_id",n).eq("is_active",!0)]);if(d.error)throw d.error;if(m.error)throw m.error;if(p.error)throw p.error;const g=d.data||[],v=(m.data||[]).map(C=>String(C.product_id)),x=(p.data||[]).map(C=>String(C.product_id)),b=c==="owner",w=b?g.map(C=>C.id):[...new Set([...v,...x])];return{products:g,access:{userId:n,globalRole:c,accessibleProductIds:w,managedProductIds:b?g.map(C=>C.id):v,canViewAllProducts:b,canViewAllPrivatePosts:b,canManageAllProducts:b,canCreateAnnouncements:b||v.length>0}}}async function I0(n=""){const{data:a,error:i}=await ft.rpc("search_support_posts",{p_query:n.trim()||null,p_limit:250});if(i)throw i;return a||[]}async function z0(n){const{data:a,error:i}=await ft.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 ft.storage.from("support-attachments").createSignedUrl(c.storage_path,3600);return{...c,signed_url:d.data?.signedUrl||void 0}}))}async function O0(){const{data:n,error:a}=await ft.from("support_notifications").select("*").order("created_at",{ascending:!1}).limit(30);if(a)throw a;return n||[]}async function H0(n){const{error:a}=await ft.rpc("mark_support_notification_read",{p_notification_id:n});if(a)throw a}async function ly(n){const{data:a,error:i}=await ft.from("support_comments").select("*").eq("post_id",n).order("created_at");if(i)throw i;return a||[]}async function F0(n){const{data:a,error:i}=await ft.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 B0(n){const{data:a,error:i}=await ft.rpc("create_support_post",{p_product_id:n.productId,p_post_type:n.postType,p_title:n.title,p_body:n.body,p_visibility:n.visibility,p_app_version:n.appVersion||null,p_platform:typeof navigator>"u"?null:navigator.platform||null,p_os_version:typeof navigator>"u"?null:navigator.platform||null,p_environment:n.includeEnvironment?L0():{}});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 P0=new Set(["image/png","image/jpeg","image/webp","text/plain","text/markdown","application/json","application/pdf"]);async function $0(n,a){if(!P0.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 ft.storage.from("support-attachments").upload(c,a,{contentType:a.type,upsert:!1});if(d.error)throw d.error;const{data:m,error:p}=await ft.rpc("add_support_attachment",{p_post_id:n,p_storage_path:c,p_file_name:i,p_mime_type:a.type,p_size_bytes:a.size});if(p)throw await ft.storage.from("support-attachments").remove([c]),p;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 U0(n,a,i,l){const{error:c}=await ft.rpc("update_support_post",{p_post_id:n,p_title:a,p_body:i,p_visibility:l});if(c)throw c}async function q0(n,a){const{error:i}=await ft.rpc("add_support_comment",{p_post_id:n,p_body:a});if(i)throw i}async function G0(n){const{data:a,error:i}=await ft.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 V0(n,a){const{error:i}=await ft.rpc("change_support_post_status",{p_post_id:n,p_target_status:a});if(i)throw i}async function W0(n){const{error:a}=await ft.rpc("set_support_post_hidden",{p_post_id:n,p_hidden:!0});if(a)throw a}async function Y0(n,a){const{error:i}=await ft.rpc("set_support_post_locked",{p_post_id:n,p_locked:a});if(i)throw i}async function K0(n,a){const{error:i}=await ft.rpc("set_support_post_pinned",{p_post_id:n,p_pinned:a});if(i)throw i}async function X0(n,a){const{error:i}=await ft.rpc("mark_support_duplicate",{p_post_id:n,p_duplicate_of_post_id:a});if(i)throw i}async function Q0(n,a){const{error:i}=await ft.rpc("accept_support_answer",{p_post_id:n,p_comment_id:a});if(i)throw i}async function Z0(n,a=!0){const{error:i}=await ft.rpc("hide_support_comment",{p_comment_id:n,p_hidden:a});if(i)throw i}const wh=[{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"}],J0=[{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"}],eC={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"]},tC={type:"all",product:"",status:"all",visibility:"all",sort:"recent",query:""};function Bm(){if(typeof window>"u")return tC;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 nC(n){return n==="all"?"":n==="question"?"questions":n==="issue"?"issues":n==="feature"?"features":"announcements"}function aC(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=nC(i.type),d=l.toString();return`/support${c?`/${c}`:""}${d?`?${d}`:""}`}function md(n){const a=new Date(n);return Number.isFinite(a.getTime())?a.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"}):n}function Pm(n){return n.replaceAll("-"," ").replace(/\b\w/g,a=>a.toUpperCase())}function oy(n){return n==="question"?BS:n==="issue"?PS:n==="feature"?$S:US}function cy(n){return wh.find(a=>a.id===n)?.shortLabel||n}function $m(n,a){return n.find(i=>i.id===a)?.name||"Product"}function Da(n){const a=D0(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 Xb({session:n,currentProductKey:a="livedesk",appVersion:i="",onSignIn:l}){const[c,d]=u.useState(()=>Bm()),[m,p]=u.useState(null),[g,v]=u.useState([]),[x,b]=u.useState([]),[w,C]=u.useState(""),[j,k]=u.useState([]),[M,A]=u.useState([]),[T,D]=u.useState([]),[B,H]=u.useState(()=>new Set),[W,_]=u.useState(!0),[Z,G]=u.useState(""),[q,Q]=u.useState(""),[O,ye]=u.useState(!1),[me,X]=u.useState(!1),[I,ee]=u.useState(""),[V,P]=u.useState(()=>Bm().query),[re,ue]=u.useState(!1),[K,xe]=u.useState(!1),[z,le]=u.useState(""),[ke,Ce]=u.useState(""),[Ue,Be]=u.useState("free"),[he,Xe]=u.useState(""),[et,ce]=u.useState(""),[ge,Ae]=u.useState("admin"),[Le,Pe]=u.useState(""),[Ve,Ke]=u.useState(""),[de,je]=u.useState(""),[fe,_e]=u.useState(""),[Ee,mt]=u.useState(""),[Ht,Dt]=u.useState([]),[yt,Ge]=u.useState({productId:"",postType:"question",title:"",body:"",visibility:"public",includeEnvironment:!0,files:[]}),At=u.useCallback(F=>{const Je={...c,...F};d(Je),typeof window<"u"&&window.history.pushState({},"",aC(c,F))},[c]);u.useEffect(()=>{const F=()=>d(Bm());return window.addEventListener("popstate",F),()=>window.removeEventListener("popstate",F)},[]);const ve=u.useCallback(async()=>{const F=await I0(c.query);return b(F),n?.user.id&&H(await F0(n.user.id)),F},[c.query,n?.user.id]),Fe=u.useCallback(async()=>{if(!n?.user.id){p(null),v([]),b([]),C(""),D([]),_(!1);return}_(!0),Q("");try{const F=await _0(n.user.id,a);p(F.access),v(F.products),await ve(),D(await O0())}catch(F){Q(Da(F))}finally{_(!1)}},[a,ve,n?.user.id]);u.useEffect(()=>{Fe()},[Fe]);const He=u.useMemo(()=>m?m.canViewAllProducts?g:g.filter(F=>m.accessibleProductIds.includes(F.id)):[],[m,g]),Me=u.useMemo(()=>{const F=He.find(Je=>Je.product_key===c.product);return m?.canViewAllProducts&&!c.product||c.product==="all"&&m?.canViewAllProducts?"all":F?F.product_key:He.some(Je=>Je.product_key===a)?a:He[0]?.product_key||""},[m?.canViewAllProducts,He,a,c.product]),rt=Me==="all"?"":He.find(F=>F.product_key===Me)?.id||"",dt=u.useMemo(()=>{const F=new Map(g.map(ze=>[ze.id,ze.product_key]));return[...x.filter(ze=>c.type!=="all"&&ze.post_type!==c.type||Me!=="all"&&rt&&ze.product_id!==rt||c.status==="needs-response"&&!["open","needs-info"].includes(ze.status)||c.status!=="all"&&c.status!=="needs-response"&&ze.status!==c.status||c.visibility!=="all"&&ze.visibility!==c.visibility?!1:F.has(ze.product_id))].sort((ze,kt)=>c.sort==="votes"?kt.vote_count-ze.vote_count||kt.updated_at.localeCompare(ze.updated_at):c.sort==="newest"?kt.created_at.localeCompare(ze.created_at):Number(kt.is_pinned)-Number(ze.is_pinned)||kt.updated_at.localeCompare(ze.updated_at))},[x,g,c.sort,c.status,c.type,c.visibility,rt,Me]),Re=dt.find(F=>F.id===w)||dt[0]||null,An=!!(Re&&m&&(m.canViewAllProducts||m.managedProductIds.includes(Re.product_id))),pa=!!(Re&&n?.user.id===Re.author_id)||An;u.useEffect(()=>{if(!Re){C(""),k([]),X(!1);return}Re.id!==w&&C(Re.id)},[Re,w]),u.useEffect(()=>{let F=!0;return w?(ly(w).then(Je=>{F&&k(Je)}).catch(Je=>{F&&Q(Da(Je))}),z0(w).then(Je=>{F&&A(Je)}).catch(Je=>{F&&Q(Da(Je))}),()=>{F=!1}):(k([]),A([]),()=>{F=!1})},[w]),u.useEffect(()=>{!yt.productId&&He[0]&&Ge(F=>({...F,productId:rt||He[0].id}))},[He,yt.productId,rt]),u.useEffect(()=>{P(c.query)},[c.query]),u.useEffect(()=>{!ke&&He[0]&&Ce(He[0].id),!et&&He[0]&&ce(He[0].id)},[He,ke,et]);const it=F=>{Re&&b(Je=>Je.map(ze=>ze.id===Re.id?{...ze,...F}:ze))},Xt=async F=>{if(F.preventDefault(),!(!n||!yt.productId)){G("create"),Q("");try{const Je=await B0({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 kt of Ht)await $0(Je,kt);const ze=await ve();ye(!1),Dt([]),Ge(kt=>({...kt,title:"",body:"",files:[]})),C(Je),ze.some(kt=>kt.id===Je)||await Fe()}catch(Je){Q(Da(Je))}finally{G("")}}},Nn=async F=>{if(F.preventDefault(),!!Re){G("edit"),Q("");try{await U0(Re.id,Re.title,Re.body,Re.visibility),X(!1),await ve()}catch(Je){Q(Da(Je))}finally{G("")}}},Mn=async F=>{if(F.preventDefault(),!(!Re||!I.trim())){G("comment"),Q("");try{await q0(Re.id,I),ee(""),k(await ly(Re.id)),await ve()}catch(Je){Q(Da(Je))}finally{G("")}}},wn=async()=>{if(!(!Re||Re.post_type!=="feature")){G("vote"),Q("");try{const F=await G0(Re.id);H(Je=>{const ze=new Set(Je);return F.voted?ze.add(Re.id):ze.delete(Re.id),ze}),it({vote_count:F.totalVotes})}catch(F){Q(Da(F))}finally{G("")}}},Cs=async F=>{if(Re){G("status"),Q("");try{await V0(Re.id,F),it({status:F}),await ve()}catch(Je){Q(Da(Je))}finally{G("")}}},Ha=async()=>{if(!(!Re||!window.confirm("Hide this Support post from the board?"))){G("hide"),Q("");try{await W0(Re.id),C(""),await ve()}catch(F){Q(Da(F))}finally{G("")}}},gr=async()=>{if(Re){G("lock"),Q("");try{await Y0(Re.id,!Re.is_locked),it({is_locked:!Re.is_locked}),await ve()}catch(F){Q(Da(F))}finally{G("")}}},rs=async()=>{if(Re){G("pin"),Q("");try{await K0(Re.id,!Re.is_pinned),it({is_pinned:!Re.is_pinned}),await ve()}catch(F){Q(Da(F))}finally{G("")}}},zn=async F=>{if(Re){G(`accept-${F}`),Q("");try{await Q0(Re.id,F),it({accepted_comment_id:F,status:Re.post_type==="question"?"answered":Re.status}),await ve()}catch(Je){Q(Da(Je))}finally{G("")}}},Xi=async()=>{if(!(!Re||!fe||fe===Re.id)){G("duplicate"),Q("");try{await X0(Re.id,fe),C(""),_e(""),await ve()}catch(F){Q(Da(F))}finally{G("")}}},Qi=async F=>{if(!F.read_at)try{await H0(F.id),D(Je=>Je.map(ze=>ze.id===F.id?{...ze,read_at:new Date().toISOString()}:ze))}catch(Je){Q(Da(Je))}F.post_id&&C(F.post_id),ue(!1)};return n?W&&!m?r.jsxs("section",{className:"support-page support-loading",children:[r.jsx(Ho,{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:()=>ue(F=>!F),title:"Notifications",children:[r.jsx(OS,{size:16})," ",T.filter(F=>!F.read_at).length>0&&r.jsx("b",{children:T.filter(F=>!F.read_at).length})]}),re&&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(F=>r.jsxs("button",{type:"button",className:F.read_at?"":"unread",onClick:()=>{Qi(F)},children:[r.jsx("b",{children:F.title}),r.jsx("span",{children:F.body}),r.jsx("small",{children:md(F.created_at)})]},F.id))]})]}),m?.canViewAllProducts&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>xe(F=>!F),children:[r.jsx(jn,{size:16})," Admin"]}),r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{Fe()},disabled:W,children:[r.jsx(Ho,{size:16,className:W?"support-spin":""})," Refresh"]}),r.jsxs("button",{className:"support-primary-button",type:"button",onClick:()=>ye(!0),disabled:He.length===0,children:[r.jsx(Lm,{size:17})," New request"]})]})}),q&&r.jsxs("div",{className:"support-error",role:"alert",children:[r.jsx(la,{size:17})," ",r.jsx("span",{children:q}),r.jsx("button",{type:"button",onClick:()=>Q(""),"aria-label":"Dismiss error",children:r.jsx(la,{size:15})})]}),O&&r.jsxs("form",{className:"support-composer",onSubmit:F=>{Xt(F)},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(la,{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:F=>Ge(Je=>({...Je,productId:F.target.value})),children:He.map(F=>r.jsx("option",{value:F.id,children:F.name},F.id))})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Type"}),r.jsx("select",{value:yt.postType,onChange:F=>Ge(Je=>({...Je,postType:F.target.value})),children:wh.filter(F=>F.id!=="announcement"||m?.canCreateAnnouncements).map(F=>r.jsx("option",{value:F.id,children:F.label},F.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:F=>Ge(Je=>({...Je,title:F.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:F=>Ge(Je=>({...Je,body:F.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:F=>Ge(Je=>({...Je,visibility:F.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:F=>Ge(Je=>({...Je,includeEnvironment:F.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:F=>Dt(Array.from(F.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:Ht.length>0?`${Ht.length} attachment${Ht.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:Z==="create",children:[r.jsx(Qc,{size:16})," ",Z==="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:()=>At({type:"all"}),children:"All"}),wh.map(F=>{const Je=oy(F.id);return r.jsxs("button",{className:c.type===F.id?"active":"",type:"button",onClick:()=>At({type:F.id}),children:[r.jsx(Je,{size:15})," ",F.label]},F.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(jn,{size:19})]}),r.jsxs("div",{className:"support-admin-grid",children:[r.jsxs("form",{onSubmit:F=>{},children:[r.jsx("strong",{children:"Grant product access"}),r.jsx("input",{type:"email",required:!0,placeholder:"User email",value:z,onChange:F=>le(F.target.value)}),r.jsx("select",{value:ke,onChange:F=>Ce(F.target.value),children:He.map(F=>r.jsx("option",{value:F.id,children:F.name},F.id))}),r.jsxs("select",{value:Ue,onChange:F=>Be(F.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:Ee==="access",children:[r.jsx(fr,{size:15})," Grant access"]})]}),r.jsxs("form",{onSubmit:F=>{},children:[r.jsx("strong",{children:"Assign product admin"}),r.jsx("input",{type:"email",required:!0,placeholder:"Admin email",value:he,onChange:F=>Xe(F.target.value)}),r.jsx("select",{value:et,onChange:F=>ce(F.target.value),children:He.map(F=>r.jsx("option",{value:F.id,children:F.name},F.id))}),r.jsxs("select",{value:ge,onChange:F=>Ae(F.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:Ee==="product-admin",children:[r.jsx(jn,{size:15})," Assign admin"]})]}),r.jsxs("form",{onSubmit:F=>{},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:Le,onChange:F=>Pe(F.target.value)}),r.jsx("input",{required:!0,placeholder:"Product name",value:Ve,onChange:F=>Ke(F.target.value)}),r.jsx("input",{placeholder:"Description",value:de,onChange:F=>je(F.target.value)}),r.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:Ee==="product",children:[r.jsx(Lm,{size:15})," Add product"]})]})]})]}),r.jsxs("form",{className:"support-search-bar",onSubmit:F=>{F.preventDefault(),At({query:V.trim()})},children:[r.jsxs("label",{children:[r.jsx("span",{children:"Search Support"}),r.jsx("input",{value:V,onChange:F=>P(F.target.value),placeholder:"Search titles and request details"})]}),r.jsxs("button",{className:"support-secondary-button",type:"submit",children:[r.jsx(Yv,{size:15})," Search"]}),c.query&&r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{P(""),At({query:""})},"aria-label":"Clear search",children:r.jsx(la,{size:16})})]}),r.jsxs("div",{className:"support-filter-bar",children:[r.jsxs("div",{className:"support-filter-title",children:[r.jsx(Yv,{size:16}),r.jsx("span",{children:"Filter"})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Product"}),r.jsxs("select",{value:Me,onChange:F=>At({product:F.target.value}),disabled:!m?.canViewAllProducts&&He.length<=1,children:[r.jsx("option",{value:"all",children:"All products"}),He.map(F=>r.jsx("option",{value:F.product_key,children:F.name},F.id))]})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Status"}),r.jsx("select",{value:c.status,onChange:F=>At({status:F.target.value}),children:J0.map(F=>r.jsx("option",{value:F.id,children:F.label},F.id))})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Visibility"}),r.jsxs("select",{value:c.visibility,onChange:F=>At({visibility:F.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:F=>At({sort:F.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(jn,{size:15})," Owner view"]}),r.jsx("button",{type:"button",onClick:()=>At({status:"needs-response"}),children:"Needs response"}),r.jsx("button",{type:"button",onClick:()=>At({visibility:"private"}),children:"Private requests"}),r.jsx("button",{type:"button",onClick:()=>At({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:[dt.length," request",dt.length===1?"":"s"]}),r.jsx("small",{children:Me==="all"?"All products":$m(He,rt)})]}),dt.length===0?r.jsxs("div",{className:"support-list-empty",children:[r.jsx(Gc,{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."}),He.length>0&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>ye(!0),children:[r.jsx(Lm,{size:16})," Create the first request"]})]}):dt.map(F=>{const Je=oy(F.post_type);return r.jsxs("button",{type:"button",className:`support-post-row ${F.id===Re?.id?"active":""}`,onClick:()=>{C(F.id),X(!1)},children:[r.jsx("span",{className:"support-post-row-icon",children:r.jsx(Je,{size:17})}),r.jsxs("span",{className:"support-post-row-copy",children:[r.jsxs("span",{className:"support-post-row-meta",children:[r.jsx("b",{children:$m(g,F.product_id)}),r.jsx("em",{children:cy(F.post_type)}),F.visibility==="private"&&r.jsx(Zr,{size:13})]}),r.jsx("strong",{children:F.title}),r.jsxs("small",{children:[Pm(F.status)," · ",md(F.updated_at)," · ",F.comment_count," comments"]})]}),F.post_type==="feature"&&r.jsxs("span",{className:"support-vote-count",children:[r.jsx(Hb,{size:14})," ",F.vote_count]})]},F.id)})]}),r.jsx("section",{className:"support-post-detail","aria-label":"Support post detail",children:Re?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:$m(g,Re.product_id)}),r.jsx("span",{className:"support-type-badge",children:cy(Re.post_type)}),r.jsx("span",{className:`support-status-badge status-${Re.status}`,children:Pm(Re.status)}),Re.visibility==="private"&&r.jsxs("span",{className:"support-private-badge",children:[r.jsx(Zr,{size:13})," Private"]})]}),r.jsxs("div",{className:"support-detail-actions",children:[pa&&r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>X(F=>!F),title:"Edit post",children:r.jsx(HS,{size:16})}),An&&r.jsxs(r.Fragment,{children:[r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{rs()},disabled:Z==="pin",title:Re.is_pinned?"Unpin post":"Pin post",children:r.jsx(Kv,{size:16})}),r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{gr()},disabled:Z==="lock",title:Re.is_locked?"Unlock post":"Lock post",children:r.jsx(Zr,{size:16})}),r.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{Ha()},disabled:Z==="hide",title:"Hide post",children:r.jsx(Xv,{size:16})})]})]})]}),me?r.jsxs("form",{className:"support-edit-form",onSubmit:F=>{Nn(F)},children:[r.jsx("input",{value:Re.title,onChange:F=>it({title:F.target.value}),minLength:3,maxLength:180,required:!0}),r.jsx("textarea",{value:Re.body,onChange:F=>it({body:F.target.value}),rows:9,required:!0}),r.jsxs("div",{className:"support-edit-actions",children:[r.jsxs("select",{value:Re.visibility,onChange:F=>it({visibility:F.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:Z==="edit",children:[r.jsx(fr,{size:16})," Save changes"]})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("h3",{children:Re.title}),r.jsx("div",{className:"support-detail-body",children:Re.body.split(`
10
+ `).map((F,Je)=>r.jsx("p",{children:F||" "},`${Re.id}-body-${Je}`))})]}),r.jsxs("div",{className:"support-detail-meta",children:[r.jsxs("span",{children:["Opened ",md(Re.created_at)]}),Re.app_version&&r.jsxs("span",{children:["Version ",Re.app_version]}),Re.platform&&r.jsx("span",{children:Re.platform}),Re.is_locked&&r.jsxs("span",{children:[r.jsx(Zr,{size:13})," Locked"]}),Re.is_pinned&&r.jsxs("span",{children:[r.jsx(Kv,{size:13})," Pinned"]})]}),r.jsxs("div",{className:"support-detail-controls",children:[Re.post_type==="feature"&&r.jsxs("button",{className:`support-vote-button ${B.has(Re.id)?"voted":""}`,type:"button",onClick:()=>{wn()},disabled:Z==="vote",children:[r.jsx(FS,{size:16})," ",B.has(Re.id)?"Voted":"Vote"," ",r.jsx("b",{children:Re.vote_count})]}),An&&r.jsxs("label",{className:"support-status-control",children:[r.jsx("span",{children:"Change status"}),r.jsx("select",{value:Re.status,onChange:F=>{Cs(F.target.value)},disabled:Z==="status",children:(eC[Re.post_type]||[]).map(F=>r.jsx("option",{value:F,children:Pm(F)},F))})]}),An&&r.jsxs(r.Fragment,{children:[r.jsxs("select",{className:"support-status-control",value:fe,onChange:F=>_e(F.target.value),children:[r.jsx("option",{value:"",children:"Duplicate of..."}),dt.filter(F=>F.id!==Re.id&&F.product_id===Re.product_id).map(F=>r.jsx("option",{value:F.id,children:F.title.slice(0,55)},F.id))]}),r.jsx("button",{className:"support-secondary-button",type:"button",onClick:()=>{Xi()},disabled:!fe||Z==="duplicate",children:"Merge duplicate"})]})]}),M.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:[M.length," file",M.length===1?"":"s"]})]})}),M.map(F=>r.jsxs("a",{href:F.signed_url,target:"_blank",rel:"noreferrer",children:[r.jsx(Bh,{size:14})," ",F.file_name,r.jsxs("small",{children:[Math.ceil(F.size_bytes/1024)," KB"]})]},F.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"]})]}),Re.is_locked&&r.jsxs("span",{className:"support-locked-label",children:[r.jsx(Zr,{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(F=>r.jsxs("article",{className:`support-comment ${F.is_staff_answer?"staff":""} ${Re.accepted_comment_id===F.id?"accepted":""}`,children:[r.jsxs("div",{className:"support-comment-head",children:[r.jsx("strong",{children:F.is_staff_answer?"LiveDesk Support":F.author_id===n.user.id?"You":"Support user"}),F.is_staff_answer&&r.jsxs("span",{children:[r.jsx(jn,{size:13})," Staff answer"]}),Re.accepted_comment_id===F.id&&r.jsxs("span",{children:[r.jsx(Dn,{size:13})," Accepted"]}),r.jsx("time",{children:md(F.created_at)})]}),r.jsx("p",{children:F.body}),r.jsxs("div",{className:"support-comment-actions",children:[(n.user.id===Re.author_id||An)&&Re.post_type==="question"&&Re.accepted_comment_id!==F.id&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{zn(F.id)},disabled:Z===`accept-${F.id}`,children:[r.jsx(fr,{size:14})," Accept answer"]}),An&&r.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{Z0(F.id)},title:"Hide comment",children:r.jsx(Xv,{size:14})})]})]},F.id))}),!Re.is_locked&&r.jsxs("form",{className:"support-comment-form",onSubmit:F=>{Mn(F)},children:[r.jsx("textarea",{value:I,onChange:F=>ee(F.target.value),placeholder:"Add a focused reply...",rows:3}),r.jsxs("button",{className:"support-primary-button",type:"submit",disabled:Z==="comment"||!I.trim(),children:[r.jsx(Qc,{size:15})," Reply"]})]})]})]}):r.jsxs("div",{className:"support-detail-empty",children:[r.jsx(Gc,{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(Gc,{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(jn,{size:17})," Sign in with Google"]})]})})}function hd(n){return!!n&&typeof n=="object"}function Qb(n){let a=n;return hd(a)&&"data"in a&&(a=a.data),hd(a)&&"session"in a&&(a=a.session),!hd(a)||typeof a.access_token!="string"||!a.access_token||!hd(a.user)||typeof a.user.id!="string"||!a.user.id?null:a}function uy(n){return n?.access_token?n.refresh_token?"":"refresh-token-required":"access-token-required"}const Vc=5179,fn=Ki(`http://127.0.0.1:${Vc}`);function sC(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 rC(n){const a=n.trim().toLowerCase();return a==="localhost"||a==="127.0.0.1"||a==="::1"||a==="[::1]"}function iC(n){const a=n.trim().toLowerCase();return!a||a==="0.0.0.0"||a==="::"||a==="[::]"}function lC(n){const a=sC(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 oC(n){return n.includes(":")&&!n.startsWith("[")?`[${n}]`:n}function cC(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||iC(c)?null:{host:c,port:d}}catch{return null}}function Ki(n){const a=String(n||"").trim()||`http://127.0.0.1:${Vc}`,i=/^[a-z][a-z\d+.-]*:\/\//i.test(a)?a:`http://${a}`;try{const l=new URL(i);return l.port||(l.port=String(Vc)),l.hash="",l.search="",l.toString().replace(/\/+$/,"")}catch{return`http://127.0.0.1:${Vc}`}}function uC(n){const a=cC(n);return a?Ki(`http://${oC(a.host)}:${Vc}`):""}function dy(n){const i=[n?.endpoint,...Array.isArray(n?.endpoint_candidates)?n.endpoint_candidates:[]].map(l=>uC(String(l||""))).filter(Boolean);return[...new Set(i)]}function Wc(n=fn){if(!(typeof window>"u"||window.location.protocol!=="https:"))try{const a=new URL(n);if(a.protocol!=="http:")return;if(rC(a.hostname))return"loopback";if(lC(a.hostname))return"local"}catch{return}}function nf(n,a=fn){const i=new URL(n,Ki(a));return i.protocol=i.protocol==="https:"?"wss:":"ws:",i.toString()}async function Ye(n,a,i=fn){const l=Ki(i),c={...a,headers:{"Content-Type":"application/json",...a?.headers||{}},cache:"no-store"},d=Wc(l);d&&(c.targetAddressSpace=d);let m;try{m=await fetch(`${l}${n}`,c)}catch(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 p=null;try{p=await m.json()}catch{p=null}if(!m.ok){const g=p&&typeof p=="object"&&"error"in p?String(p.error||""):"";throw new Error(`${m.status} ${g||m.statusText}`)}return p}async function Zb({baseUrl:n=fn,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 Ye("/api/runtime/status",void 0,n),v=String(g.role||"").toLowerCase(),x=String(g.state||"").toLowerCase(),b=Number(g.runtimePid||0),w=i>1?b>1&&b!==i:b>1;if(v===a&&l.map(C=>C.toLowerCase()).includes(x)&&w)return g}catch(g){m=g}await new Promise(g=>setTimeout(g,300))}const p=m instanceof Error?` ${m.message}`:"";throw new Error(`LiveDesk runtime did not become ${a} with a new process.${p}`)}function dC(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 Jb(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 Hd(n){await navigator.clipboard.writeText(n)}function ex({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 tx={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."},Sh={en:tx,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 af(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(Sh[l])return l;if(Sh[d])return d}return"en"}function Gd(n,a){const i=af(a);return Sh[i]?.[n]||tx[n]}function Ch(n,a,i){return`${n}
11
+ ${Gd(a,i)}`}const nx={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"},fC={en:nx,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"}},ax={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"},mC={en:ax,ko:{eyebrow:"컴퓨터 역할",title:"이 컴퓨터를 Hub로 사용할까요?",description:"Hub는 Client 컴퓨터를 연결하고 관리합니다.",restartNotice:"다른 컴퓨터가 Hub라면 이 컴퓨터가 새 Hub가 됩니다.",cancel:"취소",confirm:"Hub로 설정",closeLabel:"Hub 설정 확인 닫기"}};function hC(n){const a=af(n);return fC[a]||nx}function pC(n){const a=af(n);return mC[a]||ax}const gC=[{id:"docs",label:"Doc",icon:qd},{id:"support",label:"Support",icon:Gc},{id:"pricing",label:"Pricing",icon:Do},{id:"settings",label:"Settings",icon:Ph}],fy=[0,1e3,2e3,5e3,1e4,2e4,3e4];function vC(){return typeof window>"u"?"":window.location.port==="5179"?window.location.origin:"http://127.0.0.1:5179"}async function Nl(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 kh(n){return`${Math.max(0,Math.min(100,Number(n||0))).toFixed(0)}%`}function Um(n){return Number.isFinite(n)?`${Math.max(0,Math.min(100,Number(n))).toFixed(0)}%`:"—"}function sx(n){return Number.isFinite(n)?kh(Number(n)):"0%"}function Il(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 my(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 yC(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 bC(n,a){return!Number.isFinite(a)||Number(a)<=0?"Dedicated memory unavailable":Number.isFinite(n)?`${Il(n)} / ${Il(a)}`:`${Il(a)} available`}function xC(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 pd({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:sx(c)}})})]})}function wC(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 SC(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 CC({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 kC({session:n,status:a,pin:i,error:l,roleChangeMessage:c,videoAccelerationBusy:d,slotInput:m,slotBusy:p,onSignIn:g,onPinChange:v,onSubmitPin:x,onSlotInputChange:b,onSaveSlot:w,onEnableVideoAcceleration:C}){const j=a?.connectionState==="connected",k=a?.videoAcceleration,M=d||k?.busy||k?.state==="installing",A=k?.ready?`${k.encoder||"H.264"} · ${k.driver||"VAAPI"}`:M?"Setting up…":k?.message||"Setup available",T=a?.system?.memoryTotalBytes?Number(a.system.memoryUsedBytes||0)/a.system.memoryTotalBytes*100:0,D=a?.system?.gpus||[],B=D.find(O=>Number.isFinite(O.usagePercent)||Number.isFinite(O.memoryTotalBytes))||D[0],H=Number.isFinite(B?.usagePercent)?Number(B?.usagePercent):null,W=Number.isFinite(B?.memoryTotalBytes)&&Number(B?.memoryTotalBytes)>0&&Number.isFinite(B?.memoryUsedBytes)?Number(B?.memoryUsedBytes)/Number(B?.memoryTotalBytes)*100:null,_=a?.system?.disks||[],Z=a?.system?.network,G=Z?.interfaces||[],q=[...new Set(G.map(O=>O.name).filter(Boolean))],Q=G.map(O=>O.address).filter(Boolean);return r.jsxs("section",{className:"client-home-page",children:[r.jsxs("header",{className:"client-home-heading",children:[r.jsxs("div",{children:[r.jsx("p",{className:"client-unified-eyebrow",children:"THIS COMPUTER"}),r.jsx("h2",{children:a?.deviceName||"This Computer"})]}),r.jsxs("span",{className:`client-unified-role-chip ${j?"connected":""}`,children:[r.jsx(oa,{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(Pb,{size:14})," Uptime ",xC(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(pd,{icon:gh,label:"CPU",value:kh(a?.system?.cpuUsagePercent),detail:a?.system?.cpuLogicalCores?`${a.system.cpuLogicalCores} logical cores · Current processor usage`:"Current processor usage",percent:a?.system?.cpuUsagePercent}),r.jsx(pd,{icon:qS,label:"Memory",value:kh(T),detail:yC(a?.system?.memoryUsedBytes,a?.system?.memoryTotalBytes),percent:T}),r.jsx(pd,{icon:GS,label:"GPU",value:Um(H),detail:B?.name||(a?.system?.hardwareCollecting?"Detecting graphics hardware…":"Graphics usage unavailable"),percent:H}),r.jsx(pd,{icon:mr,label:"VRAM",value:Um(W),detail:bC(B?.memoryUsedBytes,B?.memoryTotalBytes),percent:W})]})]}),r.jsxs("section",{className:"client-storage-panel","aria-label":"Local storage",children:[r.jsxs("div",{className:"client-system-subhead",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"STORAGE"}),r.jsx("strong",{children:"Local drives"})]}),r.jsx("small",{children:_.length>0?`${_.length} ${_.length===1?"drive":"drives"}`:a?.system?.hardwareCollecting?"Detecting…":"Unavailable"})]}),r.jsxs("div",{className:"client-disk-list",children:[_.map(O=>r.jsxs("article",{className:"client-disk-row",children:[r.jsxs("div",{className:"client-disk-row-head",children:[r.jsxs("span",{children:[r.jsx(_l,{size:16}),r.jsx("strong",{children:O.mount||"Disk"}),r.jsx("small",{children:O.name||"Local disk"})]}),r.jsx("strong",{children:Um(O.usedPercent)})]}),r.jsxs("small",{children:[Il(O.freeBytes)," free · ",Il(O.totalBytes)," total"]}),r.jsx("i",{"aria-hidden":"true",children:r.jsx("b",{style:{width:sx(O.usedPercent)}})})]},`${O.mount}-${O.name||""}`)),_.length===0&&r.jsxs("div",{className:"client-disk-empty",children:[r.jsx(_l,{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:q.length>0?q.join(", "):"Detecting adapter"})]}),r.jsxs("div",{className:"client-network-live",children:[r.jsxs("div",{className:"client-network-adapter",children:[r.jsx(ef,{size:18}),r.jsxs("span",{children:[r.jsx("strong",{children:q.join(", ")||"Network"}),r.jsx("small",{children:Q.join(" / ")||"Checking active connection"})]})]}),r.jsxs("div",{className:"client-network-rate download",children:[r.jsx(VS,{size:17}),r.jsxs("span",{children:[r.jsx("small",{children:"Receive"}),r.jsx("strong",{children:my(Z?.receiveBytesPerSecond)})]})]}),r.jsxs("div",{className:"client-network-rate upload",children:[r.jsx(WS,{size:17}),r.jsxs("span",{children:[r.jsx("small",{children:"Send"}),r.jsx("strong",{children:my(Z?.sendBytesPerSecond)})]})]}),r.jsxs("small",{className:"client-network-total",children:["Total ",Il(Z?.receivedBytes)," received / ",Il(Z?.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(oa,{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(jn,{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(Lo,{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(Hl,{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(Ol,{size:16})," Sign in with Google"]}):r.jsxs("p",{className:"client-unified-success",children:[r.jsx(Dn,{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($b,{size:16}),r.jsx("input",{value:i,onChange:O=>v(O.target.value),placeholder:"6-digit Hub PIN",inputMode:"numeric","aria-label":"6-digit Hub PIN"}),r.jsx("button",{className:"client-unified-secondary",type:"button",onClick:x,disabled:i.length!==6,children:"Connect"})]})]}),k?.supported&&r.jsxs("div",{className:`client-video-acceleration state-${k.ready?"ready":k.state||"setup-required"}`,children:[r.jsx(gh,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Hardware video"}),r.jsx("small",{children:A})]}),!k.ready&&k.canInstall&&r.jsx("button",{type:"button",onClick:C,disabled:M,title:"Install and verify Linux FFmpeg hardware video support",children:M?"Setting up":"Enable"})]}),(l||a?.lastError)&&r.jsxs("p",{className:"client-unified-error",role:"alert",children:[r.jsx(Bb,{size:15})," ",l||a?.lastError]}),c&&r.jsx("p",{className:"client-unified-success",children:c}),r.jsxs("div",{className:"client-slot-setting",children:[r.jsxs("label",{htmlFor:"client-slot-number",children:[r.jsx("span",{children:"Slot"}),r.jsx("input",{id:"client-slot-number",value:m,onChange:O=>b(O.target.value),inputMode:"numeric",pattern:"[0-9]*",placeholder:"1-999","aria-label":"Wall slot number",disabled:!j||p})]}),r.jsxs("button",{type:"button",onClick:w,disabled:!j||p||!m,"aria-label":"Save slot number",title:"Save slot number",children:[r.jsx(Ph,{size:17}),r.jsx("span",{children:p?"Saving":"Set"})]})]})]})]})]})}function jC(){const[n,a]=u.useState(null),[i,l]=u.useState(null),[c,d]=u.useState(!1),[m,p]=u.useState(""),[g,v]=u.useState(""),[x,b]=u.useState(""),[w,C]=u.useState(!1),[j,k]=u.useState(!1),[M,A]=u.useState(""),[T,D]=u.useState(!1),[B,H]=u.useState(null),[W,_]=u.useState(!1),[Z,G]=u.useState("computer"),[q,Q]=u.useState(!1),O=u.useRef(null),ye=u.useRef(null),me=u.useRef(!1),X=u.useRef(!1),I=u.useRef(!1),ee=u.useRef(0),V=u.useRef(!1),P=u.useMemo(vC,[]),re=u.useMemo(()=>wC(i,n),[i,n]),ue=u.useMemo(()=>SC(i,n),[i,n]),K=re.slice(0,1).toUpperCase()||"L",xe=u.useCallback(async()=>{if(v(""),window.liveDesk?.auth?.signInWithGoogle){const de=await window.liveDesk.auth.signInWithGoogle();return de?.ok===!1?(v(de.error||"LiveDesk could not open the system browser for Google sign-in."),!1):!0}return window.location.assign(`${P}/auth/google`),!0},[P]),z=u.useCallback(async()=>{I.current||(I.current=!0,v("Your saved Google sign-in is incomplete. LiveDesk is reopening sign-in once to repair it."),await ft.auth.signOut({scope:"local"}).catch(()=>{}),l(null),await xe()||(I.current=!1))},[xe]),le=u.useCallback(async de=>{const je=uy(de);if(je)throw new Error(je);if(me.current)return!1;me.current=!0;try{const fe=await window.liveDesk?.auth?.persistSession?.(de);if(fe?.ok===!1)throw new Error(fe.error||"LiveDesk could not validate the desktop session.");for(let _e=0;_e<2;_e+=1){const Ee=await Nl(P,_e>0),mt=await fetch(`${P}/api/auth/session`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":Ee},signal:AbortSignal.timeout(1e4),body:JSON.stringify({accessToken:de.access_token,refreshToken:de.refresh_token,expiresAt:de.expires_at,user:{id:de.user.id,email:de.user.email}})}),Ht=await mt.json().catch(()=>({}));if(mt.status===403&&_e===0){sessionStorage.removeItem("livedesk.client.csrf");continue}if(!mt.ok)throw new Error(Ht.error||`Client runtime returned HTTP ${mt.status}.`);return v(""),!0}throw new Error("Client runtime rejected the session transfer.")}finally{me.current=!1}},[P]),ke=u.useCallback(async()=>{try{const de=await fetch(`${P}/api/client/status`,{cache:"no-store"}),je=await de.json().catch(()=>({}));if(!de.ok)throw new Error(je.error||`Client runtime returned HTTP ${de.status}.`);if(je.csrfToken&&sessionStorage.setItem("livedesk.client.csrf",je.csrfToken),String(je.role||"").toLowerCase()==="hub")throw new Error("This computer is assigned to the Hub role.");a(je)}catch(de){v(de instanceof Error?de.message:String(de))}},[P]);u.useEffect(()=>{ke();const de=window.setInterval(()=>{ke()},2e3);return()=>window.clearInterval(de)},[ke]),u.useEffect(()=>{if(V.current)return;const de=Number(n?.slotNumber||0);A(de>0?String(de):"")},[n?.slotNumber]),u.useEffect(()=>{if(!B)return;const de=window.setTimeout(()=>H(null),5e3);return()=>window.clearTimeout(de)},[B]);const Ce=u.useCallback(async()=>{const de=Date.now();if(!(!n?.authenticated||n.connectionState==="connected"||!["waiting","reconnecting"].includes(String(n.agent?.state||""))||de-ee.current<4e3)){ee.current=de;try{const je=await fetch(`${P}/api/client/reconnect`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Nl(P)},body:JSON.stringify({onlyIfWaiting:!0,reason:"app-active"})});if(!je.ok)throw new Error(`Client reconnect returned HTTP ${je.status}.`);await ke()}catch(je){v(je instanceof Error?je.message:String(je))}}},[P,ke,n]);u.useEffect(()=>{const de=()=>{Ce()},je=()=>{Ce()},fe=()=>{document.visibilityState==="visible"&&Ce()};return window.addEventListener("online",de),window.addEventListener("focus",je),document.addEventListener("visibilitychange",fe),()=>{window.removeEventListener("online",de),window.removeEventListener("focus",je),document.removeEventListener("visibilitychange",fe)}},[Ce]),u.useEffect(()=>{if(!c||!n||!i?.access_token||n.authenticated)return;if(uy(i)==="refresh-token-required"){z().catch(Ee=>{I.current=!1,v(Ee instanceof Error?Ee.message:String(Ee))});return}let de=!1,je,fe=0;const _e=async()=>{if(de)return;try{const mt=await le(i);if(await ke(),mt)return}catch(mt){v(mt instanceof Error?mt.message:String(mt))}if(de)return;const Ee=fy[Math.min(fe,fy.length-1)];fe+=1,je=window.setTimeout(()=>{_e()},Ee)};return _e(),()=>{de=!0,je!==void 0&&window.clearTimeout(je)}},[c,ke,z,i,n,le]),u.useEffect(()=>{const de=new URLSearchParams(window.location.search),je=de.get("auth_error");if(!je)return;v(je),de.delete("auth_error");const fe=de.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${fe?`?${fe}`:""}${window.location.hash}`)},[]),u.useEffect(()=>{let de=!0;if(!window.liveDesk?.auth)return l(null),d(!0),ke(),()=>{de=!1};const je=window.liveDesk?.auth?.onComplete?.(_e=>{_e.ok&&_e.session?ft.auth.setSession(_e.session).catch(Ee=>v(Ee instanceof Error?Ee.message:String(Ee))):_e.error&&v(_e.error)});(async()=>{try{const _e=window.liveDesk?.auth?.getSession?await window.liveDesk.auth.getSession():await ft.auth.getSession();if(!de)return;const Ee=Qb(_e);l(Ee),ke()}catch(_e){de&&v(_e instanceof Error?_e.message:String(_e))}finally{de&&d(!0)}})();const{data:fe}=ft.auth.onAuthStateChange((_e,Ee)=>{de&&(l(Ee),d(!0),ke())});return()=>{de=!1,je?.(),fe.subscription.unsubscribe()}},[ke]),u.useEffect(()=>{if(!c||!n||X.current||I.current||i||n.authenticated)return;const de=new URLSearchParams(window.location.search);if(!de.has("livedesk_launch"))return;X.current=!0,de.delete("livedesk_launch");const je=de.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${je?`?${je}`:""}${window.location.hash}`),xe().catch(fe=>v(fe instanceof Error?fe.message:String(fe)))},[c,i,xe,n]);const Ue=async()=>{Q(!1),window.liveDesk?.auth?.persistSession?(await ft.auth.signOut(),(await window.liveDesk.auth.persistSession(null))?.runtimeCleared===!1&&v("Signed out locally. The LiveDesk runtime could not be reached to clear its session.")):await fetch(`${P}/api/auth/session`,{method:"DELETE",headers:{"X-LiveDesk-CSRF":await Nl(P)}}).catch(()=>{}),l(null),await ke()};u.useEffect(()=>{if(!q)return;const de=fe=>{fe.target instanceof Element&&fe.target.closest(".account-popover, .rail-account")||Q(!1)},je=fe=>{fe.key==="Escape"&&Q(!1)};return window.addEventListener("pointerdown",de),window.addEventListener("keydown",je),()=>{window.removeEventListener("pointerdown",de),window.removeEventListener("keydown",je)}},[q]);const Be=u.useCallback((de=!0)=>{w||(_(!1),de&&window.requestAnimationFrame(()=>ye.current?.focus()))},[w]),he=u.useCallback(()=>{w||!n?.authenticated||(ye.current=document.activeElement instanceof HTMLElement?document.activeElement:null,b(""),_(!0))},[w,n?.authenticated]);u.useEffect(()=>{if(!W)return;const de=window.requestAnimationFrame(()=>O.current?.focus()),je=_e=>{_e.target instanceof Element&&_e.target.closest(".client-hub-switch-popover, .client-hub-switch-trigger")||Be(!1)},fe=_e=>{_e.key==="Escape"&&Be()};return window.addEventListener("pointerdown",je),window.addEventListener("keydown",fe),()=>{window.cancelAnimationFrame(de),window.removeEventListener("pointerdown",je),window.removeEventListener("keydown",fe)}},[Be,W]);const Xe=async()=>{v("");try{const de=await fetch(`${P}/api/client/pin`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Nl(P)},body:JSON.stringify({pin:m})}),je=await de.json().catch(()=>({}));if(!de.ok||je?.ok===!1)throw new Error(je?.error||"PIN could not be accepted.");p(""),await ke()}catch(de){v(de instanceof Error?de.message:String(de))}},et=async()=>{_(!1),C(!0),b(""),v("");try{const de=await fetch(`${P}/api/runtime/switch-role`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Nl(P)},body:JSON.stringify({role:"hub"})}),je=await de.json().catch(()=>({}));if(!de.ok||je?.ok===!1)throw new Error(je?.error||`Role change failed with HTTP ${de.status}.`);b("Hub role accepted. LiveDesk is restarting this computer with the Hub Wall.");const fe=Number(n?.runtimePid||0);await Zb({baseUrl:P,targetRole:"hub",previousRuntimePid:fe,allowedStates:["running"]}),window.location.reload()}catch(de){v(de instanceof Error?de.message:String(de)),C(!1)}},ce=async()=>{if(T)return;const de=Number(M);if(!Number.isInteger(de)||de<1||de>999){H({kind:"error",message:"Enter a slot number from 1 to 999."});return}D(!0),H(null);try{const je=await fetch(`${P}/api/client/slot`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Nl(P)},body:JSON.stringify({slotNumber:de})}),fe=await je.json().catch(()=>({}));if(!je.ok||fe.ok===!1){if(fe.error==="slot-taken"){const _e=fe.conflict?.deviceName||fe.conflict?.hostname||fe.conflict?.deviceId||"another computer";throw new Error(`Slot ${String(de).padStart(3,"0")} is already used by ${_e}.`)}throw new Error(fe.error||`Slot update failed with HTTP ${je.status}.`)}V.current=!1,A(String(de)),a(fe),H({kind:"success",message:`Slot ${String(de).padStart(3,"0")} saved. LiveDesk is reconnecting this Client.`})}catch(je){H({kind:"error",message:je instanceof Error?je.message:String(je)})}finally{D(!1),await ke()}},ge=async()=>{if(!j){k(!0),v("");try{const de=await fetch(`${P}/api/client/video-acceleration/install`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Nl(P)},body:JSON.stringify({confirm:!0})}),je=await de.json().catch(()=>({}));if(a(je),!de.ok||je.videoAcceleration?.ready!==!0)throw new Error(je.videoAcceleration?.error||je.error||"Linux hardware video setup did not complete.")}catch(de){v(de instanceof Error?de.message:String(de))}finally{k(!1),await ke()}}},Ae=!!(n?.authenticated||i),Le=u.useMemo(()=>af(),[]),Pe=Gd("switch-to-hub",Le),Ve=Gd("client",Le),Ke=hC(Le);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(ex,{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:he,disabled:w||!n?.authenticated,"aria-busy":w,"aria-expanded":W,"aria-haspopup":"dialog","aria-controls":W?"client-hub-switch-popover":void 0,"aria-label":`Hub. ${Pe}`,"data-tooltip":W?void 0:Ch("Hub","switch-to-hub",Le),children:[r.jsx(mr,{size:19}),r.jsx("span",{children:w?"Switching…":"Hub"})]}),r.jsxs("button",{className:`rail-tool client-main-tool accent-blue ${Z==="computer"?"active":""}`,type:"button",onClick:()=>G("computer"),"aria-current":Z==="computer"?"page":void 0,"aria-label":`Client. ${Ve}`,"data-tooltip":Ch("Client","client",Le),children:[r.jsx(oa,{size:19}),r.jsx("span",{children:"Client"})]})]})}),r.jsxs("div",{className:"rail-footer",children:[gC.map(de=>{const je=de.icon;return r.jsxs("button",{className:`rail-tool compact ${Z===de.id?"active":""}`,type:"button",onClick:()=>G(de.id),title:de.label,children:[r.jsx(je,{size:18}),r.jsx("span",{children:de.label})]},de.id)}),r.jsxs("button",{className:`rail-account ${Ae?"signed-in":""}`,type:"button",onClick:()=>Q(de=>!de),"aria-expanded":q,"aria-haspopup":"dialog",title:Ae?"Account":"Sign in",children:[Ae&&ue?r.jsx("img",{src:ue,alt:re,referrerPolicy:"no-referrer"}):Ae?r.jsx("span",{className:"avatar-fallback",children:K}):r.jsx(Ol,{size:18}),r.jsx("span",{children:Ae?"Account":"Sign in"})]})]})]}),W&&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(mr,{size:19})}),r.jsx("span",{className:"client-hub-switch-eyebrow",children:Ke.eyebrow}),r.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>Be(),"aria-label":Ke.closeLabel,children:r.jsx(la,{size:17})})]}),r.jsx("h2",{id:"client-hub-switch-title",children:Ke.title}),r.jsx("p",{id:"client-hub-switch-description",children:Ke.description}),r.jsxs("p",{id:"client-hub-switch-restart",className:"client-hub-switch-notice",children:[r.jsx(jn,{size:16,"aria-hidden":"true"}),r.jsx("span",{children:Ke.restartNotice})]}),r.jsxs("div",{className:"client-hub-switch-actions",children:[r.jsx("button",{type:"button",onClick:()=>Be(),children:Ke.cancel}),r.jsxs("button",{ref:O,className:"primary",type:"button",onClick:()=>{et()},disabled:w||!n?.authenticated,children:[r.jsx(mr,{size:16}),Ke.confirm]})]})]}),q&&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:Ae&&ue?r.jsx("img",{src:ue,alt:re,referrerPolicy:"no-referrer"}):Ae?r.jsx("span",{children:K}):r.jsx(Ol,{size:18})}),r.jsxs("div",{children:[r.jsx("strong",{children:Ae?re:"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":Ae?"Active for this run":"Not saved"}),r.jsx("dt",{children:"Role"}),r.jsx("dd",{children:"Client"})]}),Ae?r.jsxs("button",{className:"account-popover-action",onClick:()=>{Ue()},type:"button",children:[r.jsx(Fb,{size:16}),"Logout"]}):r.jsxs("button",{className:"account-popover-action primary",onClick:()=>{Q(!1),xe()},type:"button",children:[r.jsx(Ol,{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(Hl,{size:18})}),r.jsxs("div",{children:[r.jsx("h1",{children:"LiveDesk"}),r.jsx("p",{children:"Client workspace"})]})]})}),Z==="support"?r.jsx("section",{className:"client-unified-page",children:r.jsx(Xb,{session:i,currentProductKey:"livedesk",appVersion:n?.appVersion||"",onSignIn:()=>{xe()}})}):Z!=="computer"?r.jsx("section",{className:"client-unified-page",children:r.jsx(CC,{page:Z,status:n})}):r.jsx(kC,{session:i,status:n,pin:m,error:g,roleChangeMessage:x,videoAccelerationBusy:j,slotInput:M,slotBusy:T,onSignIn:()=>{xe()},onPinChange:de=>p(de.replace(/\D/g,"").slice(0,6)),onSubmitPin:()=>{Xe()},onSlotInputChange:de=>{V.current=!0,A(de.replace(/\D/g,"").slice(0,3))},onSaveSlot:()=>{ce()},onEnableVideoAcceleration:()=>{ge()}})]}),B&&r.jsxs("div",{className:`client-side-toast ${B.kind}`,role:B.kind==="error"?"alert":"status",children:[B.kind==="error"?r.jsx(Bb,{size:18}):r.jsx(Dn,{size:18}),r.jsx("span",{children:B.message}),r.jsx("button",{type:"button",onClick:()=>H(null),"aria-label":"Dismiss notification",children:r.jsx(la,{size:16})})]})]})}function Pi(n,a,i){if(i<0||a<0||a+i>n.length)throw new Error("Invalid LZO1X block: input overrun.")}function qm(n,a,i){let l=0;for(;Pi(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 gd(n,a,i,l){if(Pi(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 AC(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 rx(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,gd(n,l,i,m),c=4}else n[l.inputIndex]>=18&&(c=n[l.inputIndex]-17,l.inputIndex+=1,gd(n,l,i,c));for(;;){Pi(n,l.inputIndex,1);const m=n[l.inputIndex];l.inputIndex+=1;let p,g;if((m&192)!==0)Pi(n,l.inputIndex,1),g=l.outputIndex-((n[l.inputIndex]<<3)+(m>>2&7)+1),l.inputIndex+=1,d=(m>>5)+1,p=m&3;else if((m&32)!==0){d=(m&31)+2,d===2&&(d+=qm(n,l,31)),Pi(n,l.inputIndex,2);const v=n[l.inputIndex]|n[l.inputIndex+1]<<8;l.inputIndex+=2,g=l.outputIndex-((v>>2)+1),p=v&3}else if((m&16)!==0){d=(m&7)+2,d===2&&(d+=qm(n,l,7)),Pi(n,l.inputIndex,2);const v=n[l.inputIndex]|n[l.inputIndex+1]<<8;if(l.inputIndex+=2,g=l.outputIndex-(((m&8)<<11)+(v>>2)),p=v&3,g===l.outputIndex)break;g-=16384}else if(c===0){let v=m+3;v===3&&(v+=qm(n,l,15)),gd(n,l,i,v),c=4;continue}else c!==4?(Pi(n,l.inputIndex,1),p=m&3,g=l.outputIndex-((m>>2)+(n[l.inputIndex]<<2)+1),l.inputIndex+=1,d=2):(Pi(n,l.inputIndex,1),p=m&3,g=l.outputIndex-((m>>2)+(n[l.inputIndex]<<2)+2049),l.inputIndex+=1,d=3);if(g<0||l.outputIndex+d+p>i.length)throw new Error("Invalid LZO1X block: lookbehind overrun.");l.outputIndex=AC(i,l.outputIndex,g,d),c=p,gd(n,l,i,p)}if(d!==3||l.inputIndex!==n.length||l.outputIndex!==i.length)throw new Error("Invalid LZO1X block: incomplete output.");return i}const hy=16,py=8,NC=24*1024*1024,ix=new Uint8Array(new Uint32Array([16909060]).buffer)[0]===4,jh=new Uint32Array(65536);for(let n=0;n<jh.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);jh[n]=ix?(a|i<<8|l<<16|4278190080)>>>0:(a<<24|i<<16|l<<8|255)>>>0}function Bi(n,a){return n[a]|n[a+1]<<8}function MC(n,a){const i=Number(a);if(!Number.isSafeInteger(i)||i<hy||i>NC)throw new Error(`Invalid Mode 5 packet length: ${a}.`);const l=n instanceof Uint8Array?n:new Uint8Array(n),c=rx(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=Bi(c,6),p=Bi(c,8),g=Bi(c,10),v=Bi(c,12);if(m<=0||p<=0||m>3840||p>2160)throw new Error(`Invalid Mode 5 frame size: ${m}x${p}.`);if(g<=0||g>256||v>8192)throw new Error(`Invalid Mode 5 tile header: ${g}/${v}.`);const x=[];let b=hy;for(let w=0;w<v;w+=1){if(b+py>c.length)throw new Error("Mode 5 tile header is truncated.");const C=Bi(c,b),j=Bi(c,b+2),k=Bi(c,b+4),M=Bi(c,b+6);b+=py;const A=k*M*2;if(k<=0||M<=0||k>g||M>g||C+k>m||j+M>p||b+A>c.length)throw new Error(`Invalid Mode 5 tile ${w}.`);x.push({x:C,y:j,width:k,height:M,pixels:c.subarray(b,b+A)}),b+=A}if(b!==c.length)throw new Error(`Mode 5 packet has ${c.length-b} trailing bytes.`);return{keyFrame:d,width:m,height:p,tileSize:g,tiles:x}}function TC(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,p=0;const g=new Uint32Array(n.buffer,n.byteOffset,n.byteLength>>>2);for(const v of l.tiles){const x=ix&&(v.pixels.byteOffset&1)===0?new Uint16Array(v.pixels.buffer,v.pixels.byteOffset,v.pixels.byteLength>>>1):null;let b=0;for(let w=0;w<v.height;w+=1){let C=(v.y+w)*a+v.x;for(let j=0;j<v.width;j+=1){const k=b<<1,M=x?x[b]:v.pixels[k]|v.pixels[k+1]<<8;g[C]=jh[M],b+=1,C+=1}}c=Math.min(c,v.x),d=Math.min(d,v.y),m=Math.max(m,v.x+v.width),p=Math.max(p,v.y+v.height)}return l.tiles.length>0?{x:c,y:d,width:m-c,height:p-d}:null}const ha=new WeakMap,Jc=new WeakMap,Ah=new WeakMap,eu=new Set,zl=new Set,Fo=new WeakMap,_o=new Set,tu=new WeakMap,Nh=new WeakMap,Mh=new WeakMap,Vd=new WeakMap,lx=4,EC=2,RC=2,DC=2,LC=18,_C=40,IC=0,zC=250,ox=80,gy=5,OC=150,HC=1200,FC=18,BC=.65,PC=2e3,$C=500,Wh=250,UC=globalThis.LIVEDESK_ENABLE_CANVAS_VISUAL_SAMPLING===!0;let cx=1,ux=0,dx=0,fx=0,mx,hx,ti={h264DecodeAcceleration:"prefer-hardware"};function qC(n){n.h264DecodeAcceleration&&(ti={...ti,h264DecodeAcceleration:n.h264DecodeAcceleration})}function Th(n,a=ti.h264DecodeAcceleration){const i=Fo.get(n);return i?.requested===a?(i.actual!=="prefer-hardware"&&(zl.delete(n),_o.add(n)),i.actual):(i&&(Fo.delete(n),_o.delete(n)),a!=="prefer-hardware"?(zl.delete(n),_o.delete(n),a):(zl.has(n)||zl.add(n),"prefer-hardware"))}function Yh(n,a,i){if(a!=="prefer-hardware")return!1;const l=Fo.get(n),c=ha.get(n),d=Date.now();return tu.has(n)||tu.set(n,cx++),Fo.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}),zl.delete(n),_o.add(n),fx+=1,mx=i,hx=d,!0}function GC(n,a,i,l=64){try{let c=Nh.get(n);c||(c={canvas:document.createElement("canvas"),lastHash:"",initialized:!1},Nh.set(n,c));const d=Math.max(8,Math.min(64,Math.round(l))),m=Math.max(1,Math.round(d*Math.max(1,i)/Math.max(1,a)));(c.canvas.width!==d||c.canvas.height!==m)&&(c.canvas.width=d,c.canvas.height=m);const p=c.canvas.getContext("2d",{willReadFrequently:!0});if(!p)return{visualHash:"",visualChanged:!0};p.drawImage(n,0,0,Math.max(1,a),Math.max(1,i),0,0,d,m);const g=p.getImageData(0,0,d,m).data;let v=2166136261;for(let w=0;w<g.length;w+=4)v^=g[w],v=Math.imul(v,16777619),v^=g[w+1],v=Math.imul(v,16777619),v^=g[w+2],v=Math.imul(v,16777619);const x=(v>>>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 Eh(n,a,i,l=Wh,c=64,d){if(!UC&&d)return px(n,d);let m=Mh.get(n);m||(m={lastHash:"",initialized:!1,lastCanvasSampleAt:0},Mh.set(n,m));const p=performance.now();if(m.initialized&&l>0&&p-m.lastCanvasSampleAt<l)return{visualHash:m.lastHash,visualChanged:!1};const g=GC(n,a,i,c);return m.initialized=!0,m.lastHash=g.visualHash,m.lastCanvasSampleAt=p,g}function px(n,a){let i=Vd.get(n);i||(i={lastHash:"",initialized:!1},Vd.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 gx(n,a){const i=Ah.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 Ah.set(n,d),d}return null}function VC(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 WC(n){return String(n.frameMode||n.mode||"").toLowerCase()==="mode3-h264-hw"||String(n.codec||"").toLowerCase()==="h264"||String(n.mimeType||"").toLowerCase()==="video/h264"}function YC(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 vy(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 KC(n,a){const i=new Uint8Array(a);let l=0,c=0;for(;l<n.length;){const d=n[l];l+=1;const m=vy(n,l,d>>4);l=m.cursor;const p=m.length;if(l+p>n.length||c+p>i.length)throw new Error("Invalid LZ4 block: literal overrun.");if(i.set(n.subarray(l,l+p),c),l+=p,c+=p,l>=n.length)break;if(l+2>n.length)throw new Error("Invalid LZ4 block: missing offset.");const g=n[l]|n[l+1]<<8;if(l+=2,g<=0||g>c)throw new Error("Invalid LZ4 block: bad match offset.");const v=vy(n,l,d&15);l=v.cursor;const x=v.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 XC(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 C=rx(n.payload,b),j=new Uint8ClampedArray(a*i*4);for(let k=0,M=0;k<C.length;k+=2,M+=4){const A=C[k]|C[k+1]<<8,T=A>>11&31,D=A>>5&63,B=A&31;j[M]=T<<3|T>>2,j[M+1]=D<<2|D>>4,j[M+2]=B<<3|B>>2,j[M+3]=255}return new ImageData(j,a,i)}const m=Math.max(1,Math.floor(n.bytesPerPixel||4)),p=Math.max(a*i*m,Math.floor(n.uncompressedByteLength||0)),g=KC(n.payload,p);if(m!==4)throw new Error(`Unsupported mode2 pixel size: ${m}`);const v=new Uint8ClampedArray(a*i*4);if(c==="rgba32"||c==="rgba")v.set(g.subarray(0,v.length));else for(let x=0,b=0;b<v.length;x+=4,b+=4)v[b]=g[x+2],v[b+1]=g[x+1],v[b+2]=g[x],v[b+3]=g[x+3];return new ImageData(v,a,i)}function yy(n,a="smooth",i=ti.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&&ws(n);let d;const m=new l({output:p=>{if(ha.get(n)!==d){p.close();return}const g=Number(p.timestamp||0);d.outputSerial+=1;let v=d.pendingFrames.get(g);if(v)d.pendingFrames.delete(g);else if(d.pendingFrames.size>0){const k=d.pendingFrames.entries().next().value;k&&(d.pendingFrames.delete(k[0]),v=k[1],d.timestampFallbacks+=1)}const x=p.displayWidth||p.codedWidth||n.width||960,b=p.displayHeight||p.codedHeight||n.height||540,w=Number(v?.frame.durationUs||0),C=Number(p.duration||0),j=Math.max(16,Math.min(250,(w>0?w:C||83333)/1e3));for(d.targetPaintIntervalMs=j,d.decodedFrames.push({videoFrame:p,pending:v,decodedAt:performance.now(),width:x,height:b,durationMs:j}),d.lastOutputAt=performance.now();d.decodedFrames.length>Kh(d);)Wd(d,d.decodedFrames.shift());yx(d),d.renderTimer!==null&&d.renderScheduledAt>0&&performance.now()-d.renderScheduledAt>$C&&(typeof document>"u"||document.visibilityState==="visible")&&(window.cancelAnimationFrame(d.renderTimer),d.renderTimer=null,d.renderScheduledAt=0),d.renderTimer!==null&&d.decodedFrames.length>=lx&&(window.cancelAnimationFrame(d.renderTimer),d.renderTimer=null,d.renderScheduledAt=0),Yd(n,d)},error:()=>{ha.get(n)===d&&(Yh(n,d.requestedAcceleration,"decoder-error"),ws(n))}});return ux+=1,tu.has(n)||tu.set(n,cx++),d={decoder:m,configured:!1,configKey:"",codec:"",requestedAcceleration:i,hardwareAcceleration:Th(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),eu.add(n),d}function vx(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 Wd(n,a){a&&(a.videoFrame.close(),n.droppedForLatency+=1)}function Kh(n){return n.latencyMode==="interactive"?RC:String(n.decodedFrames[0]?.pending?.frame.frameMode||n.decodedFrames[0]?.pending?.frame.mode||"").toLowerCase()==="mode4-h264-atlas"?EC:lx}function yx(n,a=performance.now()){const i=Kh(n);for(;n.decodedFrames.length>i;)Wd(n,n.decodedFrames.shift());const l=n.latencyMode==="interactive"?ox:zC;let c=n.decodedFrames[0];for(;n.decodedFrames.length>1&&c?.pending&&a-c.pending.queuedAt>l;)Wd(n,n.decodedFrames.shift()),c=n.decodedFrames[0]}function bx(n,a){if(a.hardwareAcceleration!=="prefer-hardware"||a.latencyMode==="interactive"||a.flushTimer!==null||a.flushInFlight)return;const i=OC;a.flushTimer=window.setTimeout(async()=>{a.flushTimer=null;const l=performance.now();for(const[d,m]of a.pendingFrames.entries())l-m.queuedAt>PC&&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&&Fd(a)}finally{a.flushInFlight=!1,ha.get(n)===a&&a.inputSerial>c&&a.pendingFrames.size>0&&performance.now()-a.lastOutputAt>=i&&bx(n,a)}},i)}function by(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=gx(n,a.latencyMode);if(c?.context.drawImage(i.videoFrame,0,0,i.width,i.height),i.pending){const d=performance.now(),p=a.latencyMode==="interactive"?px(n,i.pending.frame):Eh(n,i.width,i.height,Wh,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:p.visualHash,visualChanged:p.visualChanged,paintedAt:d})}catch{}}a.lastPaintAt=performance.now()}finally{i.videoFrame.close()}}function Yd(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(yx(a,c),a.decodedFrames.length===0)return;if(a.latencyMode==="interactive"){const g=a.targetPaintIntervalMs<=_C,v=a.targetPaintIntervalMs<=20;if(v&&!a.interactiveBufferPrimed){a.interactiveBufferStartedAt<=0&&(a.interactiveBufferStartedAt=c,a.interactiveBufferWaitCount+=1);const k=a.decodedFrames.length>=DC,M=c-a.interactiveBufferStartedAt>=LC;if(!k&&!M){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}a.interactiveBufferWaitMs+=Math.max(0,c-a.interactiveBufferStartedAt),a.interactiveBufferPrimed=!0}else v||(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+gy>=w||b>=ox)){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}const j=a.decodedFrames.shift();if(j)try{by(n,a,j)}catch{}a.decodedFrames.length===0&&(a.interactiveQueueDrainCount+=1,a.interactiveBufferPrimed=!1,a.interactiveBufferStartedAt=0),Yd(n,a);return}const d=a.lastPaintAt>0?a.lastPaintAt+i:c+IC;if(!(c+gy>=d||a.decodedFrames.length>=Math.max(1,Kh(a)-1))){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}const p=a.decodedFrames.shift();if(p)try{by(n,a,p)}catch{}Yd(n,a)};a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l)}function xx(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;)Wd(a,a.decodedFrames.shift());return a.lastPaintAt=0,a.interactiveBufferPrimed=!1,a.interactiveBufferStartedAt=0,Yd(n,a),!0}function Gm(){if(!(typeof document>"u"||document.visibilityState!=="visible"))for(const n of eu){const a=ha.get(n);if(!a||a.decoder.state==="closed"){eu.delete(n);continue}xx(n,a)}}typeof document<"u"&&typeof window<"u"&&(document.addEventListener("visibilitychange",Gm),window.addEventListener("focus",Gm),window.addEventListener("pageshow",Gm));function ws(n){zl.delete(n),eu.delete(n),Vd.delete(n);const a=ha.get(n);if(a){ha.delete(n),dx+=1;try{vx(a),a.decoder.state!=="closed"&&a.decoder.close()}catch{}}}function Ao(n){n&&(Fo.delete(n),_o.delete(n),Ah.delete(n),Mh.delete(n),Nh.delete(n),Vd.delete(n),Jc.delete(n),ws(n))}function QC(n,a){const i=ha.get(n),l=Fo.get(n);if(!i&&!l)return null;const c=d=>d>0?Math.max(0,a-d):void 0;return{canvasId:tu.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||ti.h264DecodeAcceleration,configuredAcceleration:i?.hardwareAcceleration||l?.actual||ti.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 xy(n){const a=performance.now(),l=(n?[n]:[...new Set([...eu,..._o])]).map(c=>QC(c,a)).filter(c=>c!==null);return{capturedAt:Date.now(),hardwareRequestPolicy:"all-active",activeDecoderCount:l.filter(c=>c.decoderState!=="fallback-pending").length,hardwareLeaseCount:zl.size,activeSoftwareFallbackCount:l.filter(c=>c.configuredAcceleration==="prefer-software"&&c.requestedAcceleration==="prefer-hardware").length,decoderCreateCount:ux,decoderCloseCount:dx,softwareFallbackEventCount:fx,lastSoftwareFallbackReason:mx,lastSoftwareFallbackAt:hx,canvases:l}}function Fd(n,a=1){try{n.decoder.state!=="closed"&&n.decoder.reset()}catch{}n.configured=!1,n.configKey="",n.keyFrameSeen=!1,n.pendingFrames.clear(),vx(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 ZC(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 JC(n,a){if(a.latencyMode!=="interactive"||a.hardwareAcceleration!=="prefer-hardware")return!1;const i=performance.now();if(i-a.healthSampleStartedAt<HC)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<FC||c/Math.max(1,l)>=BC?!1:(Yh(n,a.requestedAcceleration,"interactive-health"),ws(n),!0)}function Hc(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))),ws(n),!0):!1}function e1(n){if(!n)return!1;const a=ha.get(n);return a?xx(n,a):!1}function t1(n,a,i,l="interactive"){ws(n);const c=performance.now(),d=MC(a.payload,a.uncompressedByteLength||0),m=String(a.streamId||"mode5");let p=Jc.get(n);if(!p||p.streamId!==m||p.width!==d.width||p.height!==d.height){const k=new Uint8ClampedArray(d.width*d.height*4);for(let M=3;M<k.length;M+=4)k[M]=255;p={streamId:m,width:d.width,height:d.height,rgba:k,imageData:new ImageData(k,d.width,d.height),keyFrameSeen:!1,inputSerial:0,outputSerial:0},Jc.set(n,p)}if(!p)throw new Error("Mode 5 canvas state could not be initialized.");p.inputSerial+=1;const v=Number(a.streamFrameSeq||0);if(v>0&&(p.lastStreamFrameSeq=v),!d.keyFrame&&!p.keyFrameSeen)return;d.keyFrame&&(p.keyFrameSeen=!0);const x=TC(p.rgba,p.width,p.height,d),b=performance.now();(n.width!==p.width||n.height!==p.height)&&(n.width=p.width,n.height=p.height);const w=gx(n,l),C=performance.now();x&&w?.context.putImageData(p.imageData,0,0,x.x,x.y,x.width,x.height);const j=performance.now();p.outputSerial+=1,i?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.mimeType,width:p.width,height:p.height,byteLength:a.byteLength,queuedForMs:Math.max(0,j-c),decodedForMs:Math.max(0,b-c),scheduledForMs:0,drawMs:Math.max(0,j-C),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:"prefer-software",decoderLabel:"lzo-rgb565-delta",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:p.inputSerial,decoderOutputCount:p.outputSerial,targetPaintIntervalMs:Math.max(1,Number(a.durationUs||0)/1e3||1e3/30),canvasPresentation:w?.presentation||"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:String(a.contentHash||""),visualChanged:Number(a.deltaVisualTileCount||0)>0,paintedAt:j})}const Vm=[{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 wy(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 n1(n){let a=0;for(;a<n.length;){const i=wy(n,a);if(!i)break;const l=i.index+i.length,c=wy(n,l),d=c?.index??n.length;if(l<d&&(n[l]&31)===7){const m=[];let p=0;for(let g=l+1;g<d;g+=1){const v=n[g];if(p>=2&&v===3){p=0;continue}m.push(v),p=v===0?p+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 a1(n,a,i,l,c=""){const d=Math.ceil(n/16)*Math.ceil(a/16),m=i>0?1e6/i:30,p=d*m,g=Vm.find(v=>d<=v.maxFrameSize&&p<=v.maxMacroblocksPerSecond)||Vm[Vm.length-1];return n1(l)||c||`avc1.42E0${g.code.toString(16).toUpperCase().padStart(2,"0")}`}function wx(n,a,i,l,c="smooth",d=!0){Jc.delete(n);const m=String(a.h264Format||"").toLowerCase()==="avc"?"avc":"annexb",p=Math.max(1,Math.floor(a.width||960)),g=Math.max(1,Math.floor(a.height||540)),v=Math.max(1,Math.floor(a.durationUs||1e6/12)),x=l||ti.h264DecodeAcceleration;let b=yy(n,c,x);const w=a1(p,g,v,a.payload,b.codec),C=a.isKeyFrame===!0||String(a.chunkType||"").toLowerCase()==="key";let j=Th(n,x),k="";const M=()=>{k=[a.streamId||"",a.commandId||"",p,g,w,m,x,j,c].join("|")};M(),b.onPaint=i,b.configured&&b.decoder.state!=="configured"&&(b.configured=!1,b.configKey=""),b.configured&&b.configKey!==k&&(ws(n),b=yy(n,c,x),b.onPaint=i,j=Th(n,x),M());const A=()=>({codec:w,codedWidth:p,codedHeight:g,hardwareAcceleration:j,optimizeForLatency:!0,avc:{format:m}}),T=Z=>b.hardwareAcceleration!=="prefer-hardware"||!Yh(n,b.requestedAcceleration,Z)?!1:(ws(n),d&&C&&wx(n,a,i,x,c,!1),!0),D=()=>{try{return ZC(b,A(),k,j,x),!0}catch(Z){if(T("configure-error"))return!1;throw ws(n),Z}};if(!b.configured&&!D())return;const B=Number(a.streamFrameSeq||0);if(B>0&&b.lastInputFrameSeq!==void 0&&(B<=b.lastInputFrameSeq&&(!C||B===b.lastInputFrameSeq||(Fd(b,b.lastInputFrameSeq-B+1),!D()))||B>b.lastInputFrameSeq+1&&(Fd(b,B-b.lastInputFrameSeq-1),!C||!D()))||(B>0&&(b.lastInputFrameSeq=B),!C&&!b.keyFrameSeen))return;C&&(b.keyFrameSeen=!0);const H=Number(b.decoder.decodeQueueSize||0);if(H>8){if(b.latencyMode==="interactive"&&b.hardwareAcceleration==="prefer-hardware"){T("decode-queue-overflow");return}if(Fd(b),!C||!D())return;b.keyFrameSeen=!0}const W=b.nextChunkTimestampUs;b.nextChunkTimestampUs+=v,b.pendingFrames.set(W,{frame:a,queuedAt:performance.now(),queueSize:H}),b.inputSerial+=1,b.lastInputAt=performance.now();const _=new EncodedVideoChunk({type:C?"key":"delta",timestamp:W,duration:v,data:a.payload});try{b.decoder.decode(_)}catch(Z){if(T("decode-error"))return;throw ws(n),Z}bx(n,b),JC(n,b)}async function Wm(n,a,i,l,c,d="smooth"){if(YC(a)){i()||t1(n,a,l,d);return}if(WC(a)){i()||wx(n,a,l,c,d);return}if(Jc.delete(n),VC(a)){ws(n);const b=XC(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"),C=performance.now();w?.putImageData(b,0,0);const j=performance.now(),k=Eh(n,b.width,b.height,Wh,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-C),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:ti.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}ws(n);const m=new Blob([a.payload],{type:a.mimeType}),p=await createImageBitmap(m);if(i()){p.close();return}const g=a.width||p.width||960,v=a.height||p.height||540;(n.width!==g||n.height!==v)&&(n.width=g,n.height=v);const x=n.getContext("2d");if(x){const b=performance.now();x.clearRect(0,0,g,v),x.drawImage(p,0,0,g,v);const w=performance.now(),C=Eh(n,g,v);l?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.codec||a.mimeType,width:g,height:v,byteLength:a.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,w-b),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:ti.h264DecodeAcceleration,decoderLabel:"image",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:C.visualHash,visualChanged:C.visualChanged,paintedAt:w})}p.close()}const Sy="livedesk_remote_host_targets",s1="livedesk_entitlements",Xh=new TextDecoder;function r1(n){const i=(Array.isArray(n)?n:[n||fn]).map(l=>Ki(l||fn));return[...new Set(i.filter(Boolean))]}function i1(){const[n,a]=u.useState(null),[i,l]=u.useState(!0);return u.useEffect(()=>{let c=!0;const d=window.liveDesk?.auth?.onComplete?.(p=>{p.ok&&p.session&&ft.auth.setSession(p.session)});(window.liveDesk?.auth?.getSession?.()||ft.auth.getSession()).then(p=>{c&&(a(Qb(p)),l(!1))});const{data:{subscription:m}}=ft.auth.onAuthStateChange((p,g)=>{a(g),l(!1),window.liveDesk?.auth?.persistSession?.(g)});return()=>{c=!1,d?.(),m.unsubscribe()}},[]),{session:n,loading:i}}function l1(n,a=!0){const[i,l]=u.useState(null),[c,d]=u.useState([]),[m,p]=u.useState(""),[g,v]=u.useState(""),[x,b]=u.useState(0),w=u.useRef(new Map),C=Array.isArray(n)?n.join(`
12
+ `):String(n||""),j=u.useMemo(()=>r1(n),[C]),k=u.useMemo(()=>j.find(T=>Wc(T)==="loopback")||j[0]||fn,[j]),M=u.useCallback(async()=>{if(!a){l(null),d([]),v(""),p("");return}let T=null;const D=Date.now(),B=j.filter(H=>(w.current.get(H)||0)<=D);if(B.length===0)throw new Error("No LiveDesk Hub endpoint is reachable. Retrying shortly.");for(const H of B)try{const[W,_]=await Promise.all([Ye("/api/remote/status",void 0,H),Ye("/api/remote/devices",void 0,H)]);if(!Array.isArray(_.devices))throw new Error("Invalid Hub devices response.");w.current.delete(H),l(W),d(_.devices),v(H),p("");return}catch(W){T=W,w.current.set(H,Date.now()+1e4)}throw v(""),T||new Error("No LiveDesk Hub endpoint is reachable.")},[a,j]),A=u.useCallback(()=>{w.current.clear(),M().catch(T=>{p(T instanceof Error?T.message:String(T))}),b(T=>T+1)},[M]);return u.useEffect(()=>{if(!a){l(null),d([]),v(""),p("");return}let T=!0;const D=async()=>{try{await M()}catch(H){T&&p(H instanceof Error?H.message:String(H))}};D();const B=window.setInterval(D,2500);return()=>{T=!1,window.clearInterval(B)}},[a,M,x]),{status:i,devices:c,error:m,refresh:A,hubBaseUrl:g||k,hubCandidates:j}}function o1(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:p,error:g}=await ft.from(Sy).select("*").eq("user_id",d).maybeSingle();if(g){c(g.message);return}i(p),c("")},[d]);return u.useEffect(()=>{m()},[m]),u.useEffect(()=>{if(!d)return;const p=ft.channel(`livedesk-remote-host-targets-${d.replace(/[^a-zA-Z0-9]/g,"")}`).on("postgres_changes",{event:"*",schema:"public",table:Sy,filter:`user_id=eq.${d}`},g=>i(g.new)).subscribe();return()=>{ft.removeChannel(p)}},[d]),{target:a,error:l,refresh:m}}function c1(n){const[a,i]=u.useState(null),[l,c]=u.useState(!1),[d,m]=u.useState(""),p=n?.user?.id||"",g=u.useCallback(async()=>{if(!p){i(null),m(""),c(!1);return}c(!0);const{data:x,error:b}=await ft.from(s1).select("*").eq("user_id",p).eq("product_key","livedesk").maybeSingle();if(b){m(b.message),c(!1);return}i(x),m(""),c(!1)},[p]);u.useEffect(()=>{g()},[g]);const v=u.useMemo(()=>!a||a.status!=="active"?!1:a.expires_at?new Date(a.expires_at).getTime()>Date.now():!0,[a]);return{entitlement:a,licensed:v,loading:l,error:d,refresh:g}}const Yc={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},u1=2500,d1=3e4,f1=64*1024,m1=6,h1=m1,Sx=new Map;function p1(n){return Sx.get(n)}const Cy={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function g1(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>d1?(n.minimumHubClockOffsetMs=c,0):m}function vd(n){if(n==null||n==="")return;const a=Number(n);return Number.isFinite(a)?a:void 0}function ky(n,a,i=fn,l={}){const[c,d]=u.useState(new Map),[m,p]=u.useState("idle"),[g,v]=u.useState(""),[x,b]=u.useState(Yc),w=u.useRef(new Map),C=u.useRef(new Map),j=u.useRef(0),k=u.useRef(new Map),M=u.useRef({enabled:!1,token:"",reason:""}),A=u.useRef(new Set),[T,D]=u.useState(0),B=u.useRef(l.onFrame),H=u.useRef(l.onStreamReady),W=u.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),_=u.useMemo(()=>[...n].sort().join(","),[n]),Z=Number.isFinite(l.fps)?Number(l.fps):2,G=Number.isFinite(l.maxWidth)?Number(l.maxWidth):640,q=Number.isFinite(l.maxHeight)?Number(l.maxHeight):360,Q=Number.isFinite(l.quality)?Number(l.quality):45,O=String(l.frameMode||l.mode||"mode3-h264-hw").trim()||"mode3-h264-hw",ye=l.streamPurpose==="control"?"control":"wall",me=l.forceRestart===!0,X=String(l.forceRestartToken||"").trim(),I=String(l.restartReason||"").trim();M.current={enabled:me,token:X,reason:I};const ee=u.useMemo(()=>{const z=Object.entries(l.monitorSelections||{}).filter(([le])=>!!le).sort(([le],[ke])=>le.localeCompare(ke));return JSON.stringify(Object.fromEntries(z))},[l.monitorSelections]);u.useEffect(()=>{B.current=l.onFrame},[l.onFrame]),u.useEffect(()=>{H.current=l.onStreamReady},[l.onStreamReady]);const V=u.useCallback((z,le="livedesk-frame-socket-release")=>{z.disposed=!0;try{z.socket.readyState===WebSocket.CONNECTING||z.socket.readyState===WebSocket.OPEN?z.socket.close(1e3,le):z.socket.close()}catch{}},[]),P=u.useCallback(()=>{const z=[...C.current.values()].map(le=>le.socket);if(z.length===0){p("idle");return}if(z.some(le=>le.readyState===WebSocket.OPEN)){p("open");return}if(z.some(le=>le.readyState===WebSocket.CONNECTING)){p("connecting");return}p("closed")},[]),re=u.useCallback((z,le,ke,Ce)=>{if(le.disposed||le.socket.readyState!==WebSocket.OPEN)return!1;try{return le.socket.send(JSON.stringify({...le.payload,type:"restart-live",deviceIds:[z],forceRestart:!0,restartReason:ke,restartToken:Ce})),!0}catch{return!1}},[]),ue=u.useCallback((z,le)=>{if(!z||z.byteLength<5)return;const ke=Date.now(),Ue=new DataView(z).getUint32(0,!1);if(Ue<=0||Ue+4>z.byteLength)return;const Be=new Uint8Array(z,4,Ue),he=JSON.parse(Xh.decode(Be)),Xe=vd(he.hubPacketEpochMs),et=Xe!==void 0&&Xe>0?Xe:void 0,ce=g1(le,et,ke);if(ce>u1)return;const ge=new Uint8Array(z,4+Ue),Ae={deviceId:String(he.deviceId||""),kind:he.kind==="thumbnail"?"thumbnail":"live",frameSeq:Number(he.frameSeq||0),streamFrameSeq:Number(he.streamFrameSeq||0)||void 0,streamId:String(he.streamId||""),commandId:he.commandId?String(he.commandId):void 0,sessionId:he.sessionId?String(he.sessionId):void 0,captureGeneration:Number(he.captureGeneration||0)||void 0,streamPurpose:he.streamPurpose?String(he.streamPurpose):void 0,width:Number(he.width||0),height:Number(he.height||0),sourceWidth:Number(he.sourceWidth||0)||void 0,sourceHeight:Number(he.sourceHeight||0)||void 0,mimeType:String(he.mimeType||"image/jpeg"),mode:he.mode?String(he.mode):void 0,frameMode:he.frameMode?String(he.frameMode):void 0,frameProfile:he.frameProfile?String(he.frameProfile):void 0,encoding:he.encoding?String(he.encoding):void 0,codec:he.codec?String(he.codec):void 0,compression:he.compression?String(he.compression):void 0,pixelFormat:he.pixelFormat?String(he.pixelFormat):void 0,bytesPerPixel:Number(he.bytesPerPixel||0)||0,uncompressedByteLength:Number(he.uncompressedByteLength||0)||0,h264Format:he.h264Format?String(he.h264Format):void 0,isKeyFrame:he.isKeyFrame===!0,chunkType:he.chunkType?String(he.chunkType):void 0,timestampUs:Number(he.timestampUs||0)||0,durationUs:Number(he.durationUs||0)||0,sourceGapMs:Number(he.sourceGapMs||0)||0,agentSendGapMs:Number(he.agentSendGapMs||0)||0,agentSendDurationMs:Number(he.agentSendDurationMs||0)||0,agentSendDurationFrameSeq:Number(he.agentSendDurationFrameSeq||0)||0,agentPaceMs:Number(he.agentPaceMs||0)||0,agentQueueBeforePaceMs:Number(he.agentQueueBeforePaceMs||0)||0,agentFrameAgeMs:Number(he.agentFrameAgeMs||0)||0,droppedByAgent:Number(he.droppedByAgent||0)||0,hubIngressDropped:Number(he.hubIngressDropped||0)||0,hubClientDropped:Number(he.hubClientDropped||0)||0,hardwareEncoder:he.hardwareEncoder?String(he.hardwareEncoder):void 0,platformProfile:he.platformProfile?String(he.platformProfile):void 0,monitorIndex:Number.isFinite(Number(he.monitorIndex))?Number(he.monitorIndex):void 0,monitorCount:Number.isFinite(Number(he.monitorCount))?Number(he.monitorCount):void 0,requestedFps:Number(he.requestedFps||0)||0,effectiveFps:Number(he.effectiveFps||0)||0,captureAverageMs:vd(he.captureAverageMs),captureP95Ms:vd(he.captureP95Ms),slowFrameCount:Number(he.slowFrameCount||0)||0,captureHelperRestarts:Number(he.captureHelperRestarts||0)||0,capturedAt:String(he.capturedAt||""),receivedAt:String(he.receivedAt||""),hubPacketAt:he.hubPacketAt?String(he.hubPacketAt):void 0,hubPacketEpochMs:et,browserReceivedEpochMs:ke,hubPacketTransitAgeMs:et!==void 0?ce:void 0,byteLength:Number(he.byteLength||ge.byteLength),contentHash:he.contentHash?String(he.contentHash):void 0,captureMs:Number(he.captureMs||0)||0,captureStageMs:vd(he.captureStageMs),convertMs:Number(he.convertMs||0)||0,compressMs:Number(he.compressMs||0)||0,captureSourceSerial:Number(he.captureSourceSerial||0)||0,captureSourceSkipped:Number(he.captureSourceSkipped||0)||0,deltaTileSize:Number(he.deltaTileSize||0)||0,deltaTileCount:Number(he.deltaTileCount||0)||0,deltaVisualTileCount:Number(he.deltaVisualTileCount||0)||0,deltaRefreshTileCount:Number(he.deltaRefreshTileCount||0)||0,deltaTotalTiles:Number(he.deltaTotalTiles||0)||0,payload:ge};if(!Ae.deviceId)return;const Le={streamId:le.lastFrameStreamId,commandId:le.lastFrameCommandId,order:le.lastFrameOrder},Pe=Number(Ae.streamFrameSeq||Ae.frameSeq||0),Ve=!!Le.commandId&&!!Ae.commandId,Ke=Le.streamId===Ae.streamId&&(!Ve||Le.commandId===Ae.commandId),de=Le.order;if(Ke&&de>=Pe&&(de===Pe||Ve))return;le.lastFrameStreamId=Ae.streamId,le.lastFrameCommandId=Ae.commandId||"",le.lastFrameOrder=Pe;const je=W.current;je.totalFrames+=1,je.totalBytes+=ge.byteLength,je.sampleFrames+=1,je.sampleBytes+=ge.byteLength;const fe=!w.current.has(Ae.deviceId);w.current.set(Ae.deviceId,Ae),fe&&d(new Map(w.current)),B.current?.(Ae)},[]);u.useEffect(()=>{const z=window.setInterval(()=>{const le=performance.now(),ke=W.current,Ce=Math.max(1,le-ke.sampleStartedAt);b({totalFrames:ke.totalFrames,totalBytes:ke.totalBytes,framesPerSecond:ke.sampleFrames*1e3/Ce,bytesPerSecond:ke.sampleBytes*1e3/Ce,sampleMs:Ce,lastUpdatedAt:Date.now()}),d(new Map(w.current)),ke.sampleFrames=0,ke.sampleBytes=0,ke.sampleStartedAt=le},2e3);return()=>{window.clearInterval(z)}},[]),u.useEffect(()=>{const z=_?_.split(",").filter(Boolean):[],le=new Set(z),ke=performance.now();for(const[Ce,Ue]of C.current.entries())le.has(Ce)||(V(Ue,"livedesk-device-unsubscribed"),C.current.delete(Ce),k.current.delete(Ce),w.current.delete(Ce));if(z.length===0){for(const Ce of C.current.values())V(Ce,"livedesk-no-devices");C.current.clear(),k.current.clear(),w.current=new Map,d(new Map),v(""),W.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},b(Yc),P();return}W.current.sampleStartedAt<=0&&(W.current.sampleStartedAt=ke,b({...Yc,lastUpdatedAt:Date.now()}));for(const Ce of z){const Ue=l.monitorSelections?.[Ce],Be=Number.isFinite(Number(Ue))?{[Ce]:Number(Ue)}:{},he={type:"subscribe",deviceIds:[Ce],autoStartLive:a,fps:Z,maxWidth:G,maxHeight:q,quality:Q,mode:O,frameMode:O,streamPurpose:ye,monitorSelections:Be},Xe=JSON.stringify(he),et=C.current.get(Ce),ce=Number(et?.payload.monitorSelections?.[Ce]),ge=Number(Be[Ce]),Ae=!!et&&Number.isFinite(ce)&&Number.isFinite(ge)&&ce!==ge;if(et){const Ke=et.socket.readyState===WebSocket.CONNECTING||et.socket.readyState===WebSocket.OPEN;if(et.payloadKey===Xe&&Ke&&!et.disposed)continue}const Le=et&&(et.socket.readyState===WebSocket.CONNECTING||et.socket.readyState===WebSocket.OPEN)&&!et.disposed?et.handoffFrom&&!et.handoffCompleted?et.handoffFrom:et:void 0;et&&et!==Le&&V(et,"livedesk-subscription-superseded");const Pe=new WebSocket(nf(`/api/remote/frames/ws?devices=${encodeURIComponent(Ce)}`,i));Pe.binaryType="arraybuffer";const Ve={socket:Pe,payload:he,payloadKey:Xe,generation:j.current+1,monitorRestartToken:Ae?`monitor-${Ce}-${ge}-${j.current+1}`:"",disposed:!1,handoffFrom:Le,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1};j.current=Ve.generation,Ae&&(w.current.delete(Ce),d(new Map(w.current))),C.current.set(Ce,Ve),Pe.addEventListener("open",()=>{if(Ve.disposed||C.current.get(Ce)!==Ve){V(Ve,"livedesk-stale-frame-socket");return}v("");const Ke=M.current,de=Ke.enabled&&(!Ke.token||k.current.get(Ce)!==Ke.token),je=de||Ve.monitorRestartToken!=="",fe=de?Ke.token:Ve.monitorRestartToken,_e=de?Ke.reason:Ve.monitorRestartToken?"monitor-selection-change":"";Pe.send(JSON.stringify({...Ve.payload,forceRestart:je,restartReason:je?_e:"",restartToken:je?fe:""})),de&&Ke.token&&k.current.set(Ce,Ke.token);const Ee=Ve.handoffFrom;Ve.handoffFrom=void 0,Ve.handoffCompleted=!0,Ee&&!Ee.disposed&&V(Ee,"livedesk-subscription-replaced"),P()}),Pe.addEventListener("message",Ke=>{if(Ve.disposed||C.current.get(Ce)!==Ve)return;if(typeof Ke.data=="string"){try{const je=JSON.parse(Ke.data);if(je?.type==="RemoteFrameSubscriptionError")v(String(je.error||"control-stream-start-failed"));else if(je?.type==="RemoteFrameLiveAutoStart"){const _e=(Array.isArray(je.skipped)?je.skipped:[]).find(Ee=>Ee?.deviceId===Ce);if(_e)v(String(_e.reason||"control-stream-start-failed"));else if(Array.isArray(je.started)){const Ee=je.started.find(mt=>mt?.deviceId===Ce);Ee&&(v(""),Ee.ready===!0&&Ee.streamPurpose==="control"&&Ee.sessionId&&Ee.commandId&&Number(Ee.captureGeneration||0)>0&&H.current?.({deviceId:Ce,sessionId:String(Ee.sessionId),streamId:String(Ee.streamId||""),streamPurpose:"control",commandId:String(Ee.commandId),captureGeneration:Number(Ee.captureGeneration),monitorIndex:Number(Ee.monitorIndex||0)}))}}else je?.type==="RemoteFrameStreamReady"&&je.deviceId===Ce&&je.streamPurpose==="control"&&je.sessionId&&je.commandId&&Number(je.captureGeneration||0)>0&&(v(""),H.current?.({deviceId:Ce,sessionId:String(je.sessionId),streamId:String(je.streamId||""),streamPurpose:"control",commandId:String(je.commandId),captureGeneration:Number(je.captureGeneration),monitorIndex:Number(je.monitorIndex||0)}))}catch{}return}const de=Ke.data instanceof ArrayBuffer?Ke.data:null;de&&(v(""),ue(de,Ve))}),Pe.addEventListener("error",()=>{Ve.disposed||C.current.get(Ce)!==Ve||p("connecting")}),Pe.addEventListener("close",()=>{const Ke=!Ve.disposed;Ve.disposed=!0;const de=C.current.get(Ce);let je=!1;if(de===Ve){const fe=Ve.handoffFrom;Ve.handoffFrom=void 0,fe&&!fe.disposed&&(fe.socket.readyState===WebSocket.CONNECTING||fe.socket.readyState===WebSocket.OPEN)?(C.current.set(Ce,fe),je=!0):C.current.delete(Ce)}if(P(),Ke&&de===Ve&&!je){const fe=window.setTimeout(()=>{A.current.delete(fe),D(_e=>_e+1)},750);A.current.add(fe)}})}P()},[a,V,_,Z,O,ue,i,q,G,ee,l.monitorSelections,Q,T,ye,P]),u.useEffect(()=>{if(!me||!X)return;const z=_?_.split(",").filter(Boolean):[];for(const le of z){if(k.current.get(le)===X)continue;const ke=C.current.get(le);!ke||!re(le,ke,I,X)||k.current.set(le,X)}},[_,me,X,I,re]),u.useEffect(()=>()=>{for(const z of C.current.values())V(z,"livedesk-hook-unmount");C.current.clear();for(const z of A.current)window.clearTimeout(z);A.current.clear()},[V]);const K=u.useCallback((z,le="browser-stale")=>{const ke=Array.isArray(z)&&z.length>0?z:_.split(",").filter(Boolean);if(ke.length===0)return!1;let Ce=!1;for(const Ue of ke){const Be=C.current.get(Ue);!Be||Be.socket.readyState!==WebSocket.OPEN||(Ce=re(Ue,Be,le,`${Date.now()}-${Math.random().toString(36).slice(2)}`)||Ce)}return Ce},[_,re]),xe=u.useCallback((z,le="browser-reconnect")=>{const ke=Array.isArray(z)&&z.length>0?z:_.split(",").filter(Boolean);if(ke.length===0)return!1;let Ce=!1;for(const Ue of ke){const Be=C.current.get(Ue);Be&&(V(Be,`livedesk-${le}`),C.current.delete(Ue),k.current.delete(Ue),w.current.delete(Ue),Ce=!0)}return Ce&&d(new Map(w.current)),D(Ue=>Ue+1),P(),!0},[V,_,P]);return{frames:c,state:m,error:g,stats:x,restartLive:K,reconnectLive:xe}}function v1(n,a,i=fn,l={}){const[c,d]=u.useState(null),[m,p]=u.useState(null),[g,v]=u.useState("idle"),[x,b]=u.useState(Yc),w=u.useRef(null),C=u.useRef(l.onFrame),j=u.useRef(null),k=u.useRef(0),M=u.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),A=u.useMemo(()=>[...new Set(n.filter(Boolean))].join(","),[n]),T=u.useMemo(()=>[...new Set((l.captureDeviceIds||n).filter(Boolean))].join(","),[n,l.captureDeviceIds]),D=u.useMemo(()=>JSON.stringify(l.monitorSelections||{}),[l.monitorSelections]),B=u.useMemo(()=>({deviceIds:A.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,A,D,l.fps,l.height,l.inputFps,l.monitorSelections,l.tileHeight,l.tileWidth,l.width]),H=u.useMemo(()=>JSON.stringify(B),[B]),W=u.useRef(B);W.current=B;const _=a&&B.deviceIds.length>0,Z=u.useCallback(q=>q.readyState!==WebSocket.OPEN?!1:(q.send(JSON.stringify({type:"configure",...W.current})),!0),[]);u.useEffect(()=>{C.current=l.onFrame},[l.onFrame]),u.useEffect(()=>{const q=window.setInterval(()=>{const Q=M.current,O=performance.now(),ye=Math.max(1,O-Q.sampleStartedAt);b({totalFrames:Q.totalFrames,totalBytes:Q.totalBytes,framesPerSecond:Q.sampleFrames*1e3/ye,bytesPerSecond:Q.sampleBytes*1e3/ye,sampleMs:ye,lastUpdatedAt:Date.now()});const me=j.current;me&&me.frameSeq!==k.current&&(k.current=me.frameSeq,d(me)),Q.sampleFrames=0,Q.sampleBytes=0,Q.sampleStartedAt=O},1e3);return()=>window.clearInterval(q)},[]),u.useEffect(()=>{if(!_){w.current?.close(),w.current=null,d(null),j.current=null,k.current=0,p(null),v("idle"),b(Yc);return}let q=!1,Q=0;const O=()=>{if(q)return;const ye=new WebSocket(nf("/api/remote/atlas/ws",i));ye.binaryType="arraybuffer",w.current=ye,v("connecting"),ye.addEventListener("open",()=>{M.current.sampleStartedAt=performance.now(),v("open"),Z(ye)}),ye.addEventListener("message",me=>{if(typeof me.data=="string"){try{const I=JSON.parse(me.data);I?.type==="Mode4AtlasLayout"&&p({layoutVersion:Number(I.layoutVersion||0),width:Number(I.width||1920),height:Number(I.height||1080),columns:Number(I.columns||1),rows:Number(I.rows||1),tiles:Array.isArray(I.tiles)?I.tiles:[]})}catch{}return}const X=me.data instanceof ArrayBuffer?me.data:null;if(!(!X||X.byteLength<5))try{const I=Date.now(),V=new DataView(X).getUint32(0,!1);if(V<=0||V+4>X.byteLength)return;const P=JSON.parse(Xh.decode(new Uint8Array(X,4,V))),re=new Uint8Array(X,4+V),ue={deviceId:String(P.deviceId||"__livedesk_mode4_atlas__"),kind:"live",frameSeq:Number(P.frameSeq||0),streamFrameSeq:Number(P.streamFrameSeq||0)||void 0,streamId:String(P.streamId||"mode4-atlas"),commandId:P.commandId?String(P.commandId):void 0,width:Number(P.width||1920),height:Number(P.height||1080),sourceWidth:Number(P.sourceWidth||P.width||1920),sourceHeight:Number(P.sourceHeight||P.height||1080),mimeType:String(P.mimeType||"video/h264"),mode:String(P.mode||"mode4-h264-atlas"),frameMode:String(P.frameMode||"mode4-h264-atlas"),frameProfile:String(P.frameProfile||"mode4-h264-atlas-v1"),encoding:String(P.encoding||"video-atlas"),codec:String(P.codec||"h264"),compression:String(P.compression||"video/h264"),h264Format:String(P.h264Format||"annexb"),isKeyFrame:P.isKeyFrame===!0,chunkType:String(P.chunkType||""),timestampUs:Number(P.timestampUs||0),durationUs:Number(P.durationUs||0),hardwareEncoder:P.hardwareEncoder?String(P.hardwareEncoder):void 0,platformProfile:P.platformProfile?String(P.platformProfile):void 0,capturedAt:String(P.capturedAt||""),receivedAt:String(P.receivedAt||""),hubPacketAt:P.hubPacketAt?String(P.hubPacketAt):void 0,hubPacketEpochMs:Number(P.hubPacketEpochMs||0)||void 0,browserReceivedEpochMs:I,byteLength:re.byteLength,layoutVersion:Number(P.layoutVersion||0),atlasComposeMs:Number(P.atlasComposeMs||0),atlasPoolStarved:Number(P.atlasPoolStarved||0),atlasReadyTiles:Number(P.atlasReadyTiles||0),atlasTileCount:Number(P.atlasTileCount||0),atlasInputRevision:Number(P.atlasInputRevision||0),atlasSourceNewestAtEpochMs:Number(P.atlasSourceNewestAtEpochMs||0),atlasSourceOldestAtEpochMs:Number(P.atlasSourceOldestAtEpochMs||0),atlasSourceMaxAgeMs:Number(P.atlasSourceMaxAgeMs||0),payload:re},K=M.current;K.totalFrames+=1,K.totalBytes+=re.byteLength,K.sampleFrames+=1,K.sampleBytes+=re.byteLength,j.current=ue,k.current===0&&(k.current=ue.frameSeq,d(ue)),C.current?.(ue)}catch{}}),ye.addEventListener("error",()=>v("error")),ye.addEventListener("close",()=>{w.current===ye&&(w.current=null),!q&&(v("closed"),Q=window.setTimeout(O,1200))})};return O(),()=>{q=!0,window.clearTimeout(Q),w.current?.close(),w.current=null}},[_,i,Z]),u.useEffect(()=>{if(!_)return;const q=w.current;q&&Z(q)},[H,_,Z]);const G=u.useCallback(()=>{const q=w.current;return q?Z(q):!1},[Z]);return{frame:c,layout:m,state:g,stats:x,refreshInputs:G}}function y1(n,a=fn){const i=u.useRef(null),l=u.useRef(0),c=u.useRef(0),d=u.useRef(new Map),[m,p]=u.useState("idle"),[g,v]=u.useState(""),[x,b]=u.useState(Cy),w=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,p("idle"),v(""),b(Cy);return}let j=!1,k=0;const M=()=>{if(j)return;const A=new WebSocket(nf("/api/remote/input/ws",a));i.current=A,w.current.sampleStartedAt=performance.now(),p("connecting"),v(""),A.addEventListener("open",()=>{j||i.current!==A||(v(""),p("open"))}),A.addEventListener("message",T=>{if(!(j||i.current!==A||typeof T.data!="string"))try{const D=JSON.parse(T.data);if(D?.type==="RemoteInputError"){v(String(D.error||D.result?.error||"Remote input failed.")),p("error");return}if(D?.type!=="RemoteInputApplied")return;const B=Number(D.inputSeq||0),H=d.current.get(B);H!==void 0&&(w.current.lastRoundTripMs=Math.max(0,performance.now()-H),d.current.delete(B)),w.current.lastInputSeq=B,w.current.lastAgentApplyMs=Math.max(0,Number(D.agentApplyMs||0))}catch{}}),A.addEventListener("close",()=>{j||i.current!==A||(i.current=null,p("closed"),k=window.setTimeout(M,1200))}),A.addEventListener("error",()=>{!j&&i.current===A&&p("error")})};return M(),()=>{j=!0,window.clearTimeout(k);const A=i.current;i.current=null,A?.close(),d.current.clear()}},[n,a]),u.useEffect(()=>{if(!n)return;const j=window.setInterval(()=>{const k=performance.now(),M=w.current,A=Math.max(1,k-M.sampleStartedAt);b({totalSent:M.totalSent,totalDropped:M.totalDropped,sentPerSecond:M.sampleSent*1e3/A,droppedPerSecond:M.sampleDropped*1e3/A,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=k},1e3);return()=>window.clearInterval(j)},[n]);const C=u.useCallback((j,k)=>{const M=i.current;if(!M||M.readyState!==WebSocket.OPEN||!j)return!1;const A=String(k.type||"").toLowerCase(),T=A==="pointermove",B=T||A==="wheel",H=w.current;if(T&&M.bufferedAmount>f1)return H.totalDropped+=1,H.sampleDropped+=1,H.lastInputType="pointermove-drop",!1;const W=l.current+1;l.current=W;const _=Date.now(),Z=!B||W-c.current>=h1;for(Z&&(d.current.set(W,performance.now()),B&&(c.current=W)),T||Sx.set(j,{inputSeq:W,inputType:A||"input",sentAt:performance.now()});d.current.size>256;){const G=d.current.keys().next().value;if(G===void 0)break;d.current.delete(G)}return M.send(JSON.stringify({type:"input",requestId:B?"":crypto.randomUUID(),fireAndForget:B,deviceId:j,input:{...k,inputSeq:W,requestAck:Z,issuedAtEpochMs:_,issuedAt:new Date(_).toISOString()}})),H.totalSent+=1,H.sampleSent+=1,H.lastInputType=A||"input",!0},[]);return{state:m,sendInput:C,stats:x,error:g}}function b1(n){const a=String(n||"").toLowerCase();return a.includes("audio/pcm")||a.includes("audio/l16")||a.includes("f32le")||a.includes("s16le")}const yd={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},x1=.08,w1=.25,S1=.02,jy=300,C1=4,bd=1500,Ym=5e3,k1=2e3,j1=1e4,xd=[0,1e3,3e3];function Ay(n){const a=Date.parse(String(n||""));return Number.isFinite(a)?Math.max(0,Date.now()-a):0}function A1(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"),p=m?2:4,g=Math.floor(i.byteLength/p),v=Math.floor(g/l),x=n.createBuffer(l,v,c),b=new DataView(i);for(let w=0;w<l;w+=1){const C=x.getChannelData(w);for(let j=0;j<v;j+=1){const M=(j*l+w)*p;C[j]=m?Math.max(-1,Math.min(1,b.getInt16(M,!0)/32768)):Math.max(-1,Math.min(1,b.getFloat32(M,!0)))}}return x}function N1(n,a,i=fn){const l=u.useRef(null),c=u.useRef(0),[d,m]=u.useState("idle"),[p,g]=u.useState(null),[v,x]=u.useState(yd),[b,w]=u.useState("");return u.useEffect(()=>{if(!a||!n){m("idle"),g(null),x(yd),w("");return}m("connecting"),g(null),x(yd),w("");const C=window.AudioContext||window.webkitAudioContext;if(!C){m("unsupported"),x(yd),w("Audio playback is not supported in this browser.");return}const j=new C;l.current=j,c.current=j.currentTime;const k=new WebSocket(nf("/api/remote/audio/ws?devices="+encodeURIComponent(n),i));k.binaryType="arraybuffer";const M=new Set,A={browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:!1,helperAlive:!1,captureRestartCount:0,localProcessingAgeMs:0,lastPacketAt:0,lastAcceptedAt:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:String(j.state),stalledCount:0,automaticRestarts:0,activeStreamId:"",lastCaptureStatusAt:0,lastPcmAtEpochMs:0};let T=!1,D=0,B=!1,H=0,W=0;const _=(I=!0)=>{for(const ee of M)try{ee.stop()}catch{}M.clear(),I&&(c.current=j.currentTime+x1)},Z=()=>{A.audioContextState=String(j.state),!T&&(A.audioContextState==="suspended"||A.audioContextState==="interrupted"?m("suspended"):A.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(),A.audioContextState=String(j.state),!T&&!B&&A.audioContextState==="running"){const I=A.lastAcceptedAt>0&&performance.now()-A.lastAcceptedAt<=bd,ee=A.lastCaptureStatusAt>0&&performance.now()-A.lastCaptureStatusAt<=Ym&&A.captureAlive&&A.helperAlive;m(I?"playing":ee?"silent":"open")}return A.audioContextState==="running"}catch(I){return T||(m("suspended"),w(I instanceof Error?"Audio playback is suspended: "+I.message:"Audio playback is suspended.")),!1}},q=async()=>{if(T||B||k.readyState!==WebSocket.OPEN)return;if(H>=xd.length){m("error"),w("Remote audio stopped sending frames. Toggle Audio off and on to retry.");return}const I=H;H+=1,B=!0,A.stalledCount+=1,A.automaticRestarts+=1,m("reconnecting");try{const ee=await Ye("/api/remote/devices/"+encodeURIComponent(n)+"/audio/stop",{method:"POST",body:JSON.stringify({})},i);if(ee.ok===!1)throw new Error(ee.error||"Remote audio stop failed.");if(T)return;const V=await Ye("/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(V.ok===!1)throw new Error(V.error||"Remote audio start failed.");const P=performance.now();D=P,A.lastPacketAt=P,A.lastAcceptedAt=0,A.lastCaptureStatusAt=0,A.lastPcmAtEpochMs=0,A.captureAlive=!1,A.helperAlive=!1,A.silentForMs=0,W=P+(xd[I+1]??3e3),w(""),T||m("open")}catch(ee){T||(W=performance.now()+(xd[I+1]??3e3),m("error"),w(ee instanceof Error?"Remote audio restart failed: "+ee.message:"Remote audio restart failed."))}finally{B=!1}},Q=()=>{A.drops+=1},O=window.setInterval(()=>{if(T)return;const I=performance.now(),ee=A.lastPacketAt>0?Math.max(0,I-A.lastPacketAt):D>0?Math.max(0,I-D):0,V=A.lastAcceptedAt>0?Math.max(0,I-A.lastAcceptedAt):0,P=A.lastCaptureStatusAt>0?Math.max(0,I-A.lastCaptureStatusAt):0,re=k.readyState===WebSocket.OPEN,ue=A.lastCaptureStatusAt>0,K=ue&&P<=Ym,xe=ue&&(!A.captureAlive||!A.helperAlive)&&P>k1,z=ue&&P>Ym,le=!ue&&D>0&&I-D>j1,ke=D>0&&(A.lastAcceptedAt<=0?I-D>bd:V>bd);re&&D>0&&(xe||z||le)?H>=xd.length&&!B?(m("error"),w("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!B&&I>=W?q():B||m("stalled"):re&&ke&&!B&&A.audioContextState!=="suspended"&&A.audioContextState!=="interrupted"&&m(K?"silent":"open"),x({queuedMs:Math.max(0,(c.current-j.currentTime)*1e3),browserAgeMs:A.browserAgeMs,captureAgeMs:A.captureAgeMs,captureStatusAgeMs:P,silentForMs:A.silentForMs,captureAlive:A.captureAlive,helperAlive:A.helperAlive,captureRestartCount:A.captureRestartCount,localProcessingAgeMs:A.localProcessingAgeMs,lastPacketAgeMs:ee,lastAcceptedAgeMs:V,framesReceived:A.framesReceived,drops:A.drops,resyncs:A.resyncs,pendingDecodes:A.pendingDecodes,lastFrameSeq:A.lastFrameSeq,audioContextState:A.audioContextState,stalledCount:A.stalledCount,automaticRestarts:A.automaticRestarts,lastUpdatedAt:Date.now()})},250),ye=()=>{Z(),(String(j.state)==="suspended"||String(j.state)==="interrupted")&&G()},me=()=>{document.visibilityState==="visible"&&G()},X=()=>{G()};return j.addEventListener("statechange",ye),document.addEventListener("visibilitychange",me),window.addEventListener("pageshow",X),window.addEventListener("pointerdown",X),window.addEventListener("keydown",X),m("connecting"),w(""),Z(),k.addEventListener("open",()=>{T||(D=performance.now(),A.lastPacketAt=D,A.lastAcceptedAt=0,A.lastCaptureStatusAt=0,A.lastPcmAtEpochMs=0,A.captureAlive=!1,A.helperAlive=!1,A.silentForMs=0,m("open"),k.send(JSON.stringify({type:"subscribe",deviceIds:[n]})),G())}),k.addEventListener("message",I=>{if(typeof I.data=="string")return;const ee=I.data instanceof ArrayBuffer?I.data:null;if(!ee||ee.byteLength<5)return;const V=performance.now();A.lastPacketAt=V,(async()=>{try{const re=new DataView(ee).getUint32(0,!1);if(re<=0||re+4>ee.byteLength){Q();return}const ue=new Uint8Array(ee,4,re),K=JSON.parse(Xh.decode(ue)),xe=ee.slice(4+re),z=String(K.frameKind||K.kind||"").toLowerCase();if(K.type==="remote.audio.status"||z==="audio-status"){if(A.lastCaptureStatusAt=V,A.captureAlive=K.captureAlive===!0,A.helperAlive=K.helperAlive===!0,A.captureRestartCount=Math.max(0,Number(K.restartCount||0)||0),A.lastPcmAtEpochMs=Math.max(0,Number(K.lastPcmAtEpochMs||0)||0),A.silentForMs=Math.max(0,Number(K.silentForMs||0)||0),A.captureAgeMs=A.lastPcmAtEpochMs>0?Math.max(0,Date.now()-A.lastPcmAtEpochMs):A.silentForMs,A.captureAlive&&A.helperAlive){if(H=0,W=0,!B){w("");const ke=String(j.state)==="running",Ce=A.lastAcceptedAt>0&&performance.now()-A.lastAcceptedAt<=bd;m(ke?Ce?"playing":"silent":"suspended")}}else B||m("stalled");return}const le={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||xe.byteLength),payload:xe};if(!le.deviceId||T)return;if(performance.now()-V>jy){Q();return}if(A.pendingDecodes>=C1){Q();return}A.pendingDecodes+=1;try{const ke=b1(le.mimeType)?A1(j,le,xe):await j.decodeAudioData(xe.slice(0));if(A.localProcessingAgeMs=Math.max(0,performance.now()-V),T)return;if(A.localProcessingAgeMs>jy){Q();return}if(le.frameSeq>0&&le.frameSeq<=A.lastFrameSeq){Q();return}if(A.activeStreamId&&le.streamId!==A.activeStreamId&&le.frameSeq<=A.lastFrameSeq){Q();return}le.streamId&&le.streamId!==A.activeStreamId&&(A.activeStreamId=le.streamId,A.lastFrameSeq=0,_());const Ce=j.currentTime;Math.max(0,c.current-Ce)>w1&&(_(),A.resyncs+=1);const Be=j.createBufferSource();Be.buffer=ke,Be.connect(j.destination),M.add(Be),Be.onended=()=>{M.delete(Be),Be.onended=null};const he=Math.max(j.currentTime+S1,c.current);Be.start(he),c.current=he+ke.duration,A.browserAgeMs=Ay(le.receivedAt),A.captureAgeMs=Ay(le.capturedAt),A.lastAcceptedAt=performance.now(),A.framesReceived+=1,A.lastFrameSeq=le.frameSeq,H=0,W=0,g(le),G();const Xe=String(j.state)==="running";Xe&&w(""),m(Xe?"playing":"suspended")}finally{A.pendingDecodes=Math.max(0,A.pendingDecodes-1)}}catch(P){T||(m("error"),w(P instanceof Error?P.message:String(P)))}})()}),k.addEventListener("error",()=>{T||(m("error"),w("Remote audio WebSocket error."))}),k.addEventListener("close",()=>{T||m("closed")}),()=>{T=!0,window.clearInterval(O),j.removeEventListener("statechange",ye),document.removeEventListener("visibilitychange",me),window.removeEventListener("pageshow",X),window.removeEventListener("pointerdown",X),window.removeEventListener("keydown",X),_(!1),k.close(),j.close().catch(()=>{}),l.current===j&&(l.current=null)}},[n,a,i]),{state:d,lastFrame:p,stats:v,error:b}}const M1=3;function Ny(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,M1);return c<=d?0:c>=l-d?1:c/l}function T1(n,a,i){return{normalizedX:Ny(n,i.left,i.width),normalizedY:Ny(a,i.top,i.height)}}const za=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",configuredLatencyMode:"smooth"});function E1(n,a){const i=Math.max(0,Math.floor(Number(a)||0));return n===!0&&i>0}function Fc({mode4Enabled:n,directMode4WallEnabled:a,isMac:i}){return"direct"}function R1({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<=za.directFullFpsDeviceLimit?d:Math.max(za.directMinAdaptiveFps,Math.min(d,Math.floor(za.maxDirectFramesPerSecond/m)))}function D1({deviceCount:n,targetFps:a,adaptive:i=!0}){const l=Math.max(1,Math.floor(Number(n)||1)),c=Math.max(1,Math.min(za.scalableAtlasMaxInputFps,Math.floor(Number(a)||za.scalableAtlasMaxInputFps)));if(!i)return c;const d=Math.max(za.scalableAtlasMinInputFps,Math.min(za.scalableAtlasMaxInputFps,Math.floor(za.scalableAtlasAggregateInputFps/l)));return Math.min(c,d)}function L1(n,a){return n?{acceleration:za.directDecodeAcceleration,latencyMode:za.directLatencyMode}:{acceleration:a,latencyMode:za.configuredLatencyMode}}const Dl={revision:0,settings:{security:{accessMode:"trusted-only"},control:{allowKeyboardMouse:!0},filesAudio:{allowFileTransfer:!0,allowRemoteAudio:!0,rollingBufferEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0}}},_1=[{id:"connection",label:"Connection",icon:ef},{id:"remote-access",label:"Remote Access",icon:jn},{id:"capture-audio",label:"Capture & Audio",icon:vh},{id:"agent",label:"Agent",icon:Gi}];function Bd(n,a){return n?.settings?.[a]||Dl.settings[a]||{}}function My(n,a){return{...n,settings:{...n.settings,[a.section]:{...Bd(n,a.section),[a.key]:a.value}}}}function Km(n){return{revision:Number(n.revision||0),updatedAt:n.updatedAt,settings:n.settings}}function No({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 wd({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 Ty({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 I1({hubUrl:n="",runtimeRole:a="hub",runtimeDeviceId:i="",sessionAccessToken:l="",initialTab:c="connection",pin:d,agent:m,captureGallery:p}){const[g,v]=u.useState(c),[x,b]=u.useState(null),[w,C]=u.useState("loading"),[j,k]=u.useState(""),[M,A]=u.useState("idle"),[T,D]=u.useState(""),B=u.useRef(null),H=u.useRef(null),W=u.useRef([]),_=u.useRef(Promise.resolve()),Z=u.useRef(0),G=u.useRef(0);u.useEffect(()=>{const ue=++G.current;let K=!0;return W.current=[],H.current=null,B.current=null,_.current=Promise.resolve(),C("loading"),Ye("/api/settings",void 0,n).then(xe=>{if(!K||ue!==G.current)return;const z=Km(xe);H.current=z,B.current=z,b(z),C("saved")}).catch(xe=>{!K||ue!==G.current||(k(xe instanceof Error?xe.message:String(xe)),H.current=Dl,B.current=Dl,b(Dl),C("failed"))}),()=>{K=!1}},[n]);const q=async(ue,K,xe)=>{const z={id:++Z.current,section:ue,key:K,value:xe},le=G.current;W.current.push(z);const ke=My(B.current||H.current||Dl,z);B.current=ke,b(ke),C("saving"),k(""),_.current=_.current.then(async()=>{if(le!==G.current)return;let Ce=null,Ue=null;for(let Xe=0;Xe<2&&!Ce;Xe+=1){const et=H.current||Dl;try{const ce=await Ye("/api/settings",{method:"PATCH",body:JSON.stringify({revision:et.revision,[z.section]:{[z.key]:z.value}})},n);Ce=Km(ce)}catch(ce){if(Ue=ce,Xe!==0||!String(ce instanceof Error?ce.message:ce).startsWith("409 "))break;try{const ge=await Ye("/api/settings",void 0,n);if(le!==G.current)return;H.current=Km(ge)}catch(ge){Ue=ge;break}}}if(le!==G.current)return;W.current=W.current.filter(Xe=>Xe.id!==z.id),Ce&&(H.current=Ce);const Be=H.current||Dl,he=W.current.reduce(My,Be);B.current=he,b(he),Ce?(k(""),C(W.current.length>0?"saving":"saved")):(C(W.current.length>0?"saving":"failed"),k(Ue instanceof Error?Ue.message:String(Ue||"Settings could not be saved.")))}),await _.current},Q=(ue,K)=>xe=>{q(ue,K,xe)},O=async()=>{if(a!=="hub"||!i||!l){A("failed"),D("Sign in to this Hub before changing its runtime role.");return}A("changing"),D("");try{const ue=await Ye("/api/runtime/status",void 0,n);await Ye("/api/runtime/role",{method:"POST",headers:{Authorization:`Bearer ${l}`},body:JSON.stringify({role:"client"})},n),A("accepted"),await Zb({baseUrl:n,targetRole:"client",previousRuntimePid:Number(ue.runtimePid||0),allowedStates:["running","waiting-auth"]}),dC(5179)}catch(ue){A("failed"),D(ue instanceof Error?ue.message:String(ue))}},ye=Bd(x,"security"),me=Bd(x,"control"),X=Bd(x,"filesAudio"),I=`settings-panel-${g}`,ee=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(Ub,{size:20})]}),r.jsx("p",{className:"settings-help",children:"Stop hosting from this computer and reconnect it to the selected Hub."}),M==="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:()=>{O()},disabled:M==="changing"||a!=="hub",type:"button",children:M==="changing"?"Switching role...":"Switch this computer to Client"})]})]}),V=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(Zr,{size:20})]}),r.jsx(No,{icon:jn,title:"Access mode",description:"Choose the default permission boundary for remote sessions.",recommended:!0,children:r.jsx(Ty,{value:String(ye.accessMode),onChange:Q("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(oa,{size:20})]}),r.jsx(No,{icon:oa,title:"Keyboard and mouse control",description:"Allow Control to send keyboard and pointer input.",recommended:!0,children:r.jsx(wd,{checked:!!me.allowKeyboardMouse,onChange:Q("control","allowKeyboardMouse"),label:"Keyboard and mouse control"})}),r.jsx(No,{icon:vh,title:"File transfer",description:"Allow files to be delivered to connected computers.",children:r.jsx(wd,{checked:!!X.allowFileTransfer,onChange:Q("filesAudio","allowFileTransfer"),label:"File transfer"})}),r.jsx(No,{icon:Hl,title:"Remote audio",description:"Allow sound capture from connected computers.",children:r.jsx(wd,{checked:!!X.allowRemoteAudio,onChange:Q("filesAudio","allowRemoteAudio"),label:"Remote audio"})})]})]}),P=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(vh,{size:20})]}),r.jsx(No,{icon:Hl,title:"Keep a Last 30s buffer",description:"Keep recent video in memory until you explicitly save it.",children:r.jsx(wd,{checked:!!X.rollingBufferEnabled,onChange:Q("filesAudio","rollingBufferEnabled"),label:"Keep a Last 30s buffer"})}),r.jsx(No,{icon:Hl,title:"Timelapse interval",description:"Choose how often a timelapse frame is captured.",children:r.jsx(Ty,{value:Number(X.timelapseIntervalSeconds),onChange:ue=>Q("filesAudio","timelapseIntervalSeconds")(Number(ue)),label:"Timelapse interval",options:[["5","5 seconds"],["10","10 seconds"],["30","30 seconds"],["60","60 seconds"]]})})]}),p]}),re=g==="connection"?ee:g==="remote-access"?V:g==="capture-audio"?P:m;return r.jsxs("section",{className:"settings-page",children:[r.jsx("div",{className:"settings-page-tabs",role:"tablist","aria-label":"LiveDesk settings",children:_1.map(({id:ue,label:K,icon:xe})=>r.jsxs("button",{className:g===ue?"active":"",id:`settings-tab-${ue}`,role:"tab","aria-selected":g===ue,"aria-controls":`settings-panel-${ue}`,tabIndex:g===ue?0:-1,onClick:()=>v(ue),type:"button",children:[r.jsx(xe,{size:16}),K]},ue))}),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:I,role:"tabpanel","aria-labelledby":`settings-tab-${g}`,tabIndex:0,children:re})]})}function z1({children:n}){return r.jsx("div",{className:"settings-tab-content",children:n})}const Rh={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 Ey(n){return{...Rh,...n||{}}}async function O1(n,a,i){let l=null;for(let c=0;c<2;c+=1){const d=await Ye("/api/settings",{signal:i},a);if(d.settings.agent?.enabled===n)return;try{await Ye("/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 H1({hubUrl:n}){const[a,i]=u.useState(Rh),[l,c]=u.useState(null),[d,m]=u.useState(""),[p,g]=u.useState(""),[v,x]=u.useState(""),[b,w]=u.useState(""),C=u.useRef(0),j=u.useRef(null);u.useEffect(()=>{let G=!0;j.current?.abort();const q=new AbortController;j.current=q;const Q=++C.current;return c(null),i(Rh),m(""),g(""),w(""),x(""),Ye("/api/settings/agent",{signal:q.signal},n).then(O=>{!G||q.signal.aborted||Q!==C.current||(c(O.settings),i(Ey(O.settings)))}).catch(O=>{G&&!q.signal.aborted&&Q===C.current&&w(O instanceof Error?O.message:String(O))}),()=>{G=!1,q.abort(),j.current===q&&(j.current=null)}},[n]);const k=(G,q)=>i(Q=>({...Q,[G]:q})),M=G=>{c(G),i(Ey(G))},A=()=>({generation:C.current,controller:j.current}),T=G=>G.generation===C.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=A();if(T(G)){g("save"),w(""),x("");try{if(await O1(a.enabled,n,G.controller.signal),!T(G))return;const{enabled:q,...Q}=a,O={...Q};d.trim()&&(O.apiKey=d.trim());const ye=await Ye("/api/settings/agent",{method:"PUT",signal:G.controller.signal,body:JSON.stringify(O)},n);if(!T(G))return;M(ye.settings),m(""),x("Agent settings saved.")}catch(q){T(G)&&w(q instanceof Error?q.message:String(q))}finally{T(G)&&g("")}}},B=async()=>{const G=A();if(T(G)){g("reset"),w("");try{const q=await Ye("/api/settings/agent/reset",{method:"POST",signal:G.controller.signal,body:JSON.stringify({})},n);if(!T(G))return;M(q.settings),x("Codex defaults restored.")}catch(q){T(G)&&w(q instanceof Error?q.message:String(q))}finally{T(G)&&g("")}}},H=async()=>{const G=A();if(T(G)){g("test"),w(""),x("");try{const q=await Ye("/api/settings/agent/test",{method:"POST",signal:G.controller.signal,body:JSON.stringify({})},n);if(!T(G))return;const Q=await Ye("/api/settings/agent",{signal:G.controller.signal},n);if(!T(G))return;M(Q.settings),x(`Codex connection verified with ${q.connection?.modelName||"the configured model"}${q.connection?.latencyMs?` in ${q.connection.latencyMs} ms.`:"."}`)}catch(q){T(G)&&w(q instanceof Error?q.message:String(q))}finally{T(G)&&g("")}}},W=async()=>{const G=A();if(T(G)){g("clear-key"),w("");try{const q=await Ye("/api/settings/agent/api-key",{method:"DELETE",signal:G.controller.signal},n);if(!T(G))return;M(q.settings),m(""),x("The optional OpenCode Go key was removed.")}catch(q){T(G)&&w(q instanceof Error?q.message:String(q))}finally{T(G)&&g("")}}},_=l?.codexInstallation==="installed"&&l.codexAuth==="signed-in",Z=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:!Z||p!==""}),r.jsx("span",{children:"Enable Agent AI"})]})}),b&&r.jsx("div",{className:"agent-settings-alert error",role:"alert",children:b}),v&&r.jsx("div",{className:"agent-settings-alert success",role:"status",children:v}),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(jn,{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 ${_?"connected":l?.codexAuth==="not-signed-in"?"unavailable":""}`}),r.jsx("span",{children:l?.codexInstallation==="not-installed"?"Codex SDK not installed":l?.codexAuth==="signed-in"?"Codex CLI signed in":l?.codexAuth==="not-signed-in"?"Codex CLI sign-in required":"Codex status not tested"}),r.jsxs("button",{className:"settings-reset",onClick:()=>{H()},disabled:p!=="",type:"button",children:[r.jsx(YS,{size:15})," ",p==="test"?"Testing":"Test connection"]})]}),r.jsxs("p",{className:"settings-help",children:[r.jsx(KS,{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(XS,{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($b,{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:()=>{W()},disabled:p!==""||!l?.hasApiKey,type:"button",children:[r.jsx($h,{size:15})," Clear key"]})]})]}),r.jsxs("div",{className:"settings-action-row agent-settings-actions",children:[r.jsxs("button",{className:"settings-reset",onClick:()=>{B()},disabled:p!=="",type:"button",children:[r.jsx(Uh,{size:15})," Reset defaults"]}),r.jsxs("button",{className:"text-button primary",onClick:()=>{D()},disabled:!Z||p!=="",type:"button",children:[r.jsx(QS,{size:15})," ",p==="save"?"Saving":"Save Agent settings"]})]})]})}new Date().valueOf();function hr(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 Qh(n,a){return typeof n=="function"?typeof a=="object"?n(a):n():n}function Bo(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 F1(n,a="data-id"){const i=Bo(n,a);return i?i.getAttribute(a):null}function nu(n,a="data-id"){const i=Bo(n,a);return i?sf(i,a):null}function sf(n,a="data-id"){const i=n.getAttribute(a);return i?B1(i):null}function Ln(n){return typeof n=="string"?":"+n:n}function B1(n){if(n.startsWith(":"))return n.substring(1);const a=n*1;return isNaN(a)?n:a}function P1(){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 Oa=P1();function Zh(n){Object.assign(Oa,n)}function Ry(n,a,i){function l(c){const d=Bo(c);if(!d)return;const m=sf(d);if(typeof a=="function")return a(m,c);let p,g=c.target;for(;g!=d;){if(p=g.dataset?g.dataset.action:null,p&&a[p]){a[p](m,c);return}g=g.parentNode}a[i]&&a[i](m,c)}Oa.addEvent(n,i,l)}function Po(n,a){Ry(n,a,"click"),a.dblclick&&Ry(n,a.dblclick,"dblclick")}function $1(n,a){for(let i=n.length-1;i>=0;i--)if(n[i]===a){n.splice(i,1);break}}function U1(n,a,i){for(let l=0;l<ei.length;l++){if(l===i)continue;const c=ei[l],d=c.props.parent?.();if(d&&n.contains(d)&&c.node.contains(a))return!0}return!1}var Cx=new Date,Kd=!1,Sd=[],ei=[],Dy=n=>{const a=n.target;if(Kd||!a.isConnected){Kd=!1;return}for(let i=ei.length-1;i>=0;i--){const{node:l,date:c,props:d}=ei[i];if(!(c>Cx)&&!l.contains(a)&&l!==a&&(U1(l,a,i)||(d.callback&&d.callback(n),d.modal||n.defaultPrevented)))break}},q1=n=>{Cx=new Date,Kd=!0;for(let a=ei.length-1;a>=0;a--){const{node:i}=ei[a];if(!i.contains(n.target)&&i!==n.target){Kd=!1;break}}};function pr(n,a){Sd.length||(Sd=[Oa.addGlobalEvent("click",Dy,n),Oa.addGlobalEvent("contextmenu",Dy,n),Oa.addGlobalEvent("mousedown",q1,n)]),typeof a!="object"&&(a={callback:a});const i={node:n,date:new Date,props:a};return ei.push(i),{destroy(){$1(ei,i),ei.length||(Sd.forEach(l=>l()),Sd=[])}}}var Cd=n=>n.indexOf("bottom")!==-1,kd=n=>n.indexOf("left")!==-1,jd=n=>n.indexOf("right")!==-1,Xm=n=>n.indexOf("top")!==-1,Ly=n=>n.indexOf("fit")!==-1,Bc=n=>n.indexOf("overlap")!==-1,G1=n=>n.split("-").every(a=>["center","fit"].indexOf(a)>-1),V1=n=>{const a=n.match(/(start|center|end)/);return a?a[0]:null};function W1(n,a){let i=0;const l=Oa.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 bn,aa,Pc,Xn;function kx(n,a,i="bottom",l=0,c=0){if(!n)return null;bn=l,aa=c,Pc="auto";let d=0,m=0,p=i;const g=jx(n),v=Bc(i)?Oa.getTopNode(n):g;if(!g)return null;const x=g.getBoundingClientRect(),b=n.getBoundingClientRect(),w=v.getBoundingClientRect(),C=window.getComputedStyle(v),j={left:0,top:0,bottom:0,right:0};for(const B in j){const H=`border-${B}-width`;j[B]=parseFloat(C.getPropertyValue(H))}if(a){const B=W1(a,g);d=Math.max(B+1,20)}if(a){if(Xn=a.getBoundingClientRect(),Ly(i)&&(Pc=Xn.width+"px"),i!=="point")if(G1(i))Ly(i)?bn=0:(bn=w.width/2,m=1),aa=(w.height-b.height)/2;else{const B=Bc(i)?0:1;bn=jd(i)?Xn.right+B:Xn.left-B,aa=Cd(i)?Xn.bottom+1:Xn.top;const H=V1(i);H&&(jd(i)||kd(i)?H==="center"?aa-=(b.height-Xn.height)/2:H==="end"&&(aa-=b.height-Xn.height):(Cd(i)||Xm(i))&&(H==="center"?bn-=(b.width-Xn.width)/2:H==="end"&&(bn-=b.width-Xn.width),Bc(i)||(bn+=1)))}}else Xn={left:l,right:l,top:c,bottom:c};const k=(kd(i)||jd(i))&&(Cd(i)||Xm(i));kd(i)&&(m=2);const M=bn-b.width-w.left;a&&kd(i)&&!k&&M<0&&(bn=Xn.right,m=0,p=p.replace("left","right"));const A=bn+b.width*(1-m/2)-w.right;if(A>0)if(!jd(i))bn=w.right-j.right-b.width;else{const B=Xn.left-w.x-b.width;a&&!k&&B>=0?(bn=Xn.left-b.width,p=p.replace("right","left")):bn-=A+j.right}m&&(bn=Math.round(bn-b.width*m/2));const T=M<0||A>0||!k;Xm(i)&&(aa=Xn.top-b.height,a&&aa<w.y&&T&&(aa=Xn.bottom,p=p.replace("top","bottom")));const D=aa+b.height-w.bottom;return D>0&&(a&&Cd(i)&&T?(aa-=b.height+Xn.height+1,p=p.replace("bottom","top")):aa-=D+j.bottom),bn-=x.left+j.left,aa-=x.top+j.top,bn=(Bc(i)?bn:Math.max(bn,0))+v.scrollLeft,aa=(Bc(i)?aa:Math.max(aa,0))+v.scrollTop,Pc=Pc||"auto",{at:p,x:bn,y:aa,z:d,width:Pc}}function jx(n){const a=Oa.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 Y1(n){const a=[];let i=n;const l=Oa.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 _y=new Date().valueOf();function Jh(){return _y+=1,_y}function ra(n){return n<10?"0"+n:n.toString()}function K1(n){const a=ra(n);return a.length==2?"0"+a:a}function Ax(n){const a=Math.floor(n/11)*11;return{start:a,end:a+11}}function Qm(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 Iy=["",""];function X1(n,a,i){switch(n){case"%d":return ra(a.getDate());case"%m":return ra(a.getMonth()+1);case"%j":return a.getDate();case"%n":return a.getMonth()+1;case"%y":return ra(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 ra((a.getHours()+11)%12+1);case"%g":return(a.getHours()+11)%12+1;case"%G":return a.getHours();case"%H":return ra(a.getHours());case"%i":return ra(a.getMinutes());case"%a":return((a.getHours()>11?i.pm:i.am)||Iy)[0];case"%A":return((a.getHours()>11?i.pm:i.am)||Iy)[1];case"%s":return ra(a.getSeconds());case"%S":return K1(a.getMilliseconds());case"%W":return ra(Qm(a));case"%w":{const l=i.weekStart??1;if(l===1)return ra(Qm(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)),ra(Qm(m))}case"%c":{let l=a.getFullYear()+"";return l+="-"+ra(a.getMonth()+1),l+="-"+ra(a.getDate()),l+="T",l+=ra(a.getHours()),l+=":"+ra(a.getMinutes()),l+=":"+ra(a.getSeconds()),l}case"%Q":return Math.floor(a.getMonth()/3)+1;default:return n}}var Q1=/%[a-zA-Z]/g;function Io(n,a){return typeof n=="function"?n:function(i){return i?(i.getMonth||(i=new Date(i)),n.replace(Q1,l=>X1(l,i,a))):""}}function zy(n){return n&&typeof n=="object"&&!Array.isArray(n)}function Dh(n,a){for(const i in a){const l=a[i];zy(n[i])&&zy(l)?n[i]=Dh({...n[i]},a[i]):n[i]=a[i]}return n}function su(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=Dh({...a},n):l=Dh({...n},a),su(l)}}}var Z1=Kb();const J1="en-US",ek={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"},nk={timeFormat:"%H:%i",dateFormat:"%m/%d/%Y",monthYearFormat:"%F %Y",yearFormat:"%Y"},Nx={core:tk,calendar:ek,formats:nk,lang:J1},ep=u.createContext(""),Mx=u.createContext({}),qs=u.createContext(null),Tx=u.createContext(null),In=Object.freeze(Object.defineProperty({__proto__:null,fieldId:Tx,helpers:Mx,i18n:qs,theme:ep},Symbol.toStringTag,{value:"Module"}));function Ex(n){const a=u.useContext(Tx),[i]=u.useState(()=>n||a||Jh());return i}function Kc({type:n="",css:a="",icon:i="",disabled:l=!1,title:c="",tooltip:d,text:m="",children:p,onClick:g}){const v=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 ${v} ${i&&!p?"wx-icon":""}`,disabled:l,onClick:x,"data-tooltip-text":d,children:[i&&r.jsx("i",{className:"wx-2ZWgb4 "+i}),p||m||" "]})}function ak({id:n,label:a="",inputValue:i="",value:l=!1,onChange:c,disabled:d=!1,css:m=""}){const p=Ex(n),[g,v]=hr(l),x=({target:b})=>{const w=b.checked;v(w),c&&c({value:w,inputValue:i})};return r.jsxs("div",{className:`wx-2IvefP wx-checkbox ${m}`,children:[r.jsx("input",{type:"checkbox",id:p,disabled:d,className:"wx-2IvefP wx-check",checked:g,value:i,onChange:x}),r.jsxs("label",{htmlFor:p,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 tp({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 p=u.useContext(ep);return u.useEffect(()=>{m(a||sk(c.current)||Oa.getTopNode(c.current))},[c.current]),r.jsxs(r.Fragment,{children:[r.jsx("span",{ref:c,style:{display:"none"}}),c.current&&d?Z1.createPortal(r.jsx("div",{className:`wx-3ZWsT0 wx-${n||p}-theme`,children:i}),d):null]})}function sk(n){const a=Oa.getTopNode(n);for(;n&&n!==a&&!n.getAttribute("data-wx-portal-root");)n=n.parentNode;return n}function rk({left:n=0,top:a=0,at:i="bottom",parent:l=null,width:c="auto",css:d="",onCancel:m,children:p,trackScroll:g=!1}){const[v,x]=u.useState(0),[b,w]=u.useState(0),[C,j]=u.useState("auto"),[k,M]=u.useState(!1),A=u.useRef(null),T=u.useRef(null),D=u.useRef(m);u.useEffect(()=>{D.current=m},[m]);function B(W){return l&&(c+"").indexOf("%")>-1?c.replace(/(\d+)%/,(_,Z)=>(Z=Z*l.offsetWidth/100+"px",c.replace(_,Z))):c&&c!=="auto"?c:W}const H=u.useCallback(()=>{if(!A.current)return;const W=kx(A.current,l,i,n,a);W&&(x(W.x),w(W.y),j(B(W.width)))},[A,l,i,n,a,c]);return u.useLayoutEffect(()=>{const W=Z=>{D.current&&Z.target!==T.current&&A.current&&!A.current.contains(Z.target)&&D.current(Z)};let _;return requestAnimationFrame(()=>{H(),M(!0),g&&A.current&&(T.current=jx(A.current),T.current&&T.current.addEventListener("scroll",W,!0)),l&&(_=new ResizeObserver(H),_.observe(l))}),()=>{g&&T.current&&T.current.removeEventListener("scroll",W,!0),_?.disconnect()}},[]),u.useLayoutEffect(()=>{H()},[l,i,n,a]),u.useEffect(()=>{const W=_=>{D.current&&D.current(_)};if(A.current)return pr(A.current,{callback:W,parent:()=>l}).destroy},[l]),r.jsx("div",{ref:A,className:["wx-37M6Fj","wx-popup",d].filter(Boolean).join(" "),style:{position:"absolute",visibility:k?"visible":"hidden",top:b+"px",left:v+"px",width:C},children:p})}function ik({position:n="bottom",align:a="start",autoFit:i=!0,onCancel:l=null,width:c="100%",css:d="",children:m}){const p=u.useRef(null),[g,v]=u.useState(n),[x,b]=u.useState(a),w=u.useRef(l);return u.useEffect(()=>{w.current=l},[l]),u.useEffect(()=>{if(i){const C=p.current;if(C){const j=C.getBoundingClientRect(),k=document.body.getBoundingClientRect();j.right>=k.right&&b("end"),j.bottom>=k.bottom&&v("top")}}},[]),u.useEffect(()=>{if(p.current){const C=j=>{w.current&&w.current(j)};return pr(p.current,C).destroy}},[]),r.jsx("div",{ref:p,className:["wx-dropdown",`wx-${g}-${x}`,d||"","wx-aaaVytZW"].filter(Boolean).join(" "),style:{width:c},children:m})}function np({position:n="bottom",align:a="start",autoFit:i=!0,inline:l=!1,onCancel:c,width:d="100%",children:m,...p}){const[g,v]=u.useState(void 0),x=u.useRef(null),b=u.useMemo(()=>`${n}-${a}`,[n,a]);return u.useLayoutEffect(()=>{x.current&&v(x.current.parentNode)},[]),r.jsxs(r.Fragment,{children:[g&&(l?r.jsx(ik,{onCancel:c,position:n,align:a,autoFit:i,width:d,...p,children:m}):r.jsx(tp,{children:r.jsx(rk,{parent:g,at:b,onCancel:c,width:d,...p,children:m})})),r.jsx("span",{ref:x,className:"wx-portal-node wx-32GZ52"})]})}function rf(){return su(Nx)}function lk(){let n=null,a=!1,i=!1,l,c,d,m;const p=(b,w,C,j,k)=>{l=b,c=w,d=C,m=j,i=k},g=b=>{n=b,a=n!==null,d(n)},v=(b,w)=>{if(!i&&b!==null&&l){const C=l.querySelectorAll(".wx-list > .wx-item")[b];C&&(C.scrollIntoView({block:"nearest"}),w&&w.preventDefault())}},x=(b,w)=>{const C=b===null?null:Math.max(0,Math.min(n+b,c.length-1));C!==n&&(g(C),l?v(C,w):requestAnimationFrame(()=>v(C,w)))};return{move:b=>{const w=nu(b),C=c.findIndex(j=>j.id===w);C!==n&&g(C)},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:p,navigate:x}}const Oy=10,ok=u.memo(function({data:n,checkboxes:a,itemTemplate:i,value:l}){return r.jsxs(r.Fragment,{children:[a&&r.jsx(ak,{id:n.id,css:"wx-list-checkbox",value:l&&l.includes(n.id)}),i?Qh(i,{option:n}):n.label]})});function Hy({visibleItems:n,visibleRange:a,navIndex:i,checkboxes:l,itemTemplate:c,value:d,measureRefCallback:m}){return n.map((p,g)=>{const v=a.start+g;return r.jsx("div",{ref:g===0?m:void 0,className:`wx-233fr7 wx-item ${v===i?"wx-focus":""}`,"data-id":p.id,children:r.jsx(ok,{data:p,checkboxes:l,itemTemplate:c,value:d})},p.id)})}function lf({items:n=[],children:a,onSelect:i,onReady:l,virtualized:c=!1,checkboxes:d,multiselect:m,value:p,...g}){const v=u.useRef(),x=u.useRef(!1),b=u.useRef(lk()),[w,C]=u.useState(null),j=u.useRef(w),[k,M]=u.useState(0),[A,T]=u.useState(24),D=u.useRef(!1),B=(u.useContext(qs)||rf()).getGroup("core"),H=u.useRef(n);u.useEffect(()=>{H.current=n},[n]);const W=u.useRef(p);u.useEffect(()=>{W.current=p},[p]);const _=u.useRef(0);u.useEffect(()=>{_.current=A},[A]);const Z=u.useCallback(K=>{K&&K.stopPropagation();const xe=H.current,z=W.current,le=j.current;let ke;const Ce=xe[le]?.id;m?z&&z.includes(Ce)?ke=z.filter(Ue=>Ue!==Ce):ke=[...z||[],Ce]:ke=Ce,i&&i({id:ke})},[m,i]),G=u.useRef(Z);u.useEffect(()=>{G.current=Z},[Z]);const q=u.useCallback(K=>{if(v.current){let xe=K*_.current-v.current.clientHeight+_.current;M(xe),v.current.scrollTop=xe}},[_.current]),Q=u.useCallback(K=>{v.current=K,c&&(K&&!x.current&&j.current!==null&&requestAnimationFrame(()=>{v.current&&(q(j.current),x.current=!0)}),K||(x.current=!1))},[q]),O=u.useCallback(K=>{if(!K||D.current)return;const xe=K.getBoundingClientRect().height;xe&&(T(xe),_.current=xe,D.current=!0)},[]);u.useEffect(()=>{b.current.init(v.current,n,K=>{C(K),j.current=K},K=>G.current(K),c)},[n,v.current,c]),u.useEffect(()=>{const K=(z,le)=>{b.current.navigate(z,le),q(j.current)},xe=(z,le)=>{const ke=j.current,Ce=H.current;if(ke!==0&&ke!==Ce.length-1&&(z.key==="ArrowDown"||z.key==="ArrowUp")&&z.preventDefault(),b.current.keydown(z,le),v.current){const Ue=v.current.scrollTop<=j.current*_.current,Be=v.current.scrollTop+v.current.clientHeight>=j.current*_.current+_.current;Ue?Be||q(j.current):(v.current.scrollTop=j.current*_.current,M(v.current.scrollTop))}};l&&l({navigate:c?K:b.current.navigate,keydown:c?xe:b.current.keydown,move:b.current.move})},[]);const ye=u.useRef(0),me=u.useRef(n);me.current!==n&&(me.current=n,ye.current+=1);const X=u.useCallback(()=>{b.current.navigate(null)},[b]),I=u.useCallback(K=>{c&&M(K.target.scrollTop)},[c]),ee=u.useMemo(()=>Math.ceil((v.current?.clientHeight||0)/A),[A,k]),V=u.useMemo(()=>{if(!c)return{start:0,end:n.length};if(!n.length)return{start:0,end:0};const K=Math.floor(k/A),xe=K+ee;return{start:Math.max(0,K-Oy),end:Math.min(n.length,xe+Oy)}},[c,n,k,A,ee]),P=u.useMemo(()=>{if(!c)return n;const{start:K,end:xe}=V;return n.slice(K,xe).map(z=>({...z}))},[c,n,V]),re=V.start*A,ue=n.length*A;return u.useEffect(()=>{c&&M(0)},[n,c]),u.useEffect(()=>{w===null&&(x.current=!1)},[w]),w===null?null:r.jsx(np,{onCancel:X,...g,children:r.jsx("div",{className:"wx-233fr7 wx-list",ref:Q,onClick:Z,onMouseMove:b.current.move,onScroll:I,children:n.length?c?r.jsx("div",{className:"wx-233fr7 wx-list-wrapper",style:{height:`${ue}px`},children:r.jsx("div",{className:"wx-233fr7 wx-list-content",style:{transform:`translateY(${re}px)`},children:r.jsx(Hy,{visibleRange:V,visibleItems:P,navIndex:w,measureRefCallback:O,checkboxes:d,itemTemplate:a,value:p})})}):r.jsx(Hy,{visibleRange:V,visibleItems:P,navIndex:w,measureRefCallback:O,checkboxes:d,itemTemplate:a,value:p}):r.jsx("div",{className:"wx-233fr7 wx-no-data",children:B("No data")})})},ye.current)}function ap({value:n="",id:a,readonly:i=!1,focus:l=!1,select:c=!1,type:d="text",placeholder:m="",disabled:p=!1,error:g=!1,title:v="",tooltip:x,css:b="",icon:w="",clear:C=!1,onChange:j}){const k=Ex(a),[M,A]=hr(n),T=u.useRef(null),D=u.useMemo(()=>w&&b.indexOf("wx-icon-left")===-1?"wx-icon-right "+b:b,[w,b]),B=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 H=u.useCallback(G=>{const q=G.target.value;A(q),j&&j({value:q,input:!0})},[j]),W=u.useCallback(G=>j&&j({value:G.target.value}),[j]);function _(G){G.stopPropagation(),A(""),j&&j({value:""})}let Z=d;return d!=="password"&&d!=="number"&&(Z="text"),u.useEffect(()=>{const G=W,q=T.current;return q.addEventListener("change",G),()=>{q&&q.removeEventListener("change",G)}},[W]),r.jsxs("div",{className:`wx-hQ64J4 wx-text ${D} ${g?"wx-error":""} ${p?"wx-disabled":""} ${C?"wx-clear":""}`,"data-tooltip-text":x,children:[r.jsx("input",{className:"wx-hQ64J4 wx-input",ref:T,id:k,readOnly:i,disabled:p,placeholder:m,type:Z,title:v,value:M,onInput:H}),C&&!p&&M?r.jsxs(r.Fragment,{children:[r.jsx("i",{className:"wx-hQ64J4 wx-icon wxi-close",onClick:_}),B&&r.jsx("i",{className:`wx-hQ64J4 wx-icon ${w}`})]}):w?r.jsx("i",{className:`wx-hQ64J4 wx-icon ${w}`}):null]})}function ck({date:n,type:a,part:i,onShift:l}){const{calendar:c,formats:d}=u.useContext(qs).getRaw(),m=n.getFullYear(),p=u.useMemo(()=>{switch(a){case"month":return Io(d.monthYearFormat,c)(n);case"year":return Io(d.yearFormat,c)(n);case"duodecade":{const{start:v,end:x}=Ax(m),b=Io(d.yearFormat,c);return`${b(new Date(v,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:p}),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 sp({onClick:n,children:a}){return r.jsx("button",{className:"wx-3s8W4d wx-button",onClick:n,children:a})}function uk({value:n,current:a,part:i="",markers:l=null,css:c="",onCancel:d,onChange:m}){const p=(u.useContext(qs)||rf()).getRaw().calendar,g=(p.weekStart||7)%7,v=p.dayShort.slice(g).concat(p.dayShort.slice(0,g)),x=(H,W,_)=>new Date(H.getFullYear(),H.getMonth()+(W||0),H.getDate()+(_||0));let b=i!=="normal";function w(H){const W=H.getDay();return W===0||W===6}function C(){const H=x(a,0,1-a.getDate());return H.setDate(H.getDate()-(H.getDay()-(g-7))%7),H}function j(){const H=x(a,1,-a.getDate());return H.setDate(H.getDate()+(6-H.getDay()+g)%7),H}const k=u.useRef(0);function M(H,W){W.timeStamp!==k.current&&(k.current=W.timeStamp,W.stopPropagation(),m&&m(new Date(H)),d&&d())}const A=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 H=C(),W=j(),_=a.getMonth();let Z=[];for(let G=H;G<=W;G.setDate(G.getDate()+1)){const q={day:G.getDate(),in:G.getMonth()===_,date:G.valueOf()};let Q="";if(Q+=q.in?"":" wx-inactive",Q+=A.indexOf(q.date)>-1?" wx-selected":"",b){const O=q.date==A[0],ye=q.date==A[1];O&&!ye?Q+=" wx-left":ye&&!O&&(Q+=" wx-right"),q.date>A[0]&&q.date<A[1]&&(Q+=" wx-inrange")}if(Q+=w(G)?" wx-weekend":"",l){const O=l(G);O&&(Q+=" "+O)}Z.push({...q,css:Q})}return Z},[a,A,b,l]),D=u.useRef(null);let B=u.useRef({});return B.current.click=M,u.useEffect(()=>{Po(D.current,B.current)},[]),r.jsxs("div",{className:`wx-398RBS wx-month ${c}`,children:[r.jsx("div",{className:"wx-398RBS wx-weekdays",children:v.map(H=>r.jsx("div",{className:"wx-398RBS wx-weekday",children:H},H))}),r.jsx("div",{className:"wx-398RBS wx-days",ref:D,children:T.map(H=>r.jsx("div",{className:`wx-398RBS wx-day ${H.css} ${H.in?"":"wx-out"}`,"data-id":H.date,children:H.day},H.date))})]})}function dk({value:n,current:a,part:i,onCancel:l,onChange:c,onShift:d}){const m=u.useRef(new Date),[p,g]=hr(n||m.current),[v,x]=hr(a||m.current),b=u.useContext(qs).getRaw().calendar,w=b.monthShort||[],C=u.useMemo(()=>v.getMonth(),[v]),j=u.useCallback((A,T)=>{if(A!=null){T.stopPropagation();const D=new Date(v);D.setMonth(A),x(D),d&&d({current:D})}i==="normal"&&g(new Date(v)),l&&l()},[v,i,d,l]),k=u.useCallback(()=>{const A=new Date(Rx(p,i)||v);A.setMonth(v.getMonth()),A.setFullYear(v.getFullYear()),c&&c(A)},[p,v,i,c]),M=u.useCallback(A=>{const T=A.target.closest("[data-id]");if(T){const D=parseInt(T.getAttribute("data-id"),10);j(D,A)}},[j]);return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-34U8T8 wx-months",onClick:M,children:w.map((A,T)=>r.jsx("div",{className:"wx-34U8T8 wx-month"+(C===T?" wx-current":""),"data-id":T,children:A},T))}),r.jsx("div",{className:"wx-34U8T8 wx-buttons",children:r.jsx(sp,{onClick:k,children:b.done})})]})}const Zm="wx-1XEF33",fk=({value:n,current:a,onCancel:i,onChange:l,onShift:c,part:d})=>{const m=u.useContext(qs).getRaw().calendar,[p,g]=hr(a),[v,x]=hr(n),b=u.useMemo(()=>p.getFullYear(),[p]),w=u.useMemo(()=>{const{start:A,end:T}=Ax(b),D=[];for(let B=A;B<=T;++B)D.push(B);return D},[b]),C={click:j};function j(A,T){if(A){T.stopPropagation();const D=new Date(p);D.setFullYear(A),g(D),c&&c({current:D})}d==="normal"&&x(new Date(p)),i&&i()}function k(){const A=new Date(Rx(v,d)||p);A.setFullYear(p.getFullYear()),l&&l(A)}const M=u.useRef(null);return u.useEffect(()=>{M.current&&Po(M.current,C)},[]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:Zm+" wx-years",ref:M,children:w.map((A,T)=>r.jsx("div",{className:Zm+` wx-year ${b==A?"wx-current":""} ${T===0?"wx-prev-decade":""} ${T===11?"wx-next-decade":""}`,"data-id":A,children:A},T))}),r.jsx("div",{className:Zm+" wx-buttons",children:r.jsx(sp,{onClick:k,children:m.done})})]})},Fy={month:{component:uk,next:hk,prev:mk},year:{component:dk,next:gk,prev:pk},duodecade:{component:fk,next:yk,prev:vk}};function mk(n){return n=new Date(n),n.setMonth(n.getMonth()-1),n}function hk(n){return n=new Date(n),n.setMonth(n.getMonth()+1),n}function pk(n){return n=new Date(n),n.setFullYear(n.getFullYear()-1),n}function gk(n){return n=new Date(n),n.setFullYear(n.getFullYear()+1),n}function vk(n){return n=new Date(n),n.setFullYear(n.getFullYear()-10),n}function yk(n){return n=new Date(n),n.setFullYear(n.getFullYear()+10),n}function Rx(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 bk=["clear","today"];function xk(n){if(n==="done")return-1;if(n==="clear")return null;if(n==="today")return new Date}function wk({value:n,current:a,onCurrentChange:i,part:l="normal",markers:c=null,buttons:d,css:m="",onShift:p,onChange:g}){const v=u.useContext(qs).getGroup("calendar"),[x,b]=u.useState("month"),w=Array.isArray(d)?d:d?bk:[],C=(T,D)=>{T.preventDefault(),g&&g({value:D})},j=()=>{x==="duodecade"?b("year"):x==="year"&&b("month")},k=T=>{const{diff:D,current:B}=T;if(D===0){x==="month"?b("year"):x==="year"&&b("duodecade");return}if(D){const H=Fy[x];i(D>0?H.next(a):H.prev(a))}else B&&i(B);p&&p()},M=T=>{b("month"),g&&g({select:!0,value:T})},A=u.useMemo(()=>Fy[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(ck,{date:a,part:l,type:x,onShift:k}),r.jsxs("div",{children:[r.jsx(A,{value:n,current:a,onCurrentChange:i,part:l,markers:c,onCancel:j,onChange:M,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(sp,{onClick:D=>C(D,xk(T)),children:v(T)})},T))})]})]})})}function rp(n){let{words:a=null,optional:i=!1,children:l}=n,c=u.useContext(qs);const d=u.useMemo(()=>{let m=c;return(!m||!m.extend)&&(m=su(Nx)),a!==null&&(m=m.extend(a,i)),m},[a,i,c]);return r.jsx(qs.Provider,{value:d,children:l})}function By(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 Sk=["clear","today"];function Dx({value:n,current:a,markers:i=null,buttons:l=Sk,css:c="",onChange:d}){const[m,p]=hr(n),[g,v]=hr(a);u.useEffect(()=>{By(g,m,v,!1)},[m,g]);const x=u.useCallback(w=>{const C=w.value;C?(p(new Date(C)),By(g,new Date(C),v,!0)):p(null),d&&d({value:C?new Date(C):null})},[d,g]),b=u.useCallback(w=>{v(w)},[v]);return g?r.jsx(rp,{children:r.jsx(wk,{value:m,current:g,markers:i,buttons:l,css:c,onChange:x,onCurrentChange:b})}):null}function Ck(n){return n||(n={}),n.width||(n.width="unset"),n}const kk=["clear","today"];function jk({value:n,id:a,disabled:i=!1,error:l=!1,placeholder:c="",format:d="",buttons:m=kk,css:p="",title:g="",tooltip:v,editable:x=!1,clear:b=!1,onChange:w,dropdown:C={}}){const{calendar:j,formats:k}=(u.useContext(qs)||rf()).getRaw(),M=d||k?.dateFormat;let A=typeof M=="function"?M:Io(M,j);const[T,D]=u.useState(n),[B,H]=u.useState(!1);u.useEffect(()=>{D(n)},[n]);function W(){H(!1)}function _(q){const Q=q===T||q&&T&&q.valueOf()===T.valueOf()||!q&&!T;D(q),Q||w&&w({value:q}),setTimeout(W,1)}const Z=u.useMemo(()=>T?A(T):"",[T,A]);function G({value:q,input:Q}){if(!x&&!b||Q)return;let O=typeof x=="function"?x(q):q?new Date(q):null;O=isNaN(O)?T||null:O||null,_(O)}return u.useEffect(()=>{const q=W;return window.addEventListener("scroll",q),()=>window.removeEventListener("scroll",q)},[]),r.jsxs("div",{className:"wx-1lKOFG wx-datepicker",onClick:()=>H(!0),children:[r.jsx(ap,{css:`wx-date-input ${p}`,title:g,tooltip:v,value:Z,id:a,readonly:!x,disabled:i,error:l,placeholder:c,onInput:W,onChange:G,icon:"wxi-calendar",clear:b}),B&&!i&&r.jsx(np,{onCancel:W,...Ck(C),children:r.jsx(Dx,{buttons:m,value:T,onChange:q=>_(q.value)})})]})}function Ak({value:n="",options:a=[],textOptions:i=null,placeholder:l="",disabled:c=!1,error:d=!1,title:m="",tooltip:p,textField:g="label",clear:v=!1,css:x="",children:b,onChange:w,dropdown:C={}}){const j=u.useRef(null),k=u.useRef(null);let[M,A]=hr(n);function T(_){j.current=_.navigate,k.current=_.keydown}const D=u.useMemo(()=>M||M===0?(i||a).find(_=>_.id===M):null,[M,i,a]),B=u.useCallback(({id:_})=>{(_||_===0)&&(A(_),j.current(null),w&&w({value:_}))},[A,w]),H=u.useCallback(_=>{_.stopPropagation(),A(""),w&&w({value:""})},[A,w]),W=u.useCallback(()=>a.findIndex(_=>_.id===M),[a,M]);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(W()),onKeyDown:_=>k.current(_,W()),tabIndex:0,"data-tooltip-text":p,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}):" "}),v&&!c&&M?r.jsx("i",{className:"wx-2YgblL wx-icon wxi-close",onClick:H}):r.jsx("i",{className:"wx-2YgblL wx-icon wxi-angle-down"}),!c&&r.jsx(lf,{items:a,onReady:T,onSelect:B,...C,children:({option:_})=>b?b(_):_[g]})]})}const Nk=({options:n=[],value:a="",css:i="",children:l,onChange:c})=>{const[d,m]=u.useState(a),p=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:()=>p(g.id),"data-tooltip-text":g.tooltip,children:l?Qh(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 Mk({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 Tk({data:n=[]}){return r.jsx("div",{className:"wx-3nwoO9 wx-notices",children:n.map(a=>r.jsx(Mk,{notice:a},a.id))})}function Lh({title:n="",buttons:a=["cancel","ok"],header:i,children:l,footer:c,css:d="",onConfirm:m,onCancel:p}){const g=(u.useContext(qs)||rf()).getGroup("core"),v=u.useRef(null);u.useEffect(()=>{v.current?.focus()},[]);function x(w){switch(w.code){case"Enter":{const C=w.target.tagName;if(C==="TEXTAREA"||C==="BUTTON")return;m&&m({event:w});break}case"Escape":p&&p({event:w});break}}function b(w,C){const j={event:w,button:C};C==="cancel"?p&&p(j):m&&m(j)}return r.jsx("div",{className:`wx-1FxkZa wx-modal ${d}`,ref:v,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(Kc,{type:`block ${w==="ok"?"primary":"secondary"}`,onClick:C=>b(C,w),children:g(w)})},w))})]})})}function Ek({children:n},a){const[i,l]=u.useState(null),[c,d]=u.useState([]);return u.useImperativeHandle(a,()=>({showModal:m=>{const p={...m};return l(p),new Promise((g,v)=>{p.resolve=x=>{l(null),g(x)},p.reject=x=>{l(null),v(x)}})},showNotice:m=>{m={...m},m.id=m.id||Jh(),m.remove=()=>d(p=>p.filter(g=>g.id!==m.id)),m.expire!=-1&&setTimeout(m.remove,m.expire||5100),d(p=>[...p,m])}}),[]),r.jsxs(r.Fragment,{children:[n,i&&r.jsx(Lh,{title:i.title,buttons:i.buttons,onConfirm:i.resolve,onCancel:i.reject,children:i.message}),r.jsx(Tk,{data:c})]})}const Rk=u.forwardRef(Ek);function Dk(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(Mx.Provider,{value:l,children:r.jsx(Rk,{ref:i,children:a})})}const Lk=({value:n=!1,type:a="",icon:i="",disabled:l=!1,iconActive:c="",onClick:d,title:m="",tooltip:p,css:g="",text:v="",textActive:x="",children:b,active:w,onChange:C})=>{const[j,k]=hr(n),M=u.useMemo(()=>(j?"pressed":"")+(a?" "+a:""),[j,a]),A=u.useCallback(T=>{let D=!j;d&&d(T),T.defaultPrevented||(k(D),C&&C({value:D}))},[j,d,C]);return j&&w?r.jsx(Kc,{title:m,tooltip:p,text:j&&x||v,css:g,type:M,icon:j&&c||i,onClick:A,disabled:l,children:Qh(w,{value:j})}):b?r.jsx(Kc,{title:m,tooltip:p,text:j&&x||v,css:g,type:M,icon:j&&c||i,onClick:A,disabled:l,children:b}):r.jsx(Kc,{title:m,tooltip:p,text:j&&x||v,css:g,type:M,icon:j&&c||i,onClick:A,disabled:l})};function _k(){return r.jsx(r.Fragment,{})}function Py(n){const{fonts:a=!0,children:i}=n;return r.jsx(ep.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(_k,{}),r.jsx("link",{rel:"stylesheet",href:"https://cdn.svar.dev/fonts/wxi/wx-icons.css"})]})]})})}Zh(Oa);const ip={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 Lx=class{constructor(n){this._nextHandler=null,this._dispatch=n,this.exec=this.exec.bind(this)}async exec(n,a){return this._dispatch(n,a),this._nextHandler&&await this._nextHandler.exec(n,a),a}setNext(n){return this._nextHandler=n}};new Date().valueOf();var Ik=class{constructor(n){const a={id:0,$level:0,data:[],parent:null},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]:$y(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=Ad(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=Ad(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 p=this._pool.get(l.parent),g=c?d:this._pool.get(d.parent);g.data||(g.data=[]);const v=Ad(p,l.id);zk(p,v);const x=c?g.data.length:Ad(g,d.id)+(a==="after"?1:0);if($y(g,x,l),p.id===g.id&&v===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(p)}_clearBranch(n){n.data&&!n.data.length&&(n.open&&delete n.open,this.update(n.id,{data:null}))}toArray(){const n=[],a=this._pool.get(0).data;return a&&_x(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 _x(n,a){n.forEach(i=>{a.push(i),i.open===!0&&_x(i.data,a)})}function zk(n,a){const i=[...n.data];i.splice(a,1),n.data=i}function $y(n,a,i){const l=[...n.data];l.splice(a,0,i),n.data=l}function Ad(n,a){return n?.data.findIndex(i=>i.id===a)}var Ix=2,Ok=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 p in a){const g=i[p],v=l[p],x=a[p];if(g&&(v===x&&typeof x!="object"||x instanceof Date&&v instanceof Date&&v.getTime()===x.getTime()))continue;const b=c+(c?".":"")+p;g?(g.__parse(x,b,d,m)&&(l[p]=x),m&Ix?d[b]=g.__trigger:g.__trigger()):(x&&x.__reactive?i[p]=this._wrapNested(x,x,b,d):i[p]=this._wrapWritable(x),l[p]=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,p,g,v)=>(this._wrapProperties(m,d,i,p,g,v),!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 Uy(n,a){return Object.defineProperty(n,"__reactive",{value:!0,enumerable:!1,writable:!1}),n}var Hk=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 p=this._triggers.get(m)||[];p.push(d),this._triggers.set(m,p)}),d.out.forEach(m=>{const p=this._sources.get(m)||{};d.in.forEach(g=>p[g]=!0),this._sources.set(m,p)})}),this._routes.forEach(d=>{d.length=Math.max(...d.in.map(m=>zx(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,Ix);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],p=this._triggers.get(m);p&&p.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 zx(n,a,i){const l=a.get(n);if(!l)return i;const c=Object.keys(l).map(d=>zx(d,a,i+1));return Math.max(...c)}var Fk=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(a,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 Mo=1024;function au(n){return n<Mo?`${n} B`:n<Mo**2?`${(n/Mo).toFixed(1)} KB`:n<Mo**3?`${(n/Mo**2).toFixed(1)} MB`:`${(n/Mo**3).toFixed(1)} GB`}function qy(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(Gy(a)),d=l.sort(Gy(a));return[...c,...d]}function Bk(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 Pk(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 Gy({key:n,order:a}){const i=a==="asc"?Bk:Pk;return(l,c)=>i(l[n],c[n])}function lp(n,a){const i=n==="/"?1:n.split("/").length;return i>=a.length?null:a[i].id}function $k(n){return n.length>1?n[n.length-2].id:null}let Uk=class extends Ik{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(p=>m.push(this.renameFiles(p.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:p,size:g,lazy:v}=c,x={id:d,date:m,type:p??"file"};v&&(x.lazy=v),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 p=c!==-1?l.slice(0,c):l,g=i+(i==="/"?"":"/")+p;for(;this.byId(g+m);){const v=".new";g+=v,p+=v}return{...a,id:g+m,name:p+m,parent:i,ext:d.toLocaleLowerCase()}}},qk=class extends Ok{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:p,panels:g}=this.getState(),v=[];v[d]={_crumbs:p.getParents(g[d].path)},this.setState({panels:v},m)}}),i.push({in:["data",`panels.${d}.path`,`panels.${d}._sorts`,"search"],out:[`panels.${d}._files`],exec:m=>{const{data:p,panels:g,search:v}=this.getState();let x;v?x=p.findFiles(v,g[d].path):x=p.byId(g[d].path)?.data||[];const{path:b,_sorts:w}=g[d];x=qy(x,w[b]);const C=[];C[d]={_files:x},this.setState({panels:C},m)}}),i.push({in:["data",`panels.${d}.selected`,`panels.${d}._sorts`],out:[`panels.${d}._selected`],exec:m=>{const{data:p,panels:g}=this.getState(),v=[];g[d].selected.forEach(j=>{const k=p.byId(j);k&&v.push(k)});const{path:x,_sorts:b}=g[d],w=qy(v,b[x]),C=[];C[d]={_selected:w},this.setState({panels:C},m)}});this._router=new Hk(super.setState.bind(this),i,{data:d=>new Uk(d)});const l=this.in=new Fk;l.on("select-file",({id:d,toggle:m,range:p,panel:g,type:v})=>{const{panels:x,activePanel:b}=this.getState();typeof g>"u"&&(g=b),d||(m=p=!1);let w=[...x[g].selected];if(m){const j=w.indexOf(d);j===-1?w.push(d):w.splice(j,1)}else if(p&&x[g]._lastSelected){const j=x[g]._files;let k=j.findIndex(T=>T.id==x[g]._lastSelected),M=j.findIndex(T=>T.id==d);M<k&&([k,M]=[M,k]);const A=j.slice(k,M+1).map(T=>T.id);w=[...new Set([...w,...A])]}else w=d?[d]:[];const C=[];C[g]={selected:w,_lastSelected:d,_selectNavigation:v==="navigation"},this.setState({panels:C})}),l.on("set-path",({id:d,panel:m,selected:p})=>{const{data:g,activePanel:v}=this.getState(),x=g.byId(d);if(x){const b=[];typeof m>"u"&&(m=v),b[m]={path:d},this.setState({panels:b}),l.exec("select-file",{panel:m}),p&&p.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:p,data:g}=this.getState(),v=g.byId(d);v&&(v.lazy||(v.data=[]),v.lazy=!1,g.parse(m,d,p==="search"),this.setState({data:g}))}),l.on("open-tree-folder",({id:d,mode:m})=>{const{data:p}=this.getState();p.update(d,{open:m}),this.setState({data:p})}),l.on("show-preview",({mode:d})=>{this.setState({preview:d})}),l.on("rename-file",d=>{const{id:m,name:p}=d,{data:g,panels:v}=this.getState(),x=g.byId(m);if(x.name!==p){x.name=p;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 C=v.map(j=>({selected:j.selected,_crumbs:j._crumbs,_lastSelected:j._lastSelected,_sorts:j._sorts}));g.remove(m),this._updatePanels(C,w),this.setState({data:g,panels:C})}}),l.on("create-file",d=>{const{file:m,parent:p}=d,{data:g}=this.getState(),v=g.normalizeFile(m,p);v.type=m.type||"file",d.newId=v.id,g.add(v),this.setState({data:g}),l.exec("select-file",{id:v.id})}),l.on("delete-files",({ids:d})=>{const{data:m,panels:p}=this.getState(),g=p.map(v=>({selected:v.selected,_crumbs:v._crumbs,_lastSelected:v._lastSelected,_sorts:v._sorts}));d.forEach(v=>m.remove(v)),this._updatePanels(g,{}),this.setState({data:m,panels:g})}),l.on("copy-files",d=>{const{ids:m,target:p}=d;if(this._isPlacedIntoSelf(m,p)){console.error("You cannot copy a folder into itself"),d.skipProvider=!0;return}const{data:g,panels:v,activePanel:x}=this.getState(),b=g.copyFiles(m,p);d.newIds=m.map(w=>b[w]),this.setState({data:g}),v[x].path==p&&(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:p}=d;if(this._isPlacedIntoSelf(m,p)){console.error("You cannot move a folder into itself"),d.skipProvider=!0;return}const{data:g,panels:v,activePanel:x}=this.getState(),b=g.moveFiles(m,p);if(b){d.newIds=m.map(C=>b[C]);const w=v.map(C=>({selected:C.selected,_crumbs:C._crumbs,_lastSelected:C._lastSelected,_sorts:C._sorts}));this._updatePanels(w,b,!0),this.setState({data:g,panels:w}),v[x].path==p&&(l.exec("select-file",{}),m.forEach(C=>{l.exec("select-file",{id:b[C],toggle:!0})}))}});let c=null;l.on("filter-files",({text:d})=>{if(!d){c&&this.setState({...c});return}l.exec("select-file",{});const{panels:m,mode:p}=this.getState();c||(c={panels:m,mode:p,search:""}),this.setState({mode:"search",search:d})}),l.on("set-mode",({mode:d})=>{const{activePanel:m}=this.getState(),p=[];p[m]={_selectNavigation:!1};const g={mode:d,search:"",panels:p};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:p,path:g})=>{const{activePanel:v,panels:x}=this.getState();p=p??v,g=g??x[p].path;const b=[];b[p]={_sorts:{...x[p]._sorts,[g]:{key:d,order:m}}},this.setState({panels:b})}),this.initOnce()}initOnce(){const a=[];for(let l=0;l<2;l++)a[l]=Uy({_crumbs:[],_files:[],_selected:[],_sorts:{},path:"/",selected:[],...a[l]});const i={panels:Uy(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(v=>{c.byId(v)?m.push(v):!l&&i[v]&&m.push(i[v])}),d.selected=m,c.byId(d._lastSelected)||(d._lastSelected=l?null:i[d._lastSelected]||null);const p={};Object.keys(d._sorts).forEach(v=>{c.byId(v)?p[v]=d._sorts[v]:i[v]&&!l&&(p[i[v]]=d._sorts[v])}),d._sorts=p;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 Gk(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 Vk(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 Wk(n,a="data-id"){const i=Vk(n,a);return i?i.getAttribute(a):null}new Date().valueOf();function Yk(n,a){const{api:i}=a;function l(d,m){const p=a.getPanel(),g=p.selected,v=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 C=`${v?"ctrl+":""}${x?"shift+":""}${d}`,j=b?b.find(M=>M.hotkey?.toLowerCase()===C):!1,k=a.performAction;if(j)switch(C){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(v||x)break;const{_crumbs:M,_selectNavigation:A}=p;if(A){const T=$k(M);if(T){const D=lp(T,M);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:M,_selected:A,path:T,_selectNavigation:D}=p;let B;if(A.length){const H=A.at(0).id,W=M.findIndex(_=>_.id===H);if(W!==-1){const _=W-1;M[_]?B=M[_].id:T!=="/"&&!(v||x)&&i.exec("select-file",{type:"navigation"})}}else{if(D)break;if(T!=="/"){i.exec("select-file",{type:"navigation"});break}B=M.at(0)?.id}B&&i.exec("select-file",{id:B,toggle:v,range:x});break}case"arrowdown":case"arrowright":{const{_files:M,_selected:A,path:T,_selectNavigation:D}=p;let B;if(A.length){const H=A.at(-1).id,W=M.findIndex(_=>_.id===H);if(W!==-1){const _=W+1;M[_]&&(B=M[_].id)}}else{if(T!=="/"&&!D){i.exec("select-file",{type:"navigation"});break}B=M.at(0)?.id}B&&i.exec("select-file",{id:B,toggle:v,range:x});break}}}function c(d){const m=d.code.replace("Key","").toLowerCase();l(m,d),m=="tab"&&setTimeout(()=>{const p=document.activeElement;p.className.indexOf("table")!=-1&&i.exec("set-active-panel",{panel:+Wk(p,"data-panel")})})}return n.addEventListener("keydown",c),{destroy:()=>{n.removeEventListener("keydown",c)}}}function Kk(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 Xk(n,a="data-id"){const i=n.getAttribute(a);return i?Qk(i):null}function Qk(n){if(n.startsWith(":"))return n.substring(1);const a=n*1;return isNaN(a)?n:a}function Zk(){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 Jk=Zk();new Date().valueOf();function Ox(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 ej(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 ut(n,a){const i=n.getState(),l=n.getReactiveState();return ej(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(p=>p+1)}),[n]),[i.current,l]}function Ss(n,a){const i=n.getState(),l=n.getReactiveState();return tj(l[a],i[a])}function Hx(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,p)=>p.toUpperCase())),a[d]=c.trim()}}),a}function Fx(n){let a=n,i=[];return{subscribe:p=>{i.push(p),p(a)},unsubscribe:p=>{i=i.filter(g=>g!==p)},set:p=>{a=p,i.forEach(g=>g(a))},update:p=>{a=p(a),i.forEach(g=>g(a))}}}function Vy(n,a,i){function l(c){const d=Kk(c);if(!d)return;const m=Xk(d);if(typeof a=="function")return a(m,c);let p,g=c.target;for(;g!=d;){if(p=g.dataset?g.dataset.action:null,p&&a[p]){a[p](m,c);return}g=g.parentNode}a[i]&&a[i](m,c)}return Jk.addEvent(n,i,l)}function nj(n,a){const i=[Vy(n,a,"click")];return a.dblclick&&i.push(Vy(n,a.dblclick,"dblclick")),()=>{i.forEach(l=>l())}}function Bx(n,a){return n.map((i,l)=>{const c=a(i,l);return i.data&&i.data.length&&(c.data=Bx(i.data,a)),c}).filter(Boolean)}function Px(n,a){const i=[];return n.forEach(l=>{if(l.data){const c=Px(l.data,a);c.length&&i.push({...l,data:c})}else a(l)&&i.push(l)}),i}function aj(n){return Bx(n,(a,i)=>{const l={...a,id:a.id||Jh()};return l.type&&(l.comp=l.type),l.comp==="separator"&&n[i-1]?.comp==="separator"?null:l})}const $x={};function sj(n){return $x[n]||n}function rj(n,a){$x[n]=a}function ij({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(p=>{if(i.data){p.stopPropagation(),a(i.id,l.current);return}n(p)},[n,a,i]),m=u.useMemo(()=>i&&i.comp?sj(i.comp):null,[i]);return r.jsxs("div",{ref:l,className:`wx-cDCz9rZQ wx-option ${i.css||""} ${i.disabled?"wx-disabled":""}`,"data-id":Ln(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 op({options:n,left:a=0,top:i=0,at:l="bottom",parent:c=null,mount:d=null,context:m=null,css:p="",onClick:g,onCancel:v}){const[x,b]=u.useState(-1e4),[w,C]=u.useState(-1e4),[j,k]=u.useState(20),[M,A]=u.useState(),T=u.useRef(null),[D,B]=u.useState(!1),[H,W]=u.useState(null),_=u.useCallback(()=>{const me=kx(T.current,c,l,a,i);me&&(b(me.x),C(me.y),A(me.width));let X=me?.z??20;const I=c?Y1(c):[];let ee=0;for(const V of I){const P=parseInt(getComputedStyle(V).zIndex,10);P>ee&&(ee=P)}ee>=X&&(X=ee+1),k(X)},[c,l,a,i]);u.useEffect(()=>{d&&d(_)},[]);const Z=u.useCallback(()=>{B(!1)},[]),G=u.useCallback((me,X)=>{B(me),W(X)},[]),q=u.useMemo(()=>aj(n),[n]);u.useEffect(()=>{_()},[c,_]);const Q=u.useRef(g),O=u.useRef(v),ye=u.useRef(c);return u.useEffect(()=>{Q.current=g},[g]),u.useEffect(()=>{O.current=v},[v]),u.useEffect(()=>{ye.current=c},[c]),u.useEffect(()=>{if(!T.current)return;function me(X){O.current?O.current(X):Q.current&&Q.current({action:null,option:null})}return pr(T.current,{callback:me,modal:!0,parent:()=>ye.current}).destroy},[]),r.jsx("div",{ref:T,"data-wx-menu":"true",className:`wx-XMmAGqVx wx-menu ${p}`,style:{position:"absolute",top:w+"px",left:x+"px",width:M,zIndex:j},onMouseLeave:Z,children:q.map(me=>r.jsxs(u.Fragment,{children:[me.comp==="separator"?r.jsx("div",{className:"wx-XMmAGqVx wx-separator"}):r.jsx(ij,{option:me,onShow:G,onClick:X=>{if(!me.data&&!X.defaultPrevented){const I={context:m,action:me,option:me,event:X};me.handler&&me.handler(I),g&&g(I),X.stopPropagation()}}}),me.data&&D===me.id?r.jsx(op,{css:p,options:me.data,at:"right-overlap",parent:H,context:m,onClick:g,onCancel:v}):null]},me.id))})}const Ux=u.forwardRef(function(n,a){const{options:i,at:l="bottom",resolver:c=null,dataKey:d="contextId",filter:m=null,css:p="",children:g,onClick:v}=n,[x,b]=u.useState(null),[w,C]=u.useState(null),[j,k]=u.useState(0),[M,A]=u.useState(0),T=u.useRef(null),D=u.useMemo(()=>`data-${d.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,[d]),B=u.useMemo(()=>x!==null&&m?Px(i,Z=>m(Z,x)):i,[x,m,i]);function H(Z){C(null),v&&v(Z)}function W(Z){if(T.current===Z){T.current=null;return}C(null),v&&v({action:null,option:null})}const _=u.useCallback((Z,G)=>{if(!Z){C(null);return}if(Z.defaultPrevented)return;const q=Z.target;if(q&&q.dataset&&q.dataset.menuIgnore)return;if(w&&w===q){C(null),Z.preventDefault();return}k(Z.clientX+1),A(Z.clientY+1);let Q=typeof G<"u"?G:nu(q,D);c&&(Q=c(Q,Z),!Q)||(b(Q),C(q),T.current=Z.nativeEvent||Z,Z.preventDefault())},[w,D,c]);return u.useImperativeHandle(a,()=>({show:_}),[_]),r.jsxs(r.Fragment,{children:[g?r.jsx("span",{onClick:_,"data-menu-ignore":"true",children:typeof g=="function"?g():g}):null,w?r.jsx(tp,{children:r.jsx(op,{css:p,at:l,top:M,left:j,parent:w,context:x,onClick:H,onCancel:W,options:B},w)}):null]})}),lj=u.forwardRef(function(n,a){const{options:i,at:l="bottom",css:c="",children:d,onClick:m}=n,[p,g]=u.useState(null),v=u.useRef(null);function x(j){g(null),m&&m(j)}function b(j){if(v.current===j){v.current=null;return}g(null),m&&m({action:null,option:null})}const w=u.useCallback(j=>{g(j.target),v.current=j.nativeEvent||j,j.preventDefault()},[]);u.useImperativeHandle(a,()=>({show:w}),[w]);function C(j){let k=j.target;for(;!k.dataset.menuIgnore;)g(k),k=k.parentNode}return r.jsxs(r.Fragment,{children:[r.jsx("span",{onClick:C,"data-menu-ignore":"true",children:d}),p?r.jsx(tp,{children:r.jsx(op,{css:c,at:l,parent:p,options:i,onClick:x,onCancel:b})}):null]})}),oj=u.forwardRef(function(n,a){const{options:i,at:l="bottom",resolver:c=null,dataKey:d="contextId",filter:m=null,css:p="",children:g,onClick:v}=n,x=u.useRef(null),b=u.useCallback((w,C)=>{x.current.show(w,C)},[]);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(Ux,{css:p,at:l,options:i,resolver:c,dataKey:d,filter:m,ref:x,onClick:v})]})}),cj={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 uj=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=p=>{p.preventDefault()},m=p=>{p.preventDefault(),this.setDrag(!1),this.setSignal(["drop",i,p]),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 qx(n){const[a,i]=u.useState([]),[l,c]=u.useState(Promise.resolve(null)),[d,m]=u.useState(null),[p,g]=u.useState(!1),v=u.useRef();return v.current||(v.current=new uj(i,c,m,g,n)),v.current.files=a,v.current.ready=l,v.current.signal=d,v.current.drag=p,v.current}function dj(n,a){{if(n){const i=n.getGroup(a);if(i)return i}return su(cj).getGroup(a)}}const fj=()=>Math.random().toString(36).substr(2,9),mj=({data:n,accept:a="",multiple:i=!0,folder:l=!1,uploadURL:c="",apiOnly:d=!1,disabled:m=!1,children:p,onChange:g,onUpload:v})=>{const x=u.useRef(null),b=u.useRef(null),[w,C]=u.useState({}),j=qx(),k=n||j,M=u.useContext(In.i18n),A=dj(M,"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=q=>{const Q=new FormData;return Q.append("upload",q.file),fetch(c,{method:"POST",body:Q}).then(O=>O.json()).then(O=>({id:q.id,...O}),()=>({id:q.id,status:"error"})).catch(O=>(console.log(O),{id:q.id,status:"error"}))},D=(q,Q)=>{const O=k.updateFile(q,Q),ye={...O,status:k.getState()};O&&O.uploaded&&O.uploaded(ye),v&&v(ye),O.temp&&k.deleteFile(O.id)},B=q=>{if(!q)return;const Q=typeof c=="function"?c(q):T(q);k.setReady(Q.then(O=>{O.status=O.status||"server",D(q.id,O)}).catch(O=>{D(q.id,{status:"error",error:O})}))},H=(q,Q)=>{const O={...Q||w,id:fj(),status:"client",name:q.name,file:q};O.selected&&O.selected(O),g&&g(O),k.addFile(O,i),B(O),x.current&&(x.current.value="")},W=(q,Q,O)=>{q.isFile?q.file(ye=>{H(ye,O)}):q.isDirectory&&q.createReader().readEntries(ye=>{ye.forEach(me=>{W(me,Q+me.name+"/",O)})})},_=q=>{Array.from(q.target.files).forEach(Q=>H(Q))},Z=(q,Q)=>{Array.from(q.dataTransfer.items).forEach(O=>{const ye=O.webkitGetAsEntry();ye&&W(ye,"",Q)})},G=()=>{x.current&&x.current.click()};return u.useEffect(()=>{if(k.signal){const[q,Q,O]=k.signal;C(Q),q==="click"?G():q==="drop"&&Z(O,Q),k.setSignal(null)}},[k.signal]),d?r.jsxs(r.Fragment,{children:[r.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:x,onChange:_,accept:a,multiple:i,disabled:m}),p]}):r.jsxs("div",{className:`wx-at1A8tb8 wx-label ${k.drag?"wx-active":""} ${m?"wx-disabled":""}`,ref:b,children:[r.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:x,onChange:_,accept:a,multiple:i,disabled:m}),p||r.jsx("div",{className:"wx-at1A8tb8 wx-dropzone",children:r.jsxs("span",{children:[A("Drop files here or")," ",r.jsx("span",{className:"wx-at1A8tb8 wx-action",onClick:G,children:A("select files")})]})})]})};new Date().valueOf();function hj(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(!of(l,c))return!1}return!0}function of(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(!of(n[i],a[i]))return!1;return!0}else return hj(n,a);return n===a}function _h(n){if(typeof n!="object"||n===null)return n;if(n instanceof Date)return new Date(n);if(n instanceof Array)return n.map(_h);const a={};for(const i in n)a[i]=_h(n[i]);return a}var Gx=2,pj=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 p=a[m],g=i[m],v=n[m];if(p&&(g===v&&typeof v!="object"||v instanceof Date&&g instanceof Date&&g.getTime()===v.getTime()))continue;const x=l+(l?".":"")+m;p?(p.__parse(v,x,c,d)&&(i[m]=v),d&Gx?c[x]=p.__trigger:p.__trigger()):(v&&v.__reactive?a[m]=this._wrapNested(v,v,x,c):a[m]=this._wrapWritable(v),i[m]=v),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,p,g)=>(this._wrapProperties(d,c,a,m,p,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}}}},gj=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(p=>m[p]=!0),this._sources.set(d,m)})}),this._routes.forEach(c=>{c.length=Math.max(...c.in.map(d=>Vx(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,Gx);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(p=>{a.indexOf(p)==-1&&a.push(p)})}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 Vx(n,a,i){const l=a.get(n);if(!l)return i;const c=Object.keys(l).map(d=>Vx(d,a,i+1));return Math.max(...c)}var vj=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 yj(n){return a=>a[n]}function bj(n){return(a,i)=>a[n]=i}function Yi(n,a){return(a.getter||yj(a.id))(n)}function Jm(n,a,i){return(a.setter||bj(a.id))(n,i)}function xj(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 Vi(n,a){let i=Yi(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 wj(n,a){const i=/\n|"|;|,/;let l="";const c=a.rows||`
13
+ `,d=a.cols||" ",m=n._columns,p=n.flatData;a.header!==!1&&m[0].header&&(l=Wy("header",m,l,d,c));for(let g=0;g<p.length;g++){const v=[];for(let x=0;x<m.length;x++){let b=Vi(p[g],m[x]);i.test(b)&&(b='"'+b.replace(/"/g,'""')+'"'),v.push(b)}l+=(l?c:"")+v.join(d)}return a.footer!==!1&&m[0].footer&&(l=Wy("footer",m,l,d,c)),l}function Wy(n,a,i,l,c){const d=/\n|"|;|,/;for(let m=0;m<a[0][n].length;m++){const p=[];for(let g=0;g<a.length;g++){let v=(a[g][n][m].text||"")+"";d.test(v)&&(v='"'+v.replace(/"/g,'""')+'"'),p.push(v)}i+=(i?c:"")+p.join(l)}return i}const Sj="portrait",Cj=100,kj="a4",jj={a3:{width:11.7,height:16.5},a4:{width:8.27,height:11.7},letter:{width:8.5,height:11}};function Aj(n,a){const i=[];let l=[],c=0;const d=n.filter(p=>!p.hidden),m=Nj(a);return d.forEach((p,g)=>{c+p.width<=m?(c+=p.width,l.push(p)):(l.length&&i.push(l),l=[p],c=p.width),g===d.length-1&&l.length&&i.push(l)}),i}function Yy(n,a,i){const l=[];return n.forEach((c,d)=>{const m=c[a];for(let p=0;p<i.length;p++){l[p]||(l[p]=[]);const g={...m[p]};if(l[p][d]!==null){if(!d&&!g.rowspan&&!g.colspan){let v=1,x=n[d+v][a][p],b=g.width;for(;!x.rowspan&&!x.colspan;)v++,x=n[d+v][a][p],b+=x.width;g.colspan=v,g.width=b,g.height=i[p]}if(l[p].push(g),!g.collapsed&&g.colspan>1){let v=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+v+1).reduce((b,w)=>b+w.width,0),x>1&&(v=x-1)}for(let x=0;x<v;x++)l[p].push(null)}if(g.rowspan>1){const v=g.rowspan;for(let x=1;x<v;x++)l[p+x]||(l[p+x]=[]),l[p+x].push(null)}}}if(c.collapsed)for(let p=0;p<l.length;p++){const g=l[p],v=g[d];if(v&&v.collapsed){if(g[d]=null,!p)break}else{const x=v||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 Nj(n){const{mode:a,ppi:i,paper:l}=n,{width:c,height:d}=jj[l];return Mj(a==="portrait"?c:d,i)}function Mj(n,a){return n*a}function Tj(n={}){const{mode:a,ppi:i,paper:l}=n;return{mode:a||Sj,ppi:i||Cj,paper:l||kj}}function Wx(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 Ej(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 Ky=["resize-column","hide-column","update-cell"],Rj=["delete-row","update-row","update-cell"],Dj=["move-item"],Lj=["resize-column","move-item"];class _j{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=Yi(c,d);return of(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(p=>p.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(Lj.includes(i)){(l.inProgress&&!this.progress[i]||typeof l.inProgress!="boolean")&&(Dj.includes(i)&&this.setPrev("flatData"),Ky.includes(i)&&this.setPrev("columns")),this.progress[i]=l.inProgress;return}Rj.includes(i)&&this.setPrev("data"),Ky.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]=_h(this.getState()[a])}addToHistory(a){this.undo.push(a),this.redo=[],this.setStateHistory()}handleUndo(){if(!this.undo.length)return;const a=this.undo.pop();this.redo.push({...a.source,source:a}),this.in.exec(a.action,{...a.data,eventSource:"undo"}),this.setStateHistory()}handleRedo(){if(!this.redo.length)return;const a=this.redo.pop();this.undo.push({...a.source,source:a}),this.in.exec(a.action,{...a.data,eventSource:"redo"}),this.setStateHistory()}resetStateHistory(){this.setState({history:{undo:0,redo:0}})}setStateHistory(){this.setState({history:{undo:this.undo.length,redo:this.redo.length}})}getRow(a){const{data: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 Yx(n,a){return typeof n>"u"||n===null?-1:typeof a>"u"||a===null?1:n===a?0:n>a?1:-1}function Ij(n,a){return-Yx(n,a)}function zj(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"?Yx:Ij;return function(l,c){return i(Yi(l,a),Yi(c,a))}}function Oj(n,a){if(!n||!n.length)return;const i=n.map(l=>{const c=a.find(d=>d.id==l.key);return zj(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 Nd=28,Hj=20;function Fj(){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 Xd(n,a,i,l,c){const d=document.createElement("div"),m=document.createElement("div"),p=document.body;c=c?`${c}px`:"auto";let g,v;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),p.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),C=Math.ceil(b.height);g=Math.max(g||0,w),v=Math.max(v||0,C)}return d.remove(),{width:g,height:v}}function Xy(n,a,i,l,c){const d=[];for(let m=0;m<n.length;m++){const p=n[m][a],g=p.length;for(let v=0;v<g;v++){const{text:x,vertical:b,collapsed:w,rowspan:C,css:j}=p[v];if(!x){d[v]=Math.max(d[v]||0,l);continue}let k=0;if(b&&!w){let M=`wx-measure-cell-${a}`;if(M+=j?` ${j}`:"",k=Xd(x,M,c).width,(C>1||!p[v+1])&&i>v+1){const A=C||i-v,T=d.slice(v,v+A).reduce((D,B)=>D+B,0);if(T<k){const D=Math.ceil((k-T)/A);for(let B=v;B<v+A;B++)d[B]=(d[B]||l)+D}continue}}d[v]=Math.max(d[v]||l,k)}}return d}function Bj(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 p=a[m],g=Vi(p,n);g&&(l.push(g),n.treetoggle?c.push(a[m].$level*Nd+(a[m].$count?Nd:0)+(n.draggable?Nd:0)):n.draggable&&c.push(Nd))}return Xd(l,d,i,c).width}function Pj(n,a){const i="wx-measure-cell-header",l=n.sort?Hj:0;let c=n.header;if(typeof c=="string")return Xd(c,i,a).width+l;let d;Array.isArray(c)||(c=[c]);for(let m=0;m<c.length;m++){const p=c[m],g=typeof p=="string"?p:p.text,v=i+(typeof p=="string"?"":` ${p.css}`);let x=Xd(g,v,a).width;m===c.length-1&&(x+=l),d=Math.max(d||0,x)}return d}const $j={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&&qj(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 Kx(n){return $j[n]}function Uj(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,p=n[l];i.push(g=>{const v=Yi(g,c);return d?.handler?d.handler(v,p):Kx(m)(v,p)})}return l=>{for(let c=0;c<i.length;c++)if(!i[c](l))return!1;return!0}}function qj(n,a){return n.getFullYear()===a.getFullYear()&&n.getMonth()===a.getMonth()&&n.getDate()===a.getDate()}let Gj=class extends pj{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 gj(super.setState.bind(this),[{in:["columns","sizes","_skin"],out:["_columns","_sizes"],exec:c=>{const{columns:d,sizes:m,_skin:p}=this.getState(),g=this.copyColumns(d),v=g.reduce((w,C)=>Math.max(C.header.length,w),0),x=g.reduce((w,C)=>Math.max(C.footer.length,w),0);g.forEach(this.setCollapsibleColumns);const b=this.normalizeSizes(g,m,v,x,p);for(let w=0;w<g.length;w++)this.normalizeColumns(g,w,"header",v,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:p,_filterIds:g}=this.getState(),v=g&&new Set(g),x=m?this.flattenRows(d,[],g):v?d.filter(w=>v.has(w.id)):d,b=!p&&x.some(w=>w.rowHeight);this.setState({flatData:x,_rowHeightFromData:b},c)}}],{sizes:c=>({...i,...c})});const l=this.in=new vj;l.on("close-editor",({ignore:c})=>{const{editor:d}=this.getState();d&&(c||l.exec("update-cell",d),this.setState({editor:null}))}),l.on("open-editor",({id:c,column:d})=>{let m=this.getState().editor;m&&l.exec("close-editor",{});const p=this.getRow(c),g=d?this.getColumn(d):this.getNextEditor(p);if(g?.editor){let v=g.editor;if(typeof v=="function"&&(v=v(p,g)),!v)return;m={column:g.id,id:c,value:Yi(p,g)??"",renderedValue:Vi(p,g),type:v.type||v},typeof v=="object"&&v.config&&(m.config=v.config,v.config.options&&(m.options=v.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),p={...this.getRow(d.id)};Jm(p,m,c),d.renderedValue=Vi(p,m),this.setState({editor:d})}}),l.on("add-row",c=>{const d=this.getState();let{data:m}=d;const{select:p,_filterIds:g}=d,{row:v,before:x,after:b,select:w}=c;if(c.id=v.id=c.id||v.id||Md(),x||b){const j=x||b,k=m.findIndex(M=>M.id===j);m=[...m],m.splice(k+(b?1:0),0,c.row)}else m=[...m,c.row];const C={data:m};g&&(C._filterIds=[...g,c.id]),this.setState(C),!(typeof w=="boolean"&&!w)&&(w||p)&&l.exec("select-row",{id:v.id,show:!0})}),l.on("delete-row",c=>{const{data:d,selectedRows:m,focusCell:p,editor:g}=this.getState(),{id:v}=c,x={data:d.filter(b=>b.id!==v)};this.isSelected(v)&&(x.selectedRows=m.filter(b=>b!==v)),g?.id===v&&(x.editor=null),this.setState(x),p?.row===v&&this.in.exec("focus-cell",{eventSource:"delete-row"})}),l.on("update-cell",c=>{const d=this.getState();let{data:m}=d;m=[...m];const{tree:p}=d,{id:g,column:v,value:x}=c,b=this.getColumn(v);if(p){const w={...this._branches[g]};Jm(w,b,x);const C=this.updateTreeRow(w);w.$parent===0&&(m=C)}else{const w=m.findIndex(j=>j.id===g),C={...m[w]};Jm(C,b,x),m[w]=C}this.setState({data:m})}),l.on("update-row",c=>{let{data:d}=this.getState();const{id:m,row:p}=c,g=d.findIndex(v=>v.id===m);d=[...d],d[g]={...d[g],...p},this.setState({data:d})}),l.on("select-row",({id:c,toggle:d,range:m,mode:p,show:g,column:v})=>{const x=this.getState(),{focusCell:b}=x;let{selectedRows:w}=x;if(w.length||(m=d=!1),m){const{data:C}=this.getState();let j=C.findIndex(M=>M.id===w[w.length-1]),k=C.findIndex(M=>M.id===c);j>k&&([j,k]=[k,j]),C.slice(j,k+1).forEach(M=>{this.isSelected(M.id)||w.push(M.id)})}else if(d&&this.isSelected(c)){if(p===!0)return;w=w.filter(C=>C!==c)}else if(d){if(p===!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:v})}),this.in.on("focus-cell",c=>{const{row:d,column:m,eventSource:p}=c,{_columns:g,split:v}=this.getState();d&&m?(this.setState({focusCell:{row:d,column:m}}),p!=="click"&&((!v.left||g.findIndex(x=>x.id===c.column)>=v.left)&&(!v.right||g.findIndex(x=>x.id===c.column)<g.length-v.right)?this.in.exec("scroll",{row:d,column:m}):this.in.exec("scroll",{row:d}))):this.setState({focusCell:null})}),l.on("resize-column",c=>{const{id:d,auto:m,maxRows:p,inProgress:g}=c;if(g===!1)return;let v=c.width||0;const x=[...this.getState().columns],b=this.getColumn(d);if(m){if(m==="data"||m===!0){const{flatData:w,_skin:C}=this.getState();let j=w.length;p&&(j=Math.min(p,j));const k=w.slice(0,j);v=Bj(b,k,C)}if(m==="header"||m===!0){const{_skin:w}=this.getState();v=Math.max(Pj(b,w),v)}}b.width=Math.max(17,v),delete b.flexgrow,this.setState({columns:x})}),l.on("hide-column",c=>{const{id:d,mode:m}=c,p=[...this.getState().columns],g=this.getColumn(d),v=p.reduce((x,b)=>x+(b.hidden?0:1),0);!m||v>1?(g.hidden=!g.hidden,this.setState({columns:p})):c.skipUndo=!0}),l.on("sort-rows",c=>{const{key:d,add:m,sort:p}=c,g=this.getState(),{columns:v,data:x,tree:b}=g;if(p){const T=[...x];T.sort(p),this.setState({data:T});return}const{order:w="asc"}=c;let C=g.sortMarks;const j=Object.keys(C),k=j.length;!m||!k||k===1&&C[d]?C={[d]:{order:w}}:(k===1&&(C[j[0]]={...C[j[0]],index:0}),C={...C,[d]:{order:w,index:typeof m=="number"?m:C[d]?.index??k}});const M=Object.keys(C).sort((T,D)=>C[T].index-C[D].index).map(T=>({key:T,order:C[T].order}));this.setState({sortMarks:C});const A=Oj(M,v);if(A){const T=[...x];b?this.sortTree(T,A):T.sort(A),this.setState({data:T})}}),l.on("filter-rows",c=>{const{value:d,key:m,filter:p}=c;if(!Object.keys(c).length){this.setState({filterValues:{},_filterIds:null});return}const g=this.getState(),{data:v,tree:x,_columns:b}=g;let w=g.filterValues;const C={};m&&(w={...w,[m]:d},C.filterValues=w);const j=p??Uj(w,b);let k=[];x?k=this.filterTree(v,j,k):v.forEach(M=>{j(M)&&k.push(M.id)}),C._filterIds=k,this.setState(C)}),l.on("collapse-column",c=>{const{id:d,row:m,mode:p}=c,g=[...this.getState().columns],v=this.getColumn(d).header,x=Array.isArray(v)?v[m]:v;typeof x=="object"&&(x.collapsed=p??!x.collapsed,this.setState({columns:g}))}),l.on("move-item",c=>{const{id:d,inProgress:m}=c;let{target:p,mode:g="after"}=c;const{data:v,flatData:x,tree:b}=this.getState(),w=x.findIndex(k=>k.id===d);let C;if(g==="up"||g==="down"){if(g==="up"){if(w===0)return;C=w-1,g="before"}else if(g==="down"){if(w===x.length-1)return;C=w+1,g="after"}p=x[C]&&x[C].id}else C=x.findIndex(k=>k.id===p);if(w===-1||C===-1||m===!1)return;let j;b||(j=this.moveItem(d,p,v,g)),this.setState({data:b?this.normalizeTreeRows(j):j})}),l.on("copy-row",c=>{const{id:d,target:m,mode:p="after"}=c,g=this.getState(),{flatData:v,_filterIds:x}=g;let{data:b}=g;const w=this.getRow(d);if(!w)return;const C={...w,id:Md()};c.id=C.id;const j=v.findIndex(M=>M.id===m);if(j===-1)return;b.splice(j+(p==="after"?1:0),0,C),b=[...b];const k={data:b};x&&(k._filterIds=[...x,C.id]),this.setState(k)}),l.on("open-row",c=>{const{id:d,nested:m}=c;this.toggleBranch(d,!0,m)}),l.on("close-row",c=>{const{id:d,nested:m}=c;this.toggleBranch(d,!1,m)}),l.on("export-data",c=>new Promise((d,m)=>{const p=c.format||"csv",g=`${c.fileName||"data"}.${p}`;if(p==="csv"){const v=wj(this.getState(),c.csv||{});c.download!==!1?xj(new Blob(["\uFEFF"+v],{type:"text/csv"}),g):c.result=v,d(!0)}else m()})),l.on("hotkey",({key:c,event:d,isInput:m})=>{switch(c){case"arrowup":{const{flatData:p,focusCell:g,select:v}=this.getState();if(d.preventDefault(),m)return;const x=g?g.column:this._getFirstVisibleColumn()?.id,b=g?this.getPrevRow(g.row)?.id:p[p.length-1]?.id;x&&b&&(this.in.exec("focus-cell",{row:b,column:x,eventSource:"key"}),v&&this.in.exec("select-row",{id:b}));break}case"arrowdown":{const{flatData:p,focusCell:g,select:v}=this.getState();if(d.preventDefault(),m)return;const x=g?g.column:this._getFirstVisibleColumn()?.id,b=g?this.getNextRow(g.row)?.id:p[0]?.id;x&&b&&(this.in.exec("focus-cell",{row:b,column:x,eventSource:"key"}),v&&this.in.exec("select-row",{id:b}));break}case"arrowright":{const{focusCell:p}=this.getState();if(m)return;if(d.preventDefault(),p){const g=this.getNextColumn(p.column,!0)?.id;g&&this.in.exec("focus-cell",{row:p.row,column:g,eventSource:"key"})}break}case"arrowleft":{const{focusCell:p}=this.getState();if(m)return;if(d.preventDefault(),p){const g=this.getPrevColumn(p.column,!0)?.id;g&&this.in.exec("focus-cell",{row:p.row,column:g,eventSource:"key"})}break}case"tab":{const{editor:p,focusCell:g,select:v}=this.getState();if(p){d.preventDefault();const x=p.column;let b=p.id,w=this.getNextEditor(this.getRow(b),this.getColumn(x));if(!w){const C=this.getNextRow(b);C&&(b=C.id,w=this.getNextEditor(C))}w&&(this.in.exec("open-editor",{id:b,column:w.id}),this.in.exec("focus-cell",{row:b,column:w.id,eventSource:"key"}),v&&!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:p,focusCell:g,select:v}=this.getState();if(p){d.preventDefault();const x=p.column;let b=p.id,w=this.getPrevEditor(this.getRow(b),this.getColumn(x));if(!w){const C=this.getPrevRow(b);C&&(b=C.id,w=this.getPrevEditor(C))}w&&(this.in.exec("open-editor",{id:b,column:w.id}),this.in.exec("focus-cell",{row:b,column:w.id,eventSource:"key"}),v&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}else g&&this.in.exec("focus-cell",{eventSource:"key"});break}case"escape":{const{editor:p}=this.getState();p&&(this.in.exec("close-editor",{ignore:p.type!="multiselect"}),this.in.exec("focus-cell",{row:p.id,column:p.column,eventSource:"key"}));break}case"f2":{const{editor:p,focusCell:g}=this.getState();!p&&g&&this.in.exec("open-editor",{id:g.row,column:g.column});break}case"enter":{const{focusCell:p,tree:g}=this.getState();if(!m&&g&&p&&this.getColumn(p.column).treetoggle){const v=this.getRow(p.row);if(!v.data)return;this.in.exec(v.open?"close-row":"open-row",{id:p.row,nested:!0})}break}case"home":{const{editor:p,focusCell:g}=this.getState();if(!p&&g){d.preventDefault();const v=this._getFirstVisibleColumn()?.id;this.in.exec("focus-cell",{row:g.row,column:v,eventSource:"key"})}break}case"ctrl+home":{const{editor:p,focusCell:g,flatData:v,select:x}=this.getState();if(!p&&g){d.preventDefault();const b=v[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:p,focusCell:g}=this.getState();if(!p&&g){d.preventDefault();const v=this._getLastVisibleColumn()?.id,x=g.row;this.in.exec("focus-cell",{row:x,column:v,eventSource:"key"})}break}case"ctrl+end":{const{editor:p,focusCell:g,flatData:v,select:x}=this.getState();if(!p&&g){d.preventDefault();const b=v.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:p,flatData:g,dynamic:v,_rowHeightFromData:x}=this.getState();let b=-1,w=-1,C=0,j=0;if(c.column){b=0;const k=d.findIndex(M=>M.id===c.column);C=d[k].width;for(let M=m.left??0;M<k;M++){const A=d[M];A.hidden||(b+=A.width)}}if(c.row&&!v){const k=g.findIndex(M=>M.id===c.row);k>=0&&(x?(w=g.slice(0,k).reduce((M,A)=>M+(A.rowHeight||p.rowHeight),0),j=g[k].rowHeight):w=p.rowHeight*k)}this.setState({scroll:{top:w,left:b,width:C,height:j||p.rowHeight}})}),l.on("scroll-to",c=>{const d={};c.top!==void 0&&(d.scrollTop=c.top),c.left!==void 0&&(d.scrollLeft=c.left),Object.keys(d).length&&this.setState(d)}),l.on("print",c=>{const d=Tj(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=Fj()),a.columns&&a.columns.forEach(i=>{i.options&&(i.optionsMap=new Map(i.options.map(l=>[l.id,l.label])))}),of(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 _j(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 p=this.toggleKids(m,i,l);a===0&&(d=p)}),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],p=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(p,0,l),!0}else if(m.open)return a[d]={...m,data:[l,...m.data]},!0}return a.splice(p,0,l),!0}if(a[d].data&&(a[d]={...a[d],data:[...a[d].data]},this.insertItem(a[d].data,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 p=m.colspan;if(p){const g=c[d+1];let v=1;g&&g.colspan&&!g.collapsed&&(v=g.colspan);for(let x=v;x<p;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 p=m[l],g=d[`${l}RowHeights`];for(let v=0;v<c;v++){const x=p[v];x.id=m.id,v===p.length-1&&(x.rowspan=x.rowspan?Math.min(x.rowspan,c-v):c-v);for(let b=1;b<x.rowspan;b++){p.splice(v+b,0,{_hidden:!0});for(let w=1;w<x.colspan;w++)a[i+w][l].splice(v+b,0,{})}if(x.rowspan){const b=(x.rowspan===c?g:g.slice(v,x.rowspan+v)).reduce((w,C)=>w+C,0);x.height=b,v+x.rowspan!=c&&x.height--}if(x.colspan){let b=m.width,w=m.flexgrow||0;const C=x.colspan;for(let j=1;j<C;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})}p.length>c&&(p.length=c),m[l]=p}normalizeRows(a){for(let i=0;i<a.length;i++)a[i].id||(a[i].id=Md());return a}normalizeTreeRows(a,i,l){return!i&&!l&&(this._branches={0:{data:a}}),a.forEach(c=>{c.id||(c.id=Md()),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(v=>v.id==c),{config:m,type:p}=d.header.find(v=>v.filter).filter,g=a[c];l.push(v=>{const x=Yi(v,d);return m?.handler?m.handler(x,g):Kx(p)(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(p=>i[p.id]):d;return c.forEach(p=>{const g={};m.forEach(v=>{const x=Vi(p,v);String(x).toLowerCase().includes(a)&&(g[v.id]=!0)}),Object.keys(g).length&&(l[p.id]=g)}),l}normalizeSizes(a,i,l,c,d){const m=Xy(a,"header",l,i.headerHeight,d),p=Xy(a,"footer",c,i.footerHeight,d),g=m.reduce((x,b)=>x+b,0),v=p.reduce((x,b)=>x+b,0);return{...i,headerRowHeights:m,footerRowHeights:p,headerHeight:g,footerHeight:v}}},Vj=new Date().valueOf();function Md(){return"temp://"+Vj++}function Wj(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 Yj=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)}}},zo=[],Kj={subscribe:n=>{Xj();const a=new Yj;return zo.push(a),n(a),()=>{const i=zo.findIndex(l=>l===a);i>=0&&zo.splice(i,1)}}},Qy=!1;function Xj(){Qy||(Qy=!0,document.addEventListener("keydown",n=>{if(zo.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=zo.length-1;c>=0;c--){const d=zo[c],m=d.store.get(l)||d.store.get(i);m&&d.node.contains(n.target)&&m(n,{key:l,evKey:i})}}}))}const Qj={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 Zj(n,{keys:a,exec:i}){if(!a)return;function l(m){const p=m.target;return p.tagName==="INPUT"||p.tagName==="TEXTAREA"||Wj(p,"data-header-id")?.classList.contains("wx-filter")||!!p.closest(".wx-cell.wx-editor")}const c={};for(const m in a){const p=a[m];typeof p<"u"&&(typeof p=="function"?c[m]=p:p&&(c[m]=g=>{const v=l(g);i({key:m,event:g,isInput:v})}))}const d=Kj.subscribe(m=>{m.configure(c,n)});return{destroy:()=>{d()}}}function Jj(n,a){let i=null;a.scroll.subscribe(l=>{if(!l||l===i)return;i=l;const{left:c,top:d,height:m,width:p}=l,g=a.getHeight(),v=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+p>b+v-x&&(n.scrollLeft=c-v+p+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 ss=u.createContext(null);function eA(n,a){const i=new ResizeObserver(l=>{requestAnimationFrame(()=>a(l[0].contentRect))});return i.observe(n.parentNode),{destroy(){i.disconnect()}}}const Zy=5,tA=700;function Pd(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 Ih(n,a){const i=Pd(a);return{x:n.clientX-i.x,y:n.clientY-i.y}}function nA(n,a){const i=a.current;let l=null,c,d,m=!1,p=!1;const g=document.createElement("DIV");g.className="wx-drag-zone",g.setAttribute("tabindex",-1);function v(){clearTimeout(c),c=null}function x(_){const Z=Bo(_);Z&&(l={container:g,sourceNode:_.target,from:sf(Z),pos:Ih(_,n)},d=l.pos,b(_))}function b(_){if(!l)return;const Z=l.pos=Ih(_,n);if(!m){if(!p&&!_?.target?.getAttribute("draggable-data")&&Math.abs(d.x-Z.x)<Zy&&Math.abs(d.y-Z.y)<Zy)return;if(H(_)===!1)return W()}if(p){const G=window.scrollX||document.documentElement.scrollLeft||document.body.scrollLeft,q=window.scrollY||document.documentElement.scrollTop||document.body.scrollTop;l.targetNode=document.elementFromPoint(_.pageX-G,_.pageY-q)}else l.targetNode=_.target;i.move&&i.move(_,l),g.style.left=-(l.offset?l.offset.x:0)+"px",g.style.top=l.pos.y+(l.offset?l.offset.y:0)+"px"}function w(_){g.parentNode&&g.parentNode.removeChild(g),g.innerHTML="",m&&i.end&&i.end(_,l),l=d=null,W()}function C(_){i.getReorder&&!i.getReorder()||_.button===0&&(B(_),window.addEventListener("mousemove",j),window.addEventListener("mouseup",k),x(_))}function j(_){b(_)}function k(_){w(_)}function M(_){if(i.getReorder&&!i.getReorder())return;c=setTimeout(()=>{p=!0,x(_.touches[0])},tA),B(_);function Z(){c&&v(),_.target.removeEventListener("touchmove",A),_.target.removeEventListener("touchend",Z),w(_)}_.target.addEventListener("touchmove",A),_.target.addEventListener("touchend",Z),n.addEventListener("contextmenu",T)}function A(_){m?(_.preventDefault(),b(_.touches[0])):c&&v()}function T(_){if(m||c)return _.preventDefault(),!1}function D(_){_.preventDefault()}function B(_){if(!i.getDraggableInfo)return;const{hasDraggable:Z}=i.getDraggableInfo();(!Z||_.target.getAttribute("draggable-data"))&&(document.body.style.userSelect="none",document.body.style.webkitUserSelect="none")}function H(_){if(m=!0,i.start){if(i.start(_,l)===!1)return!1;n.appendChild(g),document.body.style.cursor="move"}}function W(_){m=p=!1,document.body.style.cursor="",document.body.style.userSelect="",document.body.style.webkitUserSelect="",window.removeEventListener("mousemove",j),window.removeEventListener("mouseup",k),_&&(n.removeEventListener("mousedown",C),n.removeEventListener("touchstart",M),n.removeEventListener("dragstart",D))}return n.addEventListener("mousedown",C),n.addEventListener("touchstart",M),n.addEventListener("dragstart",D),{destroy(){W(!0)}}}const aA=.004;function sA(){return{dirX:0,dirY:0,scrollSpeedFactor:1}}function rA(n,a,i,l){const{node:c,left:d,top:m,bottom:p,sense:g,xScroll:v,yScroll:x}=l,b=Ih(n,c);i.scrollState||(i.scrollState=sA());let w=0,C=0;b.x<d+g?w=-1:b.x>a.width-g&&(w=1),b.y<m+Math.round(g/2)?C=-1:b.y>a.height-p-Math.round(g/2)&&(C=1),(i.scrollState.dirX!==w||i.scrollState.dirY!==C)&&(Xx(i),i.scrollState.dirX=w,i.scrollState.dirY=C),(v&&i.scrollState.dirX!==0||x&&i.scrollState.dirY!==0)&&iA(i,l,{x:i.scrollState.dirX,y:i.scrollState.dirY})}function iA(n,a,i){n.autoScrollTimer||(n.autoScrollTimer=setTimeout(()=>{n.activeAutoScroll=setInterval(lA,15,n,a,i)},250))}function Xx(n){n.scrollSpeedFactor=1,n.autoScrollTimer&&(n.autoScrollTimer=clearTimeout(n.autoScrollTimer),n.activeAutoScroll=clearInterval(n.activeAutoScroll))}function lA(n,a,i){const{x:l,y:c}=i;n.scrollSpeedFactor+=aA,l!==0&&cA(n,a,l),c!==0&&oA(n,a,c)}function oA(n,a,i){const l=a.node.scrollTop;Qx(l+Math.round(a.sense/3)*n.scrollSpeedFactor*i,"scrollTop",a)}function cA(n,a,i){const l=a.node.scrollLeft;Qx(l+Math.round(a.sense/3)*n.scrollSpeedFactor*i,"scrollLeft",a)}function Qx(n,a,i){i.node[a]=n}function cf(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 Zx(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 uA(n){const{row:a,column:i,cellStyle:l=null,columnStyle:c=null,children:d,focusable:m}=n,p=u.useContext(ss),g=ut(p,"focusCell"),v=ut(p,"search"),x=ut(p,"reorder"),b=u.useMemo(()=>v?.rows[a.id]&&v.rows[a.id][i.id],[v,a.id,i.id]),w=u.useMemo(()=>cf(i.width,i.flexgrow,i.fixed,i.left,i.right),[i.width,i.flexgrow,i.fixed,i.left,i.right]);function C(H,W){let _="wx-cell";return _+=i.fixed?" "+(i.fixed===-1?"wx-shadow":"wx-fixed"):"",_+=H?" "+H(i):"",_+=W?" "+W(a,i):"",_+=i.treetoggle?" wx-tree-cell":"",_}const j=u.useMemo(()=>C(c,l),[c,l,i,a]),k=u.useMemo(()=>typeof i.draggable=="function"?i.draggable(a,i)!==!1:i.draggable,[i,a]),M=u.useRef(null);u.useEffect(()=>{M.current&&m&&g?.row===a.id&&g?.column===i.id&&M.current.focus()},[g,m,a.id,i.id]);const A=u.useCallback(()=>{m&&!g&&p.exec("focus-cell",{row:a.id,column:i.id,eventSource:"focus"})},[p,m,g,a.id,i.id]);function T(H){const W=new RegExp(`(${v.value.trim()})`,"gi");return String(H).split(W).map(_=>({text:_,highlight:W.test(_)}))}const D=u.useMemo(()=>{const H=i.fixed&&i.fixed.left===-1||i.fixed.right===-1,W=i.fixed&&i.fixed.right;return[j,H?"wx-shadow":"",W?"wx-fixed-right":""].filter(Boolean).join(" ")},[j,i]),B=i.cell;return r.jsxs("div",{className:"wx-TSCaXsGV "+D,ref:M,onFocus:A,style:w,"data-row-id":Ln(a.id),"data-col-id":Ln(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,B?r.jsx(B,{api:p,row:a,column:i,onAction:({action:H,data:W})=>p.exec(H,W)}):d?d():b?r.jsx("span",{children:T(Vi(a,i)).map(({highlight:H,text:W},_)=>H?r.jsx("mark",{className:"wx-TSCaXsGV wx-search",children:W},_):r.jsx("span",{children:W},_))}):Vi(a,i)]})}function Jy(n,a){let i,l;function c(p){i=p.clientX,n.style.opacity=1,document.body.style.cursor="ew-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",d),window.addEventListener("mouseup",m),a&&a.down&&a.down(n)}function d(p){l=p.clientX-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 dA({filter:n,column:a,action:i,filterValue:l}){function c({value:d}){i({value:d,key:a.id})}return r.jsx(ap,{...n.config??{},value:l,onChange:c})}function fA({filter:n,column:a,action:i,filterValue:l}){const c=u.useContext(ss),d=ut(c,"flatData"),m=u.useMemo(()=>n?.config?.options||a?.options||g(),[n,a,d]),p=u.useMemo(()=>n?.config?.template,[n]);function g(){const b=[];return d.forEach(w=>{const C=Yi(w,a);b.includes(C)||b.push(C)}),b.map(w=>({id:w,label:w}))}function v({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(Ak,{placeholder:"",clear:!0,...n?.config??{},options:m,value:l,onChange:v,children:b=>p?p(b):b.label})})}function mA({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 Jx(n){const{value:a,options:i=[],placeholder:l="",clear:c=!1,text:d=null,template:m=null,cell:p=null,dropdown:g={},autoOpen:v=!1,onChange:x,onAction:b}=n,[w,C]=Ox(a||[]),j=u.useMemo(()=>(w||[]).map(q=>i.find(Q=>Q.id===q)).filter(Boolean),[w,i]),k=u.useRef(null),M=u.useRef(null),[A,T]=u.useState(null),D=()=>{const q=w||[];if(!q.length)return 0;const Q=i.find(O=>q.includes(O.id));return Q?i.indexOf(Q):0};function B(q){M.current=q.navigate,T(()=>q.keydown),v&&q.navigate(D())}u.useEffect(()=>{v&&(k.current?.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges())},[]);function H({id:q}){C(q),x&&x({value:q})}function W(q){q.stopPropagation(),C([]),x&&x({value:[]})}function _(){M.current?.(D())}function Z(){M.current?.(null)}function G(q){A?.(q,D())}return r.jsxs("div",{ref:k,className:"wx-multiselect wx-aadNNOwy",onClick:_,onKeyDown:G,tabIndex:0,children:[r.jsx("div",{className:"wx-label wx-aadNNOwy",children:m?m(j):p?r.jsx(p,{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(q=>q.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:W}):r.jsx("i",{className:"wx-icon wxi-angle-down wx-aadNNOwy"}),r.jsx(lf,{items:i,onReady:B,onSelect:H,multiselect:!0,checkboxes:!0,value:w||[],onCancel:Z,...g,children:({option:q})=>r.jsx("div",{className:"wx-option wx-aadNNOwy",children:m?m(q):p?r.jsx(p,{data:q,onAction:b}):q.label})})]})}function hA({filter:n,column:a,action:i,filterValue:l}){const c=u.useContext(In.i18n)?.getGroup("grid")||su(ip).getGroup("grid"),d=u.useMemo(()=>({clear:!0,...n?.config||{}}),[n]),m=u.useMemo(()=>d.options||a.options,[d,a]),p=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 v(x){x.key!=="Tab"&&x.preventDefault()}return r.jsx("div",{style:{width:"100%"},onKeyDown:v,children:r.jsx(Jx,{placeholder:"",...d,options:m,value:l||[],text:p,onChange:g})})}const pA={text:dA,richselect:fA,datepicker:mA,multiselect:hA};function gA({filter:n,column:a}){const i=u.useContext(ss),l=ut(i,"filterValues");function c(m){i.exec("filter-rows",m)}const d=u.useMemo(()=>pA[n.type],[n.type]);return r.jsx(d,{filter:n,column:a,action:c,filterValue:l[a.id]})}function vA(n){const{cell:a,column:i,row:l,lastRow:c,sortRow:d,columnStyle:m,bodyHeight:p,hasSplit:g}=n,v=u.useContext(ss),x=ut(v,"sortMarks"),b=u.useMemo(()=>x?x[i.id]:void 0,[x,i.id]),w=u.useRef(),C=u.useCallback(me=>{w.current=a.flexgrow?me.parentNode.clientWidth:a.width},[a.flexgrow,a.width]),j=u.useCallback((me,X)=>{v.exec("resize-column",{id:a.id,width:Math.max(1,(w.current||0)+me),inProgress:X})},[v,a.id]),k=u.useCallback(me=>j(me,!0),[j]),M=u.useCallback(me=>j(me,!1),[j]),A=u.useCallback(me=>{if(!i.sort||a.filter)return;let X=b?.order;X&&(X=X==="asc"?"desc":"asc"),v.exec("sort-rows",{key:a.id,add:me.ctrlKey||me.metaKey,order:X})},[v,a.id,a.filter,i.sort,b?.order]),T=u.useCallback(me=>{me&&me.stopPropagation(),v.exec("collapse-column",{id:a.id,row:l})},[v,a.id,l]),D=u.useCallback(me=>{me.key==="Enter"&&T()},[T]),B=u.useCallback(me=>{me.key==="Enter"&&!a.filter&&A(me)},[A,a.filter]),H=u.useMemo(()=>a.collapsed&&i.collapsed,[a.collapsed,i.collapsed]),W=u.useMemo(()=>H&&!g&&a.collapsible!=="header",[H,g,a.collapsible]),_=u.useMemo(()=>W?{top:-p/2,position:"absolute"}:{},[W,p]),Z=u.useMemo(()=>cf(a.width,a.flexgrow,i.fixed,i.left,a.right??i.right,a.height+(H&&W?p:0)),[a.width,a.flexgrow,i.fixed,i.left,a.right,i.right,a.height,H,W,p]),G=u.useMemo(()=>Zx(i,a,m),[i,a,m]),q=u.useCallback(()=>Object.fromEntries(Object.entries(a).filter(([me])=>me!=="cell")),[a]),Q=`wx-cell ${G} ${a.css||""} wx-collapsed`,O=["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 me=ye.current;if(!me)return;const X=Jy(me,{down:C,move:k,up:M});return()=>{typeof X=="function"&&X()}},[C,k,M,Jy]),H?r.jsx("div",{className:"wx-RsQD74qC "+Q,style:Z,role:"button","aria-label":`Expand column ${a.text||""}`,"aria-expanded":!a.collapsed,tabIndex:0,onKeyDown:D,onClick:T,"data-header-id":Ln(i.id),children:r.jsx("div",{className:"wx-RsQD74qC wx-text",style:_,children:a.text||""})}):r.jsxs("div",{className:"wx-RsQD74qC "+O,style:Z,onClick:A,"data-header-id":Ln(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:B,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 me=a.cell;return r.jsx(me,{api:v,cell:q(),column:i,row:l,onAction:({action:X,data:I})=>v.exec(X,I)})})():a.filter?r.jsx(gA,{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:me=>me.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 yA({cell:n,column:a,row:i,columnStyle:l}){const c=u.useContext(ss),d=u.useMemo(()=>cf(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(()=>Zx(a,n,l),[a,n,l]),p=u.useCallback(()=>Object.fromEntries(Object.entries(n||{}).filter(([v])=>v!=="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?qh.createElement(n.cell,{api:c,cell:p(),column:a,row:i,onAction:({action:v,data:x})=>c.exec(v,x)}):r.jsx("div",{className:"wx-6Sdi3Dfd wx-text",children:n?.text||""}):null})}function eb({deltaLeft:n,contentWidth:a,columns:i,type:l="header",columnStyle:c,bodyHeight:d}){const m=u.useContext(ss),p=ut(m,"_sizes"),g=ut(m,"split"),v=u.useMemo(()=>p?.[`${l}RowHeights`],[p,l]),x=u.useMemo(()=>{let k=[];if(i&&i.length){const M=i[0][l].length;for(let A=0;A<M;A++){let T=0;k.push([]),i.forEach((D,B)=>{const H={...D[l][A]};T||k[A].push(H),H.colspan>1?T=H.colspan-1:T&&T--})}}return k},[i,l]),b=u.useMemo(()=>g?.left||g?.right,[g]);function w(k){return i.find(M=>M.id===k)}function C(k,M){let A=M;return k.rowspan&&(A+=k.rowspan-1),A===x.length-1}function j(k,M,A){if(!A.sort)return!1;for(let T=x.length-1;T>=0;T--){const D=A.header[T];if(!D.filter&&!D._hidden)return M===T}return C(k,M)}return r.jsx("div",{className:`wx-sAsPVaUK wx-${l}`,style:{paddingLeft:`${n}px`,width:`${a}px`},role:"rowgroup",children:x.map((k,M)=>r.jsx("div",{className:l==="header"?"wx-sAsPVaUK wx-h-row":"wx-sAsPVaUK wx-f-row",style:{height:`${v?.[M]}px`,display:"flex"},role:"row",children:k.map(A=>{const T=w(A.id);return l==="header"?r.jsx(vA,{cell:A,columnStyle:c,column:T,row:M,lastRow:C(A,M),bodyHeight:d,sortRow:j(A,M,T),hasSplit:b},A.id):r.jsx(yA,{cell:A,columnStyle:c,column:w(A.id),row:M},A.id)})},M))})}function bA({overlay:n}){const a=u.useContext(ss);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 xA(n){const{editor:a,onSave:i,onApply:l}=n,[c,d]=u.useState(a?.value||""),{type:m="text"}=u.useMemo(()=>a?.config||{},[a]),p=u.useRef(null);u.useEffect(()=>{p.current&&p.current.focus()},[]),u.useEffect(()=>{if(!p.current)return;const x=pr(p.current,()=>i(!0));return()=>x.destroy()},[i]);function g(){p.current&&(d(p.current.value),l(p.current.value))}function v({key:x}){x==="Enter"&&i()}return r.jsx("input",{className:"wx-e7Ao5ejY wx-text",onInput:g,onKeyDown:v,ref:p,type:m,value:c})}function wA({editor:n,onAction:a,onSave:i,onApply:l,onCancel:c}){const[d,m]=u.useState(n?.value),[p,g]=u.useState(n?.renderedValue),[v,x]=u.useState(n?.options||[]),b=u.useMemo(()=>n?.config?.template,[n]),w=u.useMemo(()=>n?.config?.cell,[n]),C=u.useMemo(()=>n?.config?.dropdown||{},[n]),j=u.useMemo(()=>({trackScroll:!0,...C}),[C]),k=u.useMemo(()=>(v||[]).findIndex(_=>_.id===d),[v,d]),M=u.useRef(null),A=u.useRef(null),T=u.useCallback(_=>{M.current=_.navigate,A.current=_.keydown,M.current(k)},[k,M]),D=u.useCallback(_=>{const Z=_?.target?.value??"";g(Z);const G=Z?(n?.options||[]).filter(q=>(q.label||"").toLowerCase().includes(Z.toLowerCase())):n?.options||[];x(G),G.length?M.current(-1/0):M.current(null)},[n]),B=u.useRef(null);u.useEffect(()=>{B.current&&B.current.focus()},[]);const H=u.useRef(i);u.useEffect(()=>{H.current=i},[i]),u.useEffect(()=>{if(!B.current)return;const _=pr(B.current,()=>H.current(!0));return()=>_.destroy()},[]),u.useEffect(()=>{m(n?.value),g(n?.renderedValue),x(n?.options||[])},[n]);const W=u.useCallback(({id:_})=>{l(_),i()},[l,i]);return r.jsxs(r.Fragment,{children:[r.jsx("input",{className:"wx-0UYfSd1x wx-input",ref:B,value:p??"",onChange:D,onKeyDown:_=>A.current?A.current(_,k):void 0}),r.jsx(lf,{items:v,onReady:T,onSelect:W,...j,onCancel:c,children:({option:_})=>b?b(_):w?r.jsx(w,{data:_,onAction:a}):_.label})]})}function SA({editor:n,onAction:a,onSave:i,onApply:l,onCancel:c}){const[d]=u.useState(()=>n.value||new Date),{template:m,cell:p,dropdown:g={}}=n?.config||{},v=u.useMemo(()=>({trackScroll:!0,width:"auto",...g}),[g]);function x({value:j}){l(j),i()}const b=u.useRef(null),[w,C]=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=pr(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):p?r.jsx(p,{data:n.value,onAction:a}):r.jsx("span",{className:"wx-lNWNYUb6 wx-text",children:n.renderedValue})}),r.jsx(np,{...v,onCancel:c,children:r.jsx("div",{ref:C,className:"wx-lNWNYUb6",children:r.jsx(Dx,{value:d,onChange:x,buttons:n.config?.buttons})})})]})}function CA(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:p={}}=m,g=u.useMemo(()=>({trackScroll:!0,...p}),[p]),[v]=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 C({id:D}){c(D),l()}let j;const[k,M]=u.useState();function A(D){j=D.navigate,M(()=>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=pr(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(v):m.cell?(()=>{const D=m.cell;return r.jsx(D,{data:v,onAction:i})})():r.jsx("span",{className:"wx-ywGRk611 wx-text",children:a.renderedValue})}),r.jsx(lf,{items:b,onReady:A,onSelect:C,...g,onCancel:d,children:({option:D})=>m.template?m.template(D):m.cell?(()=>{const B=m.cell;return r.jsx(B,{data:D,onAction:i})})():D.label})]})}function kA(n){const{editor:a,onAction:i,onSave:l,onApply:c}=n,d=a?.config||{},m=a?.options??[],p=a?.value||[],g=a?.renderedValue,v=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=pr(b.current,()=>l(!0));return()=>w.destroy()},[l]),r.jsx("div",{ref:b,className:"wx-value wx-aacZ4gNU",onClick:()=>l(!0),children:r.jsx(Jx,{value:p,options:m,text:g,template:d.template,cell:d.cell,clear:d.clear,dropdown:v,autoOpen:!0,onChange:x,onAction:i})})}const jA={text:xA,combo:wA,datepicker:SA,richselect:CA,multiselect:kA};function AA({column:n,row:a}){const i=u.useContext(ss),l=ut(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]),p=u.useCallback(j=>{i.exec("editor",{value:j})},[i]),g=u.useCallback(j=>{j.key==="Enter"&&l&&(n.editor.type==="multiselect"?p(l.value):m())},[l,n.editor,m,p]),v=u.useMemo(()=>cf(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 v=="string"&&b.current.setAttribute("style",v)},[v]);const w=typeof a.$parent<"u"?"gridcell":"cell",C=typeof a.$parent<"u"?!n.editor:void 0;return r.jsx("div",{className:"wx-8l724t2g wx-cell wx-editor",ref:b,style:typeof v=="object"&&v!==null?v:void 0,role:w,"aria-readonly":C,tabIndex:-1,onClick:j=>j.stopPropagation(),onDoubleClick:j=>j.stopPropagation(),onKeyDown:g,children:x?r.jsx(x,{editor:l,onSave:d,onApply:p,onCancel:m,onAction:({action:j,data:k})=>i.exec(j,k)}):null})}function tb(n){const{columns:a,type:i,columnStyle:l}=n,c=u.useContext(ss),{filterValues:d,_columns:m,_sizes:p}=c.getState();function g(v){return l?" "+l(v):""}return r.jsx(r.Fragment,{children:a.map((v,x)=>r.jsx("tr",{children:v.map(b=>{const w=m.find(k=>k.id===b.id),C=`wx-print-cell-${i}${g(w)}${b.filter?" wx-print-cell-filter":""}${b.vertical?" wx-vertical":""}`,j=b.cell;return r.jsx("th",{style:Hx(Wx(b,p.columnWidth)),className:"wx-Gy81xq2u "+C,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:Ej(d,m,b)}):r.jsx("div",{className:"wx-Gy81xq2u wx-text",children:b.text??""})},b.id)})},x))})}function NA(n){const{columns:a,rowStyle:i,columnStyle:l,cellStyle:c,header:d,footer:m,reorder:p}=n,g=u.useContext(ss),{flatData:v,_sizes:x}=g.getState(),b=d&&Yy(a,"header",x.headerRowHeights),w=m&&Yy(a,"footer",x.footerRowHeights);function C(k,M){let A="";return A+=l?" "+l(M):"",A+=c?" "+c(k,M):"",A}function j(k,M){return typeof M.draggable=="function"?M.draggable(k,M)!==!1:M.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(tb,{columns:b,type:"header",columnStyle:l})}):null,r.jsx("tbody",{children:v.map((k,M)=>r.jsx("tr",{className:"wx-8NTMLH0z wx-row"+(i?" "+i(k):""),style:{height:`${k.rowHeight||x.rowHeight}px`},children:a.map(A=>A.collapsed?null:r.jsxs("td",{className:`wx-8NTMLH0z wx-print-cell wx-cell ${C(k,A)}`,style:Hx(Wx(A,x.columnWidth)),children:[p&&A.draggable?r.jsx("span",{className:"wx-8NTMLH0z wx-print-draggable",children:j(k,A)?r.jsx("i",{className:"wx-8NTMLH0z wxi-drag"}):null}):null,A.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,A.cell?(()=>{const T=A.cell;return r.jsx(T,{api:g,row:k,column:A})})():r.jsx("span",{children:Vi(k,A)})]},A.id))},M))}),m?r.jsx("tfoot",{children:r.jsx(tb,{columns:w,type:"footer",columnStyle:l})}):null]})}function MA(n){const{config:a,...i}=n,l=u.useContext(ss),{_skin:c,_columns:d}=l.getState(),m=u.useMemo(()=>Aj(d,a),[]),p=u.useRef(null);return u.useEffect(()=>{const g=document.body;g.classList.add("wx-print");const v=p.current;if(!v)return;const x=v.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:p,children:m.map((g,v)=>r.jsx("div",{className:"wx-4zwCKA7C wx-print-grid-wrapper",children:r.jsx(NA,{columns:g,...i})},v))})}function TA(n){const{header:a,footer:i,overlay:l,multiselect:c,onreorder:d,rowStyle:m,columnStyle:p,cellStyle:g,autoRowHeight:v,resize:x,clientWidth:b,clientHeight:w,responsiveLevel:C,hotkeys:j}=n,k=u.useContext(ss),M=ut(k,"dynamic"),A=ut(k,"_columns"),T=ut(k,"flatData"),D=ut(k,"split"),B=ut(k,"_sizes"),[H,W]=Ss(k,"selectedRows"),_=ut(k,"select"),Z=ut(k,"editor"),G=ut(k,"scrollLeft"),q=ut(k,"scrollTop"),Q=ut(k,"tree"),O=ut(k,"focusCell"),ye=ut(k,"_print"),me=ut(k,"undo"),X=ut(k,"reorder"),I=ut(k,"_rowHeightFromData"),[ee,V]=u.useState(0);u.useEffect(()=>{V(rs())},[]);const[P,re]=u.useState(0),ue=u.useMemo(()=>(A||[]).some(ne=>!ne.hidden&&ne.flexgrow),[A]),K=u.useMemo(()=>B?.rowHeight||0,[B]),xe=u.useRef(null),[z,le]=u.useState(null),[ke,Ce]=u.useState(null),Ue=u.useMemo(()=>{let ne=[],Te=0;return D&&D.left&&(ne=(A||[]).slice(0,D.left).filter(De=>!De.hidden).map(De=>({...De})),ne.forEach(De=>{De.fixed={left:1,leftSize:D.left},De.left=Te,Te+=De.width}),ne.length&&(ne[ne.length-1].fixed.left=-1)),{columns:ne,width:Te}},[D,A]),Be=u.useMemo(()=>{let ne=[],Te=0;if(D&&D.right){ne=(A||[]).slice(D.right*-1).filter(De=>!De.hidden).map(De=>({...De}));for(let De=ne.length-1;De>=0;De--){const st=ne[De];st.fixed={right:1},st.right=Te,Te+=st.width}ne.length&&(ne[0].fixed={right:-1})}return{columns:ne,width:Te}},[D,A]),he=u.useMemo(()=>{const ne=(A||[]).slice(D?.left||0,(A||[]).length-(D?.right??0)).filter(Te=>!Te.hidden);return ne.forEach(Te=>{Te.fixed=0}),ne},[A,D]),Xe=u.useMemo(()=>(A||[]).reduce((ne,Te)=>(Te.hidden||(ne+=Te.width),ne),0),[A]),et=1;function ce(ne,Te,De){let st=Te,Gt=ne;if(he.length){let It=he.length;for(let Qe=ne;Qe>=0;Qe--)he[Qe][De].forEach(jt=>{jt.colspan>1&&Qe>ne-jt.colspan&&Qe<It&&(It=Qe)});if(It!==he.length&&It<ne){for(let Qe=It;Qe<ne;Qe++)st-=he[Qe].width;Gt=It}}return{index:Gt,delta:st}}const ge=u.useMemo(()=>{let ne,Te,De;const st=G||0,Gt=(G||0)+(b||0);let It=0,Qe=0,jt=0,cn=0;he.forEach((Nt,Vt)=>{st>jt&&(It=Vt,cn=jt),jt=jt+Nt.width,Gt>jt&&(Qe=Vt+et)});const Jt={header:0,footer:0};for(let Nt=Qe;Nt>=It;Nt--)["header","footer"].forEach(Vt=>{he[Nt]&&he[Nt][Vt].forEach(is=>{const Ba=is.colspan;if(Ba&&Ba>1){const hn=Ba-(Qe-Nt+1);hn>0&&(Jt[Vt]=Math.max(Jt[Vt],hn))}})});const On=ce(It,cn,"header"),Wt=ce(It,cn,"footer"),mn=On.delta,Yt=On.index,Gs=Wt.delta,Fa=Wt.index;return ue&&Xe>(b||0)?ne=Te=De=[...Ue.columns,...he,...Be.columns]:(ne=[...Ue.columns,...he.slice(It,Qe+1),...Be.columns],Te=[...Ue.columns,...he.slice(Yt,Qe+Jt.header+1),...Be.columns],De=[...Ue.columns,...he.slice(Fa,Qe+Jt.footer+1),...Be.columns]),{data:ne||[],header:Te||[],footer:De||[],d:cn,df:Gs,dh:mn}},[he,Ue,Be,G,b,ue,Xe]),Ae=u.useMemo(()=>a&&B?.headerHeight||0,[a,B]),Le=u.useMemo(()=>i&&B?.footerHeight||0,[i,B]),Pe=u.useMemo(()=>b&&w?Xe>=b:!1,[b,w,Xe]),[Ve,Ke]=u.useState(!1),de=u.useMemo(()=>(w||0)-Ae-Le-(Pe?ee:0),[w,Ae,Le,Pe,ee]),je=u.useMemo(()=>Math.ceil((de||0)/(K||1))+1,[de,K]),fe=u.useRef([]),[_e,Ee]=u.useState(0),[mt,Ht]=u.useState(void 0),Dt=u.useMemo(()=>{let ne=0,Te=0;const De=2,st=q||0;if(v){let Qe=st;for(;Qe>0;)Qe-=fe.current[ne]||K,ne++;Te=st-Qe;for(let jt=Math.max(0,ne-De-1);jt<ne;jt++)Te-=fe.current[ne-jt]||K;ne=Math.max(0,ne-De)}else{if(I){let Qe=0,jt=0;for(let Wt=0;Wt<(T||[]).length;Wt++){const mn=T[Wt].rowHeight||K;if(jt+mn>st){Qe=Wt;break}jt+=mn}ne=Math.max(0,Qe-De);for(let Wt=0;Wt<ne;Wt++)Te+=T[Wt].rowHeight||K;let cn=0,Jt=0;for(let Wt=Qe+1;Wt<(T||[]).length;Wt++){const mn=T[Wt].rowHeight||K;if(cn++,Jt+mn>de)break;Jt+=mn}const On=Math.min(M?M.rowCount:(T||[]).length,Qe+cn+De);return{d:Te,start:ne,end:On}}ne=Math.floor(st/(K||1)),ne=Math.max(0,ne-De),Te=ne*(K||0)}const Gt=M?M.rowCount:(T||[]).length,It=Math.min(Gt,ne+(je||0)+De);return{d:Te,start:ne,end:It}},[v,I,q,K,M,T,je,de]),yt=u.useMemo(()=>{const ne=M?M.rowCount:(T||[]).length;if(v)return _e+Dt.d+(ne-(mt||0))*(K||0);if(!I)return ne*(K||0);let Te=0;for(let De=0;De<ne;De++)Te+=T[De]?.rowHeight||K;return Te},[M,T,K,v,I,_e,Dt.d,mt]),Ge=u.useRef({});Ge.current={clientWidth:b,clientHeight:w,fullHeight:yt,headerHeight:Ae,footerHeight:Le,fullWidth:Xe,SCROLLSIZE:ee};const At=u.useCallback(()=>{const ne=Ge.current;Ke(ne.clientWidth&&ne.clientHeight?ne.fullHeight+ne.headerHeight+ne.footerHeight>=ne.clientHeight-(ne.fullWidth>=ne.clientWidth?ne.SCROLLSIZE:0):!1)},[]);u.useEffect(()=>{const ne=requestAnimationFrame(At);return()=>window.cancelAnimationFrame(ne)},[P,At]),u.useEffect(()=>{At()},[w,At]);const ve=u.useMemo(()=>ue&&Xe<=(b||0)?(b||0)-0-(Ve?ee:0):Xe,[ue,Xe,b,Ve,ee,Pe]),Fe=u.useMemo(()=>ue&&Xe<=(b||0)?b||0:ve<(b||0)?Xe+(Ve?ee:0):-1,[ue,Xe,b,ve,Ve,ee]),He=u.useRef({});u.useEffect(()=>{if(M&&(He.current.start!==Dt.start||He.current.end!==Dt.end)){const{start:ne,end:Te}=Dt;He.current={start:ne,end:Te},k&&k.exec&&k.exec("request-data",{row:{start:ne,end:Te}})}},[M,Dt,k]);const Me=u.useMemo(()=>M?T||[]:(T||[]).slice(Dt.start,Dt.end),[M,T,Dt]),rt=u.useMemo(()=>(H||[]).filter(ne=>(Me||[]).some(Te=>Te.id===ne)),[W,Me]),dt=u.useMemo(()=>Dt.start,[Dt.start]),Re=u.useRef({top:q,left:G});Re.current={top:q,left:G};const An=u.useCallback(ne=>{const Te=ne.target.scrollTop,De=ne.target.scrollLeft,st=Re.current;(Te!==st.top||De!==st.left)&&k.exec("scroll-to",{top:Te,left:De})},[k]),pa=u.useCallback(ne=>{ne.shiftKey&&ne.preventDefault(),xe.current&&xe.current.focus&&xe.current.focus()},[]),it=u.useCallback(()=>!!(A||[]).find(ne=>!!ne.draggable),[A]),Xt=u.useRef(null),Nn=u.useRef(null),Mn=u.useRef({dblclick:(ne,Te)=>{const De={id:ne,column:nu(Te,"data-col-id")};k.exec("open-editor",De)},click:(ne,Te)=>{if(Te.target.closest("input")||Xt.current)return;const De=nu(Te,"data-col-id");if(O?.id!==ne&&k.exec("focus-cell",{row:ne,column:De,eventSource:"click"}),_===!1)return;const st=c&&(Te.ctrlKey||Te.metaKey),Gt=c&&Te.shiftKey;(st||H.length>1||!H.includes(ne))&&k.exec("select-row",{id:ne,toggle:st,range:Gt})},"toggle-row":ne=>{const Te=k.getRow(ne);k.exec(Te.open!==!1?"close-row":"open-row",{id:ne})},"ignore-click":()=>!1}),wn=u.useMemo(()=>({top:Ae,bottom:Le,left:Ue.width,xScroll:Pe,yScroll:Ve,sense:v&&ke?ke.offsetHeight:Math.max(B?.rowHeight||0,40),node:xe.current&&xe.current.firstElementChild}),[Ae,Le,Ue.width,Pe,Ve,v,ke,B]);function Cs(ne,Te){const{container:De,sourceNode:st,from:Gt}=Te;if(it()&&!st.getAttribute("draggable-data"))return!1;le(Gt),Q&&k.getRow(Gt).open&&k.exec("close-row",{id:Gt,nested:!0});const It=Bo(st),Qe=It.cloneNode(!0);Qe.classList.remove("wx-selected"),Qe.querySelectorAll("[tabindex]").forEach(On=>On.setAttribute("tabindex","-1")),De.appendChild(Qe),Ce(Qe);const jt=(G||0)-ge.d,cn=Ve?ee:0;De.style.width=Math.min((b||0)-cn,ue&&Xe<=(b||0)?ve:ve-cn)+jt+"px";const Jt=Pd(It);Te.offset={x:jt,y:-Math.round(Jt.height/2)},Nn.current||(Nn.current=ne.clientY)}function Ha(ne,Te){const{from:De}=Te,st=Te.pos,Gt=Pd(xe.current);st.x=Gt.x;const It=wn.top;if(st.y<It)st.y=It;else{const Qe=Gt.height-(Pe&&ee>0?ee:Math.round(wn.sense/2))-wn.bottom;st.y>Qe&&(st.y=Qe)}if(xe.current.contains(Te.targetNode)){const Qe=Bo(Te.targetNode),jt=Qe&&sf(Qe);if(jt&&jt!==De){Te.to=jt;const cn=v?ke?.offsetHeight:B?.rowHeight;if(ke&&((q||0)===0||st.y>It+cn-1)){const Jt=Qe.getBoundingClientRect(),On=Pd(ke).y,Wt=Jt.y,mn=On>Wt?-1:1,Yt=mn===1?"after":"before",Gs=k.getState().flatData,Fa=Math.abs(Gs.findIndex(Vt=>Vt.id===De)-Gs.findIndex(Vt=>Vt.id===jt)),Nt=Fa!==1?Yt==="before"?"after":"before":Yt;if(Fa===1&&(mn===-1&&ne.clientY>Nn.current||mn===1&&ne.clientY<Nn.current))return;Nn.current=ne.clientY,k.exec("move-item",{id:De,target:jt,mode:Nt,inProgress:!0})}}d&&d({event:ne,context:Te})}rA(ne,Gt,Te,wn)}function gr(ne,Te){const{from:De,to:st}=Te;k.exec("move-item",{id:De,target:st,inProgress:!1}),Xt.current=setTimeout(()=>{Xt.current=0},1),le(null),Ce(null),Nn.current=null,Xx(Te)}function rs(){const ne=document.createElement("div");ne.style.cssText="position:absolute;left:-1000px;width:100px;padding:0px;margin:0px;min-height:100px;overflow-y:scroll;",document.body.appendChild(ne);const Te=ne.offsetWidth-ne.clientWidth;return document.body.removeChild(ne),Te}const zn=u.useMemo(()=>Fe>0?{width:`${Fe}px`}:void 0,[Fe]),Xi=u.useRef(null);function Qi(){Promise.resolve().then(()=>{let ne=0,Te=dt;const De=Xi.current;De&&(Array.from(De.children).forEach((st,Gt)=>{fe.current[dt+Gt]=st.offsetHeight,ne+=st.offsetHeight,Te++}),Ee(ne),Ht(Te))})}u.useEffect(()=>{Me&&v&&Qi()},[Me,v,dt]);let[F,Je]=u.useState();u.useEffect(()=>{if(O&&(!_||!rt.length||rt.includes(O.row)))Je({...O});else if(Me.length&&ge.data.length){if(!F||rt.length&&!rt.includes(F.row)||Me.findIndex(ne=>ne.id===F.row)===-1||ge.data.findIndex(ne=>ne.id===F.column&&!ne.collapsed)===-1){const ne=rt[0]||Me[0].id,Te=ge.data.findIndex(De=>!De.collapsed);Je(Te!==-1?{row:ne,column:ge.data[Te].id}:null)}}else Je(null)},[O]);const ze=u.useRef(null);u.useEffect(()=>{const ne=xe.current;if(!ne)return;const Te=eA(ne,x);return()=>{typeof Te=="function"&&Te()}},[x]);const kt=u.useRef({});Object.assign(kt.current,{start:Cs,move:Ha,end:gr,getReorder:()=>X,getDraggableInfo:()=>({hasDraggable:it()})}),u.useEffect(()=>{const ne=xe.current;return ne?nA(ne,kt).destroy:void 0},[X,xe.current]),u.useEffect(()=>{const ne=xe.current;return ne?Zj(ne,{keys:j!==!1&&{...Qj,"ctrl+z":me,"ctrl+y":me,...j},exec:Te=>k.exec("hotkey",Te)}).destroy:void 0},[k,me,j]);const ks=u.useRef({scroll:k.getReactiveState().scroll,scrollLeft:k.getReactiveState().scrollLeft,scrollTop:k.getReactiveState().scrollTop});ks.current.getWidth=()=>(b||0)-(Ve?ee:0),ks.current.getHeight=()=>de,ks.current.getScrollMargin=()=>Ue.width+Be.width,u.useEffect(()=>{Jj(ze.current,ks.current)},[]);const Mt=u.useRef(null);u.useEffect(()=>{const ne=Mt.current;if(!ne)return;const Te=[];Te.push(pr(ne,()=>O&&k.exec("focus-cell",{eventSource:"click"})).destroy),Te.push(nj(ne,Mn.current)),re(ne.clientHeight);const De=new ResizeObserver(()=>{re(ne.clientHeight)});return De.observe(ne),Te.push(()=>De.disconnect()),()=>Te.forEach(st=>st())},[]);const ga=`wx-grid ${C?`wx-responsive-${C}`:""}`;return u.useEffect(()=>{O&&(Me.some(ne=>ne.id===O.row)&&ge.data.some(ne=>ne.id===O.column&&!ne.collapsed)||k.exec("focus-cell",{eventSource:"destroy"}))},[O,Me,ge.data,k]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-4VuBwK2D "+ga,style:{"--header-height":`${Ae}px`,"--footer-height":`${Le}px`,"--split-left-width":`${Ue.width}px`,"--split-right-width":`${Be.width}px`},children:r.jsx("div",{ref:xe,className:"wx-4VuBwK2D wx-table-box",style:zn,role:Q?"treegrid":"grid","aria-colcount":ge.data.length,"aria-rowcount":Me.length,"aria-multiselectable":Q&&c?!0:void 0,tabIndex:-1,children:r.jsxs("div",{ref:ze,className:"wx-4VuBwK2D wx-scroll",style:{overflowX:Pe?"scroll":"hidden",overflowY:Ve?"scroll":"hidden"},onScroll:An,children:[a?r.jsx("div",{className:"wx-4VuBwK2D wx-header-wrapper",children:r.jsx(eb,{contentWidth:ve,deltaLeft:ge.dh,columns:ge.header,columnStyle:p,bodyHeight:de-+i})}):null,r.jsxs("div",{ref:Mt,className:"wx-4VuBwK2D wx-body",style:{width:`${ve}px`,height:`${yt}px`},onMouseDown:ne=>pa(ne),children:[l?r.jsx(bA,{overlay:l}):null,r.jsx("div",{ref:Xi,className:"wx-4VuBwK2D wx-data",style:{paddingTop:`${Dt.d}px`,paddingLeft:`${ge.d}px`},children:Me.map((ne,Te)=>{const De=H.indexOf(ne.id)!==-1,st=z===ne.id,Gt="wx-row"+(v?" wx-autoheight":"")+(m?" "+m(ne):"")+(De?" wx-selected":"")+(st?" wx-inactive":""),It=v?{minHeight:`${ne.rowHeight||K}px`}:{height:`${ne.rowHeight||K}px`};return r.jsx("div",{className:"wx-4VuBwK2D "+Gt,"data-id":Ln(ne.id),"data-context-id":Ln(ne.id),style:It,role:"row","aria-rowindex":Te,"aria-expanded":ne.open,"aria-level":Q?ne.$level+1:void 0,"aria-selected":Q?De:void 0,tabIndex:-1,children:ge.data.map(Qe=>Qe.collapsed?r.jsx("div",{className:"wx-4VuBwK2D wx-cell wx-collapsed"},Qe.id):Z?.id===ne.id&&Z.column===Qe.id?r.jsx(AA,{row:ne,column:Qe},Qe.id):r.jsx(uA,{row:ne,column:Qe,columnStyle:p,cellStyle:g,reorder:X,focusable:F?.row===ne.id&&F?.column===Qe.id},Qe.id))},ne.id)})})]}),i&&(T||[]).length?r.jsx(eb,{type:"footer",contentWidth:ve,deltaLeft:ge.df,columns:ge.footer,columnStyle:p}):null]})})}),ye?r.jsx(MA,{config:ye,rowStyle:m,columnStyle:p,cellStyle:g,header:a,footer:i,reorder:X}):null]})}const EA=n=>n.split("-").map(a=>a?a.charAt(0).toUpperCase()+a.slice(1):"").join(""),RA=u.forwardRef(function({data:n=[],columns:a=[],rowStyle:i=null,columnStyle:l=null,cellStyle:c=null,selectedRows:d,select:m=!0,multiselect:p=!1,header:g=!0,footer:v=!1,dynamic:x=null,overlay:b=null,reorder:w=!1,onReorder:C=null,autoRowHeight:j=!1,sizes:k,split:M,tree:A=!1,autoConfig:T=!1,init:D=null,responsive:B=null,sortMarks:H,undo:W=!1,hotkeys:_=null,filterValues:Z,...G},q){const Q=u.useRef();Q.current=G;const O=u.useMemo(()=>new Gj(Fx),[]),ye=u.useMemo(()=>O.in,[O]),me=u.useRef(null);me.current===null&&(me.current=new Lx((Be,he)=>{const Xe="on"+EA(Be);Q.current&&Q.current[Xe]&&Q.current[Xe](he)}),ye.setNext(me.current));const X=u.useMemo(()=>({getState:O.getState.bind(O),getReactiveState:O.getReactive.bind(O),getStores:()=>({data:O}),exec:ye.exec,setNext:Be=>(me.current=me.current.setNext(Be),me.current),intercept:ye.intercept.bind(ye),on:ye.on.bind(ye),detach:ye.detach.bind(ye),getRow:O.getRow.bind(O),getColumn:O.getColumn.bind(O)}),[O,ye]),[I,ee]=u.useState(0),[V,P]=u.useState(0),[re,ue]=u.useState(null),[K,xe]=u.useState(null),z=u.useMemo(()=>{if(T&&!a.length&&n.length){const Be=n[0],he=[];for(let Xe in Be)if(Xe!=="id"&&Xe[0]!=="$"){let et={id:Xe,header:Xe[0].toUpperCase()+Xe.slice(1)};typeof T=="object"&&(et={...et,...T}),he.push(et)}return he}return(K&&K.columns)??a},[T,a,n,K]),le=u.useMemo(()=>(K&&K.sizes)??k,[K,k]),ke=u.useCallback(Be=>{if(ee(Be.width),P(Be.height),B){const he=Object.keys(B).map(Number).sort((Xe,et)=>Xe-et).find(Xe=>Be.width<=Xe)??null;he!==re&&(xe(B[he]),ue(he))}},[B,re]),Ce=u.useContext(In.theme),Ue=u.useRef(0);return u.useEffect(()=>{if(!Ue.current)D&&D(X);else{const Be=O.getState();O.init({data:n,columns:z,split:M||Be.split,sizes:le||Be.sizes,selectedRows:d||Be.selectedRows,dynamic:x,tree:A,sortMarks:H||Be.sortMarks,filterValues:Z||Be.filterValues,undo:W,reorder:w,_skin:Ce,_select:m})}Ue.current++},[O,n,z,M,le,d,x,A,H,Z,W,w,Ce,m,D,X]),Ue.current===0&&O.init({data:n,columns:z,split:M||{left:0},sizes:le||{},selectedRows:d||[],dynamic:x,tree:A,sortMarks:H||{},filterValues:Z||{},undo:W,reorder:w,_skin:Ce,select:m}),u.useImperativeHandle(q,()=>({...X}),[X]),r.jsx(ss.Provider,{value:X,children:r.jsx(rp,{words:ip,optional:!0,children:r.jsx(TA,{header:g,footer:v,overlay:b,rowStyle:i,columnStyle:l,cellStyle:c,onReorder:C,multiselect:p,autoRowHeight:j,clientWidth:I,clientHeight:V,responsiveLevel:re,resize:ke,hotkeys:_})})})});Zh(Oa);const _n=u.createContext(null),cp=u.createContext(null),up=u.createContext(null);function DA({children:n}){const a=u.useContext(In.i18n),i=u.useMemo(()=>a.getGroup("filemanager"),[a]),l=u.useContext(_n),[c]=Ss(l,"panels"),d=ut(l,"activePanel"),m=c[d].path,[p,g]=u.useState(null),[v,x]=u.useState(null),[b,w]=u.useState(""),[C,j]=u.useState(""),[k,M]=u.useState(!1);function A(){const H=b.trim();if(!H){M(!0);return}p.add?l.exec("create-file",{file:{...p.item,name:H},parent:m}):C!==H&&l.exec("rename-file",{id:p.item.id,name:H}),T()}function T(){g(null),M(null),j(""),w("")}function D(){l.exec("delete-files",{ids:v.selected}),x(null)}const B=u.useMemo(()=>({showPrompt(H){const W=H.item.name||(H.item.type==="folder"?i("New folder"):`${i("New file")}.txt`);j(W),w(W),g({...H})},showConfirm(H){x({...H})}}),[i]);return r.jsxs(cp.Provider,{value:B,children:[r.jsx(Dk,{children:n}),p?r.jsx(Lh,{title:i(`Enter ${p.item.type} name`),onConfirm:A,onCancel:T,children:r.jsx(ap,{error:k,select:!0,focus:!0,value:b,onChange:({value:H})=>w(H)})}):null,v?r.jsx(Lh,{title:i("Are you sure you want to delete these items:"),onConfirm:D,onCancel:()=>x(null),children:v.selected?r.jsx("ul",{className:"wx-gq7BMzEP wx-list",children:v.selected.map((H,W)=>r.jsx("li",{children:H},W))}):null}):null]})}let nb={"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 LA(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 _A({item:n}){const a=u.useContext(_n),i=u.useContext(In.i18n).getGroup("filemanager"),l=u.useContext(_n).templates,[c]=Ss(a,"panels"),d=ut(a,"activePanel"),m=ut(a,"mode"),p=c[d].selected,g=u.useMemo(()=>l.preview(n,214,163),[l,n]),v=u.useMemo(()=>l.icon(n,"big"),[l,n]),[x,b]=u.useMemo(()=>LA(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":Ln("/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 ${p?.length&&p.indexOf(n.id)>=0?"wx-selected":""}`,"data-id":Ln(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})}):v?r.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-icon",children:r.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:"",src:v})}):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":Ln(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":Ln(n.id),className:"wx-GAOa4kDV wx-more",children:r.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]})]})})}function ew(){const n=u.useContext(_n),a=u.useContext(In.i18n),i=u.useMemo(()=>a.getGroup("filemanager"),[a]),[l]=Ss(n,"panels"),c=ut(n,"activePanel"),d=ut(n,"mode"),m=l[c]._files,p=l[c].selected,g=l[c].path,v=l[c]._crumbs,x=l[c]._selectNavigation,b=u.useCallback((T,D)=>{const B=D&&(D.ctrlKey||D.metaKey),H=D&&D.shiftKey;if(T==="/wx-filemanager-parent-link"){if(p.length&&(B||H))return;n.exec("select-file",{type:"navigation"});return}let W=T==="body"&&D?null:T;const _=D.target.className.indexOf("wx-more")!==-1||D.target.className.indexOf("wxi-dots-v")!==-1;setTimeout(()=>{n.exec("select-file",{id:W,toggle:B&&!_,range:H&&!_,panel:c})},1)},[n,p,c]),w=u.useCallback(()=>{v.length>1&&n.exec("set-path",{id:v[v.length-2].id,panel:c,selected:[v[v.length-1].id]})},[n,v,c]),C=u.useCallback(T=>{if(T==="/wx-filemanager-parent-link")return w();d==="search"&&n.exec("filter-files",{text:""});const D=m.find(B=>B.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)=>{(!p?.length||!p.filter(B=>B?.id===T).length>0)&&b(T,D)},[p,b]),k=u.useMemo(()=>g!=="/"?[{id:"/wx-filemanager-parent-link",name:i("Back to parent folder"),navigation:x},...m]:m,[g,i,x,m]),M=u.useRef(null),A=u.useRef();return u.useEffect(()=>{M.current&&(A.current?(A.current.click=b,A.current._dblclick=C,A.current.context=j):(A.current={click:b,dblclick:T=>A.current._dblclick(T),_dblclick:C,context:j},Po(M.current,A.current)))},[b,C,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":Ln("body"),ref:M,children:k.map(T=>r.jsx(_A,{item:T},T.id))})}function Fl({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 IA(){const n=u.useContext(In.i18n).getGroup("filemanager"),a=u.useContext(_n),i=ut(a,"activePanel"),[l]=Ss(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(Fl,{name:"angle-left",onClick:d})}),r.jsxs("div",{className:"wx-GDJvtROw wx-text",children:[n("Search results in")," ",Array.isArray(c)&&c.map((m,p)=>r.jsxs(u.Fragment,{children:[p?"/":null,m.id=="/"?n(m.name):m.name]},p))]})]}),r.jsx(ew,{})]})}function eh({narrowMode:n,extraInfo:a}){const i=u.useContext(_n),{preview:l,icon:c}=i.templates,d=u.useContext(In.i18n),m=u.useMemo(()=>d.getGroup("filemanager"),[d]),p=u.useMemo(()=>Io("%D, %d %F %Y, %H:%i",d.getRaw().calendar),[d]),[g,v]=Ss(i,"panels"),x=ut(i,"activePanel"),b=ut(i,"preview"),w=ut(i,"search"),C=u.useMemo(()=>{const _=g&&x!=null&&g[x]?._selected?.length||0;return w&&!_},[w,v,x]),j=u.useMemo(()=>{const _=g&&x!=null?g[x]:null;return _?C?_._files:_._selected:[]},[C,v,x]),k=u.useCallback((_,Z)=>(_?`${_} ${m(_>1?"folders":"folder")} `:"")+(Z?`${Z} ${m(Z>1?"files":"file")}`:""),[m]),M=u.useCallback(()=>{i.exec("show-preview",{mode:!b})},[i,b]),A=u.useCallback(_=>_.type==="folder"?m("Folder"):_.ext||m("Unknown file"),[m]),T=u.useMemo(()=>{let _,Z,G,q,Q,O,ye,me;if(j.length===1&&!C){Z=j[0],_=Z.name;const X=l(Z,400,500);X?(G=X,q=""):(q=c(Z,"big"),G=""),Q=Z.type!=="folder"}else{if(Z=Q=null,_="",j.length){let X=0,I=0,ee=0,V=[],P;j.forEach(ue=>{typeof ue.size>"u"&&(P=!0,X=void 0),P||(X+=ue.size),V.push(A(ue)),ue.type==="folder"?I++:ee++});const re=new Set(V);O=re.size>1?m("multiple"):[...re][0],ye=k(I,ee),me=X,C||(_=m("Multiple files"))}q=c({type:C?"search":j.length?"multiple":"none"},"big"),G=""}return{name:_,item:Z,previewSrc:G,iconSrc:q,showDownloadIcon:Q,type:O,totalCount:ye,totalSize:me}},[j,C,l,c,m,A,k]),D=u.useCallback(()=>{i.exec("download-file",{id:j[0].id})},[i,j]),B=u.useCallback(async _=>{if(!a||!_)return null;try{return await a(_)}catch(Z){return console.log(Z),null}},[a]),[H,W]=u.useState(null);return u.useEffect(()=>{let _=!1;return W(null),Promise.resolve(B(T.item)).then(Z=>{_||W(Z)}).catch(()=>{_||W(null)}),()=>{_=!0}},[B,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(Fl,{name:"download",onClick:D}):null,n?r.jsx(Fl,{name:"close",onClick:M}):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-${C?"search":"file-multiple-outline"}`})})]}),r.jsxs("div",{className:"wx-O0BTtRrH wx-info-panel",children:[r.jsx("div",{className:"wx-O0BTtRrH wx-title",children:m(C?"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:A(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:au(T.item.size)})]}):null,r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Date")}),r.jsxs("span",{className:"wx-O0BTtRrH wx-value",children:[p(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:au(T.totalSize)})]}):null]}),H?Object.entries(H).map(([_,Z])=>r.jsxs(qh.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:_}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:Z})]},_)):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(Fl,{name:"close",onClick:M}):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-${C?"search":"message-question-outline"}`})}),r.jsx("span",{className:"wx-O0BTtRrH wx-text",children:C?"":m("Select file or folder to view details")})]})})]})})}function tw({panel:n}){const a=u.useContext(_n),i=u.useContext(In.i18n),l=u.useMemo(()=>i.getGroup("filemanager"),[i]),[c,d]=Ss(a,"panels"),m=u.useMemo(()=>c[n]._files,[d,n]),p=u.useMemo(()=>c[n]._crumbs||[],[d,n]);function g(j){const k=lp(j,p);a.exec("set-path",{id:j,panel:n,...k&&{selected:[k]}})}const[v,x]=u.useState(null);u.useEffect(()=>{m&&x(null)},[m]);function b(){x(!0),a.exec("request-data",{id:p[p.length-1].id}),setTimeout(()=>{x(null)},5e3)}const w=u.useRef(null),C=u.useRef();return u.useEffect(()=>{C.current?C.current.click=g:(C.current={click:g},Po(w.current,C.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(Fl,{name:"refresh",spin:!!v,onClick:b})}),p.map((j,k)=>r.jsxs(qh.Fragment,{children:[k?r.jsx(Fl,{name:"angle-right"}):null,r.jsx("div",{className:"wx-SNY5LTYx wx-item","data-id":Ln(j.id),"data-menu-ignore":"true",children:j.id=="/"?l(j.name):j.name})]},k))]})}function zA({row:n}){const a=u.useContext(In.i18n),[i]=u.useState(()=>a.getGroup("filemanager")),l=u.useContext(_n).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 nw({children:n}){const a=u.useContext(_n),i=ut(a,"activePanel"),l=u.useContext(up),c=u.useRef(null);let d=u.useRef({});return d.current.drop=()=>{const m=c.current,p=F1(m,"data-panel");p&&p!=i&&a.exec("set-active-panel",{panel:p*1})},d.current.dragEnter=()=>{const m=c.current;m&&m.classList.toggle("wx-active")},d.current.dragLeave=()=>{const m=c.current;m&&m.classList.toggle("wx-active")},u.useEffect(()=>{const m=c.current;return l.droparea(m,d.current)},[]),r.jsx("div",{className:"wx-LT9X7tb7 wx-upload-area",ref:c,children:n})}function zh({panel:n,active:a=!1,onClick:i,onContextMenu:l}){const c=u.useContext(_n),d=u.useContext(In.i18n),m=u.useMemo(()=>d.getGroup("filemanager"),[d]),p=u.useMemo(()=>Io("%d %M %Y",d.getRaw().calendar),[d]),[g]=Ss(c,"panels"),v=g[n].selected,x=g[n].path,b=g[n]._crumbs,w=g[n]._sorts,C=g[n]._selectNavigation,j=g[n]._files,k=u.useMemo(()=>[{id:"name",header:m("Name"),flexgrow:3,sort:!0,resize:!0,cell:zA},{id:"size",header:m("Size"),width:100,sort:!0,resize:!0,template:O=>typeof O=="number"?au(O):""},{id:"date",header:m("Date"),width:120,sort:!0,resize:!0,template:O=>O?p(O):""}],[m,p]),M=u.useRef(null),A=u.useRef(null),T=u.useMemo(()=>C?["/wx-filemanager-parent-link"]:[...v],[C,v]);function D(O,ye){if(ye&&ye.target&&ye.target.className&&ye.target.className.indexOf("wx-grip")!==-1)return;const me=ye&&(ye.ctrlKey||ye.metaKey),X=ye&&ye.shiftKey;if(O==="/wx-filemanager-parent-link"){if(v.length&&(me||X))return;c.exec("select-file",{type:"navigation"});return}let I=O==="body"&&ye?null:O;!M.current&&!A.current?c.exec("select-file",{id:I,toggle:me,range:X,panel:n}):(M.current=null,A.current=null)}function B(){b.length>1&&c.exec("set-path",{id:b[b.length-2].id,panel:n,selected:[b[b.length-1].id]})}function H(O){if(O==="/wx-filemanager-parent-link")return B();const ye=j.find(me=>me.id===O);ye&&(ye.type==="folder"?c.exec("set-path",{id:ye.id,panel:n}):c.exec("open-file",{id:ye.id}))}function W(O){const ye=O.key,me=w[x];let X=me?"asc":"desc";me&&me.key===ye&&(X=me.order==="asc"?"desc":"asc"),c.exec("sort-files",{key:ye,order:X,panel:n,path:x})}function _(O){O.intercept("sort-rows",ye=>(M.current=!0,W(ye),!1)),O.intercept("select-row",()=>!1),O.on("resize-column",()=>A.current=!0),O.intercept("hotkey",()=>!1)}const Z=u.useMemo(()=>x!=="/"?[{id:"/wx-filemanager-parent-link",name:m("Back to parent folder")},...j]:j,[x,j,m]),G=u.useMemo(()=>{if(Z&&w&&w[x]){const{key:O,order:ye}=w[x];return{[O]:{order:ye}}}},[Z,w,x]),q=u.useRef(null),Q=u.useRef();return u.useEffect(()=>{Q.current?(Q.current.click=D,Q.current._dblclick=H):(Q.current={click:D,dblclick:O=>Q.current._dblclick(O),_dblclick:H},Po(q.current,Q.current))},[D,H]),r.jsxs("div",{onClick:i,onContextMenu:l,className:"wx-SSaVhET7 wx-wrapper",children:[r.jsx(tw,{panel:n}),r.jsx("div",{"data-id":Ln("body"),className:`wx-SSaVhET7 wx-list ${a?"wx-active":""}`,ref:q,children:r.jsx(nw,{children:r.jsx(RA,{init:_,data:Z,columns:k,selectedRows:T,columnStyle:()=>"wx-SSaVhET7 wx-each-cell",sizes:{rowHeight:42,headerHeight:42},sortMarks:G})})})]})}function OA(){const n=u.useContext(_n),a=ut(n,"activePanel");function i(l){n.exec("set-active-panel",{panel:l})}return r.jsxs("div",{className:"wx-L55BfJa2 wx-panels","data-id":Ln("body"),children:[r.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":0,children:r.jsx(zh,{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(zh,{panel:1,active:a==1,onClick:()=>i(1),onContextMenu:()=>i(1)})})]})}function aw({folderIcon:n=!1,folder:a={}}){const i=u.useContext(_n),[l,c]=Ss(i,"panels"),d=ut(i,"activePanel"),m=u.useMemo(()=>l[d].path,[c,d]),p=u.useContext(In.i18n),g=u.useMemo(()=>p.getGroup("filemanager"),[p]),v=u.useMemo(()=>!!a.data?.find(C=>C.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":Ln(a.id),className:`wx-NYfhvGIt wx-folder${m===a.id?" wx-selected":""}`,style:{paddingLeft:`${b}px`},children:[v?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&&v?r.jsx(r.Fragment,{children:a.data.map(C=>C.type==="folder"?r.jsx(aw,{folder:C},C.id):null)}):null]})}function HA(){const n=u.useContext(_n),[a,i]=Ss(n,"data"),[l,c]=Ss(n,"panels"),d=ut(n,"activePanel"),m=u.useMemo(()=>l[d]._crumbs,[c,d]),p=u.useCallback(C=>{n.exec("open-tree-folder",{id:C,mode:!a.byId(C).open})},[n,i]),g=u.useCallback(C=>{const j=lp(C,m);n.exec("set-path",{id:C,panel:d,...j&&{selected:[j]}})},[n,m,d]),[v,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=p):(w.current={click:g,toggle:p},Po(b.current,w.current))},[g,p]),r.jsx("ul",{ref:b,className:"wx-LyHJ6R6A",children:v.map(C=>C.type==="folder"?r.jsx(aw,{folder:C},C.id):null)})}function FA(){const n=u.useContext(_n),a=u.useContext(In.i18n),i=u.useMemo(()=>a.getGroup("filemanager"),[a]),l=ut(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:[au(c)," ",i("of")," ",au(d)," ",i("used")]})]}):null}function BA({option:n}){const a=u.useContext(In.i18n).getGroup("filemanager"),i=u.useContext(up),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 PA({readonly:n,menuOptions:a}){const i=u.useContext(In.i18n).getGroup("filemanager"),{showPrompt:l}=u.useContext(cp);u.useEffect(()=>{rj("upload",BA)},[]);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(lj,{options:d,at:"bottom-fit",onClick:c,children:r.jsx(Kc,{type:"primary block",children:i("Add New")})})}),r.jsx("div",{className:"wx-FlucfALM wx-tree",children:r.jsx(HA,{})}),r.jsx(FA,{})]})}function $A({value:n="",onSearch:a}){const[i,l]=Ox(n),c=u.useContext(In.i18n).getGroup("filemanager"),d=u.useRef(null),m=u.useMemo(()=>i!==""?"wxi-close":"wxi-search",[i]);function p(v){const x=v.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:p,placeholder:c("Search")})]})}function UA({narrowMode:n=!1,onShowTree:a}){const i=u.useContext(_n),l=u.useContext(In.i18n).getGroup("filemanager"),c=ut(i,"mode"),d=ut(i,"preview"),m=ut(i,"search"),p=[{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 v(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":Ln("toggle-tree"),children:r.jsx(Fl,{onClick:()=>a&&a(),name:"subtask"})}):r.jsx("div",{className:"wx-5PZQQztG wx-name",children:l("Files")}),r.jsx($A,{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(Lk,{onClick:v,value:d,children:r.jsx("i",{className:"wx-5PZQQztG wxi-eye"})})}),r.jsx("div",{className:"wx-5PZQQztG wx-modes",children:r.jsx(Nk,{value:c,options:p,onChange:g})})]})]})}function qA(){const n=u.useContext(_n),a=ut(n,"activePanel");return r.jsxs("div",{className:"wx-NwohNJzN wx-wrapper",children:[r.jsx(tw,{panel:a}),r.jsx(nw,{children:r.jsx(ew,{})})]})}function GA({readonly:n=!1,menuOptions:a,extraInfo:i}){const l=u.useRef(null),c=u.useRef(null),[d,m]=u.useState(void 0),[p,g]=u.useState(void 0),[v,x]=u.useState(!1),b=qx(),w=u.useContext(_n),{showPrompt:C,showConfirm:j}=u.useContext(cp),k=u.useContext(In.i18n),M=u.useMemo(()=>k.getGroup("filemanager"),[k]),A=ut(w,"mode"),T=ut(w,"preview"),D=ut(w,"activePanel"),[B,H]=Ss(w,"panels"),W=u.useMemo(()=>(B&&D!=null?B[D]:null)?.selected??[],[H,D]),_=u.useMemo(()=>(B&&D!=null?B[D]:null)?.path,[H,D]),[Z,G]=u.useState([]);u.useEffect(()=>{const re=l.current;if(!re)return;const ue=new ResizeObserver(K=>{const xe=K[0]?.borderBoxSize?.[0]?.inlineSize;typeof xe=="number"&&g(xe<768)});return ue.observe(re),()=>{ue.disconnect()}},[]);const q=u.useCallback(()=>{x(re=>!re)},[]),Q=u.useCallback(re=>{p&&nu(re)!=="toggle-tree"&&x(!1)},[p]);u.useEffect(()=>{const re=c.current;if(re)return pr(re,Q).destroy},[Q]),u.useEffect(()=>{const re=c.current;if(!re)return;const ue=new ResizeObserver(()=>{re&&m(re.clientWidth)});return ue.observe(re),re&&m(re.clientWidth),()=>{ue.disconnect()}},[]);const O=u.useMemo(()=>({icon:"wxi-eye",text:"Preview",id:"preview"}),[]),ye=u.useCallback(re=>{let ue=p?[O]:[];return re==="file"&&(ue=[...ue,...a().filter(K=>K.id==="download")]),ue},[p,O,a]),me=u.useRef(null),X=u.useCallback((re,ue,K)=>{const xe=K?[ue.id]:W;switch(re){case"download":w.exec("download-file",{id:ue.id});break;case"copy":case"move":me.current={action:re,ids:xe};break;case"paste":me.current&&w.exec(me.current.action==="copy"?"copy-files":"move-files",{ids:me.current.ids,target:ue?.type==="folder"?ue.id:_});break;case"rename":C({item:ue});break;case"delete":j({selected:xe});break;case"preview":w.exec("show-preview",{mode:!T});break}},[w,W,_,C,j,T]),I=u.useCallback(()=>B?.[D],[B,D]);u.useEffect(()=>{const re=l.current;if(!re)return;const ue=Yk(re,{api:w,menuOptions:n?ye:a,performAction:X,getPanel:I});return()=>{typeof ue=="function"?ue():ue&&typeof ue.destroy=="function"&&ue.destroy()}},[w,n,ye,a,X,I]);const ee=u.useCallback((re,ue)=>{const K=re?w.getFile(re):null,xe=ue.target.closest(".tree-item.folder");let z;if(n)z=ye(K?.type);else{switch(re){case"body":z=a(re);break;default:if(K)if(!xe&&W.length>1)z=p?[O,...a("multiselect")]:a("multiselect");else if(re==="/")z=a("folder",K).filter(le=>le.id==="paste");else{const le=a(K.type,K);le&&(z=p?[O,...le]:le)}}A==="search"&&(z=z?.filter(le=>le.id!=="paste"))}if(K?.id&&(!W.length||!W.some(le=>le===K.id))&&!xe&&w.exec("select-file",{id:K.id}),z?.length)return z.forEach(le=>{xe&&(le.hotkey=""),le.text&&(le.text=M(le.text)),le.hotkey&&(le.subtext=le.hotkey)}),G(z),K||{}},[w,n,ye,a,W,p,O,A,M]),V=u.useCallback(re=>{const{action:ue,context:K}=re;ue&&X(ue.id,K,!ue.hotkey)},[X]);async function P(re){await Promise.resolve();const{name:ue,size:K}=re.file;w.exec("create-file",{file:{name:ue,size:K,date:new Date,file:re.file},parent:_})}return r.jsx("div",{className:"wx-RJbNonjJ wx-filemanager wx-flex",ref:l,"data-menu-ignore":"false",children:p&&T?r.jsx("div",{className:"wx-RJbNonjJ wx-info-narrow",children:r.jsx(eh,{narrowMode:p,extraInfo:i})}):r.jsxs(r.Fragment,{children:[r.jsx(UA,{narrowMode:p,onShowTree:q}),r.jsx(oj,{dataKey:"id",at:"point",options:Z,resolver:ee,onClick:V,children:r.jsxs(Ux,{dataKey:"actionId",options:Z,resolver:ee,onClick:V,children:[r.jsx(mj,{data:b,apiOnly:!0,uploadURL:P}),r.jsx(up.Provider,{value:b,children:r.jsx("div",{className:"wx-RJbNonjJ wx-content-wrapper wx-flex",children:A!=="panels"&&A!=="search"?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-RJbNonjJ "+["wx-sidebar",p?"wx-sidebar-narrow":"",v?"wx-sidebar-visible":""].filter(Boolean).join(" "),ref:c,children:r.jsx(PA,{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":Ln("body"),children:A==="table"?r.jsx(zh,{panel:D}):r.jsx(qA,{})}),T?r.jsx("div",{className:"wx-RJbNonjJ wx-info",children:r.jsx(eh,{extraInfo:i})}):null]})]}):r.jsxs(r.Fragment,{children:[r.jsx("div",{className:`wx-RJbNonjJ wx-content-item${T?"":"-fit"}`,children:A==="panels"?r.jsx(OA,{}):r.jsx(IA,{})}),T?r.jsx("div",{className:"wx-RJbNonjJ wx-info",children:r.jsx(eh,{extraInfo:i})}):null]})})})]})})]})})}const VA=n=>n.split("-").map(a=>a?a.charAt(0).toUpperCase()+a.slice(1):"").join("");function WA(n,a){const{type:i,ext:l}=n;if(i==="folder")return!1;let c;return i&&i!=="file"&&nb[i]?c=i:l?c=nb[l]?l:"file":c="unknown",`https://cdn.svar.dev/icons/filemanager/vivid/${a}/${c}.svg`}const YA=u.forwardRef(function(n,a){const{data:i=[],mode:l="cards",drive:c=null,preview:d=!1,panels:m=null,activePanel:p=0,readonly:g=!1,menuOptions:v=Gk,extraInfo:x=null,init:b=null,icons:w=WA,previews:C=null,...j}=n,k=u.useRef();k.current=j;const M=u.useMemo(()=>new qk(Fx),[]),A=u.useMemo(()=>M.in,[M]),T=u.useRef(null);T.current===null&&(T.current=new Lx((H,W)=>{const _="on"+VA(H);k.current&&k.current[_]&&k.current[_](W)}),A.setNext(T.current));const D=u.useMemo(()=>({getState:M.getState.bind(M),getReactiveState:M.getReactive.bind(M),getStores:()=>({data:M}),exec:A.exec,setNext:H=>(T.current=T.current.setNext(H),T.current),intercept:A.intercept.bind(A),on:A.on.bind(A),detach:A.detach.bind(A),getFile:M.getFile.bind(M),serialize:M.serialize.bind(M),templates:{preview:C||(()=>null),icon:w==="simple"?(()=>null):w}}),[M,A]),B=u.useRef(0);return u.useEffect(()=>{if(!B.current)b&&b(D);else{const H=M.getState();M.init({data:i,mode:l,drive:c,preview:d,panels:m||H.panels||[],activePanel:p})}B.current++},[M,i,l,c,d,m,p,b,D]),B.current===0&&M.init({data:i,mode:l,drive:c,preview:d,panels:m||[],activePanel:p}),u.useImperativeHandle(a,()=>({...D}),[D]),r.jsx(_n.Provider,{value:D,children:r.jsx(rp,{words:ip,optional:!0,children:r.jsx(DA,{children:r.jsx(GA,{readonly:g,menuOptions:v,extraInfo:x})})})})});function KA({fonts:n=!0,children:a}){return a?r.jsx(Py,{fonts:n,children:a}):r.jsx(Py,{fonts:n})}Zh(Oa);function dp(n,a){if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`Invalid Hub ${a} response.`);return n}function ru(n,a,i){const l=dp(n,i);if(!Array.isArray(l[a]))throw new Error(`Invalid Hub ${i} response: ${a} must be an array.`);return l[a]}function XA(n,a,i){const l=dp(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 QA(n,a=!1){return ru(await Ye(`/api/remote/filesystem/roots${a?"?refresh=1":""}`,void 0,n),"roots","filesystem roots")}async function th(n,a){const i=await Ye(`/api/remote/filesystem/entries?id=${encodeURIComponent(n)}`,void 0,a);return{folder:XA(i,"folder","filesystem entries"),entries:ru(i,"entries","filesystem entries")}}async function ZA(n,a){return Ye("/api/remote/filesystem/selection/scan",{method:"POST",body:JSON.stringify({itemIds:n})},a)}async function JA(n,a,i,l){return Ye("/api/remote/files/from-hub",{method:"POST",body:JSON.stringify({itemIds:n,deviceIds:a,remoteDirectory:i})},l)}async function eN(n,a=!1){const i=await Ye(`/api/remote/files/jobs?active=${a?"1":"0"}`,void 0,n);return{jobs:ru(i,"jobs","file transfer jobs")}}async function tN(n,a){return Ye(`/api/remote/files/jobs/${encodeURIComponent(n)}`,void 0,a)}async function nN(n,a){return Ye(`/api/remote/files/jobs/${encodeURIComponent(n)}/cancel`,{method:"POST"},a)}async function ab(n){return ru(await Ye("/api/remote/filesystem/shared-folders",void 0,n),"folders","shared folders")}async function aN(n,a){return Ye("/api/remote/filesystem/shared-folders",{method:"POST",body:JSON.stringify({sourceId:n})},a)}async function sN(n,a,i){return Ye(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)},i)}async function rN(n,a){return Ye(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}`,{method:"DELETE"},a)}async function iN(n,a,i,l){const c=await Ye(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}/sync`,{method:"POST",body:JSON.stringify({deviceIds:a,remoteDirectory:i})},l),d=dp(c,"shared folder sync");return{ok:d.ok===!0,jobs:ru(c,"jobs","shared folder sync"),files:Number(d.files||0),totalBytes:Number(d.totalBytes||0)}}function lN(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 sb(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 $d(n){return n.driveType==="network"?"network":n.driveType==="removable"?"removable":"local"}function oN(n){const a=n.filter(i=>$d(i)==="local");return a.find(i=>/\bC:/i.test(`${i.name} ${i.displayPath||""}`))||a[0]||n[0]||null}function cN({hubUrl:n,roots:a,loading:i,error:l,onRefreshRoots:c,onImportFiles:d,onImportFolder:m,onSelectionChange:p,onShareItem:g,onAddSyncFolder:v,onNotice:x}){const b=u.useRef(null),w=u.useRef("/"),C=u.useRef(0),j=u.useRef([]),k=u.useRef(new Map),[M,A]=u.useState(null),[T,D]=u.useState([]),[B,H]=u.useState([]),[W,_]=u.useState(0),[Z,G]=u.useState(null),[q,Q]=u.useState(!1),[O,ye]=u.useState(""),[me,X]=u.useState(new Set),I=a.find(ce=>ce.id===M)||null,ee=T[T.length-1]||null,V=I?ee?.svarPath||`/${I.name}`:null,P=V;u.useEffect(()=>{j.current=T,w.current=P||"/"},[P,T]);const re=u.useMemo(()=>(k.current.clear(),!I||!P||T.length===0?[]:(T.forEach(ce=>k.current.set(ce.svarPath,ce.hubId)),[...T.map((ce,ge)=>({id:ce.svarPath,parent:ge===0?"/":T[ge-1].svarPath,type:"folder",name:ce.name,date:ce.modifiedAt?new Date(ce.modifiedAt):void 0,lazy:!1})),...B.map(ce=>{const ge=`${P}/${ce.name}`;return k.current.set(ge,ce.id),{id:ge,parent:P,name:ce.name,type:ce.type==="file"?"file":"folder",...ce.type==="file"?{size:ce.size}:{},date:ce.modifiedAt?new Date(ce.modifiedAt):void 0,lazy:ce.type!=="file"&&ce.hasChildren===!0,displayPath:ce.displayPath,locked:ce.locked,driveType:ce.driveType,totalBytes:ce.totalBytes,freeBytes:ce.freeBytes}})])),[I,B,P,T]),ue=ce=>k.current.get(String(ce))||String(ce),K=ce=>lN({...ce,id:ue(String(ce.id)),parent:ue(String(ce.parent))}),xe=async(ce,ge)=>{const Ae=ce[ce.length-1];if(!Ae)return;const Le=++C.current;Q(!0),ye("");try{const Pe=await th(Ae.hubId,n);if(Le!==C.current)return;if(!Array.isArray(Pe.entries))throw new Error("Invalid Hub filesystem entries response.");const Ve={...Ae,displayPath:Pe.folder.displayPath||Ae.displayPath,modifiedAt:Pe.folder.modifiedAt||Ae.modifiedAt},Ke=[...ce.slice(0,-1),Ve];j.current=Ke,D(Ke),H(Pe.entries),_(de=>de+1)}catch(Pe){if(Le!==C.current)return;console.error("[LiveDesk FS] folder navigation failed",{folderId:Ae.hubId,error:Pe}),ye(Pe instanceof Error?`${ge}: ${Pe.message}`:`${ge}: Unable to read this folder.`)}finally{Le===C.current&&Q(!1)}},z=async ce=>{const ge={svarPath:`/${ce.name}`,hubId:ce.id,name:ce.name,displayPath:ce.displayPath,modifiedAt:ce.modifiedAt},Ae=++C.current;A(ce.id),j.current=[ge],D([ge]),w.current=ge.svarPath,H([]),ye(""),Q(!0),G(ce.id),X(Le=>{const Pe=new Set(Le);return Pe.delete(ce.id),Pe});try{const Le=await th(ce.id,n);if(Ae!==C.current)return;if(!Array.isArray(Le.entries))throw new Error("Invalid Hub filesystem entries response.");const Pe={...ge,displayPath:Le.folder.displayPath||ge.displayPath,modifiedAt:Le.folder.modifiedAt||ge.modifiedAt};j.current=[Pe],D([Pe]),H(Le.entries),_(Ve=>Ve+1)}catch(Le){if(Ae!==C.current)return;console.error("[LiveDesk FS] getEntries failed",{rootId:ce.id,error:Le}),X(Pe=>new Set(Pe).add(ce.id)),ye(Le instanceof Error?`${ce.name}: ${Le.message}`:`${ce.name}: Unable to read this drive.`),x(Le instanceof Error?`${ce.name}: ${Le.message}`:`${ce.name}: Unable to read this drive.`)}finally{Ae===C.current&&(G(null),Q(!1))}},le=ce=>{const ge=j.current;ce<0||ce>=ge.length||ce===ge.length-1||xe(ge.slice(0,ce+1),ge[ce].name)},ke=(ce,ge)=>{if(ce.type!=="folder")return;const Ae=j.current,Le=Ae.findIndex(Ve=>Ve.svarPath===ge);if(Le<0)return;const Pe={svarPath:`${ge}/${ce.name}`,hubId:ce.id,name:ce.name,displayPath:ce.displayPath,modifiedAt:ce.modifiedAt};xe([...Ae.slice(0,Le+1),Pe],ce.name)},Ce=()=>le(j.current.length-2),Ue=ce=>{if(ce.key!=="Enter"&&ce.code!=="Enter"&&ce.code!=="NumpadEnter"||ce.target?.closest('button, input, textarea, [contenteditable="true"]'))return;const Ae=b.current;if(!Ae)return;const Le=Ae.getState().panels?.flatMap(Ve=>Ve.selected||[])||[];if(Le.length!==1)return;const Pe=Ae.getFile(String(Le[0]));Pe?.type==="folder"&&(ce.preventDefault(),ce.stopPropagation(),ke(K(Pe),String(Pe.parent||w.current)))};u.useEffect(()=>{const ce=a.find(ge=>ge.id===M)||oN(a);if(X(ge=>new Set([...ge].filter(Ae=>a.some(Le=>Le.id===Ae)))),!ce){A(null),j.current=[],D([]),H([]);return}z(ce)},[a]);const Be=ce=>{b.current=ce,ce.on("request-data",async({id:ge})=>{const Ae=String(ge),Le=ue(Ae);try{const Pe=await th(Le,n);if(!Array.isArray(Pe.entries))throw new Error("Invalid Hub filesystem entries response.");const Ve=Pe.entries.map(Ke=>{const de=`${Ae}/${Ke.name}`;return k.current.set(de,Ke.id),{id:de,parent:Ae,name:Ke.name,type:Ke.type==="file"?"file":"folder",...Ke.type==="file"?{size:Ke.size}:{},date:Ke.modifiedAt?new Date(Ke.modifiedAt):void 0,lazy:Ke.type!=="file"&&Ke.hasChildren===!0,displayPath:Ke.displayPath,locked:Ke.locked,driveType:Ke.driveType,totalBytes:Ke.totalBytes,freeBytes:Ke.freeBytes}});await ce.exec("provide-data",{id:Ae,data:Ve})}catch(Pe){console.error("[LiveDesk FS] nested getEntries failed",{id:Le,error:Pe}),x(Pe instanceof Error?Pe.message:"Unable to read this folder.")}}),ce.intercept("set-path",({id:ge})=>{const Ae=String(ge),Le=j.current.findIndex(Ve=>Ve.svarPath===Ae);if(Le>=0)return le(Le),!1;const Pe=ce.getFile(Ae);if(Pe?.type==="folder")return ke(K(Pe),String(Pe.parent||w.current)),!1}),ce.intercept("open-file",()=>!1),ce.on("select-file",()=>{window.setTimeout(()=>{const Le=(ce.getState().panels?.flatMap(Pe=>Pe.selected||[])||[]).map(Pe=>ce.getFile(Pe)).filter(Boolean).map(Pe=>K(Pe));p(Le.map(Pe=>Pe.id),Le)},0)})},he=(ce,ge)=>{const Ae=ge?K(ge):null,Le=()=>{const Pe=Ae?.type==="file"?String(ge?.parent||w.current):String(ge?.id||w.current);b.current?.exec("request-data",{id:Pe})};return ce==="body"?[{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Le},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>x("Select a file or folder to view its properties.")}]:ce==="multiselect"?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>{(b.current?.getState().panels?.flatMap(Ve=>Ve.selected||[])||[]).forEach(Ve=>{const Ke=b.current?.getFile(Ve);Ke&&g(K(Ke))})}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Le}]:Ae?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>g(Ae)},...Ae.type==="folder"?[{id:"sync",text:"Add folder to Sync",icon:"mdi mdi-folder-sync-outline",handler:()=>v(Ae)}]:[],{id:"copy-path",text:"Copy path",icon:"mdi mdi-content-copy",handler:()=>{Hd(Ae.displayPath||Ae.name)}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Le},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>x(`${Ae.name}
14
+ ${Ae.displayPath||""}`)}]:[]},Xe=async()=>{try{await c()}catch(ce){x(ce instanceof Error?ce.message:"Unable to refresh Hub drives.")}},et=[{id:"local",label:"Local drives",icon:_l,roots:a.filter(ce=>$d(ce)==="local")},{id:"removable",label:"Removable drives",icon:ZS,roots:a.filter(ce=>$d(ce)==="removable")},{id:"network",label:"Network drives",icon:Gh,roots:a.filter(ce=>$d(ce)==="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(_l,{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(qb,{size:16})}),r.jsx("button",{className:"icon-button",onClick:m,title:"Import folder from this browser",type:"button",children:r.jsx(JS,{size:16})}),r.jsx("button",{className:"icon-button",onClick:()=>{Xe()},title:"Refresh drives",type:"button",children:r.jsx(Ho,{size:16})})]})]}),i?r.jsxs("div",{className:"hub-file-explorer-state",children:[r.jsx(_l,{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(Zr,{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(_l,{size:15}),r.jsx("strong",{children:"This PC"})]}),et.map(ce=>ce.roots.length>0&&r.jsxs("section",{className:"hub-drive-group",children:[r.jsxs("h3",{children:[r.jsx(ce.icon,{size:13}),ce.label]}),r.jsx("div",{className:"hub-drive-list",children:ce.roots.map(ge=>{const Ae=ce.icon,Le=me.has(ge.id)||ge.locked===!0;return r.jsxs("button",{className:`hub-drive-item ${M===ge.id?"active":""} ${Le?"unavailable":""}`,onClick:()=>{z(ge)},"aria-pressed":M===ge.id,type:"button",children:[r.jsx("span",{className:"hub-drive-item-icon",children:r.jsx(Ae,{size:16})}),r.jsxs("span",{className:"hub-drive-item-copy",children:[r.jsx("strong",{children:ge.name}),r.jsx("small",{children:ge.displayPath||ge.name}),r.jsxs("em",{children:[sb(ge.freeBytes||0)," free / ",sb(ge.totalBytes||0)]})]}),Z===ge.id?r.jsx(Jr,{className:"hub-drive-item-status spin",size:15}):Le?r.jsx(Qv,{className:"hub-drive-item-status",size:15}):null]},ge.id)})})]},ce.id)),a.length===0&&r.jsxs("div",{className:"hub-drive-sidebar-empty",children:[r.jsx(Zr,{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((ce,ge)=>r.jsxs("span",{className:"hub-file-explorer-breadcrumb-item",children:[ge>0&&r.jsx(Vh,{size:13,"aria-hidden":"true"}),r.jsx("button",{className:`hub-file-explorer-breadcrumb ${ge===T.length-1?"current":""}`,onClick:()=>le(ge),"aria-current":ge===T.length-1?"location":void 0,type:"button",children:ce.name})]},ce.svarPath))}),r.jsxs("div",{className:"hub-file-explorer-navigation-actions",children:[q&&r.jsx(Jr,{className:"hub-file-explorer-loading-icon spin",size:15,"aria-label":"Loading folder"}),r.jsx("button",{className:"icon-button",onClick:Ce,disabled:T.length<=1||q,title:"Back to parent folder",type:"button",children:r.jsx(Hb,{size:16})})]})]}),O&&r.jsxs("div",{className:"hub-file-explorer-folder-error",role:"alert",children:[r.jsx(Qv,{size:15}),r.jsx("span",{children:O})]}),r.jsx("div",{className:"hub-file-explorer-svar",onKeyDownCapture:Ue,children:r.jsx(KA,{fonts:!1,children:r.jsx(YA,{data:re,panels:V?[{path:V,selected:[]}]:void 0,readonly:!0,mode:"table",preview:!1,init:Be,icons:"simple",menuOptions:he},`${I?.id||"no-root"}:${W}`)})})]})]})]})}class uN 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(tf,{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(Ho,{size:15})," Retry"]})]}):this.props.children}}function dN(n){return n.deviceName||n.hostname||n.deviceId}function fN({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(Zc,{size:14})," All connected"]}),r.jsxs("button",{className:a==="selected"?"active":"",onClick:()=>l("selected"),type:"button",children:[r.jsx(oa,{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 p=a==="all"||d.has(m.deviceId);return r.jsxs("label",{className:`file-share-device-option ${p?"selected":""}`,children:[r.jsx("input",{type:"checkbox",checked:p,disabled:a==="all",onChange:()=>c(m.deviceId)}),r.jsx(oa,{size:20,"aria-hidden":"true"}),r.jsxs("span",{children:[r.jsx("strong",{children:dN(m)}),r.jsxs("small",{children:["Slot ",m.slotNumber?String(m.slotNumber).padStart(3,"0"):"-"," / ",m.platform||"unknown OS"]})]}),r.jsx(Dn,{size:17,"aria-hidden":"true"})]},m.deviceId)})})]})}function mN(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 hN({folders:n,loading:a,busy:i,canSync:l,onSyncAll:c,onSync:d,onToggleAuto:m,onRemove:p,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(Od,{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(Od,{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(v=>r.jsxs("article",{className:`file-share-sync-row state-${v.status}`,children:[r.jsx("div",{className:"file-share-sync-icon",children:r.jsx(Od,{size:19})}),r.jsxs("div",{className:"file-share-sync-info",children:[r.jsx("strong",{children:v.name}),r.jsx("span",{children:v.displayPath}),r.jsxs("small",{children:[v.fileCount," files / ",mN(v.totalBytes)," · ",v.lastSyncedAt?`Last sync ${Jb(v.lastSyncedAt)} ago`:v.message||"Not synced yet"]})]}),r.jsxs("label",{className:"file-share-auto-sync",children:[r.jsx("input",{type:"checkbox",checked:v.autoSync,onChange:()=>m(v)}),r.jsx("span",{children:"Auto"})]}),r.jsxs("button",{className:"text-button compact",onClick:()=>d(v),disabled:i||!l||v.status==="syncing",type:"button",children:[r.jsx(Ho,{size:14})," Sync now"]}),r.jsx("button",{className:"icon-button",onClick:()=>p(v),title:"Remove sync folder",type:"button",children:r.jsx($h,{size:15})})]},v.id))})]})}function pN(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(Qc,{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(fN,{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(Lo,{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(Qc,{size:17})," Share selected"]}),r.jsxs("button",{className:"file-share-secondary-button",onClick:n.onAddSync,disabled:!n.canAddSync,type:"button",children:[r.jsx(Lo,{size:16})," Add selected folder to Sync"]})]}):r.jsx(hN,{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 gN(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 rb(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(Oh(n.state)?100:99,a))}function ib(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 Oh(n){return["completed","partially-failed","failed","cancelled"].includes(n)}function vN({hubUrl:n,devices:a,localFeatureAccess:i,upgradeNotice:l,remoteDirectory:c,onRemoteDirectoryChange:d,targetMode:m,selectedTargetIds:p,onTargetModeChange:g,onTargetToggle:v,filePickerRef:x,folderPickerRef:b,onBrowserFileImport:w,onBrowserFolderImport:C,onNotice:j,onTransferChange:k}){const M=Array.isArray(a)?a:[],[A,T]=u.useState([]),[D,B]=u.useState(!0),[H,W]=u.useState(""),[_,Z]=u.useState([]),[G,q]=u.useState([]),[Q,O]=u.useState(null),[ye,me]=u.useState(!1),[X,I]=u.useState([]),[ee,V]=u.useState(!0),[P,re]=u.useState(!1),[ue,K]=u.useState("send"),[xe,z]=u.useState([]),le=u.useRef(new Set),ke=u.useRef(!1),Ce=u.useMemo(()=>m==="all"?M.map(fe=>fe.deviceId):p.filter(fe=>M.some(_e=>_e.deviceId===fe)),[M,p,m]),Ue=xe.find(fe=>!Oh(fe.state)),Be=G.length===1&&G[0].type==="folder"?G[0]:null,he=G.length===0?"Select files or folders from the Hub explorer.":ye?"Calculating selection size...":Q?`${Q.files} files, ${Q.folders} folders · ${gN(Q.totalBytes)}`:`${G.length} item${G.length===1?"":"s"} selected`,Xe=fe=>{k({id:fe.jobId,state:fe.state,progress:rb(fe),message:ib(fe)})},et=u.useCallback(async()=>{const fe=await QA(n,!0);return T(fe),W(""),fe},[n]),ce=async()=>{if(!ke.current){ke.current=!0;try{const _e=(await eN(n,!0)).jobs||[],Ee=await Promise.all([...le.current].map(async Dt=>{try{return await tN(Dt,n)}catch{return null}})),mt=[..._e,...Ee.filter(Boolean)],Ht=[...new Map(mt.map(Dt=>[Dt.jobId,Dt])).values()];z(Ht),Ht.forEach(Xe),Ht.filter(Dt=>Oh(Dt.state)).forEach(Dt=>le.current.delete(Dt.jobId))}catch{}finally{ke.current=!1}}};u.useEffect(()=>{let fe=!0;B(!0),W(""),Promise.all([et(),ab(n).then(Ee=>{fe&&I(Ee)})]).catch(Ee=>{fe&&(W(Ee instanceof Error?"Hub file system is unavailable. Make sure LiveDesk Hub is running on this computer.":"Hub file system is unavailable."),j(Ee instanceof Error?Ee.message:"Hub file system is unavailable."))}).finally(()=>{fe&&(B(!1),V(!1))}),ce();const _e=window.setInterval(()=>{ce()},800);return()=>{fe=!1,window.clearInterval(_e)}},[n,et]),u.useEffect(()=>{if(_.length===0){O(null);return}let fe=!1;return me(!0),ZA(_,n).then(_e=>{fe||O(_e)}).catch(_e=>{fe||j(_e instanceof Error?_e.message:"Unable to calculate selected size.")}).finally(()=>{fe||me(!1)}),()=>{fe=!0}},[n,_.join("|")]);const ge=(fe,_e)=>{Z(fe),q(_e)},Ae=fe=>{fe.forEach(_e=>le.current.add(_e.jobId)),z(_e=>[...new Map([..._e,...fe].map(Ee=>[Ee.jobId,Ee])).values()]),fe.forEach(Xe)},Le=async()=>{if(!i){j(l);return}if(_.length===0){j("Select files or folders from the Hub explorer.");return}if(Ce.length===0){j("Choose at least one connected Client.");return}if(Ue){j("A Hub transfer is already running.");return}try{const fe=await JA(_,Ce,c.trim(),n);le.current.add(fe.jobId),j("Hub transfer queued."),await ce()}catch(fe){j(fe instanceof Error?fe.message:"Unable to start Hub transfer.")}},Pe=async fe=>{const _e=fe||Be;if(!_e||_e.type!=="folder"){j("Select one folder to add it to Sync.");return}try{const Ee=await aN(_e.id,n);I(mt=>[...mt.filter(Ht=>Ht.id!==Ee.folder.id),Ee.folder]),K("sync"),j(`${_e.name} is ready for Hub sync.`)}catch(Ee){j(Ee instanceof Error?Ee.message:"Unable to add the Hub folder to Sync.")}},Ve=async fe=>{if(Ce.length===0){j("Choose at least one connected Client.");return}re(!0),I(_e=>_e.map(Ee=>Ee.id===fe.id?{...Ee,status:"syncing"}:Ee));try{const _e=await iN(fe.id,Ce,c.trim(),n);Ae(_e.jobs||[]),j(_e.jobs?.length?"Hub sync queued.":"No changed files to sync.");const Ee=await ab(n);I(Ee)}catch(_e){j(_e instanceof Error?_e.message:"Unable to sync the Hub folder."),I(Ee=>Ee.map(mt=>mt.id===fe.id?{...mt,status:"error",message:"Sync failed"}:mt))}finally{re(!1)}},Ke=async()=>{re(!0);try{for(const fe of X)await Ve(fe)}finally{re(!1)}},de=async fe=>{try{const _e=await sN(fe.id,{autoSync:!fe.autoSync},n);I(Ee=>Ee.map(mt=>mt.id===fe.id?_e.folder:mt))}catch(_e){j(_e instanceof Error?_e.message:"Unable to update auto sync.")}},je=async fe=>{try{await rN(fe.id,n),I(_e=>_e.filter(Ee=>Ee.id!==fe.id))}catch(_e){j(_e instanceof Error?_e.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:fe=>{fe.currentTarget.files&&w(fe.currentTarget.files),fe.currentTarget.value=""}}),r.jsx("input",{ref:b,className:"hidden-file-input",type:"file",multiple:!0,webkitdirectory:"",directory:"",onChange:fe=>{fe.currentTarget.files&&C(fe.currentTarget.files),fe.currentTarget.value=""}}),r.jsx("div",{className:"file-share-workspace",children:r.jsxs(uN,{onRetry:()=>window.location.reload(),children:[r.jsx(cN,{hubUrl:n,roots:A,loading:D,error:H,onRefreshRoots:et,onImportFiles:()=>x.current?.click(),onImportFolder:()=>b.current?.click(),onSelectionChange:ge,onShareItem:fe=>{Z([fe.id]),q([fe]),K("send")},onAddSyncFolder:fe=>{Z([fe.id]),q([fe]),Pe(fe)},onNotice:j}),r.jsx(pN,{devices:M,targetMode:m,selectedTargetIds:p,onTargetModeChange:g,onTargetToggle:v,remoteDirectory:c,onRemoteDirectoryChange:d,selectedEntries:G,selectedSummary:he,canShare:i&&!Ue&&_.length>0&&Ce.length>0&&!ye,onShare:()=>{Le()},canAddSync:!!Be,onAddSync:()=>{Pe()},tab:ue,onTabChange:K,folders:X,foldersLoading:ee,syncBusy:P,onSyncAll:()=>{Ke()},onSync:fe=>{Ve(fe)},onToggleAuto:fe=>{de(fe)},onRemove:fe=>{je(fe)},onAddFolder:()=>{Pe()}})]})}),Ue&&r.jsx("footer",{className:"file-share-workspace-footer",children:r.jsxs("span",{children:[ib(Ue)," · ",rb(Ue),"% ",r.jsx("button",{className:"icon-button",onClick:()=>{nN(Ue.jobId,n).then(fe=>{z(_e=>_e.map(Ee=>Ee.jobId===fe.jobId?fe:Ee)),Xe(fe)})},title:"Cancel transfer",type:"button",children:r.jsx(la,{size:14})})]})})]})}const yN=u.forwardRef(function({value:a,onChange:i,onSubmit:l,onOpenSuggestedTasks:c,suggestedOpen:d=!1,suggestedTaskCount:m,disabled:p=!1,placeholder:g="Ask LiveDesk to work across your machines...",compact:v=!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:p,children:r.jsx(e0,{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:v?1:2,disabled:p}),r.jsxs("button",{className:"agents-run-button",type:"submit",disabled:p||!a.trim(),children:[p?r.jsx(Jr,{className:"spin",size:16}):r.jsx(Qc,{size:16}),p?"Running":"Run"]})]})}),bN=["read","processControl","serviceControl","applicationControl","fileRead","fileWrite","fileDelete","shell","script","softwareInstall","network","systemPower","systemConfiguration","userAccount"];function Qd(n){return n.deviceName?.trim()||n.hostname?.trim()||n.deviceId}function Zd(n){return n.connected!==!0?!1:n.synthetic===!0?!0:!n.channels||n.channels.control===!0}function xN(n){return n==="running"||n==="completed"||n==="failed"||n==="cancelled"?n:"queued"}function wN(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 SN(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:null}function ns(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Td(n){const a=ns(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 CN(n){const a=ns(n);return a===null?"":`${Math.round((a<=1?a:a/100)*100)}%`}function kN(n){return!n||/^(?:[\w .-]+ )?collected(?:\.)?$/i.test(n.trim())?"":n.trim()}function Jd(n,a){if(a.error)return a.error;const i=SN(a.data),l=kN(a.result||"");if(!i)return l||a.stage||a.status;if(n==="system.health"){const c=typeof i.machine=="string"?i.machine:"",d=Td(i.freeMemoryBytes),m=Td(i.totalMemoryBytes),p=ns(i.totalMemoryBytes)&&ns(i.freeMemoryBytes)!==null?`${Math.round(ns(i.freeMemoryBytes)/ns(i.totalMemoryBytes)*100)}% RAM free`:"";return[c,d&&m?`RAM ${d}/${m}`:"",p,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=Td(i.freeBytes),m=ns(i.totalBytes)&&ns(i.freeBytes)!==null?`${Math.round(ns(i.freeBytes)/ns(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=CN(i.usageRatio),m=ns(i.temperatureC)!==null?`${Math.round(ns(i.temperatureC))}°C`:"",p=Td(i.freeMemoryBytes);return[c,d&&`GPU ${d}`,m,p&&`${p} free`].filter(Boolean).join(" · ")||l||a.status}if(n==="process.list"){const c=ns(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 lb(n,a){const i=Jd(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 jN({state:n,operation:a}){const i=n.status==="completed"?fr:n.status==="failed"||n.status==="cancelled"?la:n.status==="running"?Jr:Gb,l=n.status==="running"?n.stage||"Working":n.status==="completed"?a?Jd(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 AN({operation:n,states:a,status:i,onCancel:l,onRetry:c,busy:d=!1}){const m=["running","queued"].includes(i),[p,g]=u.useState(!1),[v,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=>lb(n,D)),C=w.filter(D=>D.status==="completed").length,j=b.failed>0,k=w.length>0,M=a.filter(D=>v==="issues"?lb(n,D):v==="running"?D.status==="running"||D.status==="queued":v==="completed"?D.status==="completed":v==="failed"?D.status==="failed":!0),A=k&&!m||i==="completed-with-failures"?"Completed with issues":i[0]?.toUpperCase()+i.slice(1),T=a.filter(D=>D.status==="completed").map(D=>Jd(n,D)).filter(Boolean).filter((D,B,H)=>H.indexOf(D)===B).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:wN(n)})]}),r.jsx("span",{className:`agent-task-status status-${k?"completed-with-failures":i}`,children:A})]}),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"]}),C>0&&r.jsxs("span",{className:"summary-cancelled",children:[C," 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,B)=>{const H=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}: ${Jd(n,D)}`,"aria-label":`${B+1}. ${D.deviceName}: ${D.status}`,children:[r.jsx("b",{children:String(B+1).padStart(2,"0")}),r.jsx("span",{children:H})]},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":p,children:[p?r.jsx(t0,{size:14}):r.jsx(Vb,{size:14}),p?"Hide details":"Show details"]})}),p&&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:v===D?"active":"",onClick:()=>x(D),role:"tab","aria-selected":v===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:M.length>0?M.map(D=>r.jsx(jN,{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(n0,{size:14})," Cancel"]}),!m&&j&&c&&r.jsxs("button",{onClick:c,disabled:d,type:"button",children:[r.jsx(Uh,{size:14})," Retry failed"]})]})]})}function NN(n){try{return JSON.stringify(n,null,2).slice(0,6e3)}catch{return"{}"}}function MN({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:NN(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(la,{size:14})," Reject"]}),r.jsxs("button",{disabled:a,onClick:()=>i("once"),type:"button",children:[r.jsx(fr,{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(tf,{size:13})," Approval is bound to this run, tool, arguments, selected devices, and policy hash."]})]})}function TN(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 EN({items:n,onCancel:a,onRetry:i,busyBatchId:l,approvals:c,onApprove:d,onReject:m,busyApprovalId:p,progress:g,emptyTitle:v="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),C=u.useRef(""),j=n[n.length-1];return u.useLayoutEffect(()=>{const k=b.current;k&&(j?.type==="user"&&j.id!==C.current&&(w.current=!0),C.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 M=k.currentTarget;w.current=M.scrollHeight-M.scrollTop-M.clientHeight<72},children:[c.filter(k=>k.status==="pending").map(k=>r.jsx(MN,{approval:k,busy:p===k.approvalId,onApprove:M=>d(k,M),onReject:()=>m(k)},k.approvalId)),n.length===0&&r.jsxs("div",{className:"agents-empty-conversation",children:[r.jsx("strong",{children:v}),r.jsx("span",{children:x})]}),n.map(k=>{if(k.type==="task"){const M=k;return r.jsx(AN,{operation:M.operation,states:M.states,status:M.status,onCancel:()=>a(M.batchId,M.agentRunId),onRetry:()=>i(M.batchId),busy:l===M.batchId},M.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(Jr,{"aria-hidden":"true",size:15}),TN(g.stage)]}),r.jsx("p",{children:g.message})]})]})}const ob=["Recommended","Health & capacity","Processes & services","AI workloads","Files & configuration","Software & automation","Network & connectivity","Power & maintenance","Troubleshooting & recovery"],dn=["windows","macos","linux"],$i={"system.health":{label:"system health",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:dn},"gpu.status":{label:"GPU status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:dn},"disk.status":{label:"disk status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:dn},"process.list":{label:"process inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:dn},"service.status":{label:"service inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:dn},"diagnostics.collect":{label:"diagnostics collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:dn},"process.control":{label:"process control",permissionCategory:"processControl",readOnly:!1,risk:"high",supportedPlatforms:dn},"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:dn},"application.close":{label:"application close",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:dn},"file.read":{label:"file reading",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:dn},"file.write":{label:"file writing",permissionCategory:"fileWrite",readOnly:!1,risk:"high",supportedPlatforms:dn},"file.delete":{label:"file deletion",permissionCategory:"fileDelete",readOnly:!1,risk:"critical",supportedPlatforms:dn},"file.list":{label:"directory listing",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:dn},"command.run":{label:"command execution",permissionCategory:"shell",readOnly:!1,risk:"critical",supportedPlatforms:dn},"script.run":{label:"script execution",permissionCategory:"script",readOnly:!1,risk:"high",supportedPlatforms:dn},"software.install":{label:"software installation",permissionCategory:"softwareInstall",readOnly:!1,risk:"high",supportedPlatforms:dn},"network.status":{label:"network inspection",permissionCategory:"network",readOnly:!0,risk:"low",supportedPlatforms:dn},"system.power":{label:"power control",permissionCategory:"systemPower",readOnly:!1,risk:"critical",supportedPlatforms:dn},"system.configure":{label:"system configuration",permissionCategory:"systemConfiguration",readOnly:!1,risk:"critical",supportedPlatforms:dn},"logs.collect":{label:"log collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:dn}};new Set(Object.keys($i));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","문제해결","복구","장애"]},cb=["low","medium","high","critical"];function DN(n){return n.reduce((a,i)=>{const l=$i[i].risk;return cb.indexOf(l)>cb.indexOf(a)?l:a},"low")}function LN(n){return dn.filter(a=>n.every(i=>$i[i].supportedPlatforms.includes(a)))}function We(n,a,i,l,c,d,m={}){const p=m.description||l,g=c.flatMap(x=>x.split(".")),v=[...new Set([...RN[a],...d,...g])];return{id:n,category:a,title:i,prompt:l,description:p,requiredOperations:c,risk:m.risk||DN(c),targetSupport:m.targetSupport||"single-or-multiple",supportedPlatforms:m.supportedPlatforms||LN(c),keywords:v,recommended:m.recommended??!1,enabled:!0}}const sw=[We("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}),We("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}),We("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}),We("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}),We("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}),We("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}),We("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}),We("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}),We("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","높은 사용량"]),We("health-uptime","Health & capacity","Review Client uptime","Show uptime, boot time, and current system health for the target Clients.",["system.health"],["uptime","boot","가동시간"]),We("health-gpu-temperature","Health & capacity","Check GPU temperature","Check GPU temperature and thermal warnings on the current targets.",["gpu.status"],["thermal","temperature","발열"]),We("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"]),We("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","디스크"]),We("health-gpu-compare","Health & capacity","Compare GPU capacity","Compare GPU model, memory, temperature, and utilization across the current targets.",["gpu.status"],["compare","graphics","capacity"]),We("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","경고"]),We("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"]),We("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","실행 중"]),We("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"]),We("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"}),We("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"}),We("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"}),We("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"}),We("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","서비스 상태"]),We("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"}),We("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"]),We("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"}),We("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"}),We("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"]),We("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"]),We("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"}),We("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"]),We("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"}),We("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"}),We("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","구성"]),We("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"]),We("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"}),We("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"}),We("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"]),We("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"}),We("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"}),We("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"]}),We("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"]}),We("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"]}),We("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"}),We("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"}),We("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"}),We("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"]),We("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"}),We("network-adapter-status","Network & connectivity","Check network adapters","Show adapter state, address, and link information for the current targets.",["network.status"],["adapter","ethernet","wifi","네트워크 상태"]),We("network-disconnected","Network & connectivity","Find disconnected targets","Find current targets with disconnected or degraded network adapters.",["network.status"],["disconnected","offline","연결 끊김"]),We("network-link-speed","Network & connectivity","Check link speed","Report network link speed and duplex information for the current targets.",["network.status"],["speed","bandwidth","duplex"]),We("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"]),We("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"]),We("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"]),We("network-compare","Network & connectivity","Compare target connectivity","Compare adapter state, addresses, and link speed across the current targets.",["network.status"],["compare","inventory","connectivity"]),We("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"]),We("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"}),We("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"}),We("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"}),We("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"}),We("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"}),We("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"}),We("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"}),We("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"}),We("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"}),We("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"}),We("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"}),We("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"}),We("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"}),We("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"}),We("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"}),We("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","장애 보고서"])],nh={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 _N(n,a){return n==="safe-auto"?nh:n==="full-access"?{...nh,processControl:"allow",serviceControl:"allow",applicationControl:"allow",fileDelete:"allow",shell:"allow",script:"allow",softwareInstall:"allow",systemPower:"allow",systemConfiguration:"allow"}:n==="custom"&&a?a:{...nh,processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileWrite:"ask",network:"ask"}}function IN(n,a,i){const l=_N(a,i),c=n.requiredOperations.map(d=>l[$i[d].permissionCategory]);if(c.includes("deny")){const d=n.requiredOperations.find(m=>l[$i[m].permissionCategory]==="deny");return{state:"blocked",label:"Blocked",reason:`This task requires ${$i[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=>$i[d].readOnly)?{state:"read-only",label:"Read only"}:a==="full-access"?{state:"full-access",label:"Full Access"}:{state:"auto",label:"Auto allowed"}}function zN(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 ON(n,a,i){const l=new Set(i);return n.filter(c=>c.connected&&(a==="all"||a==="auto"||l.has(c.deviceId)))}function HN(n,a){const i=zN(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=>$i[c].readOnly):a.requiredOperations.every(c=>l.includes(c))}function rw(n,a,i,l,c,d){const m=IN(n,c,d),p=ON(a,i,l),g=p.map(C=>C.deviceId),v={...m,available:!1,availableDeviceIds:[],unsupportedDeviceIds:g,risk:n.risk,supportedPlatforms:n.supportedPlatforms};if(p.length===0)return{...v,reason:"Select at least one connected Client."};if(n.targetSupport==="single"&&p.length!==1)return{...v,reason:"This task supports one Client at a time."};if(m.state==="blocked")return v;const x=p.filter(C=>HN(C,n)),b=x.map(C=>C.deviceId),w=g.filter(C=>!b.includes(C));return x.length===0?{...v,unsupportedDeviceIds:w,reason:"No current target supports the required platform and client capabilities."}:{...v,available:!0,availableDeviceIds:b,unsupportedDeviceIds:w}}function FN(n,a,i,l,c,d){return n.filter(m=>m.enabled&&rw(m,a,i,l,c,d).available).length}const ah="livedesk.agentPromptRecent",sh="livedesk.agentPromptFavorites",BN={Recommended:Gi,"Health & capacity":Hl,"Processes & services":i0,"AI workloads":gh,"Files & configuration":r0,"Software & automation":Ub,"Network & connectivity":Gh,"Power & maintenance":jn,"Troubleshooting & recovery":s0};function ub(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 Ed(n,a){try{window.localStorage.setItem(n,JSON.stringify(a))}catch{}}function rh(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 $N(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 UN(n){return`permission-${n}`}function qN(n){return n==="low"?"Low risk":n==="medium"?"Medium risk":n==="high"?"High risk":"Critical risk"}function GN(n){return n==="windows"?"Windows":n==="macos"?"macOS":"Linux"}function VN({devices:n,targetMode:a,selectedIds:i,permissionMode:l,customCategories:c,onSelectPrompt:d,onClose:m}){const[p,g]=u.useState(""),[v,x]=u.useState("all"),[b,w]=u.useState(()=>ub(ah)),[C,j]=u.useState(()=>ub(sh)),[k,M]=u.useState(0),[A,T]=u.useState(""),D=u.useRef(null),B=u.useRef(null),H=u.useMemo(()=>sw.filter(X=>X.enabled),[]),W=u.useMemo(()=>new Map(H.map(X=>[X.id,rw(X,n,a,i,l,c)])),[c,n,l,i,a,H]),_=u.useMemo(()=>[...W.values()].filter(X=>X.available).length,[W]),Z=u.useMemo(()=>n.filter(X=>X.connected&&(a==="all"||a==="auto"||i.includes(X.deviceId))).length,[n,i,a]),G=u.useMemo(()=>{const X=H.filter(I=>$N(I,W.get(I.id),p));return v==="recent"?b.map(I=>X.find(ee=>ee.id===I)).filter(I=>!!I):v==="favorites"?C.map(I=>X.find(ee=>ee.id===I)).filter(I=>!!I):v==="all"?X:X.filter(I=>{const ee=W.get(I.id);return v==="read-only"?ee.state==="read-only":v==="auto"?ee.state==="auto":v==="approval"?ee.state==="approval":v==="full-access"?ee.state==="full-access":v==="available"?ee.available:v==="unavailable"?!ee.available:I.category===v})},[W,C,v,b,p,H]),q=u.useMemo(()=>v!=="all"?[{category:rh(v),templates:G}]:ob.map(X=>({category:X,templates:G.filter(I=>I.category===X)})).filter(X=>X.templates.length>0),[v,G]);u.useEffect(()=>{M(X=>Math.min(X,Math.max(0,G.length-1)))},[G.length]),u.useEffect(()=>{Ed(ah,b)},[b]),u.useEffect(()=>{Ed(sh,C)},[C]),u.useEffect(()=>{B.current?.focus();const X=ee=>{ee.target instanceof Node&&!D.current?.contains(ee.target)&&m()},I=ee=>{ee.key==="Escape"&&(ee.preventDefault(),m())};return document.addEventListener("pointerdown",X),document.addEventListener("keydown",I),()=>{document.removeEventListener("pointerdown",X),document.removeEventListener("keydown",I)}},[m]);const Q=X=>{const I=W.get(X.id);if(!I.available){T(I.reason||"This task is not available for the current targets and permission policy.");return}const ee=[X.id,...b.filter(V=>V!==X.id)].slice(0,10);w(ee),Ed(ah,ee),d(X.prompt),m()},O=X=>{j(I=>{const ee=I.includes(X)?I.filter(V=>V!==X):[X,...I];return Ed(sh,ee),ee})},ye=X=>{X.key==="ArrowDown"?(X.preventDefault(),M(I=>Math.min(I+1,Math.max(0,G.length-1)))):X.key==="ArrowUp"?(X.preventDefault(),M(I=>Math.max(I-1,0))):X.key==="Enter"&&G[k]&&(X.preventDefault(),Q(G[k]))};let me=-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(Gi,{size:15})," Suggested tasks"]}),r.jsxs("small",{children:[_," available · ",H.length," total. Choose a task, edit it, then run it."]})]}),r.jsx("button",{className:"agents-suggested-close",type:"button","aria-label":"Close suggested tasks",onClick:m,children:r.jsx(la,{size:16})})]}),r.jsxs("label",{className:"agents-suggested-search",children:[r.jsx(a0,{size:15,"aria-hidden":"true"}),r.jsx("input",{ref:B,value:p,onChange:X=>g(X.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",...ob].map(X=>{const I=X==="recent"?Pb:X==="favorites"?yh:X==="all"?Gi:X==="available"?Dn:X==="unavailable"?Wb:X==="read-only"||X==="auto"||X==="approval"||X==="full-access"?jn:BN[X];return r.jsxs("button",{className:v===X?"active":"",type:"button",title:rh(X),"aria-label":rh(X),"aria-pressed":v===X,onClick:()=>{x(X),M(0),T("")},children:[r.jsx(I,{size:12})," ",PN(X)]},X)})}),A&&r.jsx("div",{className:"agents-suggested-notice",role:"status",children:A}),r.jsxs("div",{className:"agents-suggested-list",role:"listbox","aria-label":"Suggested tasks",children:[q.map(X=>r.jsxs("div",{className:"agents-suggested-group",children:[r.jsx("strong",{children:X.category}),X.templates.map(I=>{me+=1;const ee=me===k,V=C.includes(I.id),P=W.get(I.id),re=P.availableDeviceIds.length+P.unsupportedDeviceIds.length||Z,ue=P.available?`Available on ${P.availableDeviceIds.length} of ${re} target${re===1?"":"s"}`:`Unavailable: ${P.reason||"not supported by the current targets"}`;return r.jsxs("div",{className:`agents-suggested-item ${ee?"active":""} ${P.available?"":"unavailable"}`,children:[r.jsxs("button",{className:"agents-suggested-prompt",type:"button",role:"option","aria-selected":ee,"aria-disabled":!P.available,onClick:()=>Q(I),children:[r.jsx("span",{children:I.title}),r.jsx("small",{className:"agents-suggested-description",children:I.description}),r.jsxs("span",{className:"agents-suggested-meta",children:[r.jsx("em",{children:I.category}),r.jsx("em",{className:UN(P.state),children:P.label}),r.jsx("em",{className:`risk-${I.risk}`,children:qN(I.risk)}),r.jsx("em",{children:I.supportedPlatforms.map(GN).join(" · ")}),r.jsx("em",{className:P.available?"availability-ok":"availability-unavailable",children:ue}),P.available&&P.unsupportedDeviceIds.length>0&&r.jsxs("em",{className:"availability-warning",children:["Unsupported on ",P.unsupportedDeviceIds.length]})]})]}),r.jsx("button",{className:`agents-suggested-favorite ${V?"favorite":""}`,type:"button","aria-label":V?`Remove ${I.title} from favorites`:`Add ${I.title} to favorites`,"aria-pressed":V,onClick:()=>O(I.id),children:r.jsx(yh,{size:14,fill:V?"currentColor":"none"})})]},I.id)})]},X.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 p=n.filter(Zd),g=i.filter(v=>p.some(x=>x.deviceId===v)).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(Zc,{size:14})," All connected ",r.jsx("small",{children:p.length})]}),r.jsxs("button",{className:a==="selected"?"active":"",onClick:()=>l("selected"),type:"button",children:[r.jsx(fr,{size:14})," Selected ",g]}),r.jsxs("button",{className:a==="auto"?"active":"",onClick:()=>l("auto"),type:"button",children:[r.jsx(Gi,{size:14})," Auto"]}),r.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[r.jsx(Zc,{size:14})," Group ",r.jsx("small",{children:"Soon"})]})]}),r.jsxs("label",{className:`agents-permission-picker permission-${d}`,children:[r.jsx(tf,{size:14}),r.jsx("span",{children:"Permission"}),r.jsxs("select",{value:d,onChange:v=>m(v.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(Vb,{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(v=>{const x=Zd(v),b=a==="all"||a==="auto"?x:i.includes(v.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(v.deviceId)}),r.jsx("span",{className:"agents-target-icon",children:r.jsx(oa,{size:15})}),r.jsxs("span",{children:[r.jsx("strong",{children:Qd(v)}),r.jsx("small",{children:x?"Ready":v.connected?"Agent reconnecting":"Offline"})]}),b&&r.jsx(fr,{className:"agents-target-check",size:15,"aria-hidden":"true"})]},v.deviceId)})})]})}async function YN(n,a){return Ye("/api/settings/agent/plan",{method:"POST",body:JSON.stringify({instruction:a})},n)}async function KN(n,a){return Ye("/api/settings/agent/run",{method:"POST",body:JSON.stringify(a)},n)}async function XN(n,a){return Ye(`/api/settings/agent/runs/${encodeURIComponent(a)}`,void 0,n)}async function QN(n,a){return Ye(`/api/settings/agent/runs/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})},n)}async function ZN(n){return Ye("/api/settings/agent/runs/cancel-all",{method:"POST",body:JSON.stringify({})},n)}async function JN(n,a,i,l){return Ye(`/api/settings/agent/runs/${encodeURIComponent(a)}/approvals/${encodeURIComponent(i)}/approve`,{method:"POST",body:JSON.stringify({scope:l})},n)}async function eM(n,a,i,l="User rejected this action."){return Ye(`/api/settings/agent/runs/${encodeURIComponent(a)}/approvals/${encodeURIComponent(i)}/reject`,{method:"POST",body:JSON.stringify({reason:l})},n)}async function tM(n,a,i){return Ye(`/api/settings/agent/policies/${encodeURIComponent(a)}`,{method:"PUT",body:JSON.stringify({categories:i})},n)}async function nM(n,a){return Ye("/api/settings/agent/summary",{method:"POST",body:JSON.stringify(a)},n)}async function aM(n,a){return Ye("/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 sM(n,a){return Ye(`/api/remote/tasks/${encodeURIComponent(a)}`,void 0,n)}async function rM(n,a){return Ye(`/api/remote/tasks/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})},n)}async function iM(n,a){return Ye(`/api/remote/tasks/${encodeURIComponent(a)}/retry`,{method:"POST",body:JSON.stringify({failedOnly:!0})},n)}function Ml(n){return`${n}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Rd(n,a){const i=new Map(a.map(l=>[l.deviceId,Qd(l)]));return n.results.map(l=>({deviceId:l.deviceId,deviceName:l.deviceName||i.get(l.deviceId)||l.deviceId,status:xN(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 lM(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 oM(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(p=>{const g=p.result||"";return!/not running|no process/i.test(g)&&/running|online|found/i.test(g)}).length}대에서 요청한 프로세스가 실행 중입니다.`;return l.length>0?`${m}
15
+ ${l.map(p=>`${p.deviceName}는 ${p.error||"응답하지 않았습니다."}`).join(`
16
+ `)}`:m}return l.length>0?`${i.length}대 완료, ${l.length}대 실패했습니다.`:`${i.length}대 작업이 완료되었습니다.`}const cM={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 uM(n){return n==="safe-auto"?"Safe Auto":n==="full-access"?"Full Access":n==="custom"?"Custom":"Ask"}function dM(n){return n.replace(/([A-Z])/g," $1").replace(/^./,a=>a.toUpperCase())}function fM(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 db({hubUrl:n,devices:a,launchRequest:i,variant:l="page",selectedDeviceIds:c=[]}){const d=l==="dock",[m,p]=u.useState(d?c.length>0?"selected":"auto":"all"),[g,v]=u.useState(c),[x,b]=u.useState("auto"),[w,C]=u.useState(""),[j,k]=u.useState([]),[M,A]=u.useState(""),[T,D]=u.useState(""),[B,H]=u.useState(""),[W,_]=u.useState("safe-auto"),[Z]=u.useState("custom-default"),[G,q]=u.useState(cM),[Q,O]=u.useState([]),[ye,me]=u.useState(""),[X,I]=u.useState(!1),[ee,V]=u.useState(null),[P,re]=u.useState(!1),[ue,K]=u.useState(""),[xe,z]=u.useState(!1),[le,ke]=u.useState(null),Ce=u.useRef(null),Ue=u.useRef(new Set),Be=u.useRef(new Set),he=u.useRef(new Set),Xe=u.useMemo(()=>a.filter(Zd).map(ve=>ve.deviceId),[a]),et=u.useMemo(()=>FN(sw,a,m,g,W,G),[G,a,W,g,m]);u.useEffect(()=>{d&&v(c)},[d,c]),u.useEffect(()=>{i?.deviceId&&(p("selected"),v([i.deviceId]),C(i.instruction),z(!1),window.requestAnimationFrame(()=>{Ce.current?.focus(),Ce.current?.setSelectionRange(i.instruction.length,i.instruction.length)}))},[i]);const ce=u.useCallback(ve=>{const Fe=Rd(ve,a);if(k(He=>He.map(Me=>Me.type==="task"&&Me.batchId===ve.batchId?{...Me,states:lM(Me.states,Fe),status:ve.status}:Me)),!["running","queued"].includes(ve.status)&&!Ue.current.has(ve.batchId)){Ue.current.add(ve.batchId);const He=Ml("agent-summary");k(Me=>[...Me,{type:"agent",id:He,text:oM(ve,Fe)}]),ve.operation&&nM(n,{instruction:ve.instructionPreview,operation:ve.operation,total:Fe.length,completed:Fe.filter(Me=>Me.status==="completed").length,failed:Fe.filter(Me=>Me.status==="failed").length,results:Fe.map(Me=>({deviceName:Me.deviceName,status:Me.status,result:Me.result,error:Me.error}))}).then(Me=>{!Me.ok||!Me.summary||k(rt=>rt.map(dt=>dt.type==="agent"&&dt.id===He?{...dt,text:Me.summary}:dt))}).catch(()=>{}),A(Me=>Me===ve.batchId?"":Me)}},[a,n]),ge=u.useCallback(async ve=>{const Fe=await sM(n,ve);return ce(Fe),Fe},[n,ce]),Ae=u.useCallback((ve,Fe)=>{he.current.has(ve.batchId)||(he.current.add(ve.batchId),k(He=>[...He,{type:"task",id:Ml("task"),batchId:ve.batchId,agentRunId:Fe,operation:ve.operation||"diagnostics.collect",instruction:ve.instructionPreview,states:Rd(ve,a),status:ve.status}])),ce(ve)},[a,ce]),Le=u.useCallback(async ve=>{const Fe=await XN(n,ve);for(const Me of Fe.taskBatches||[])Ae(Me,ve);O(Fe.approvals||[]);const He=["running","queued","waiting-approval"].includes(Fe.status);if(ke(He?{runId:ve,stage:Fe.stage||Fe.status,message:Fe.progressMessage||(Fe.status==="waiting-approval"?"Review the requested action to continue.":"Codex is preparing the answer.")}:Me=>Me?.runId===ve?null:Me),!He&&!Be.current.has(ve)){Be.current.add(ve);const Me=[Fe.error,Fe.errorMessage].filter(Boolean).join(" — "),rt=Fe.finalResponse?.trim()||(Fe.status==="cancelled"?"Codex 작업을 취소했습니다.":Me?`Codex 작업이 완료되지 않았습니다: ${Me}`:"Codex 작업이 완료되었습니다.");k(dt=>[...dt,{type:Fe.status==="failed"?"error":"agent",id:Ml("agent-run-result"),text:rt}])}return Fe},[Ae,n]);u.useEffect(()=>{if(!M)return;let ve=!0;const Fe=async()=>{try{const Me=await ge(M);ve&&!["running","queued"].includes(Me.status)&&A("")}catch(Me){ve&&K(Me instanceof Error?Me.message:String(Me))}};Fe();const He=window.setInterval(()=>{Fe()},800);return()=>{ve=!1,window.clearInterval(He)}},[M,ge]),u.useEffect(()=>{if(!T)return;let ve=!0;const Fe=async()=>{try{const Me=await Le(T);ve&&!["running","queued","waiting-approval"].includes(Me.status)&&(D(""),re(!1))}catch(Me){ve&&K(Me instanceof Error?Me.message:String(Me))}};Fe();const He=window.setInterval(()=>{Fe()},800);return()=>{ve=!1,window.clearInterval(He)}},[T,Le]);const Pe=async(ve="",Fe,He=!1)=>{const Me=(ve||w).trim();if(!Me||M||T)return;let rt=null;const dt=Fe||(m==="all"||m==="auto"?Xe:g.filter(it=>Xe.includes(it)));if(dt.length===0){K("Select at least one connected Client.");return}if(W==="full-access"&&!P&&!He){V({instruction:Me,targetIds:dt});return}if(k(it=>[...it,{type:"user",id:Ml("user"),text:Me}]),C(""),z(!1),K(""),dt.length===0){k(it=>[...it,{type:"error",id:Ml("no-targets"),text:"연결된 대상 장비를 하나 이상 선택해 주세요."}]);return}const An=x==="ask"?`Read-only request. Inspect and answer without changing Client state.
17
+
18
+ ${Me}`:x==="plan"?`Plan only. Produce a safe execution plan, but do not change Client state.
19
+
20
+ ${Me}`:x==="execute"?`Execute this request within the configured LiveDesk approval policy.
21
+
22
+ ${Me}`:Me,pa=m==="auto"?`Auto target selection is enabled. Inspect the allowed Clients and use only the most suitable target or targets for this request.
23
+
24
+ ${An}`:An;if(!rt){try{if(W==="custom"){const Xt=await tM(n,Z,G);if(!Xt.ok)throw new Error(Xt.error||"Custom Agent policy could not be saved.")}const it=await KN(n,{instruction:pa,deviceIds:dt,permissionMode:W,customPolicyId:Z});if(!it.ok||!it.runId)throw new Error(it.error||"Codex Agent run could not be started.");O(it.approvals||[]),ke({runId:it.runId,stage:it.stage||it.status||"queued",message:it.progressMessage||"Codex request queued on the Hub."}),D(it.runId);return}catch(it){try{const Xt=await YN(n,pa);Xt.ok&&Xt.plan&&(rt={operation:Xt.plan.operation,query:Xt.plan.targetQuery})}catch{k(Xt=>[...Xt,{type:"error",id:Ml("unsupported"),text:fM(it)}])}}if(!rt)return}try{const it=await aM(n,{instruction:pa,deviceIds:dt,operation:rt.operation,targetQuery:rt.query});if(!it.ok||!it.batch||!it.batchId)throw new Error(it.error||"작업을 만들지 못했습니다.");const Xt={type:"task",id:Ml("task"),batchId:it.batchId,operation:rt.operation,instruction:Me,states:Rd(it.batch,a),status:it.batch.status};he.current.add(it.batchId),k(Nn=>[...Nn,Xt]),A(it.batchId)}catch(it){K(it instanceof Error?it.message:String(it))}},Ve=async(ve,Fe)=>{me(ve.approvalId);try{const He=await JN(n,ve.runId,ve.approvalId,Fe);if(!He.ok)throw new Error(He.error||"Agent approval could not be applied.");await Le(ve.runId)}catch(He){K(He instanceof Error?He.message:String(He))}finally{me("")}},Ke=async ve=>{me(ve.approvalId);try{const Fe=await eM(n,ve.runId,ve.approvalId);if(!Fe.ok)throw new Error(Fe.error||"Agent approval could not be rejected.");await Le(ve.runId)}catch(Fe){K(Fe instanceof Error?Fe.message:String(Fe))}finally{me("")}},de=async(ve,Fe)=>{H(ve);try{if(Fe){const Me=await QN(n,Fe);for(const rt of Me.taskBatches||[])ce(rt);D(rt=>rt===Fe?"":rt),ke(rt=>rt?.runId===Fe?null:rt);return}const He=await rM(n,ve);ce(He),A(Me=>Me===ve?"":Me)}catch(He){K(He instanceof Error?He.message:String(He))}finally{H("")}},je=async()=>{if(!(X||!M&&!T)){I(!0);try{const ve=await ZN(n);if(!ve.ok)throw new Error(ve.error||"모든 Agent 작업을 취소하지 못했습니다.");A(""),D(""),ke(null),O([]),k(Fe=>Fe.map(He=>He.type==="task"&&["queued","running"].includes(He.status)?{...He,status:"cancelled",states:He.states.map(Me=>["queued","running"].includes(Me.status)?{...Me,status:"cancelled",stage:"Cancelled",error:"Cancelled by user."}:Me)}:He))}catch(ve){K(ve instanceof Error?ve.message:String(ve))}finally{I(!1)}}},fe=async ve=>{H(ve);try{const Fe=await iM(n,ve);if(!Fe.ok||!Fe.batch||!Fe.batchId)throw new Error(Fe.error||"재시도하지 못했습니다.");Ue.current.delete(Fe.batchId),k(He=>He.map(Me=>Me.type==="task"&&Me.batchId===ve?{...Me,batchId:Fe.batchId,states:Rd(Fe.batch,a),status:Fe.batch.status}:Me)),A(Fe.batchId)}catch(Fe){K(Fe instanceof Error?Fe.message:String(Fe))}finally{H("")}},_e=ve=>{C(ve),z(!1),window.requestAnimationFrame(()=>Ce.current?.focus())},Ee=u.useMemo(()=>a.filter(Zd),[a]),mt=u.useMemo(()=>Ee.filter(ve=>g.includes(ve.deviceId)),[Ee,g]),Ht=m==="auto"?`Auto · ${Ee.length} available`:m==="all"?`All ${Ee.length} computers`:mt.length===1?Qd(mt[0]):`${mt.length} selected`,Dt=m==="auto"?"LiveDesk chooses the best computer for each task.":m==="all"?"The Agent may coordinate every connected computer.":mt.length>0?mt.map(Qd).join(" · "):"Select one or more computers on the Wall.",yt=m==="selected"&&mt.length===1?["Diagnose this computer","Analyze recent errors","Summarize running applications","Check disk and GPU capacity"]:m==="all"?["Compare all computer health","Find the busiest computer","Check disk capacity everywhere","Divide a task across computers"]:["Use the fastest computer","Find an idle computer","Choose the best GPU","Check all computer health"],Ge=m==="selected"?mt.length>0?"What should this computer do?":"Choose a computer or use Auto.":m==="all"?"Use all your computers together.":"What should LiveDesk handle?",At=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(Gi,{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:Ht}),r.jsx("small",{children:Dt})]}),r.jsxs("div",{className:"agent-console-target-modes",children:[r.jsxs("button",{className:m==="selected"?"active":"",onClick:()=>p("selected"),type:"button",children:[r.jsx(fr,{size:12})," Selected"]}),r.jsxs("button",{className:m==="all"?"active":"",onClick:()=>p("all"),type:"button",children:[r.jsx(Zc,{size:12})," All"]}),r.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[r.jsx(Zc,{size:12})," Group"]}),r.jsxs("button",{className:m==="auto"?"active":"",onClick:()=>p("auto"),type:"button",children:[r.jsx(Gi,{size:12})," Auto"]})]})]}),r.jsx("div",{className:"agent-console-interaction-modes","aria-label":"Agent interaction mode",children:["auto","ask","plan","execute"].map(ve=>r.jsxs("button",{className:x===ve?"active":"",onClick:()=>b(ve),type:"button",children:[ve==="auto"?r.jsx(Gi,{size:12}):ve==="execute"?r.jsx(oa,{size:12}):null,ve[0].toUpperCase()+ve.slice(1)]},ve))})]}),r.jsxs("div",{className:"agents-workspace",children:[(M||T)&&r.jsxs("div",{className:"agents-page-status",children:[r.jsxs("span",{children:[Xe.length," Clients · ",uM(W)]}),r.jsx("button",{type:"button",className:"agents-stop-all",onClick:()=>{je()},disabled:X,children:X?"Stopping…":"Stop all"})]}),ee&&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(tf,{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:()=>V(null),children:"Cancel"}),r.jsx("button",{type:"button",className:"danger",onClick:()=>{const ve=ee;V(null),re(!0),Pe(ve.instruction,ve.targetIds,!0)},children:"Run with Full Access"})]})]})}),ue&&r.jsx("div",{className:"agents-error",role:"alert",children:ue}),r.jsx(EN,{items:j,onCancel:de,onRetry:fe,busyBatchId:B,approvals:Q,onApprove:Ve,onReject:Ke,busyApprovalId:ye,progress:le,emptyTitle:d?Ge:void 0,emptyBody:d?At:void 0}),d&&j.length===0&&!le&&r.jsx("div",{className:"agent-console-suggestions","aria-label":"Suggested Agent commands",children:yt.map(ve=>r.jsx("button",{type:"button",onClick:()=>_e(ve),children:ve},ve))}),r.jsxs("div",{className:"agents-composer-shell",children:[xe&&r.jsx(VN,{devices:a,targetMode:m,selectedIds:g,permissionMode:W,customCategories:G,onSelectPrompt:_e,onClose:()=>z(!1)}),r.jsx(yN,{ref:Ce,value:w,onChange:C,onSubmit:()=>{Pe()},onOpenSuggestedTasks:()=>z(ve=>!ve),suggestedOpen:xe,suggestedTaskCount:et,disabled:!!M||!!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:p,onToggle:ve=>v(Fe=>Fe.includes(ve)?Fe.filter(He=>He!==ve):[...Fe,ve]),permissionMode:W,onPermissionModeChange:ve=>{_(ve),ve!=="full-access"&&re(!1)}}),W==="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:bN.map(ve=>r.jsxs("label",{children:[r.jsx("span",{children:dM(ve)}),r.jsxs("select",{value:G[ve],onChange:Fe=>q(He=>({...He,[ve]:Fe.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"})]})]},ve))})]})]})]})}function iw(n){return{type:n.type,deviceIds:n.deviceIds,monitorIndex:n.monitorIndex,label:n.label}}async function lw(n){try{return(await n.json()).error||`${n.status} ${n.statusText}`}catch{return`${n.status} ${n.statusText}`}}async function ow(n,a,i){const l=encodeURIComponent(JSON.stringify({kind:a.kind,fileName:a.fileName,mimeType:n.type||"application/octet-stream",durationMs:a.durationMs,target:iw(a.target)})),c=await fetch(`${Ki(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 lw(c));return await c.json()}async function mM(n,a){return await Ye("/api/capture-sessions",{method:"POST",body:JSON.stringify({...n,target:iw(n.target)})},a)}async function hM(n,a,i,l){const c=await fetch(`${Ki(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 lw(c));return await c.json()}async function pM(n,a,i){return await Ye(`/api/capture-sessions/${encodeURIComponent(n)}/finalize`,{method:"POST",body:JSON.stringify({durationMs:a})},i)}async function fb(n,a){await Ye(`/api/capture-sessions/${encodeURIComponent(n)}`,{method:"DELETE"},a)}async function gM(n){return await Ye("/api/captures",void 0,n)}function mb(n,a){return`${Ki(a)}/api/captures/${encodeURIComponent(n)}/content`}async function vM(n,a){return await Ye(`/api/captures/${encodeURIComponent(n)}`,{method:"DELETE"},a)}function yM({hubUrl:n,onToast:a}){const[i,l]=u.useState([]),[c,d]=u.useState(!0),m=u.useCallback(async()=>{d(!0);try{l((await gM(n)).captures||[])}catch(g){a(g instanceof Error?g.message:String(g))}finally{d(!1)}},[n,a]);u.useEffect(()=>{m()},[m]);const p=async g=>{const v=mb(g.id,n);if(navigator.share)try{await navigator.share({title:g.fileName,url:v});return}catch{}window.open(v,"_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(Ho,{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 v=mb(g.id,n);return r.jsxs("article",{className:"capture-gallery-card",children:[g.mimeType.startsWith("image/")?r.jsx("img",{src:v,alt:g.target.label}):r.jsx("video",{src:v,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(v,"_blank","noopener,noreferrer"),type:"button",children:r.jsx(l0,{size:15})}),r.jsx("a",{className:"icon-button",title:"Download","aria-label":"Download",href:`${v}?download=1`,download:g.fileName,children:r.jsx(Bh,{size:15})}),r.jsx("button",{className:"icon-button",title:"Share","aria-label":"Share",onClick:()=>{p(g)},type:"button",children:r.jsx(o0,{size:15})}),r.jsx("button",{className:"icon-button danger",title:"Delete","aria-label":"Delete",onClick:()=>{window.confirm(`Delete ${g.fileName}?`)&&vM(g.id,n).then(()=>m()).catch(x=>a(x instanceof Error?x.message:String(x)))},type:"button",children:r.jsx($h,{size:15})})]})]})]},g.id)})})]})}function Dd(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 hb({controller:n,compact:a=!1,onFirstRollingUse:i,onError:l}){const{state:c,settings:d,videoSupported:m}=n,p=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)},v=c.recording?`Stop recording · ${Dd(c.recordingStartedAt)}`:`Start recording · ${c.targetLabel}`,x=c.timelapse?`Stop timelapse · ${Dd(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:()=>{p(n.takeScreenshot)},type:"button",children:r.jsx(c0,{size:17})}),r.jsx("button",{className:`capture-action ${c.recording?"active":""}`,"aria-label":v,title:v,disabled:!m||c.busy||c.timelapse,onClick:()=>{p(c.recording?n.stopRecording:n.startRecording)},type:"button",children:c.recording?r.jsxs(r.Fragment,{children:[r.jsx(Zv,{size:14,fill:"currentColor"}),r.jsx("span",{children:Dd(c.recordingStartedAt)})]}):r.jsx(Gb,{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 p(n.saveLast30Seconds):void g(),type:"button",children:[r.jsx(u0,{size:17}),r.jsx("small",{children:"30s"})]}),r.jsx("button",{className:`capture-action ${c.timelapse?"timelapse-active":""}`,"aria-label":x,title:x,disabled:!m||c.busy||c.recording,onClick:()=>{p(c.timelapse?n.stopTimelapse:n.startTimelapse)},type:"button",children:c.timelapse?r.jsxs(r.Fragment,{children:[r.jsx(Zv,{size:14,fill:"currentColor"}),r.jsx("span",{children:Dd(c.timelapseStartedAt)})]}):r.jsx(d0,{size:17})})]})}function cw({state:n}){return n==="ok"?r.jsx(Dn,{size:15,"aria-hidden":"true"}):r.jsx(Wb,{size:15,"aria-hidden":"true"})}function pb({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(f0,{size:18,"aria-hidden":"true"})})}function gb({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(mr,{size:18,"aria-hidden":"true"})})}function bM({items:n}){return r.jsx("span",{className:"remote-status-lines",role:"status","aria-label":"Remote status",children:n.map(a=>r.jsxs("span",{className:`remote-status-line state-${a.state}`,title:a.detail,children:[r.jsx(cw,{state:a.state}),r.jsxs("span",{children:[r.jsx("strong",{children:a.label}),r.jsx("small",{children:a.detail})]})]},a.id))})}function xM({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(mr,{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(la,{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(cw,{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 wM=/(nvenc|videotoolbox|qsv|quick\s*sync|amf|vaapi|v4l2m2m|mediafoundation|h264_mf)/i,SM=/(libx264|openh264|software|cpu)/i,xn=Object.freeze({frameAgeWarningMs:2500,networkDelayWarningMs:120,receiveRatioWarning:.62,decoderOutputRatioWarning:.62,captureBudgetMultiplier:2.5,minimumCaptureBudgetMs:80,cpuWarningRatio:.82,memoryWarningRatio:.86,gpuWarningRatio:.92,gpuMemoryWarningRatio:.92,gpuTemperatureWarningC:85,networkUsageWarningRatio:.85,networkLatencyWarningMs:80});function Ia(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function uw(n,a){let i=n;for(const l of String(a).split(".")){if(!i||typeof i!="object")return;i=i[l]}return i}function Ui(n,...a){for(const i of a){const l=uw(n,i);if(l==null||l==="")continue;const c=Number(l);if(Number.isFinite(c))return c}}function Ud(n,...a){for(const i of a){const l=uw(n,i);if(typeof l=="string"&&l.trim())return l.trim()}return""}function Ll(n,...a){const i=Ui(n,...a);if(i!==void 0)return Math.max(0,Math.min(1,i>1?i/100:i))}function _t(n,a,i,l){return{id:n,state:a,label:i,detail:l}}function CM(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 kM(n,a){const i=Number(n?.browserReceivedEpochMs);return Number.isFinite(i)&&i>0?Math.max(0,a-i):Number.POSITIVE_INFINITY}function jM(n){const a=String(n?.frameMode||n?.mode||n?.codec||"").toLowerCase(),i=[n?.hardwareEncoder,n?.platformProfile].filter(Boolean).join(" · ");return!n||!/h264/.test(a)?_t("encoder","warning","Video encoder unavailable","Waiting for an H.264 frame."):wM.test(i)?_t("encoder","ok","Hardware H.264 encoding",i):SM.test(i)?_t("encoder","warning","Software H.264 encoding",`${i||"CPU encoder"} may limit frame rate.`):_t("encoder","warning","H.264 encoder not identified",i||"The Client has not reported its active encoder profile.")}function AM({device:n,frame:a,receiveStat:i,paintStat:l,codec:c,selectedMonitorIndex:d=0,control:m=!1,controlInputReady:p=!1,controlBinding:g,now:v=Date.now()}={}){const x=Ia(n),b=Ia(x.status),w=Ia(l?.lastInfo),C=[],j=kM(a,v);C.push(x.connected===!0&&j<=xn.frameAgeWarningMs?_t("connection","ok","Video connection is current",`${Math.round(j)}ms since the latest frame.`):_t("connection","warning",x.connected===!0?"Video frame is stale":"Client is offline",x.connected===!0&&Number.isFinite(j)?`${Math.round(j)}ms since the latest frame.`:String(x.lastDisconnectReason||"No current Client session."))),C.push(jM(a));const k=Math.max(0,Number(a?.requestedFps||a?.effectiveFps||0)),M=Math.max(0,Number(i?.framesPerSecond||0)),A=Ui(a,"captureP95Ms","captureAverageMs","captureStageMs"),T=Math.max(0,Number(A||0)),D=k>0&&Number(i?.sampleMs||0)>0&&A!==void 0,B=Math.max(xn.minimumCaptureBudgetMs,k>0?1e3/k*xn.captureBudgetMultiplier:0),H=T>B||k>0&&i?.sampleMs>0&&M<k*xn.receiveRatioWarning;C.push(D?H?_t("capture","warning","Screen capture cannot keep target speed",`${T?`capture p95 ${Math.round(T)}ms`:"capture timing unavailable"} · ${M.toFixed(1)}/${k||"?"} fps`):_t("capture","ok","Screen capture speed is healthy",`${T?`capture p95 ${Math.round(T)}ms`:"no slow capture reported"}${k?` · ${M.toFixed(1)}/${k} fps`:""}`):_t("capture","warning","Screen capture data is still collecting","A current frame-rate and capture-time sample is required."));const W=Number(a?.droppedByAgent||0)+Number(a?.hubIngressDropped||0)+Number(a?.hubClientDropped||0),_=Ui(a,"hubPacketTransitAgeMs"),Z=Math.max(0,Number(_||0)),G=Math.max(0,Number(a?.agentSendGapMs||a?.sourceGapMs||0)),q=k>0?1e3/k:100,Q=!CM(x.remoteAddress),O=Ll(b,"network.usageRatio"),ye=Ui(b,"network.latencyMs"),me=(O??0)>=xn.networkUsageWarningRatio||(ye??0)>=xn.networkLatencyWarningMs,X=_!==void 0&&Number(i?.sampleMs||0)>0,I=W>0||Z>xn.networkDelayWarningMs||G>Math.max(xn.networkDelayWarningMs,q*3)||j>xn.frameAgeWarningMs||me;C.push(X?I||Q?_t("network","warning",Q?"External network route may add delay":me?"Client network adapter needs attention":"Network delivery needs attention",[Z?`${Math.round(Z)}ms Hub-to-browser`:"",G?`${Math.round(G)}ms source gap`:"",W?`${W} dropped`:"",ye!==void 0?`${Math.round(ye)}ms Client network latency`:"",O!==void 0?`${Math.round(O*100)}% Client link use`:"",Q?String(x.remoteAddress||"external route"):""].filter(Boolean).join(" · ")||"Frame delivery is not current."):_t("network","ok","Network delivery is healthy",`${Math.round(Z)}ms Hub-to-browser · no packet drops reported.`):_t("network","warning","Network delivery data is still collecting","A calibrated Hub-to-browser transit sample is required."));const ee=Ll(b,"cpu.usageRatio","cpu.usedRatio","cpu.percent"),V=Ll(b,"memory.usedRatio","usedMemRatio"),P=Ll(b,"gpu.usageRatio"),re=Ll(b,"gpu.memory.usedRatio"),ue=Ui(b,"gpu.temperatureC","thermal.gpuC"),K=ee!==void 0&&V!==void 0,xe=(ee??0)>=xn.cpuWarningRatio||(V??0)>=xn.memoryWarningRatio||(P??0)>=xn.gpuWarningRatio||(re??0)>=xn.gpuMemoryWarningRatio||(ue??0)>=xn.gpuTemperatureWarningC;C.push(K?xe?_t("computer","warning",(P??0)>=xn.gpuWarningRatio||(re??0)>=xn.gpuMemoryWarningRatio||(ue??0)>=xn.gpuTemperatureWarningC?"Client GPU is under load":"Client computer is under load",[`CPU ${Math.round(ee*100)}%`,`memory ${Math.round(V*100)}%`,P!==void 0?`GPU ${Math.round(P*100)}%`:"",re!==void 0?`GPU memory ${Math.round(re*100)}%`:"",ue!==void 0?`GPU ${Math.round(ue)}C`:""].filter(Boolean).join(" · ")):_t("computer","ok","Client computer has working capacity",[`CPU ${Math.round(ee*100)}%`,`memory ${Math.round(V*100)}%`,P!==void 0?`GPU ${Math.round(P*100)}%`:""].filter(Boolean).join(" · ")):_t("computer","warning","Client performance data is unavailable","CPU and memory telemetry have not been reported yet."));const z=Number(a?.monitorIndex),le=Number.isInteger(z)&&z===Number(d),ke=Ia(x.channels),Ce=Ia(x.capabilities),Ue=ke.input!==!1&&Ce.remoteInput!==!1&&Ce.accessibilityPermission!==!1,Be=Ce.screenRecordingPermission!==!1,he=Ia(g),Xe=!m||String(a?.sessionId||"")&&String(a?.sessionId||"")===String(he.sessionId||"")&&String(a?.commandId||"")&&String(a?.commandId||"")===String(he.commandId||"")&&Number(a?.captureGeneration||0)>0&&Number(a?.captureGeneration||0)===Number(he.captureGeneration||0)&&Number(a?.monitorIndex)===Number(he.monitorIndex),et=!m||p&&Xe;C.push(le&&et&&Ue&&Be?_t("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"}.`):_t("display","warning",Be?Ue?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(z)?z+1:"not available"}.`));const ce=Ia(c),ge=Array.isArray(ce.canvases)?Ia(ce.canvases[0]):{},Ae=Math.max(0,Number(l?.decoderInputFps||0)),Le=Math.max(0,Number(l?.decoderOutputFps||0)),Pe=Ae>0&&Number(l?.sampleMs||i?.sampleMs||0)>0,Ve=Ae>0?Le/Ae:0,Ke=Ud(ge,"configuredAcceleration","requestedAcceleration")||Ud(w,"h264DecodeAcceleration"),de=Ud(ge,"softwareFallbackReason"),je=!!de||Ke==="prefer-software";return C.push(Pe?je||Ve<xn.decoderOutputRatioWarning?_t("decoder","warning",je?"Browser is using software H.264 fallback":"Browser decoder output is slow",`${de||String(w.decoderLabel||Ke||"decoder")} · ${Ae.toFixed(1)} in / ${Le.toFixed(1)} out fps.`):_t("decoder","ok",Ke==="prefer-hardware"?"Browser requests hardware H.264":"Browser H.264 path is responsive",`${Ae.toFixed(1)} in / ${Le.toFixed(1)} out fps. Chrome does not expose definitive hardware acceptance.`):_t("decoder","warning","Browser decoder data is still collecting","Decoder input and output samples are required before this path can be marked healthy.")),C}function NM({status:n,deviceDiagnostics:a=[],codec:i,browser:l,frameStats:c}={}){const d=Ia(n),m=Ia(d.diagnostics),p=Ia(m.system),g=Ia(m.network),v=Ia(i),x=Ia(l),b=Array.isArray(a)?a:[],w=b.reduce((G,q)=>G+(Array.isArray(q)&&q.some(Q=>Q?.state==="warning")?1:0),0),C=Ll(p,"cpuUsageRatio","processCpuRatio"),j=Ll(p,"memoryUsedRatio"),k=Ui(p,"cpuLogicalCores")??Ui(x,"hardwareConcurrency"),M=(k??0)>0&&C!==void 0&&j!==void 0,A=(k??0)>0&&k<4||(C??0)>=xn.cpuWarningRatio||(j??0)>=xn.memoryWarningRatio,T=Math.max(0,Number(v.activeSoftwareFallbackCount??v.softwareFallbackCount??0)),D=Math.max(0,Number(v.activeDecoderCount||0)),B=Math.max(0,Number(c?.bytesPerSecond||0)*8/1e6),H=Ui(g,"externalDeviceCount"),W=Ud(g,"route"),_=H!==void 0&&!!W,Z=(H??0)>0||W==="external";return[d.started&&!d.lastError?_t("hub-runtime","ok","Hub runtime is ready",`${d.connectedDeviceCount||0} Clients connected.`):_t("hub-runtime","warning","Hub runtime needs attention",String(d.lastError||"Hub is not ready.")),M?A?_t("hub-computer","warning","Hub computer may limit remote performance",`${k||"?"} logical cores · CPU ${C===void 0?"?":Math.round(C*100)}% · memory ${j===void 0?"?":Math.round(j*100)}%.`):_t("hub-computer","ok","Hub computer capacity is healthy",`${k||"?"} logical cores · CPU ${C===void 0?"not reported":`${Math.round(C*100)}%`}.`):_t("hub-computer","warning","Hub performance data is unavailable","Logical-core, CPU, and memory telemetry are required."),D<=0?_t("hub-codec","warning","No active browser H.264 decoder to check","Open Wall or Control and wait for a video frame."):T>0?_t("hub-codec","warning","Some browser decoders use software fallback",`${D} active H.264 decoders · ${T} software fallbacks. Chrome does not expose definitive hardware acceptance.`):_t("hub-codec","ok","All active streams request hardware H.264",`${D} active decoders. Chrome hardware acceptance is inferred from health, not directly exposed.`),w>0?_t("hub-clients","warning",`${w} Clients need attention`,"Open the matching Wall slot lines for the exact cause."):_t("hub-clients","ok","Connected Clients report healthy remote paths",`${b.length} Client reports checked.`),_t("hub-network",!_||Z||B>120?"warning":"ok",_?Z?`${H} Clients use an external network route`:B>120?"Hub receive load is high":"Hub receive load is within range":"Hub network route data is unavailable",_?`${W.toUpperCase()} route · ${B.toFixed(B>=10?0:1)} Mbps received by this browser.`:"The Hub has not reported LAN/external route classification yet.")]}async function MM(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)),p=Math.floor(l/d),g=Math.floor(c/m),v=document.createElement("canvas");v.width=Math.max(320,p*d),v.height=Math.max(180,g*m);const x=v.getContext("2d",{alpha:!1});if(!x)return v;x.fillStyle="#0b1220",x.fillRect(0,0,v.width,v.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],C=b%d,j=Math.floor(b/d),k=C*p,M=j*g,A=w.canvas,T=Math.min(p/A.width,g/A.height),D=Math.max(1,Math.floor(A.width*T)),B=Math.max(1,Math.floor(A.height*T)),H=k+Math.floor((p-D)/2),W=M+Math.floor((g-B)/2);x.drawImage(A,H,W,D,B),a.includeLabels!==!1&&(x.fillStyle="rgba(4, 10, 20, .74)",x.fillRect(k,M+g-28,p,28),x.fillStyle="#f8fafc",x.fillText(w.label,k+9,M+g-9))}return v}function TM(n){return n?.signature||"none"}function EM(n){return n?.label||"No capture target"}function vb(n){return{...n,deviceIds:[...n.deviceIds],sourceCanvas:n.sourceCanvas||null}}function RM(){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 DM(n){return n.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function LM(n){return`LiveDesk_${n.type==="wall"||n.type==="selection"?"Wall":`${DM(n.label)}_Monitor-${Number(n.monitorIndex||0)+1}`}_${RM()}.png`}async function _M(n,a,i){const l=await new Promise((d,m)=>n.toBlob(p=>p?d(p):m(new Error("Screenshot could not be encoded.")),"image/png")),c=await ow(l,{kind:"screenshot",fileName:LM(a),target:a},i);try{await navigator.clipboard.write([new ClipboardItem({"image/png":l})])}catch{}return c.capture}function dw(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(a=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(a))||""}function IM(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=dw();if(!a)throw new Error("This browser does not support WebM recording.");const i=n.kind||"recording",l=await mM({kind:i,fileName:IM(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 p=0,g=!1,v=null,x=Promise.resolve();return d.ondataavailable=b=>{if(!b.data||b.data.size===0)return;const w=p++;x=x.then(()=>hM(l.sessionId,w,b.data,n.hubUrl).then(()=>{})).catch(C=>{v=v||(C instanceof Error?C:new Error(String(C))),n.onError?.(v)})},d.onerror=()=>{v=new Error("Video recording stopped unexpectedly."),n.onError?.(v)},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,v)throw await fb(l.sessionId,n.hubUrl).catch(()=>{}),v;await pM(l.sessionId,Math.max(0,performance.now()-m),n.hubUrl)}},cancel:async()=>{g||(g=!0,d.stop(),c.getTracks().forEach(b=>b.stop()),await fb(l.sessionId,n.hubUrl).catch(()=>{}))}}}class zM{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=dw();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 ow(l,{kind:"last-30s",fileName:d,target:a,durationMs:Math.min(3e4,this.segments.length*1e3)},i)}}async function OM(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 mw="livedesk.captureSettings";function HM(){const n={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const a=JSON.parse(localStorage.getItem(mw)||"null");return{...n,...a&&typeof a=="object"?a:{}}}catch{return n}}function FM(n){const[a,i]=u.useState(HM),[l,c]=u.useState(0),[d,m]=u.useState(0),[p,g]=u.useState(0),[v,x]=u.useState(!1),b=u.useRef(void 0),w=u.useRef(!1),C=u.useRef(""),j=u.useRef(null),k=u.useRef(null),M=u.useRef(null),A=u.useRef(null),T=u.useRef(new zM),D=n.sourceRegistry.resolveCurrentTarget(),B=TM(D),H=EM(D),W=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;u.useEffect(()=>{if(localStorage.setItem(mw,JSON.stringify(a)),!w.current)return;const V=JSON.stringify(a);V!==C.current&&(C.current=V,Ye("/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(P=>{b.current=Number(P.revision||b.current||0)}).catch(()=>{}))},[n.hubUrl,a]),u.useEffect(()=>{let V=!0;return Ye("/api/settings",void 0,n.hubUrl).then(P=>{if(!V)return;const re=P.settings?.filesAudio||{},ue=typeof re.rollingBufferEnabled=="boolean"?re.rollingBufferEnabled:a.rollingEnabled,K=re.recordingQuality==="high"?"high":"standard",xe=[5,10,30,60].includes(Number(re.timelapseIntervalSeconds))?Number(re.timelapseIntervalSeconds):a.timelapseIntervalSeconds,z=typeof re.includeRemoteCursor=="boolean"?re.includeRemoteCursor:a.includeRemoteCursor,le={rollingEnabled:ue,recordingQuality:K,timelapseIntervalSeconds:xe,includeRemoteCursor:z};b.current=Number(P.revision||0),C.current=JSON.stringify(le),w.current=!0,i(le)}).catch(()=>{w.current=!0}),()=>{V=!1}},[n.hubUrl]);const _=u.useCallback(async V=>{if(V.sourceCanvas&&V.sourceCanvas.width>0&&V.sourceCanvas.height>0)return{target:vb(V),canvas:V.sourceCanvas,cleanup:()=>{}};const P=await n.sourceRegistry.composeWall(V.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let re=!1;const ue=window.setInterval(async()=>{if(re)return;const K=await n.sourceRegistry.composeWall(V.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0}).catch(()=>null);!K||re||((P.width!==K.width||P.height!==K.height)&&(P.width=K.width,P.height=K.height),P.getContext("2d")?.drawImage(K,0,0))},100);return{target:vb(V),canvas:P,cleanup:()=>{re=!0,window.clearInterval(ue)}}},[n.sourceRegistry]);u.useEffect(()=>{const V=T.current;if(!a.rollingEnabled||!D||!W){V.stop(),g(0);return}let P=!1,re=null;return(async()=>{try{if(re=await _(D),P)return;await V.start(re.canvas,re.target);const K=window.setInterval(()=>g(Math.round(V.seconds)),500),xe=()=>{window.clearInterval(K),re?.cleanup()};V.__cleanup=xe}catch(K){P||n.onToast(K instanceof Error?K.message:String(K))}})(),()=>{P=!0,V.stop(),V.__cleanup?.(),V.__cleanup=void 0,g(0)}},[_,n.onToast,a.rollingEnabled,B,W]);const Z=u.useCallback(V=>i(P=>({...P,rollingEnabled:V})),[]),G=u.useCallback(V=>i(P=>({...P,recordingQuality:V})),[]),q=u.useCallback(V=>i(P=>({...P,timelapseIntervalSeconds:V})),[]),Q=u.useCallback(async()=>{const V=n.sourceRegistry.resolveCurrentTarget();if(!V)throw new Error("화면이 준비된 후 다시 시도하세요.");x(!0);let P=null;try{P=await _(V),await _M(P.canvas,P.target,n.hubUrl),n.onToast("Screenshot saved")}finally{P?.cleanup(),x(!1)}},[_,n.hubUrl,n.onToast,n.sourceRegistry]),O=u.useCallback(async()=>{if(M.current)throw new Error("Stop the timelapse before recording.");const V=n.sourceRegistry.resolveCurrentTarget();if(!V)throw new Error("화면이 준비된 후 다시 시도하세요.");const P=await _(V),re=await fw({canvas:P.canvas,target:P.target,fps:V.type==="control"?30:15,hubUrl:n.hubUrl,onError:ue=>n.onToast(ue.message)});k.current=P.cleanup,j.current=re,c(Date.now()),n.onToast("Recording started")},[_,n.hubUrl,n.onToast,n.sourceRegistry]),ye=u.useCallback(async()=>{const V=j.current;if(V){x(!0);try{await V.stop(),n.onToast("Recording saved")}finally{j.current=null,k.current?.(),k.current=null,c(0),x(!1)}}},[n.onToast]),me=u.useCallback(async()=>{if(j.current||M.current)throw new Error("Last 30s is unavailable during a recording.");const V=n.sourceRegistry.resolveCurrentTarget();if(!V)throw new Error("화면이 준비된 후 다시 시도하세요.");x(!0);try{await T.current.save(V,n.hubUrl),n.onToast("Last 30 seconds saved")}finally{x(!1)}},[n.hubUrl,n.onToast,n.sourceRegistry]),X=u.useCallback(async()=>{if(j.current)throw new Error("Stop the recording before starting a timelapse.");const V=n.sourceRegistry.resolveCurrentTarget();if(!V)throw new Error("화면이 준비된 후 다시 시도하세요.");const P=await _(V),re=await OM(P.canvas,P.target,a.timelapseIntervalSeconds,n.hubUrl,ue=>n.onToast(ue.message));A.current=P.cleanup,M.current=re,m(Date.now()),n.onToast("Timelapse started")},[_,n.hubUrl,n.onToast,n.sourceRegistry,a.timelapseIntervalSeconds]),I=u.useCallback(async()=>{const V=M.current;if(V){x(!0);try{await V.stop(),n.onToast("Timelapse saved")}finally{M.current=null,A.current?.(),A.current=null,m(0),x(!1)}}},[n.onToast]);return u.useEffect(()=>{const V=P=>{!j.current&&!M.current||(P.preventDefault(),P.returnValue="")};return window.addEventListener("beforeunload",V),()=>window.removeEventListener("beforeunload",V)},[]),u.useEffect(()=>()=>{T.current.stop(),j.current?.cancel(),M.current?.cancel(),k.current?.(),A.current?.()},[]),{state:u.useMemo(()=>({recording:!!j.current,recordingStartedAt:l,timelapse:!!M.current,timelapseStartedAt:d,bufferSeconds:p,bufferEnabled:a.rollingEnabled,busy:v,targetLabel:H}),[p,v,l,a.rollingEnabled,H,d]),settings:a,videoSupported:W,targetKey:B,setRollingEnabled:Z,setRecordingQuality:G,setTimelapseInterval:q,takeScreenshot:Q,startRecording:O,stopRecording:ye,saveLast30Seconds:me,startTimelapse:X,stopTimelapse:I}}const BM=120,PM=999,$c=5,Uc=30,$M=Number.POSITIVE_INFINITY,hw="livedesk.remoteDirectory",Hh="livedesk.localHubAccessEnabled",UM="livedesk.streamSettings",qM=18,GM="livedesk.controlStreamSettings",VM=8,pw="livedesk.wallMonitorSelections",gw=2,ih=512*1024,Fh="".trim(),vw="".trim(),yb="livedesk-adsense-script",lh=!!Fh&&!!vw,WM=1e3/60,oh=1500,YM=650,KM=1800,XM=650,QM=2500,bb=1500,xb=15e3,ZM=6e4,wb=240,JM=1024,eT=640,tT=360,Sb="Connected LiveDesk clients are updating in batches. Hub will restart after every target reconnects on the requested versions.",Ld="LiveDesk is replacing the Hub and verifying the requested version.",_d=5*6e4,nT=5e3;function To({label:n,tooltip:a,disabled:i=!1,active:l=!1,danger:c=!1,pressed:d,onClick:m,children:p}){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:p})})}function aT(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 Tl={free:{name:"Free",price:"$0",limit:$c,audience:"Personal trial",note:"5 devices with a standard ad banner."},ltd:{name:"Plus",price:"$79 LTD",ltd:"$79 LTD",limit:Uc,audience:"Creators and homelabs",note:"30 devices, no ads, personal use."},pro:{name:"Pro",price:"$199 LTD",ltd:"$199 LTD",limit:$M,audience:"Business and studios",note:"Commercial use and larger Client walls."}},sT={"mode3-h264-hw":30};function Cb(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 v=g[4]?g[4].split(".").map(x=>/^\d+$/.test(x)?x.length>1&&x.startsWith("0")?Number.NaN:Number(x):x):[];return v.some(x=>typeof x=="number"&&!Number.isFinite(x))?null:{core:[Number(g[1]),Number(g[2]),Number(g[3])],prerelease:v}},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 p=l.prerelease[m],g=c.prerelease[m];if(p===void 0||g===void 0)return g===void 0;if(p!==g){if(typeof p=="number"&&typeof g=="number")return p>g;if(typeof p=="number")return!1;if(typeof g=="number"||p>g)return!0;if(p<g)return!1}}return!0}function La(n,a){return`${n}:${a}`}const rT={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:sT["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},iT={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:30,maxWidth:1920,maxHeight:1080,quality:75,showScreenStatus:!1};function ch(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 yw(n,a){n.push(a),n.length>wb&&n.splice(0,n.length-wb)}function kb(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 jb(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),yw(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 Ab(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 Nb(n){return!n||n.seqGapCount<=0?"none":`${n.seqGapCount} gaps / max ${n.maxSeqGap}`}function lT(n){return Number.isFinite(n)?String(n):"30+"}const bw=[1,2,5,8,12,20,30],Mb={large:{maxWidth:1280,maxHeight:720},medium:{maxWidth:960,maxHeight:540},list:{maxWidth:640,maxHeight:360}},ia={preserveConfiguredFpsDeviceCount:6,visibleRootMargin:"520px 0px 760px 0px",fallbackVisibleCounts:{large:12,medium:18,list:32},maxWallFramesPerSecond:za.maxDirectFramesPerSecond,maxWallBytesPerSecond:80*1024*1024,maxFrameGapMs:280,lowLoadFrameRatio:.58,lowLoadByteRatio:.52,downshiftCooldownMs:1800,recoveryCooldownMs:14e3,minFps:5},Tb=2200,oT=8e3,cT=3500,uT=7e3,dT=2,fT=7e3,mT=2600,hT=4200,pT=750,gT=2,Eb=4200;function Rb(n,a){return Math.min(3e4,n*2**Math.min(3,Math.max(0,a)))}function Xc(n,a){const i=n.capabilities?.[a];return typeof i=="boolean"?i:/^(1|true|yes|on)$/i.test(String(i||"").trim())}function _a(n){return n.deviceName||n.hostname||n.deviceId}function vT(){return"npx -y --prefer-online livedesk@latest client"}function yT(){return"npx -y --prefer-online livedesk@latest"}function bT(){try{return localStorage.getItem(hw)||""}catch{return""}}function xT(){try{return localStorage.getItem(Hh)==="1"}catch{return!1}}function Eo(n){try{n?localStorage.setItem(Hh,"1"):localStorage.removeItem(Hh)}catch{}}function Wi(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function Qn(n){const a=Wi(n.status),i=Wi(a.screens),l=Wi(n.capabilities),c=[a.monitorCount,a.screenCount,i.count,l.monitorCount,l.screenCount];for(const d of c){const m=Number(d);if(Number.isFinite(m)&&m>0)return Math.max(1,Math.min(64,Math.floor(m)))}return 1}function qi(n){const a=Number(n);return Number.isFinite(a)&&a>0?Math.floor(a):0}function xw(n){const a=Wi(n.status),l=[Wi(a.screens).displays,a.displays,a.monitors];for(const c of l)if(!(!Array.isArray(c)||c.length===0))return c.map(d=>Wi(d));return[]}function ww(n,a){const i=xw(n),l=i.find(g=>Number(g.index)===a)||i[a]||i[0]||{},c=qi(l.width),d=qi(l.height),m=[l.name,l.displayName,l.deviceName,l.id].find(g=>typeof g=="string"&&g.trim()),p=typeof m=="string"?m.trim():`Display ${a+1}`;return{index:a,name:p,width:c,height:d,primary:l.primary===!0||l.isPrimary===!0}}function wT(n){const a=Qn(n);return Array.from({length:a},(i,l)=>ww(n,l))}function ST(n){const a=xw(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()),p=g=>{const v=Number(g);return Number.isFinite(v)?v:null};return[Number.isFinite(d)?Math.floor(d):c,typeof m=="string"?m.trim().toLowerCase():"",p(l.left),p(l.top),p(l.width),p(l.height),l.primary===!0||l.isPrimary===!0]}).sort((l,c)=>l[0]-c[0]);return JSON.stringify(i)}function CT(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 Sw(n,a){const i=ww(n,a);if(i.width>0&&i.height>0)return{width:i.width,height:i.height};const l=Wi(n.status),c=qi(l.screenWidth||l.width),d=qi(l.screenHeight||l.height);return c>0&&d>0?{width:c,height:d}:null}function Cw(n){if(!n)return null;const a=qi(n.sourceWidth)||qi(n.width),i=qi(n.sourceHeight)||qi(n.height);return a>0&&i>0?{width:a,height:i}:null}function kT(n,a,i){const d=((typeof a?.monitorIndex=="number"?Zn(a.monitorIndex,Math.max(1,a.monitorCount||1)):i)===i?Cw(a):null)||Sw(n,i);return d?Math.max(.25,Math.min(4,d.width/d.height)):16/9}const Id=16/9;function Zn(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 jT(){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)!==gw||!i||typeof i!="object"||Array.isArray(i))return{selections:{},topologyFingerprints:{}};const l={},c={};for(const[d,m]of Object.entries(i)){const p=d.trim(),g=Wi(m),v=g.monitorIndex,x=Math.floor(Number(v));if(!p||!Number.isFinite(x))continue;l[p]=Math.max(0,Math.min(63,x));const b=typeof g.topologyFingerprint=="string"?g.topologyFingerprint.trim():"";b&&(c[p]=b)}return{selections:l,topologyFingerprints:c}}catch{return{selections:{},topologyFingerprints:{}}}}function AT(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:gw,selections:i}))}catch{}}function NT(){return{...rT}}function MT(n){try{localStorage.setItem(UM,JSON.stringify({...n,version:qM}))}catch{}}function TT(){return{...iT}}function ET(n){try{localStorage.setItem(GM,JSON.stringify({...n,version:VM}))}catch{}}function uh(n,a){return n.length!==a.length?!1:n.every((i,l)=>i===a[l])}function dh(n){return[...new Set(n.filter(Boolean))].sort()}function RT(n){return ia.fallbackVisibleCounts[n]||ia.fallbackVisibleCounts.large}function DT(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=Mb[a]||Mb.large;return{maxWidth:Math.min(n.maxWidth,l.maxWidth),maxHeight:Math.min(n.maxHeight,l.maxHeight)}}function LT(n,a=ia.minFps){const i=[...bw].sort((c,d)=>c-d),l=Math.max(a,Math.floor(n/2));return[...i].reverse().find(c=>c<n&&c>=a)||l}function _T(n,a){return[...bw].sort((l,c)=>l-c).find(l=>l>n&&l<=a)||a}function qc(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 Db(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 fh(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`${Db(i)} / ${Db(n)}`}function IT(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 Lb(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 zT(n){return n===1?"middle":n===2?"right":"left"}function _b(n,...a){for(const i of a){const l=n?.[i];if(typeof l=="string"&&l.trim())return l.trim()}return""}function Ib(n){const a=Number(n);return Number.isInteger(a)&&a>=1&&a<=PM?a:0}const OT={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function HT(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=OT[c.id]||c.label;return c.value&&c.value!=="-"?`${d} ${c.value}`:d}function uf(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 on(n,...a){for(const i of a){const l=uf(n,i),c=Number(l);if(Number.isFinite(c))return c}}function as(n,...a){for(const i of a){const l=uf(n,i);if(typeof l=="string"&&l.trim())return l.trim();if(typeof l=="number"&&Number.isFinite(l))return String(l)}return""}function FT(n,...a){for(const i of a){const l=uf(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 Xr(n){const a=Number(n);if(Number.isFinite(a))return Math.max(0,Math.min(1,a>1?a/100:a))}function mh(n,a){if(!(typeof n!="number"||typeof a!="number"||!Number.isFinite(n)||!Number.isFinite(a)||n<=0))return Xr((n-Math.max(0,a))/n)}function Ro(n){return n===void 0?"-":`${Math.round(n*100)}%`}function hh(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 El(n,a=.92,i=.78){return n===void 0?"unknown":n>=a?"critical":n>=i?"warn":"good"}function BT(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 zd(n,a,i){const l=uf(n,`tools.${a}`),c=as(n,`tools.${a}.status`,`tooling.${a}.status`,`${a}.status`).toLowerCase(),d=FT(n,`tools.${a}.running`,`tooling.${a}.running`,`${a}.running`),m=as(n,`tools.${a}.version`,`tooling.${a}.version`,`${a}.version`),p=as(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||(p?`:${p}`:g==="unknown"?"not reported":g)}}function kw(n){const a=n.status||{},i=on(a,"cpu.cores","cpuCores","processorCount"),l=on(a,"loadavg.0","cpu.load1"),c=Xr(on(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=on(a,"memory.totalBytes","totalMem"),m=on(a,"memory.freeBytes","freeMem"),p=Xr(on(a,"memory.usedRatio","memory.usedPct","usedMemRatio"))??mh(d,m),g=on(a,"disk.totalBytes","rootDisk.totalBytes","storage.totalBytes"),v=on(a,"disk.freeBytes","rootDisk.freeBytes","storage.freeBytes"),x=Xr(on(a,"disk.usedRatio","disk.usedPct","rootDisk.usedRatio","storage.usedRatio"))??mh(g,v),b=on(a,"thermal.cpuC","temperatureC","cpu.temperatureC","gpu.temperatureC"),w=Xr(on(a,"gpu.usedRatio","gpu.usageRatio","gpu.usedPct","gpu.usagePct","gpu.percent","accelerators.gpu.usageRatio")),C=as(a,"gpu.name","gpu.model","accelerators.gpu.name"),j=on(a,"gpu.memory.totalBytes","gpu.totalMemoryBytes","gpu.vramTotalBytes"),k=on(a,"gpu.memory.freeBytes","gpu.freeMemoryBytes","gpu.vramFreeBytes"),M=Xr(on(a,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??mh(j,k),A=on(a,"gpu.temperatureC","thermal.gpuC"),T=Xr(on(a,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),D=as(a,"npu.name","npu.model","accelerators.npu.name"),B=on(a,"npu.tops","npu.topsInt8","accelerators.npu.tops"),H=on(a,"network.rxMbps","network.receiveMbps","network.downMbps"),W=on(a,"network.txMbps","network.transmitMbps","network.upMbps"),_=on(a,"network.latencyMs","network.rttMs"),Z=Xr(on(a,"network.usedRatio","network.usageRatio","network.saturationRatio")),G=as(a,"network.link","network.interface","network.name"),q=Math.max(b??Number.NEGATIVE_INFINITY,A??Number.NEGATIVE_INFINITY),Q=Number.isFinite(q)?q:void 0,O=Q===void 0?void 0:Xr((Q-35)/60),ye=b!==void 0&&A!==void 0?`CPU ${Math.round(b)}° · GPU ${Math.round(A)}°`:b!==void 0?`CPU ${Math.round(b)}°`:A!==void 0?`GPU ${Math.round(A)}°`:"-",me=as(a,"workload.role","role","lane")||(Xc(n,"aiAssist")?"Agent worker":Xc(n,"taskDispatch")?"Task worker":"Local machine"),X=as(n.latestTask,"status")||as(a,"workload.status")||"idle",I=as(n.latestTask,"title","instructionPreview")||as(a,"workload.title"),ee=as(n.latestTask,"resultSummary","error","instructionPreview")||as(a,"workload.summary"),V=[zd(a,"ollama","Ollama"),zd(a,"lmStudio","LM Studio"),zd(a,"comfyui","ComfyUI"),zd(a,"stableDiffusion","Stable Diffusion")],P=V.some(le=>le.status!=="unknown"),re=Date.parse(n.lastSeenAt||n.connectedAt||""),ue=Number.isFinite(re)?Date.now()-re:0;let K="online";n.connected?ue>5*6e4?K="stale":(b??0)>=86||(A??0)>=88||(c??0)>=.94||(w??0)>=.96||(M??0)>=.96||(T??0)>=.96||(p??0)>=.94||(x??0)>=.94||(_??0)>=200||X==="failed"?K="critical":(b??0)>=78||(A??0)>=80||(c??0)>=.82||(w??0)>=.86||(M??0)>=.88||(T??0)>=.86||(p??0)>=.82||(x??0)>=.86||(_??0)>=80?K="warn":(["queued","running","targeted"].includes(X)||V.some(le=>le.status==="busy"))&&(K="busy"):K="offline";const xe=V.filter(le=>le.status==="online"||le.status==="busy").length,z=[{id:"cpu",label:"CPU",value:Ro(c),detail:i?`${i} cores`:l!==void 0?`load ${l.toFixed(1)}`:"not reported",ratio:c,state:El(c,.92,.78)},{id:"memory",label:"RAM",value:Ro(p),detail:fh(d,m),ratio:p,state:El(p,.92,.78)},{id:"disk",label:"DISK",value:Ro(x),detail:fh(g,v),ratio:x,state:El(x,.92,.82)},{id:"gpu",label:"GPU",value:Ro(w),detail:C||(j&&k!==void 0?`${qc(k)} VRAM free`:A!==void 0?`${Math.round(A)}C`:"not reported"),ratio:w,state:A!==void 0&&A>=88?"critical":A!==void 0&&A>=80?"warn":El(w,.96,.86)},{id:"vram",label:"VRAM",value:Ro(M),detail:fh(j,k),ratio:M,state:El(M,.96,.88)},{id:"npu",label:"NPU",value:T!==void 0?Ro(T):B!==void 0?`${Math.round(B)} TOPS`:"-",detail:D||(B!==void 0?"neural engine":"not reported"),ratio:T,state:El(T,.96,.86)},{id:"temp",label:"TEMP",value:ye,detail:xe>0?`${xe} local tools`:`uptime ${BT(on(a,"uptimeSec"))}`,ratio:O,state:Q===void 0?"unknown":Q>=86?"critical":Q>=78?"warn":"good"},{id:"network",label:"NET",value:hh(H)||(_!==void 0?`${Math.round(_)}ms`:G||"-"),detail:hh(W)?`${hh(W)} up`:G||"not reported",ratio:Z,state:_!==void 0&&_>=200?"critical":_!==void 0&&_>=80?"warn":El(Z,.9,.75)}];return{state:K,label:HT(K,z,X),role:me,taskLabel:I||(X==="idle"?"idle":X),taskStatus:X,taskSummary:ee,tools:P?V:V.map(le=>({...le,detail:"not reported"})),metrics:z}}const PT=[{id:"list",label:"List"},{id:"medium",label:"Small"},{id:"large",label:"Large"}],$T=[{id:"sync-server",label:"Hub",icon:mr,accent:"blue",tooltip:"hub"},{id:"wall",label:"Wall",icon:m0,accent:"blue",tooltip:"wall"},{id:"control",label:"Control",icon:bh,accent:"red",tooltip:"control"},{id:"share-files",label:"Share Files",icon:Od,accent:"green",tooltip:"share-files"},{id:"agents",label:"Agents",icon:xh,accent:"violet",tooltip:"agents"}],UT=[{id:"doc",label:"Doc",icon:qd,accent:"amber"},{id:"support",label:"Support",icon:Gc,accent:"violet"},{id:"pricing",label:"Pricing",icon:Do,accent:"green"}];function qT(n){return n.replaceAll("npx -y @livedesk/client","npx -y --prefer-online livedesk@latest client").replaceAll("npx @livedesk/client","npx -y --prefer-online livedesk@latest client").replaceAll("npx -y livedesk client","npx -y --prefer-online livedesk@latest client").replaceAll("npx livedesk client","npx -y --prefer-online livedesk@latest client").replaceAll("npx -y livedesk","npx -y --prefer-online livedesk@latest").replaceAll("npx livedesk","npx -y --prefer-online livedesk@latest")}function nn(n){return qT(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 Rl(n){return n.map(a=>nn(a))}function sa(n){return{languageName:n.languageName,languageLabel:n.languageLabel,eyebrow:n.eyebrow,title:nn(n.title),intro:nn(n.intro),sections:[{title:nn(n.managerTitle),body:nn(n.managerBody),points:Rl(n.managerPoints)},{title:nn(n.clientTitle),body:nn(n.clientBody),points:Rl(n.clientPoints)},{title:nn(n.syncTitle),body:nn(n.syncBody),points:Rl(n.syncPoints)},...n.agentTitle&&n.agentBody&&n.agentPoints?[{title:nn(n.agentTitle),body:nn(n.agentBody),points:Rl(n.agentPoints)}]:[],{title:nn(n.platformTitle),body:nn(n.platformBody),points:Rl(n.platformPoints)}],sync:{title:nn(n.syncTitle),body:nn(n.syncBody),points:Rl(n.syncPoints)},firewall:{title:nn(n.firewallTitle),body:nn(n.firewallBody),points:Rl(n.firewallPoints)},commands:{title:nn(n.commandsTitle),body:nn(n.commandsBody),manager:nn(n.managerCommandLabel),primary:nn(n.clientCommandLabel),slot:nn(n.slotCommandLabel),manual:nn(n.manualCommandLabel)}}}const Oo={ko:sa({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:sa({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:sa({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":sa({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":sa({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:sa({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:sa({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:sa({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":sa({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:sa({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:sa({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:sa({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:sa({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:sa({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:sa({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:sa({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ı"})},GT=Object.entries(Oo).map(([n,a])=>({id:n,label:a.languageName}));function VT(){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(Oo[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(Oo[l])return l}return"en"}function zb({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(oa,{size:24}),r.jsxs("strong",{children:["Slot ",String(a).padStart(3,"0")]})]})]})})}const WT=["cpu","gpu","memory","vram","network","disk","temp"];function YT({device:n,slotNumber:a,selected:i,updateIndicator:l,onSelect:c,onOpenControl:d}){const m=kw(n),p=new Map(m.metrics.map(v=>[v.id,v])),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:v=>{v.preventDefault(),d()},onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&(v.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(oa,{size:17})}),r.jsxs("span",{children:[r.jsx("strong",{children:_a(n)}),r.jsxs("small",{children:["Slot ",String(a).padStart(3,"0"),n.platform?` · ${n.platform}`:"",n.arch?` · ${n.arch}`:""]})]}),i&&r.jsx(fr,{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})]}),WT.map(v=>{const x=p.get(v);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"})]},v)})]})}function KT(n){if(!n)return!1;const a=String(n.platform||"").trim().toLowerCase();return Qr(a)&&n.capabilities?.screenRecordingPermission===!1}function Qr(n){const a=String(n||"").trim().toLowerCase();return a==="macos"||a==="darwin"||a==="mac"||a==="macosx"}function XT(n){const a=String(n||"").trim().toLowerCase();return a==="linux"||a.startsWith("linux ")}function Ob(n){if(!n)return!1;const a=String(n.capabilities?.liveCaptureConcurrency||"").trim().toLowerCase();return a==="exclusive"?!0:a==="parallel"?!1:Qr(n.platform)}function ph({device:n,frame:a,selected:i,controlEnabled:l,showStatus:c,monitorIndex:d,monitorCount:m,onSelect:p,onFocusDevice:g,onOpenControl:v,onCycleMonitor:x,onCanvasReady:b,sendInput:w,updateIndicator:C,presentationReady:j,showPresentationSpinner:k=!1,remoteDiagnostics:M}){const A=u.useRef(null),T=u.useRef(null),D=u.useRef(0),B=u.useRef(null),H=kw(n),W=["cpu","gpu","memory","vram"].map(z=>H.metrics.find(le=>le.id===z)).filter(z=>!!z),_=Zn(d,m),Z=m>1,G=j??!!a,q=KT(n)&&!G,Q=k&&n.connected&&!G&&!q,O=kT(n,a,_),ye=O>=Id?100:O/Id*100,me=O>=Id?Id/O*100:100,X={"--screen-aspect":O.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,ye)).toFixed(3)}%`,"--screen-content-height":`${Math.max(1,Math.min(100,me)).toFixed(3)}%`},I=u.useCallback(z=>{A.current=z,b(n.deviceId,z)},[n.deviceId,b]),ee=z=>{const le=z.currentTarget.getBoundingClientRect();return T1(z.clientX,z.clientY,le)},V=z=>({shiftKey:z.shiftKey,ctrlKey:z.ctrlKey,altKey:z.altKey,metaKey:z.metaKey}),P=u.useCallback(()=>{B.current!==null&&(window.cancelAnimationFrame(B.current),B.current=null)},[]),re=u.useCallback(()=>{const z=T.current;if(!z)return;T.current=null;const le=Number(z.input.normalizedX),ke=Number(z.input.normalizedY);if(!Number.isFinite(le)||!Number.isFinite(ke))return;w(n.deviceId,{...z.input,normalizedX:le,normalizedY:ke})&&(D.current=performance.now())},[n.deviceId,w]),ue=u.useCallback(()=>{B.current===null&&(B.current=window.requestAnimationFrame(()=>{B.current=null,re()}))},[re]);u.useEffect(()=>()=>{P(),T.current=null},[P]);const K=(z,le)=>{if(!l)return;const ke={type:le,monitorIndex:_,...ee(z),button:zT(z.button),...V(z)};if(le==="pointermove"){const Ce=performance.now();T.current={input:ke},Ce-D.current>=WM&&(P(),re()),ue();return}T.current&&(P(),re()),w(n.deviceId,ke)},xe=u.useCallback(z=>{const le=document.activeElement;le instanceof HTMLElement&&z.contains(le)&&le.classList.contains("monitor-cycle-button")&&le.blur()},[]);return r.jsx("article",{className:`device-tile ${i?"selected":""} ${n.connected?"online":"offline"}`,"data-live-device-id":n.deviceId,style:X,children:r.jsxs("div",{className:`tile-screen ${G?"has-frame":"is-empty"}`,role:"button",tabIndex:l?-1:0,"aria-pressed":i,onClick:z=>{z.target instanceof Element&&z.target.closest(".monitor-cycle")||l||p()},onKeyDown:z=>{z.target instanceof Element&&z.target.closest(".monitor-cycle")||l||(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),p())},onDoubleClick:z=>{z.target instanceof Element&&z.target.closest(".monitor-cycle")||(z.preventDefault(),v())},onPointerLeave:z=>xe(z.currentTarget),children:[r.jsx("span",{className:`screen-content ${G?"has-frame":"is-empty"}`,children:r.jsx("canvas",{ref:I,className:`remote-canvas ${G?"has-frame":"is-empty"}`,tabIndex:l?0:-1,onPointerDown:z=>{l&&(z.preventDefault(),z.stopPropagation(),g(),z.currentTarget.focus(),z.currentTarget.setPointerCapture(z.pointerId),K(z,"pointerdown"))},onPointerMove:z=>{l&&z.preventDefault(),K(z,"pointermove")},onPointerLeave:z=>{l&&(K(z,"pointermove"),P(),re())},onPointerUp:z=>{l&&(z.preventDefault(),z.stopPropagation(),K(z,"pointerup"),z.currentTarget.hasPointerCapture(z.pointerId)&&z.currentTarget.releasePointerCapture(z.pointerId))},onPointerCancel:z=>{z.currentTarget.hasPointerCapture(z.pointerId)&&z.currentTarget.releasePointerCapture(z.pointerId)},onWheel:z=>{l&&(z.preventDefault(),w(n.deviceId,{type:"wheel",monitorIndex:_,...ee(z),deltaX:z.deltaX,deltaY:z.deltaY,...V(z)}))},onKeyDown:z=>{l&&(z.preventDefault(),z.stopPropagation(),w(n.deviceId,{type:"keydown",monitorIndex:_,key:z.key,code:z.code,keyCode:z.keyCode||z.which||0,location:z.location,text:z.key.length===1?z.key:"",repeat:z.repeat,...V(z)}))},onKeyUp:z=>{l&&(z.preventDefault(),z.stopPropagation(),w(n.deviceId,{type:"keyup",monitorIndex:_,key:z.key,code:z.code,keyCode:z.keyCode||z.which||0,location:z.location,text:z.key.length===1?z.key:"",repeat:!1,...V(z)}))},onContextMenu:z=>l&&z.preventDefault()})}),!G&&r.jsx("span",{className:"empty-screen",children:r.jsx(oa,{size:26})}),r.jsx("span",{className:"wall-device-title",title:_a(n),children:_a(n)}),Q&&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"})]}),q&&r.jsxs("span",{className:"wall-presentation-loading permission-required",role:"status","aria-live":"polite",children:[r.jsx(jn,{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."})]}),C&&r.jsxs("span",{className:`wall-update-status state-${C.state}`,role:"status","aria-live":"polite",title:C.error||C.label,children:[C.state==="updated"?r.jsx(Dn,{size:20,"aria-hidden":"true"}):C.state==="failed"?r.jsx(la,{size:22,"aria-hidden":"true"}):C.state==="offline"?r.jsx(ef,{size:22,"aria-hidden":"true"}):r.jsx("span",{className:"wall-update-spinner","aria-hidden":"true"}),r.jsx("strong",{children:C.label}),C.error?r.jsx("small",{children:C.error}):null]}),c&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:`tile-health-pill state-${H.state}`,children:H.label}),r.jsx("span",{className:"tile-metrics","aria-label":`${_a(n)} status`,children:W.map(z=>r.jsxs("span",{className:`tile-metric state-${z.state}`,children:[r.jsx("b",{children:z.label}),r.jsx("em",{children:z.value}),z.ratio!==void 0&&r.jsx("i",{style:{width:`${Math.round(z.ratio*100)}%`}})]},z.id))})]}),M&&r.jsx(bM,{items:M}),Z&&r.jsxs("span",{className:"monitor-cycle","aria-label":`${_a(n)} display ${_+1} of ${m}`,onPointerDown:z=>z.stopPropagation(),onClick:z=>z.stopPropagation(),onDoubleClick:z=>z.stopPropagation(),children:[r.jsx("button",{className:"monitor-cycle-button previous",onClick:z=>{z.preventDefault(),z.stopPropagation(),x(-1),z.currentTarget.blur()},title:"Previous display",type:"button",children:r.jsx(Yb,{size:18})}),r.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",_+1,"/",m]}),r.jsx("button",{className:"monitor-cycle-button next",onClick:z=>{z.preventDefault(),z.stopPropagation(),x(1),z.currentTarget.blur()},title:"Next display",type:"button",children:r.jsx(Vh,{size:18})})]}),i&&r.jsx("span",{className:"device-selection-check","aria-hidden":"true",children:r.jsx(fr,{size:23,strokeWidth:3.5})})]})})}function QT({visible:n}){return u.useEffect(()=>{if(!n||!lh)return;if(!document.getElementById(yb)){const i=document.createElement("script");i.id=yb,i.async=!0,i.crossOrigin="anonymous",i.src=`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${encodeURIComponent(Fh)}`,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 ${lh?"adsense-ready":"house-ad"}`,"aria-label":"Advertisement",children:[r.jsx("span",{className:"ad-label",children:"Advertisement"}),lh?r.jsx("ins",{className:"adsbygoogle livedesk-ad-unit",style:{display:"block"},"data-ad-client":Fh,"data-ad-slot":vw,"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 ZT(){const{session:n,loading:a}=i1(),{target:i,error:l,refresh:c}=o1(n),d=u.useMemo(()=>{if(!i?.active)return null;const y=i.expires_at?Date.parse(i.expires_at):Number.POSITIVE_INFINITY;return Number.isFinite(y)&&y<=Date.now()?null:i},[i]),m=u.useMemo(()=>dy(d),[d]),p=u.useMemo(()=>m.length>0?[...new Set([...m,fn])]:[fn],[m]),[g,v]=u.useState(xT),x=u.useMemo(()=>p.some(y=>!!Wc(y)),[p]),b=!x||g,{status:w,devices:C,error:j,refresh:k,hubBaseUrl:M}=l1(p,b),{entitlement:A,licensed:T,loading:D,error:B,refresh:H}=c1(n),[W,_]=u.useState([]),[Z,G]=u.useState(""),[q,Q]=u.useState(""),[O,ye]=u.useState(""),[me,X]=u.useState(""),[I,ee]=u.useState(""),[V,P]=u.useState("idle"),[re,ue]=u.useState(!1),[K,xe]=u.useState(null),[z,le]=u.useState(""),ke=u.useRef("");ke.current=me;const[Ce,Ue]=u.useState(!1),[Be,he]=u.useState(!1),Xe=u.useRef(""),et=u.useRef(new Map),ce=u.useRef(0),[ge,Ae]=u.useState(""),[Le,Pe]=u.useState(""),[Ve,Ke]=u.useState(!1),de=u.useRef(null),je=u.useRef(null);u.useEffect(()=>{ge==="auth"&&n?.access_token&&Ae("")},[ge,n?.access_token]);const[fe,_e]=u.useState(""),[Ee,mt]=u.useState(null),Ht=u.useRef(null),Dt=u.useRef(0),yt=u.useCallback((y,N,L)=>{const $=String(y||"").trim();if(_e($),Ht.current!==null&&(window.clearTimeout(Ht.current),Ht.current=null),!$){mt(null);return}const R=++Dt.current;if(mt({id:R,message:$,tone:N}),!L)return;const ae=window.setTimeout(()=>{mt(te=>te?.id===R?null:te),Ht.current===ae&&(Ht.current=null)},5e3);Ht.current=ae},[]),Ge=u.useCallback((y,N="info")=>{yt(y,N,!0)},[yt]),At=u.useCallback(y=>{yt(y,"progress",!1)},[yt]);u.useEffect(()=>()=>{Ht.current!==null&&window.clearTimeout(Ht.current)},[]);const[ve,Fe]=u.useState(()=>typeof window<"u"&&window.location.pathname.startsWith("/support")?"support":"wall");u.useEffect(()=>{const y=()=>{Fe(window.location.pathname.startsWith("/support")?"support":N=>N==="support"?"wall":N)};return window.addEventListener("popstate",y),()=>window.removeEventListener("popstate",y)},[]);const[He,Me]=u.useState("large"),[rt,dt]=u.useState(!1),[Re,An]=u.useState(!1),[pa,it]=u.useState(!1),[Xt,Nn]=u.useState(Date.now),Mn=u.useRef(null);u.useEffect(()=>()=>{Mn.current!==null&&window.clearTimeout(Mn.current)},[]);const[wn,Cs]=u.useState(VT),[Ha,gr]=u.useState(!1),[rs,zn]=u.useState(!1),[Xi,Qi]=u.useState(!1),[F,Je]=u.useState(bT),[ze]=u.useState(NT),[kt]=u.useState(TT),[ks]=u.useState(jT),[Mt,ga]=u.useState(ks.selections),ne=u.useRef({...ks.topologyFingerprints}),Te=u.useRef({...ks.selections}),[De,st]=u.useState(null),[Gt,It]=u.useState([]),[Qe,jt]=u.useState(ze.fps),[cn,Jt]=u.useState(""),[On,Wt]=u.useState(0),[mn,Yt]=u.useState(0),[Gs,Fa]=u.useState(()=>new Set),Nt=u.useRef(new Map),Vt=u.useRef(new Map),is=u.useRef(new Map),Ba=u.useRef(new Map),hn=u.useRef(new Map),ni=u.useRef(new Map),ca=u.useRef(new Set),vr=u.useRef(new Map),en=u.useRef(""),Hn=u.useRef(""),Zi=u.useRef(null),yr=u.useRef(null),ls=u.useRef(new Map),Ji=u.useRef(null),ai=u.useRef(0),Bl=u.useRef(new Map),[Fn,Pl]=u.useState({}),el=u.useRef(new Map),[si,br]=u.useState({}),[$o,va]=u.useState(!1),Vs=u.useRef(null),os=u.useRef(null),ua=u.useRef(0),Ws=u.useRef(""),cs=u.useRef(new Map),xr=u.useRef(new Map),$l=u.useRef(performance.now()),js=u.useRef(new Map),Bn=u.useRef(new Map),As=u.useRef(new Map),Ys=u.useRef(new Map),Ns=u.useRef(new Map),us=u.useRef(0),tl=u.useRef(0),ri=u.useRef(0),nl=u.useRef(0),wr=u.useRef(0),ds=u.useRef(new Map),Pa=u.useRef(new Map),Pn=u.useCallback((y,N)=>{const L=La(y,N),$=performance.now();cs.current.delete(L),xr.current.delete(L),js.current.delete(L),Ns.current.delete(L),Pa.current.delete(L),el.current.delete(L),Bl.current.delete(L),br(R=>{if(!Object.prototype.hasOwnProperty.call(R,L))return R;const ae={...R};return delete ae[L],ae}),Pl(R=>{if(!Object.prototype.hasOwnProperty.call(R,L))return R;const ae={...R};return delete ae[L],ae}),y==="control"?(Bn.current.delete(L),As.current.set(L,$)):Ys.current.set(L,$)},[]),[Jn,fs]=u.useState(null),[Ul,ql]=u.useState(!1),[Uo,Gl]=u.useState([]),[Sr,ea]=u.useState("all"),[ya,ii]=u.useState([]),[Vl,fp]=u.useState(!1),[iu,qo]=u.useState(!0),li=u.useRef(null),al=u.useRef(null),lu=u.useRef(null),df=u.useRef(null),ff=u.useRef(!1),Go=u.useRef(!1),sl=u.useRef(!1),rl=u.useRef(0),Ks=u.useRef(0),Wl=ve==="settings",ou=ve==="pricing",cu=ve==="doc",Vo=ve==="support",il=ve==="share-files",Wo=ve==="agents",ll=!Wl&&!ou&&!cu&&!Vo&&!il&&!Wo,ct=ve==="control";u.useEffect(()=>{ll||(dt(!1),An(!1))},[ll]);const pt=ze.frameMode==="mode4-h264-atlas",da=I||kt.frameMode,ol=da!=="mode3-h264-hw"?Math.min(30,kt.fps):kt.fps,mf=C.find(y=>y.deviceId===q)?.platform,Yo=XT(mf)?{maxWidth:1280,maxHeight:720}:{maxWidth:3840,maxHeight:2160},oi={maxWidth:Math.min(da!=="mode3-h264-hw"?1920:3840,Yo.maxWidth,kt.maxWidth),maxHeight:Math.min(da!=="mode3-h264-hw"?1080:2160,Yo.maxHeight,kt.maxHeight)};u.useEffect(()=>{if(w?.started){if(!n?.access_token){Ye("/api/remote/license",{method:"DELETE"},M).catch(()=>{});return}Ye("/api/remote/license/sync",{method:"POST",headers:{Authorization:`Bearer ${n.access_token}`}},M).catch(y=>{console.warn("[LiveDesk] Hub license sync failed",y)})}},[A?.updated_at,M,n?.access_token,w?.started]),u.useEffect(()=>{!n?.access_token||!w?.started||w.runtimeRole!=="hub"||!w.deviceId||(async()=>{try{const{data:y,error:N}=await ft.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||""}),L=Array.isArray(y)?y[0]:y;(N||L?.ok===!1)&&console.warn("[LiveDesk] Hub device role registration failed",N||L?.reason||"unknown-error")}catch(y){console.warn("[LiveDesk] Hub device role registration failed",y)}})()},[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"||sl.current||(sl.current=!0,Ye("/api/auth/session",{method:"POST",body:JSON.stringify({accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:n.expires_at,user:{id:n.user.id,email:n.user.email}})},M||fn).then(y=>{y.hostTarget?.ok===!1&&console.warn("[LiveDesk] Hub host target publish is waiting for a valid Hub role:",y.hostTarget.error||"unknown-error"),k()}).catch(y=>{console.warn("[LiveDesk] Hub session sync failed:",y)}).finally(()=>{sl.current=!1}))},[M,k,n?.access_token,n?.expires_at,n?.refresh_token,n?.user?.email,n?.user?.id,w?.runtimeRole,w?.started]);const at=u.useMemo(()=>C.filter(y=>y.connected),[C]),uu=Sr==="all"?at.length:ya.filter(y=>at.some(N=>N.deviceId===y)).length,hf=u.useMemo(()=>at.reduce((y,N)=>Math.max(y,Ib(N.slotNumber)),0),[at]),Yl=Math.max(BM,at.length,hf),Cr=u.useMemo(()=>{const y=Array(Yl).fill(null),N=[];for(const L of at){const $=Ib(L.slotNumber);$>0&&$<=Yl&&!y[$-1]?y[$-1]=L:N.push(L)}for(const L of N){const $=y.findIndex(R=>!R);$<0?y.push(L):y[$]=L}return y},[at]),du=u.useMemo(()=>Cr.flatMap((y,N)=>y?[{device:y,slotNumber:N+1}]:[]),[Cr]),Ko=u.useMemo(()=>at.map(y=>y.deviceId),[at]),kr=u.useMemo(()=>new Set(W),[W]),$n=u.useMemo(()=>at.filter(y=>kr.has(y.deviceId)),[at,kr]),ms=u.useMemo(()=>C.find(y=>y.deviceId===Z)||$n[0]||null,[C,Z,$n]),Un=u.useMemo(()=>C.find(y=>y.deviceId===q)||null,[q,C]),hs=Un?Zn(Mt[Un.deviceId],Qn(Un)):0,$e=ct?Un:ms,Xo=u.useMemo(()=>new Set(ya),[ya]),fu=u.useMemo(()=>Sr==="all"?at.map(y=>y.deviceId):at.filter(y=>Xo.has(y.deviceId)).map(y=>y.deviceId),[at,Xo,Sr]),mu=$e?Xc($e,"control"):!1,Xs=Qr($e?.platform)&&($e?.capabilities?.controlPermission===!1||$e?.capabilities?.accessibilityPermission===!1),cl=$e?Xc($e,"audio")||Xc($e,"remoteAudio"):!1,hu=(Array.isArray($e?.capabilities?.agentTools)?$e.capabilities.agentTools.map(String):[]).includes("system.power"),$t=T?A?.plan==="pro"?"pro":"ltd":"free",Qo=Tl[$t],Qs=Qo.limit,ps=u.useMemo(()=>{if(!Number.isFinite(Qs))return new Set(at.map(N=>N.deviceId));const y=$e?[$e,...at.filter(N=>N.deviceId!==$e.deviceId)]:at;return new Set(y.slice(0,Qs).map(N=>N.deviceId))},[Qs,at,$e]),pf=!$e||ps.has($e.deviceId),Kl=$t==="free",Qt=pf,ci=$t==="ltd"?`Plus includes up to ${Uc} Clients. Upgrade to Pro for commercial use and larger walls.`:`Free includes up to ${$c} Clients. Upgrade to Plus for ${Uc} devices and no ads.`,Zo=$t==="free",$a=Qt&&!!$e&&mu,Jo=Qt&&!!$e&&cl,ul=u.useMemo(()=>Cr.filter(y=>!!y?.connected).slice(0,RT(He)).map(y=>y.deviceId),[Cr,He]),dl=u.useMemo(()=>He==="list"?[]:pt?Ko:ze.visibleOnlyLive?Gt.length>0?Gt:ul:Ko,[ul,pt,Gt,ze.visibleOnlyLive,Ko,He]),Ua=u.useMemo(()=>dh(dl.filter(y=>ps.has(y))),[ps,dl]),Zs=u.useMemo(()=>Ua.filter(y=>y!==cn),[Ua,cn]),Xl=u.useMemo(()=>new Map(at.map(y=>[y.deviceId,y.platform])),[at]),gs=E1(pt,Ua.length),ta=u.useMemo(()=>pt?Zs.filter(y=>Fc({mode4Enabled:pt,directMode4WallEnabled:gs,isMac:Qr(Xl.get(y))})==="atlas"):[],[gs,pt,Xl,Zs]),Ut=u.useMemo(()=>Zs.filter(y=>Fc({mode4Enabled:pt,directMode4WallEnabled:gs,isMac:Qr(Xl.get(y))})==="direct"),[gs,pt,Xl,Zs]);u.useEffect(()=>{const y=new Set(Ua);Fa(N=>{let L=!1;const $=new Set;for(const R of N)y.has(R)?$.add(R):L=!0;return L?$:N})},[Ua]);const fl=u.useMemo(()=>{const y=R=>at.find(ae=>ae.deviceId===R)||null,N=R=>Zn(Mt[R],y(R)?Qn(y(R)):0),L=(R,ae=N(R))=>R===O&&(V==="connecting"||V==="active"||V==="warm")?hn.current.get(R)||Vt.current.get(R)||null:pt?ls.current.get(R)||Nt.current.get(R)||null:Nt.current.get(R)||null,$=(R,ae=N(R))=>{const te=y(R);return`${te?_a(te):R} · Monitor ${ae+1}`};return{resolveCurrentTarget(){if(ct&&Un){const qe=hs;return{type:"control",deviceIds:[Un.deviceId],monitorIndex:qe,label:`${_a(Un)} · Monitor ${qe+1}`,sourceCanvas:L(Un.deviceId,qe),signature:`control:${Un.deviceId}:${qe}:${kt.frameMode}`}}const R=$n.map(qe=>qe.deviceId).filter(qe=>Zs.includes(qe)),ae=ms&&Zs.includes(ms.deviceId)?ms.deviceId:"",te=R.length>0?R:ae?[ae]:Zs,Ie=R.length===0&&!ae;if(te.length===0)return null;if(te.length===1){const qe=te[0],Ne=N(qe);return{type:Ie?"wall":R.length>1?"selection":"device",deviceIds:te,monitorIndex:Ne,label:Ie?"Wall":$(qe,Ne),sourceCanvas:Ie?null:L(qe,Ne),signature:`${Ie?"wall":"device"}:${qe}:${Ne}:${pt?"atlas":"direct"}`}}return{type:R.length>1?"selection":"wall",deviceIds:te,label:R.length>1?`${te.length} selected Clients`:"Wall",sourceCanvas:null,signature:`${R.length>1?"selection":"wall"}:${te.join(",")}:${He}`}},getDeviceCanvas:L,composeWall(R,ae={}){return MM(R.map(te=>{const Ie=N(te);return{deviceId:te,label:$(te,Ie),canvas:L(te,Ie)}}),ae)}}},[at,Un,O,V,kt.frameMode,Nt,pt,Mt,hs,$n,ct,Zs,ms,He]),ec=FM({hubUrl:M,sourceRegistry:fl,onToast:Ge}),jr=u.useMemo(()=>Qt&&O&&ps.has(O)&&(V==="connecting"||V==="active"||V==="warm")?[O]:[],[O,V,Qt,ps]),pu=u.useMemo(()=>dh([...Ua,...jr]),[jr,Ua]),ba=u.useMemo(()=>DT(ze,He),[ze,He]),Ms=R1({mode4Enabled:pt,directMode4WallEnabled:gs,adaptiveFps:Qe,directDeviceCount:Ut.length,adaptive:ze.adaptiveLoadShedding}),tc=D1({deviceCount:ta.length,targetFps:Qe,adaptive:ze.adaptiveLoadShedding});pt&&ta.length>0;const an=u.useCallback((y,N,L)=>{if(y.width<=0||y.height<=0)return!1;const $=L?Math.min(1,L.maxWidth/y.width,L.maxHeight/y.height):1,R=Math.max(1,Math.round(y.width*$)),ae=Math.max(1,Math.round(y.height*$));(N.width!==R||N.height!==ae)&&(N.width=R,N.height=ae);const te=N.getContext("2d",{alpha:!1});return te?(te.imageSmoothingEnabled=!0,te.imageSmoothingQuality="high",te.drawImage(y,0,0,y.width,y.height,0,0,N.width,N.height),!0):!1},[]),xa=u.useCallback(y=>{y&&Fa(N=>{if(N.has(y))return N;const L=new Set(N);return L.add(y),L})},[]),Js=u.useCallback(y=>{y&&Fa(N=>{if(!N.has(y))return N;const L=new Set(N);return L.delete(y),L})},[]),er=u.useCallback((y,N)=>{if(!N||N.width<=0||N.height<=0)return!1;const L=document.createElement("canvas");return L.width=N.width,L.height=N.height,an(N,L)?(is.current.set(y,L),xa(y),!0):!1},[xa,an]),Ts=u.useCallback(y=>{const N=Ba.current.get(y);N!==void 0&&(window.cancelAnimationFrame(N),Ba.current.delete(y))},[]),wa=u.useCallback(y=>{Ts(y),is.current.delete(y)},[Ts]),Es=u.useCallback((y,N)=>{Ts(y);const L=()=>{const $=is.current.get(y),R=Nt.current.get(y)===N||ls.current.get(y)===N;if(!$||!R){Ba.current.delete(y);return}an($,N),Ba.current.set(y,window.requestAnimationFrame(L))};L()},[an,Ts]);u.useEffect(()=>()=>{for(const y of Ba.current.values())window.cancelAnimationFrame(y);Ba.current.clear()},[]);const qa=u.useCallback((y,N=!1)=>{if(!ca.current.has(y))return!1;const L=performance.now(),$=vr.current.get(y)||0,R=Math.max(1,Math.min(za.controlWallReuseMaxFps,ol)),ae=ol>R?Math.max(0,1e3/R-2):0;if(!N&&L-$<ae)return!1;const te=hn.current.get(y)||Vt.current.get(y),Ie=Nt.current.get(y)||ls.current.get(y);return!te||!Ie||!an(te,Ie,ba)?!1:(vr.current.set(y,L),xa(y),wa(y),!0)},[ol,ba,xa,an,wa]);u.useEffect(()=>{en.current=cn},[cn]);const nc=u.useCallback((y,N)=>{const L=Nt.current.get(y);if(L&&L!==N&&(Ts(y),er(y,L),Ao(L)),N){Nt.current.set(y,N);const $=is.current.get(y);$&&an($,N)&&(xa(y),Es(y,N)),qa(y,!0);return}Nt.current.delete(y),is.current.has(y)||Js(y)},[Js,Es,xa,an,qa,er,Ts]),Ar=u.useCallback((y,N)=>{const L=Vt.current.get(y);if(L&&L!==N&&Ao(L),N){Vt.current.set(y,N);const $=O===y&&re?hn.current.get(y):null;$&&an($,N)&&y===q&&va(!0);return}Vt.current.delete(y)},[q,O,re,an]),ml=u.useCallback((y,N,L)=>{const $=performance.now(),R=La(y,L.deviceId);let ae=L;if(y==="control"&&L.visualChanged){const Ie=p1(L.deviceId),qe=ds.current.get(L.deviceId)||0,Ne=Ie?$-Ie.sentAt:Number.POSITIVE_INFINITY;Ie&&Ie.inputSeq>qe&&Ne<=bb&&(ae={...L,inputFeedbackSeq:Ie.inputSeq,inputFeedbackMs:Math.max(0,Ne),inputFeedbackAt:$},ds.current.set(L.deviceId,Ie.inputSeq))}xr.current.set(R,$);const te=Bl.current.get(R)||{totalFrames:0,totalChangedFrames:0,sampleFrames:0,sampleChangedFrames:0,sampleStartedAt:$,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleDecoderInputBase:0,sampleDecoderOutputBase:0};y==="control"&&ae.inputFeedbackMs===void 0&&te.lastInfo?.inputFeedbackMs!==void 0&&te.lastInfo.inputFeedbackAt!==void 0&&$-te.lastInfo.inputFeedbackAt<=bb&&(ae={...ae,inputFeedbackSeq:te.lastInfo.inputFeedbackSeq,inputFeedbackMs:te.lastInfo.inputFeedbackMs,inputFeedbackAt:te.lastInfo.inputFeedbackAt}),te.totalFrames+=1,te.sampleFrames+=1,jb(te,$,ae.frameSeq),ae.visualChanged&&(te.totalChangedFrames+=1,te.sampleChangedFrames+=1),te.lastInfo=ae,Bl.current.set(R,te)},[]),hl=u.useCallback((y,N)=>{ml("wall",y,N),y.kind==="live"&&(xa(y.deviceId),wa(y.deviceId));const L=re&&O===y.deviceId;en.current!==y.deviceId&&!L&&(ca.current.delete(y.deviceId),vr.current.delete(y.deviceId))},[O,re,xa,ml,wa]),ac=u.useCallback((y,N)=>{ml("control",y,N),le(ae=>ae&&"");const L=hn.current.get(y.deviceId),$=Vt.current.get(y.deviceId);L&&L.width>0&&L.height>0&&($&&an(L,$),ni.current.set(y.deviceId,{...y,payload:new Uint8Array(0),byteLength:0}),ca.current.add(y.deviceId),y.deviceId===O&&(ue(!0),P(ae=>ae==="connecting"?"active":ae)),qa(y.deviceId));const R=Vs.current;!R||!aT(R,y)||va(!0)},[O,an,qa,ml]);u.useEffect(()=>{const y=window.setInterval(()=>{const N=performance.now(),L={};for(const[$,R]of Bl.current.entries()){const ae=Math.max(1,N-R.sampleStartedAt);L[$]={totalFrames:R.totalFrames,totalChangedFrames:R.totalChangedFrames,framesPerSecond:R.sampleFrames*1e3/ae,changedFramesPerSecond:R.sampleChangedFrames*1e3/ae,averageIntervalMs:R.intervalCount>0?R.intervalSumMs/R.intervalCount:0,minIntervalMs:Number.isFinite(R.minIntervalMs)?R.minIntervalMs:0,maxIntervalMs:R.maxIntervalMs,p95IntervalMs:ch(R.intervalSamplesMs,.95),intervalCount:R.intervalCount,seqGapCount:R.seqGapCount,maxSeqGap:R.maxSeqGap,decoderInputFps:Math.max(0,(Number(R.lastInfo?.decoderInputCount||0)-R.sampleDecoderInputBase)*1e3/ae),decoderOutputFps:Math.max(0,(Number(R.lastInfo?.decoderOutputCount||0)-R.sampleDecoderOutputBase)*1e3/ae),sampleMs:ae,lastInfo:R.lastInfo},R.sampleDecoderInputBase=Number(R.lastInfo?.decoderInputCount||0),R.sampleDecoderOutputBase=Number(R.lastInfo?.decoderOutputCount||0),R.sampleChangedFrames=0,kb(R,N)}Pl(L)},1e3);return()=>window.clearInterval(y)},[]);const ui=u.useCallback((y,N)=>{const L=performance.now(),$=La(y,N.deviceId);cs.current.set($,L),Pa.current.delete($),y==="control"?Bn.current.delete($):Ys.current.delete($);const R=el.current.get($)||{totalFrames:0,sampleFrames:0,sampleStartedAt:L,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(R.totalFrames+=1,R.sampleFrames+=1,R.sampleBytes+=Math.max(0,Number(N.byteLength||0)),String(N.frameMode||N.mode||N.codec||N.mimeType||"").toLowerCase().includes("h264")){R.sampleH264Frames+=1,Number(N.byteLength||0)<=JM&&(R.sampleTinyFrames+=1);const qe=String(N.contentHash||"");qe&&R.lastContentHash===qe&&(R.sampleRepeatedFrames+=1),R.lastContentHash=qe}const Ie=Number(N.agentSendGapMs||0);Ie>0&&Ie<1e3&&yw(R.sourceSendIntervalsMs,Ie),R.lastFrame=N,jb(R,L,N.frameSeq),el.current.set($,R)},[]);u.useEffect(()=>{const y=window.setInterval(()=>{const N=performance.now(),L={};for(const[$,R]of el.current.entries()){const ae=Math.max(1,N-R.sampleStartedAt);L[$]={totalFrames:R.totalFrames,framesPerSecond:R.sampleFrames*1e3/ae,averageIntervalMs:R.intervalCount>0?R.intervalSumMs/R.intervalCount:0,minIntervalMs:Number.isFinite(R.minIntervalMs)?R.minIntervalMs:0,maxIntervalMs:R.maxIntervalMs,p95IntervalMs:ch(R.intervalSamplesMs,.95),intervalCount:R.intervalCount,seqGapCount:R.seqGapCount,maxSeqGap:R.maxSeqGap,averageFrameBytes:R.sampleFrames>0?R.sampleBytes/R.sampleFrames:0,tinyFrameRatio:R.sampleH264Frames>0?R.sampleTinyFrames/R.sampleH264Frames:0,repeatedFrameRatio:R.sampleH264Frames>0?R.sampleRepeatedFrames/R.sampleH264Frames:0,sourceSendAverageMs:R.sourceSendIntervalsMs.length>0?R.sourceSendIntervalsMs.reduce((te,Ie)=>te+Ie,0)/R.sourceSendIntervalsMs.length:0,sourceSendP95Ms:ch(R.sourceSendIntervalsMs,.95),sourceSendSampleCount:R.sourceSendIntervalsMs.length,sampleMs:ae,lastFrame:R.lastFrame},R.sampleBytes=0,R.sampleH264Frames=0,R.sampleTinyFrames=0,R.sampleRepeatedFrames=0,R.sourceSendIntervalsMs.length=0,kb(R,N)}br(L)},1e3);return()=>window.clearInterval(y)},[]);const gu=u.useCallback(y=>{ui("wall",y);const N=Nt.current.get(y.deviceId);if(!N)return;const L=L1(pt,ze.h264DecodeAcceleration);Wm(N,y,()=>Nt.current.get(y.deviceId)!==N,hl,L.acceleration,L.latencyMode).catch(()=>{})},[hl,pt,ui,ze.h264DecodeAcceleration]),vu=u.useCallback(y=>{ui("control",y);let N=hn.current.get(y.deviceId);N||(N=document.createElement("canvas"),N.setAttribute("aria-hidden","true"),hn.current.set(y.deviceId,N));const L=N,$=ke.current;Wm(L,y,()=>hn.current.get(y.deviceId)!==L,ac,kt.h264DecodeAcceleration,"interactive").catch(R=>{ke.current!==$||hn.current.get(y.deviceId)!==L||O!==y.deviceId||le(R instanceof Error?R.message:String(R||"Control H.264 decode failed"))})},[O,kt.h264DecodeAcceleration,ac,ui]),yu=u.useCallback(y=>{const N=yr.current;N&&N!==y&&Ao(N),yr.current=y,us.current=0,tl.current=0,ri.current=0,nl.current=0,wr.current=0,ai.current=0},[]),Nr=u.useCallback(()=>{const y=new Set,N=yr.current,L=Ji.current;if(!N||!L||N.width<=0||N.height<=0||ai.current!==L.layoutVersion)return y;for(const $ of L.tiles){const R=ls.current.get($.deviceId);if(!R||$.width<=0||$.height<=0)continue;const ae=Math.max(1,Math.round($.width)),te=Math.max(1,Math.round($.height)),Ie=eT,qe=tT;(R.width!==Ie||R.height!==qe)&&(R.width=Ie,R.height=qe);const Ne=R.getContext("2d",{alpha:!1});if(Ne){Ne.imageSmoothingEnabled=!0,Ne.imageSmoothingQuality="high";try{Ne.drawImage(N,Math.round($.x),Math.round($.y),ae,te,0,0,Ie,qe),y.add($.deviceId)}catch{}}}return y},[]),sc=u.useCallback((y,N)=>{if(N){ls.current.set(y,N);const $=is.current.get(y);$&&an($,N)&&(xa(y),Es(y,N)),window.requestAnimationFrame(()=>{Nr().has(y)&&wa(y)}),window.requestAnimationFrame(()=>qa(y,!0));return}const L=ls.current.get(y);Ts(y),er(y,L),ls.current.delete(y),is.current.has(y)||Js(y)},[Js,Es,xa,Nr,an,qa,er,wa,Ts]),Sa=u.useCallback((y,N)=>{ri.current=performance.now(),ai.current=Number(y.layoutVersion||0),Nr();const L=Ji.current?.tiles||[],$=L.length>0?Math.round(y.byteLength/L.length):y.byteLength;for(const R of L){const ae={...y,deviceId:R.deviceId,width:R.width,height:R.height,sourceWidth:R.width,sourceHeight:R.height,byteLength:$};hl(ae,{...N,deviceId:R.deviceId,width:R.width,height:R.height,byteLength:$}),en.current===R.deviceId&&qa(R.deviceId,!0)}},[hl,Nr,qa]),Ql=u.useCallback(y=>{const N=performance.now();us.current<=0&&(us.current=N),tl.current=N;const L=yr.current;if(!L)return;const $=Ji.current?.tiles||[],R=$.length>0?Math.round(y.byteLength/$.length):y.byteLength;for(const ae of $)ui("wall",{...y,deviceId:ae.deviceId,width:ae.width,height:ae.height,sourceWidth:ae.width,sourceHeight:ae.height,byteLength:R});Wm(L,y,()=>yr.current!==L,Sa).catch(()=>{})},[Sa,ui]),Ca=u.useMemo(()=>({fps:Ms,maxWidth:ba.maxWidth,maxHeight:ba.maxHeight,quality:ze.quality,mode:pt?"mode3-h264-hw":ze.frameMode,frameMode:pt?"mode3-h264-hw":ze.frameMode,streamPurpose:"wall",monitorSelections:Mt,onFrame:gu}),[Ms,gu,ba,pt,Mt,ze]),Mr=u.useCallback(y=>{if(y.deviceId!==O||y.streamPurpose!=="control"||y.monitorIndex!==hs)return;const N=at.find(L=>L.deviceId===y.deviceId);!N?.sessionId||N.sessionId!==y.sessionId||(xe(y),P(L=>L==="connecting"?"active":L))},[at,O,hs]);u.useEffect(()=>{xe(null)},[O,me,da,hs]);const di=me?`${me}-monitor-${hs}`:"",Zl=u.useMemo(()=>({fps:ol,maxWidth:oi.maxWidth,maxHeight:oi.maxHeight,quality:kt.quality,mode:da,frameMode:da,streamPurpose:"control",forceRestart:di!=="",forceRestartToken:di,restartReason:di?"control-session-or-monitor-change":"",monitorSelections:Mt,onFrame:vu,onStreamReady:Mr}),[di,kt.quality,vu,ol,da,oi.maxHeight,oi.maxWidth,Mr,Mt]),{frames:pl,state:Tr,error:tr,stats:Rs,restartLive:Er}=ky(Ut,ze.autoStartLive&&Ut.length>0,M,Ca),{frame:Ga,layout:Rr,state:qn,stats:rc,refreshInputs:vs}=v1(ta,pt&&ze.autoStartLive&&ta.length>0,M,{fps:za.atlasOutputFps,inputFps:tc,width:1920,height:1080,tileWidth:ba.maxWidth,tileHeight:ba.maxHeight,captureDeviceIds:ta,monitorSelections:Mt,onFrame:Ql});u.useEffect(()=>{Ji.current=Rr,Rr&&window.requestAnimationFrame(Nr)},[Rr,Nr]),u.useEffect(()=>{if(!pt||qn!=="open"){us.current=0,tl.current=0,ri.current=0;return}const y=window.setInterval(()=>{const N=yr.current,L=performance.now();if(!N||document.visibilityState!=="visible"||L-$l.current<oh)return;const $=tl.current,R=us.current;if($<=0||R<=0||L-$>500)return;const ae=ri.current||R,te=L-ae;if(te>=KM&&L-wr.current>=QM){Hc(N)&&(wr.current=L,nl.current=L);return}te>=YM&&L-nl.current>=XM&&e1(N)&&(nl.current=L)},250);return()=>window.clearInterval(y)},[qn,pt]);const{frames:gl,state:fi,error:Va,stats:ic,restartLive:vl,reconnectLive:Jl}=ky(jr,jr.length>0,M,Zl);u.useEffect(()=>{const y=Te.current,N=new Set([...Object.keys(y),...Object.keys(Mt)]);for(const L of N){const $=Math.max(0,Math.floor(Number(y[L])||0)),R=Math.max(0,Math.floor(Number(Mt[L])||0));$!==R&&(Pn("wall",L),Pn("control",L),Hc(Nt.current.get(L)||null),Hc(hn.current.get(L)||null))}Te.current={...Mt}},[Mt,Pn]);const mi=u.useMemo(()=>{const y=(L,$)=>{const R=at.find(te=>te.deviceId===L),ae=Zn(Mt[L],R?Qn(R):1);return!Number.isFinite(Number($.monitorIndex))||Number($.monitorIndex)===ae},N=new Map;for(const[L,$]of pl.entries())y(L,$)&&N.set(L,$);if(pt&&Ga&&ta.length>0){const L=new Map((Rr?.tiles||[]).map(R=>[R.deviceId,R])),$=Math.max(1,L.size);for(const R of ta){const ae=L.get(R);ae&&N.set(R,{...Ga,deviceId:R,width:ae.width,height:ae.height,sourceWidth:ae.width,sourceHeight:ae.height,byteLength:Math.round(Ga.byteLength/$)})}}for(const[L,$]of gl.entries())y(L,$)&&N.set(L,$);for(const L of dl){if(!ca.current.has(L)||N.has(L))continue;const $=ni.current.get(L);$&&y(L,$)&&N.set(L,$)}return N},[Ga,Rr,at,gl,ta,pt,Mt,pl,dl,mn]),na=ct&&jr.length>0?fi:ta.length>0?qn:Tr,Ds=ct&&jr.length>0?ic:ta.length>0?rc:Rs;u.useCallback((y,N="browser-stale")=>{const L=Er(y,N),$=vl(y,N);return L||$},[vl,Er]),u.useEffect(()=>{pt&&ta.length>0&&!ct&&vs()},[ta.length,pt,vs,ct]);const Ls=u.useCallback((y,N,L)=>{const $=N==="control"?hn.current.get(y)||null:Nt.current.get(y)||null;if(!$||!Hc($))return!1;const R=performance.now();return Ns.current.set(La(N,y),R),!0},[]),Dr=u.useCallback(y=>{if(da!=="mode3-h264-hw"||!O||I)return!1;const N=at.find(Ie=>Ie.deviceId===O)||Un,L=String(N?.platform||"").toLowerCase();if(!["win32","windows","win32nt"].includes(L))return!1;const $="mode5-lzo-delta",R=La("control",O),ae=performance.now();As.current.set(R,ae),cs.current.delete(R),xr.current.delete(R),js.current.delete(R),Bn.current.delete(R),Pa.current.delete(R),Hc(hn.current.get(O)||null),Jl([O],"control-decode-fallback"),ee($),X(`control-${$}-fallback-${O}-${Date.now()}`),ue(!1),va(!1);const te=y==="no first frame"||y==="control-first-frame-timeout";return le(Ie=>Ie||(te?`Control frame transport timeout; retrying Control with Mode 5 (${y})`:`H.264 decode failed; retrying Control with Mode 5 (${y})`)),P("connecting"),!0},[at,Un,O,I,da,Jl]);u.useEffect(()=>{const y=ct?Un:null;if(y){Vs.current={deviceId:y.deviceId,monitorIndex:hs,frameMode:da,startedAtEpochMs:Date.now()},va(O===y.deviceId&&re);return}Vs.current=null,va(!1)},[Un?.sessionId,q,O,re,da,hs,ct]);const _s=u.useCallback(async y=>{const N=C.find(ae=>ae.deviceId===y);Fc({mode4Enabled:pt,directMode4WallEnabled:gs,isMac:Qr(N?.platform)});const L=Zn(Mt[y],N?Qn(N):1),$={fps:pt?Ms:Qe,maxWidth:ba.maxWidth,maxHeight:ba.maxHeight,quality:ze.quality,mode:pt?"mode3-h264-hw":ze.frameMode,frameMode:pt?"mode3-h264-hw":ze.frameMode,streamPurpose:"wall",monitorIndex:L},R=await Ye(`/api/remote/devices/${encodeURIComponent(y)}/live/start`,{method:"POST",body:JSON.stringify($)},M);if(R?.ok===!1)throw new Error(R.error||"wall-stream-start-failed");return R},[Qe,tc,C,gs,Ms,ba.maxHeight,ba.maxWidth,M,pt,Mt,ze.frameMode,ze.quality]),Gn=u.useCallback(async y=>{const N=C.find($=>$.deviceId===y);Fc({mode4Enabled:pt,directMode4WallEnabled:gs,isMac:Qr(N?.platform)});const L=await Ye(`/api/remote/devices/${encodeURIComponent(y)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"wall",reason:"control-active"})},M);if(L?.ok===!1)throw new Error(L.error||"wall-stream-stop-failed");return L},[C,gs,M,pt]),Sn=u.useCallback(async(y,N="control-session-stop")=>{const L=await Ye(`/api/remote/devices/${encodeURIComponent(y)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"control",reason:N})},M);if(L?.ok===!1)throw new Error(L.error||"control-stream-stop-failed");return L},[M]),fa=u.useCallback(y=>{const N=hn.current.get(y);N&&(is.current.has(y)||Nt.current.has(y)||ls.current.has(y)||er(y,N),Ao(N),hn.current.delete(y));const L=Vt.current.get(y);L&&Ao(L),ni.current.delete(y),ca.current.delete(y),vr.current.delete(y)},[er]);u.useEffect(()=>{const y=q&&at.find(R=>R.deviceId===q)||null;if(!ct||!Qt||!y){Ws.current&&(++ua.current,Ws.current="");return}if(O===y.deviceId&&(V==="active"||V==="warm"||V==="connecting")){P(R=>R==="warm"?"active":R);return}if(Ws.current===y.deviceId)return;const N=++ua.current,L=O;Ws.current=y.deviceId,(async()=>{if(L){if(P("stopping"),await Sn(L,"control-session-switch").catch(()=>{}),N!==ua.current)return;const te=en.current;if(te&&te!==y.deviceId)try{await _s(te)}catch(Ie){Ge(Ie instanceof Error?Ie.message:String(Ie))}finally{en.current===te&&(en.current="",Jt(""))}if(N!==ua.current)return;fa(L)}if(N!==ua.current)return;if(Ob(y)){try{await Gn(y.deviceId)}catch(te){N===ua.current&&(Ws.current="",P("error"),Ge(te instanceof Error?te.message:String(te)));return}if(N!==ua.current){await _s(y.deviceId).catch(()=>{});return}en.current=y.deviceId,Jt(y.deviceId),ca.current.add(y.deviceId)}const R=La("control",y.deviceId),ae=`control-session-${N}-${y.deviceId}`;As.current.set(R,performance.now()),cs.current.delete(R),xr.current.delete(R),Pa.current.delete(R),Bn.current.delete(R),ee(""),le(""),X(ae),ye(y.deviceId),ue(!1),P("connecting"),ua.current===N&&Ws.current===y.deviceId&&(Ws.current="")})()},[at,q,O,V,Qt,fa,Ge,ct,_s,Sn,Gn]),u.useEffect(()=>{if(!O||at.some(L=>L.deviceId===O))return;const y=O,N=++ua.current;P("stopping"),Sn(y,"control-device-disconnected").catch(()=>{}).finally(()=>{N===ua.current&&(fa(y),ue(!1),X(""),ee(""),le(""),ye(L=>L===y?"":L),P("idle"))})},[at,O,fa,Sn]);const Wa=Ob(at.find(y=>y.deviceId===O));u.useEffect(()=>{if(os.current!==null&&(window.clearTimeout(os.current),os.current=null),!O||V==="idle"||V==="stopping"||V==="error"||ct||ve==="wall"){O&&!ct&&ve==="wall"&&P(L=>L==="warm"||L==="active"?"active":L);return}P(L=>L==="idle"||L==="stopping"?L:"warm");const y=O,N=++ua.current;return os.current=window.setTimeout(()=>{os.current=null,P("stopping"),Sn(y,"control-session-warm-timeout").catch(()=>{}).finally(()=>{N===ua.current&&(fa(y),ue(!1),X(""),ee(""),le(""),ye(L=>L===y?"":L),P("idle"))})},ZM),()=>{os.current!==null&&(window.clearTimeout(os.current),os.current=null)}},[ve,O,V,fa,ct,Sn]),u.useEffect(()=>()=>{os.current!==null&&window.clearTimeout(os.current)},[]),u.useEffect(()=>{const N=O&&(Wa&&(V==="connecting"||V==="active"||V==="warm"||V==="stopping")||re&&(V==="active"||V==="warm"))?O:"";if(Hn.current=N,Zi.current)return;const L=async()=>{for(;;){const R=Hn.current,ae=en.current;if(ae===R)return;if(ae){try{await _s(ae)}catch(te){Ge(te instanceof Error?te.message:String(te))}finally{en.current===ae&&(en.current="",Jt(""))}continue}if(!R)return;try{await Gn(R)}catch(te){Hn.current=en.current,Ge(te instanceof Error?te.message:String(te));return}Ao(Nt.current.get(R)||null),en.current=R,Jt(R),ca.current.add(R)}};let $;$=L().finally(()=>{Zi.current===$&&(Zi.current=null),en.current!==Hn.current&&Wt(R=>R+1)}),Zi.current=$},[O,re,V,Wa,pt,Ge,_s,Gn,On]);const Tn=O&&at.find(y=>y.deviceId===O)||null,ka=!!(ct&&Ce&&V==="active"&&Tn?.sessionId&&K?.deviceId===Tn.deviceId&&K.sessionId===Tn.sessionId&&K.streamPurpose==="control"&&K.commandId&&K.captureGeneration>0&&K.monitorIndex===hs),{state:eo,sendInput:to,stats:ja,error:lc}=y1($a&&ka,M),tn=u.useCallback((y,N)=>!ka||!Tn||!K||y!==Tn.deviceId?!1:to(y,{...N,controlSessionId:Tn.sessionId,controlCommandId:K.commandId,captureGeneration:K.captureGeneration}),[ka,Tn,K,to]),Tt=ka&&eo==="open",{state:bt,lastFrame:Is,stats:Ft,error:no}=N1($e?.deviceId||"",Jo&&Be,M),Ya=u.useRef(new Map);u.useEffect(()=>{const y=[["hub",j],["registry",l],["license",B],["wall-stream",tr],["control-stream",Va],["control-decode",z],["remote-input",lc],["remote-audio",no]];for(const[N,L]of y){const $=String(L||"").trim();if(N==="hub"&&De?.requiresHubRestart&&De.stage==="updating"){Ya.current.delete(N);continue}if(!$){Ya.current.delete(N);continue}Ya.current.get(N)!==$&&(Ya.current.set(N,$),Ge($))}},[no,z,Va,j,lc,B,l,Ge,tr,De]),u.useEffect(()=>{if(!ct||!Ce||!$a||!Tt||!$e)return;const y=($,R)=>{const ae=$.target,te=ae?.tagName?.toLowerCase();ae?.isContentEditable||te==="input"||te==="textarea"||te==="select"||($.preventDefault(),$.stopPropagation(),tn($e.deviceId,{type:R,monitorIndex:Zn(Mt[$e.deviceId],Qn($e)),key:$.key,code:$.code,keyCode:$.keyCode||$.which||0,location:$.location,text:$.key.length===1?$.key:"",repeat:R==="keydown"?$.repeat:!1,shiftKey:$.shiftKey,ctrlKey:$.ctrlKey,altKey:$.altKey,metaKey:$.metaKey}))},N=$=>y($,"keydown"),L=$=>y($,"keyup");return window.addEventListener("keydown",N),window.addEventListener("keyup",L),()=>{window.removeEventListener("keydown",N),window.removeEventListener("keyup",L)}},[$a,Tt,Ce,Mt,$e,tn,ct]),u.useEffect(()=>{const y=()=>{document.visibilityState==="visible"&&($l.current=performance.now())};return document.addEventListener("visibilitychange",y),window.addEventListener("pageshow",y),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("pageshow",y)}},[]),u.useEffect(()=>{if(!O||V!=="connecting"&&V!=="active"&&V!=="warm"||fi!=="open")return;const y=O,N=La("control",y),L=window.setInterval(()=>{const $=performance.now();if(document.visibilityState!=="visible"||$-$l.current<oh)return;const R=cs.current.get(N)||0,ae=xr.current.get(N)||0,te=js.current.get(N)||0,Ie=As.current.get(N)||$;As.current.has(N)||As.current.set(N,Ie);const qe=R<=0,Ne=qe?$-Ie>oT:$-R>Tb,lt=R>0&&(ae<=0||$-ae>Tb);if(!Ne&&lt){const Aa=Ns.current.get(N)||0;$-Aa>=Eb&&Ls(y,"control","decoder-paint-stale");return}if(!Ne)return;const vt=Bn.current.get(N)||0;if(vt>0){if($-vt<uT)return;Bn.current.delete(N)}const Wn=Pa.current.get(N)||0;if(Wn>=dT){if(Dr(qe?"no first frame":"stale stream"))return;ue(!1),va(!1),P("error");return}if($-te<Rb(cT,Wn))return;vl([y],qe?"control-first-frame-timeout":"control-receive-stale")&&(js.current.set(N,$),Bn.current.set(N,$),As.current.set(N,$),Pa.current.set(N,Wn+1))},650);return()=>window.clearInterval(L)},[fi,O,V,Dr,Ls,vl]),u.useEffect(()=>{!z||da!=="mode3-h264-hw"||Dr(z)||(ue(!1),va(!1),P("error"))},[z,da,Dr]),u.useEffect(()=>{!ct||!O||!Va||P(y=>y==="error"?y:"error")},[Va,O,ct]),u.useEffect(()=>{if(Tr!=="open"||!ze.autoStartLive||Ut.length===0)return;const y=window.setInterval(()=>{const N=performance.now();if(document.visibilityState!=="visible"||N-$l.current<oh)return;const L=1e3/Math.max(1,Ms||ze.fps||1),$=Math.max(mT,Math.ceil(L*4)),R=[];for(const ae of Ut){if(R.length>=gT)break;const te=La("wall",ae),Ie=cs.current.get(te)||0,qe=Ie<=0,Ne=Ys.current.get(te)||N;if(Ys.current.has(te)||Ys.current.set(te,Ne),qe&&N-Ne<=fT)continue;const lt=js.current.get(te)||0,vt=xr.current.get(te)||0,Wn=qe||N-Ie>$,Ps=!qe&&(vt<=0||N-vt>$);if(!Wn&&Ps){const ji=Ns.current.get(te)||0;N-ji>=Eb&&Ls(ae,"wall","decoder-paint-stale");continue}if(!Wn)continue;const Aa=Pa.current.get(te)||0;N-lt>=Rb(hT,Aa)&&R.push(ae)}if(R.length>0&&Er(R,R.some(ae=>(cs.current.get(La("wall",ae))||0)<=0)?"wall-first-frame-timeout":"wall-frame-stale"))for(const ae of R){const te=La("wall",ae);js.current.set(te,N),Ys.current.set(te,N),cs.current.delete(te),xr.current.delete(te),Pa.current.set(te,(Pa.current.get(te)||0)+1)}},pT);return()=>window.clearInterval(y)},[Ms,Ut,Ls,Er,ze.autoStartLive,ze.fps,Tr]),u.useEffect(()=>{jt(ze.fps),rl.current=Date.now(),Ks.current=0},[ze.fps,ze.frameMode,ze.adaptiveLoadShedding]),u.useEffect(()=>{qC({h264DecodeAcceleration:ze.h264DecodeAcceleration})},[ze.h264DecodeAcceleration]),u.useEffect(()=>{if(!Qt||ct||He==="list"||!ze.visibleOnlyLive){It([]);return}const y=li.current;if(!y||typeof IntersectionObserver>"u"){It(ul);return}const N=Array.from(y.querySelectorAll("[data-live-device-id]"));if(N.length===0){It([]);return}const L=new Map,$=()=>{const ae=dh(N.map(te=>String(te.dataset.liveDeviceId||"")).filter(te=>(L.get(te)||0)>0));It(te=>uh(te,ae)?te:ae)},R=new IntersectionObserver(ae=>{for(const te of ae){const Ie=String(te.target.dataset.liveDeviceId||"");Ie&&L.set(Ie,te.isIntersecting?te.intersectionRatio||.01:0)}$()},{root:null,rootMargin:ia.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return N.forEach(ae=>R.observe(ae)),$(),()=>R.disconnect()},[ul,Qt,ct,Cr,ze.visibleOnlyLive,He]),u.useEffect(()=>{if(!ze.adaptiveLoadShedding||!ze.autoStartLive||Ut.length===0)return;const y=ze.fps;if(Ut.length<=ia.preserveConfiguredFpsDeviceCount){Qe!==y&&(jt(y),rl.current=Date.now(),Ks.current=0);return}if(Tr!=="open"||Rs.sampleMs<500)return;const N=Date.now(),L=Ut.length*Qe,$=Rs.framesPerSecond,R=Rs.bytesPerSecond,ae=Math.max(0,...Ut.map(lt=>si[La("wall",lt)]?.maxIntervalMs||0)),te=Math.max(0,...Ut.map(lt=>Fn[La("wall",lt)]?.maxIntervalMs||0)),Ie=L>8&&$>0&&$<L*.72;if($>ia.maxWallFramesPerSecond||R>ia.maxWallBytesPerSecond||ae>ia.maxFrameGapMs||te>ia.maxFrameGapMs||Ie){Ks.current=0;const lt=ia.minFps;if(N-rl.current>=ia.downshiftCooldownMs&&Qe>lt){const vt=Math.max(lt,LT(Qe,lt));vt<Qe&&(jt(vt),rl.current=N)}return}const Ne=$<ia.maxWallFramesPerSecond*ia.lowLoadFrameRatio&&R<ia.maxWallBytesPerSecond*ia.lowLoadByteRatio;if(!Ne||Qe>=y){Ne||(Ks.current=0);return}if(!Ks.current){Ks.current=N;return}if(N-Ks.current>=ia.recoveryCooldownMs){const lt=Math.min(y,_T(Qe,y));lt>Qe&&(jt(lt),rl.current=N,Ks.current=0)}},[Qe,Ut.length,Ut,Fn,si,Tr,Rs.bytesPerSecond,Rs.framesPerSecond,Rs.lastUpdatedAt,Rs.sampleMs,ze.adaptiveLoadShedding,ze.autoStartLive,ze.frameMode,ze.fps]),u.useEffect(()=>{const y=new URLSearchParams(window.location.search).get("checkout");if(y==="success"){Ge("Checkout returned. Waiting for Dodo confirmation."),H();const N=window.setInterval(()=>{H()},4e3),L=window.setTimeout(()=>{window.clearInterval(N)},45e3);return()=>{window.clearInterval(N),window.clearTimeout(L)}}y==="cancelled"&&Ge("Checkout cancelled.")},[H]),u.useEffect(()=>{!Qt&&Ce&&Ue(!1),!Qt&&Be&&he(!1)},[Be,Ce,Qt]),u.useEffect(()=>{const y=$e?.deviceId||"",N=Xe.current;if(Xe.current=y,!N||N===y)return;const L=++ce.current,$=y?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";y&&Be&&et.current.set(y,$);let R=!0;return(async()=>{try{const te=et.current.get(N);if(et.current.delete(N),await Ye(`/api/remote/devices/${encodeURIComponent(N)}/audio/stop`,{method:"POST",body:JSON.stringify(te?{streamId:te}:{})},M),!R||L!==ce.current||!Be||!y||!Qt||!cl)return;const Ie=await Ye(`/api/remote/devices/${encodeURIComponent(y)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:$,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},M);if(Ie.ok===!1)throw new Error(Ie.error||"Remote audio start failed.")}catch(te){R&&(et.current.delete(y),he(!1),Ge(te instanceof Error?te.message:String(te)))}})(),()=>{R=!1}},[Be,Qt,M,cl,$e?.deviceId]),u.useEffect(()=>{const y=at.map(R=>R.deviceId),N=new Set(y),L=new Map(at.map(R=>[R.deviceId,R])),$=new Set;for(const R of at){const ae=ST(R);if(!ae)continue;const te=ne.current[R.deviceId]||"";te&&te!==ae&&$.add(R.deviceId),ne.current[R.deviceId]=ae}_(R=>{const ae=R.filter(te=>N.has(te));return uh(R,ae)?R:ae}),G(R=>R&&N.has(R)?R:""),Q(R=>R&&N.has(R)?R:""),ga(R=>{let ae=!1;const te={};for(const[Ie,qe]of Object.entries(R)){const Ne=L.get(Ie);if(!Ne){te[Ie]=qe;continue}const lt=$.has(Ie)?0:Zn(qe,Qn(Ne));te[Ie]=lt,lt!==qe&&(ae=!0)}return ae?te:R});for(const R of $)Pn("wall",R),Pn("control",R),ni.current.delete(R),ca.current.delete(R);ii(R=>{const ae=R.filter(te=>N.has(te));return uh(R,ae)?R:ae})},[at,Pn,Yl]),u.useEffect(()=>{Gl([]),qo(!1)},[qa]),u.useEffect(()=>{!il||Sr!=="selected"||ya.length>0||$n.length===0||ii($n.map(y=>y.deviceId))},[$n,ya.length,Sr,il]),u.useEffect(()=>{try{localStorage.setItem(hw,F)}catch{}},[F]),u.useEffect(()=>{MT(ze)},[ze]),u.useEffect(()=>{ET(kt)},[kt]),u.useEffect(()=>{AT(Mt,ne.current)},[at,Mt]);const ao=u.useCallback(async()=>{const y=new Set(p);y.add(fn);try{const ae=await Ye("/api/remote/status",void 0,fn);dy({endpoint:ae.agentEndpoint,endpoint_candidates:[...ae.agentEndpointCandidates||[],...ae.hostTargetEndpointCandidates||[]]}).forEach(te=>y.add(te))}catch{}const N=[...y].sort((ae,te)=>{const Ie=qe=>{const Ne=Wc(qe);return Ne==="local"?0:Ne==="loopback"?1:2};return Ie(ae)-Ie(te)||ae.localeCompare(te)});let L=!1,$="",R=!1;try{for(const ae of N){const te=Wc(ae);try{if(await Ye("/api/health",void 0,ae),te==="local")return v(!0),Eo(!0),ae;te==="loopback"&&(L=!0,$=ae)}catch{te==="local"&&(R=!0)}}return L?(R&&Ge("LiveDesk Hub is reachable on this PC, but not through the LAN address yet. Restart LiveDesk Hub to bind 5179 on the network."),v(!0),Eo(!0),$||fn):(v(!1),Eo(!1),"")}catch{return v(!1),Eo(!1),""}},[p]),hi=async()=>{if(Ae("auth"),zn(!1),await ao(),window.liveDesk?.auth?.signInWithGoogle){const L=await window.liveDesk.auth.signInWithGoogle();L?.ok===!1&&(Ge(L.error||"LiveDesk could not open the system browser for Google sign-in."),Ae(""));return}const{data:y,error:N}=await ft.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}/callback`}});N&&(Ge(N.message),Ae(""))},pi=async()=>{Ae("auth"),zn(!1),await ft.auth.signOut(),(await window.liveDesk?.auth?.persistSession?.(null))?.runtimeCleared===!1?Ge("Signed out locally. The LiveDesk runtime could not be reached to clear its session."):window.liveDesk?.auth?.persistSession||await Ye("/api/auth/session",{method:"DELETE"},fn).catch(()=>{}),Ae("")};u.useEffect(()=>{if(!rs)return;const y=L=>{L.target instanceof Element&&(L.target.closest(".account-popover, .rail-account")||zn(!1))},N=L=>{L.key==="Escape"&&zn(!1)};return window.addEventListener("pointerdown",y),window.addEventListener("keydown",N),()=>{window.removeEventListener("pointerdown",y),window.removeEventListener("keydown",N)}},[rs]);const zs=u.useCallback(async(y={})=>{const N=y.silent===!0,L=y.takeover===!0,$=y.requestLocalAccess===!0;if(!n?.user){N||Ge("Sign in before publishing this host.","error");return}if(!Go.current){Go.current=!0,N||(Ae("host"),At("Hub · 1/4 · Checking the local runtime…"));try{const ae=($?await ao():"")||M||fn;if(!(w||await Ye("/api/remote/status",void 0,ae)).started)throw new Error("Start LiveDesk on this computer before syncing the server.");N||At("Hub · 2/4 · Sending the signed-in session to the Hub…");const Ie=await Ye("/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}})},ae);if(!Ie.ok||!Ie.authenticated)throw new Error(Ie.error||"hub-session-sync-failed");N||At("Hub · 3/4 · Claiming the Hub role and publishing its endpoint…");const qe=await Ye("/api/hub/sync",{method:"POST",body:JSON.stringify({takeover:L})},ae);if(!qe.ok)throw new Error(qe.error||"host-target-failed");if(!N){At("Hub · 4/4 · Verifying the endpoint and lease renewal…");const Ne=await Ye("/api/hub/status",void 0,ae);if(!Ne.hostTargetActive)throw new Error(Ne.hostTargetLease?.lastError||"host-target-not-active-after-sync");const lt=Ne.hostTargetEndpoint||Ne.agentEndpoint||"endpoint ready",vt=Number(Ne.connectedDeviceCount||0),Wn=vt>0?`${vt} client${vt===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";Ge(`Hub ready · ${lt} · lease auto-renewal active. ${Wn}`,"success"),($||x)&&(v(!0),Eo(!0)),k()}c()}catch(R){if(!N){const ae=R instanceof Error?R.message:String(R);ae.includes("local network access")&&(v(!1),Eo(!1)),Ge(`Hub setup failed · ${ae}`,"error")}}finally{Go.current=!1,N||Ae("")}}},[M,x,k,c,ao,n,Ge,At,w]),Lr=u.useCallback((y=!0)=>{ge!=="host"&&(Ke(!1),y&&window.requestAnimationFrame(()=>je.current?.focus()))},[ge]),yl=u.useCallback(()=>{ge!=="host"&&(je.current=document.activeElement instanceof HTMLElement?document.activeElement:null,zn(!1),Ke(!0))},[ge]),oc=u.useCallback(()=>{Ke(!1),zs({takeover:!0,requestLocalAccess:!0})},[zs]);u.useEffect(()=>{if(!Ve)return;const y=window.requestAnimationFrame(()=>de.current?.focus()),N=$=>{$.target instanceof Element&&$.target.closest(".client-hub-switch-popover, .hub-sync-trigger")||Lr(!1)},L=$=>{$.key==="Escape"&&Lr()};return window.addEventListener("pointerdown",N),window.addEventListener("keydown",L),()=>{window.cancelAnimationFrame(y),window.removeEventListener("pointerdown",N),window.removeEventListener("keydown",L)}},[Lr,Ve]);const _r=u.useCallback(async()=>{if(!(!w?.update?.canApply||ge==="update")){Ae("update");try{const y=await Ye("/api/update/apply",{method:"POST",body:JSON.stringify({})},M||fn);if(!y.ok)throw new Error(y.error||"LiveDesk update could not be started.");const N=[...new Set((y.targets||[]).map(R=>String(R.deviceId||"").trim()).filter(Boolean))],L=!!(y.managerUpdateAvailable||y.clientPackageUpdateAvailable),$=y.state==="hub-restart-requested"?Date.now():void 0;(N.length>0||L)&&st({operationId:String(y.operationId||`wall-update-${Date.now()}`),targetIds:N,stage:y.state==="clients-updated"?"updated":"updating",requiresHubRestart:L,initialHostInstanceId:String(w.hostInstanceId||""),targetManagerVersion:String(y.latestVersion||w.update?.latestVersion||""),targetClientVersion:String(y.latestClientVersion||w.update?.latestClientVersion||""),restartRequestedAt:$,restartDeadlineAt:$?$+_d:void 0}),At(y.state==="hub-restart-requested"?Ld:Sb),k()}catch(y){Ge(y instanceof Error?y.message:String(y),"error")}finally{Ae("")}}},[ge,M,k,Ge,At,w]);u.useEffect(()=>{const y=De,N=w?.update;if(!y||y.stage!=="updating"||!N)return;const L=N.restartResult?.operationId===y.operationId?N.restartResult:null;if(L?.outcome==="restored"){const qe=L.error||`The requested Hub ${L.targetVersion||y.targetManagerVersion||"version"} failed verification.`;st(Ne=>Ne?.operationId===y.operationId?{...Ne,stage:"restored",error:qe}:Ne),Ge(`LiveDesk update did not complete. Hub ${L.fallbackVersion||L.appVersion||"the previous version"} was restored. ${qe}`,"error");return}if(L?.outcome==="failed"){const qe=L.error||"No verified LiveDesk Hub replacement could be started.";st(Ne=>Ne?.operationId===y.operationId?{...Ne,stage:"failed",error:qe}:Ne),Ge(`LiveDesk Hub update failed. ${qe}`,"error");return}if(N.operationId===y.operationId&&N.state==="failed"){const qe=N.error||"LiveDesk update failed before the Hub replacement completed.";st(Ne=>Ne?.operationId===y.operationId?{...Ne,stage:"failed",error:qe}:Ne),Ge(qe,"error");return}if(N.operationId===y.operationId){if(N.state==="hub-restart-requested"&&!y.restartDeadlineAt){const qe=Date.now();st(Ne=>Ne?.operationId===y.operationId?{...Ne,restartRequestedAt:qe,restartDeadlineAt:qe+_d}:Ne),At(Ld)}!y.requiresHubRestart&&N.state==="clients-updated"&&(st(qe=>qe?.operationId===y.operationId?{...qe,stage:"updated"}:qe),Ge("LiveDesk clients updated and reconnected successfully.","success"));return}if(!y.requiresHubRestart)return;const $=w.started===!0&&(!y.initialHostInstanceId||w.hostInstanceId&&w.hostInstanceId!==y.initialHostInstanceId),R=!!N.checkedAt,ae=Cb(N.currentVersion,y.targetManagerVersion),te=!y.targetClientVersion||Cb(N.currentClientVersion,y.targetClientVersion),Ie=R&&N.state==="idle"&&N.updateAvailable===!1&&ae&&te;$&&Ie&&(st(qe=>qe?.operationId===y.operationId?{...qe,stage:"updated"}:qe),Ge(`LiveDesk Hub ${N.currentVersion||L?.appVersion||y.targetManagerVersion} restarted and passed version verification.`,"success"))},[Ge,At,w,De]),u.useEffect(()=>{const y=De;if(!y||y.stage!=="updating"||!y.requiresHubRestart||y.restartDeadlineAt)return;const N=()=>{const $=Date.now();st(R=>R?.operationId===y.operationId&&R.stage==="updating"&&!R.restartDeadlineAt?{...R,restartRequestedAt:$,restartDeadlineAt:$+_d}:R),At(Ld)};if(w?.update?.state==="hub-restart-requested"){N();return}if(!j)return;const L=window.setTimeout(N,nT);return()=>window.clearTimeout(L)},[j,At,w?.update?.state,De]),u.useEffect(()=>{const y=De;if(!y||y.stage!=="updating"||!y.requiresHubRestart||!y.restartDeadlineAt)return;const N=Math.max(0,y.restartDeadlineAt-Date.now()),L=y.operationId,$=window.setTimeout(()=>{const R=`LiveDesk Hub did not return and verify ${y.targetManagerVersion||"the requested version"} within ${Math.round(_d/6e4)} minutes. Check the Hub terminal or restart log, then run livedesk@latest manually if the Hub is still offline.`;st(ae=>ae?.operationId===L&&ae.stage==="updating"?{...ae,stage:"failed",error:R}:ae),Ge(R,"error")},N);return()=>window.clearTimeout($)},[Ge,De]),u.useEffect(()=>{if(!De||De.stage!=="updated")return;const y=De.operationId,N=window.setTimeout(()=>{st(L=>L?.operationId===y?null:L)},8e3);return()=>window.clearTimeout(N)},[De]),u.useEffect(()=>{if(fe!==Sb&&fe!==Ld)return;const y=w?.update;if(String(y?.state||"")==="failed"){Ge(y?.error||"LiveDesk update failed.","error");return}De?.stage==="updated"&&Ge("")},[fe,Ge,w?.update?.error,w?.update?.state,De?.stage]);const Os=u.useCallback(async()=>{if(!ge){Ae("pin");try{const N=await Ye("/api/remote/pairing-pin",{method:"POST"},M||fn);if(!N.ok)throw new Error(N.error||"pin-rotation-failed");await k(),Ge("New PIN published.")}catch(y){Ge(y instanceof Error?y.message:String(y))}finally{Ae("")}}},[ge,M,k]),ys=u.useCallback(y=>{y&&(G(y),_(N=>N.includes(y)?N:[...N,y]))},[]),Ka=u.useCallback(y=>{if(!y)return;const N=kr.has(y);G(L=>N?L===y?"":L:y),_(L=>N?L.filter($=>$!==y):L.includes(y)?L:[...L,y])},[kr]),Ir=u.useCallback(()=>{_([]),G("")},[an]),so=u.useCallback(()=>{_(at.map(y=>y.deviceId)),G("")},[at]),nr=u.useCallback((y,N)=>{const L=at.find(R=>R.deviceId===y);if(!L)return;const $=Qn(L);$<=1||(ga(R=>{const ae=Zn(R[y],$),te=(ae+N+$)%$;return te===ae?R:{...R,[y]:te}}),Pn("wall",y),Pn("control",y),Fa(R=>{if(!R.has(y))return R;const ae=new Set(R);return ae.delete(y),ae}),ni.current.delete(y),ca.current.delete(y),ct&&(ue(!1),P("connecting"),va(!1),Q(y)))},[at,Pn,ct]);u.useEffect(()=>{const y=N=>{if(ct&&Ce&&$a)return;const L=N.target,$=L?.tagName?.toLowerCase();L?.isContentEditable||$==="input"||$==="textarea"||$==="select"||((N.ctrlKey||N.metaKey)&&N.key.toLowerCase()==="a"&&(N.preventDefault(),so()),N.key==="Escape"&&Ir())};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[$a,Ir,Ce,so,ct]);const ro=(y,N)=>{const L=at.find(te=>te.deviceId===y),$=L?Qn(L):1,R=Zn(Mt[y],$),ae=Zn(N,$);R!==ae&&(ga(te=>({...te,[y]:ae})),Fa(te=>{if(!te.has(y))return te;const Ie=new Set(te);return Ie.delete(y),Ie}),ni.current.delete(y),ca.current.delete(y),Pn("wall",y),Pn("control",y)),ct?(R!==ae&&(ue(!1),P("connecting")),va(!1),Q(y)):ys(y)},Xa=async y=>{if(va(!1),Q(y),Fe("control"),!ps.has(y)){Ue(!1),Ge(ci);return}const N=at.find($=>$.deviceId===y);if(Qr(N?.platform)&&(N?.capabilities?.controlPermission===!1||N?.capabilities?.accessibilityPermission===!1)){Ue(!1),Ge("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts LiveDesk, then restart the Mac client.","error");return}Ue(!0),Ge(`Opening remote control${N?` for ${_a(N)}`:""}.`,"success")},Cn=async()=>{if(!$e){Ge("Select a Client before playing audio.");return}if(!Qt){Ge(ci);return}if(!cl){Ge("Selected Client does not report remote audio support yet.");return}if(Le)return;const y=!Be,N=y?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:et.current.get($e.deviceId);y&&N?et.current.set($e.deviceId,N):y||et.current.delete($e.deviceId),Pe("audio"),he(y);try{await Ye(`/api/remote/devices/${encodeURIComponent($e.deviceId)}/audio/${y?"start":"stop"}`,{method:"POST",body:JSON.stringify({...N?{streamId:N}:{},mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},M),Ge(`${y?"Audio started":"Audio stopped"} for ${_a($e)}.`,"success")}catch(L){y&&et.current.delete($e.deviceId),he(!1),Ge(L instanceof Error?L.message:String(L),"error")}finally{Pe("")}},io=y=>{const N=y instanceof Error?y.message:String(y);return/remote-actions-disabled|allowAgent-blocked-by-settings/i.test(N)?"Remote actions are off. Turn on Settings > Agent > Enable AI Agent first.":/power-actions-disabled/i.test(N)?"Power actions are off. Turn on Settings > Agent > Allow power actions first.":/agent-tool-capability-unavailable|unsupported-agent-operation/i.test(N)?"This Client needs a newer LiveDesk Client for power actions.":/device-not-connected|404 device-not-found/i.test(N)?"The Client disconnected before the action could be sent.":N},lo=async y=>{if(!$e||Le)return;const N=$e,$={sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[y];if(window.confirm(`${$} ${_a(N)}? Unsaved work on that computer may be lost.`)){Pe(y),Ge(`Sending ${$.toLowerCase()} request to ${_a(N)}...`);try{const R=await Ye(`/api/remote/devices/${encodeURIComponent(N.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:y})},M);if(!R.ok)throw new Error(R.error||"The remote action could not be sent.");Ge(`${$} request sent to ${_a(N)}.`,"success"),k()}catch(R){Ge(io(R),"error")}finally{Pe("")}}},bu=async(y,N,L="files")=>{const $=y.filter(Ie=>Ie.file.size>=0);if($.length===0)return{files:0,bytes:0};if(!Qt)throw new Error(ci);if(N.length===0)throw new Error("Select at least one connected Client.");const R=crypto.randomUUID(),ae=$.reduce((Ie,qe)=>Ie+qe.file.size,0);let te=0;fs({id:R,status:"reading",progress:1,message:`Preparing ${$.length} ${L}`});try{for(let Ie=0;Ie<$.length;Ie+=1){const qe=$[Ie],Ne=qe.file,lt=Math.max(1,Math.ceil(Ne.size/ih));for(let vt=0;vt<lt;vt+=1){const Wn=vt*ih,Ps=Math.min(Ne.size,Wn+ih),Aa=Ne.size===0?new ArrayBuffer(0):await Ne.slice(Wn,Ps).arrayBuffer(),ji=vt===lt-1;fs({id:R,status:"sending",progress:Math.max(2,Math.min(98,Math.round(te/Math.max(1,ae)*96))),message:`${Ie+1}/${$.length} ${qe.relativePath}`});const cr=await Ye("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:R,deviceIds:N,remoteDirectory:F.trim(),name:Ne.name,relativePath:qe.relativePath,size:Ne.size,type:Ne.type,lastModified:Ne.lastModified,offset:Wn,totalBytes:Ne.size,final:ji,dataBase64:IT(Aa)})},M);if(!cr.ok||cr.queued!==N.length)throw new Error(cr.error||`file-chunk-not-queued-${cr.queued}/${N.length}`);te+=Aa.byteLength,await new Promise(Ai=>window.setTimeout(Ai,0))}}return fs({id:R,status:"queued",progress:100,message:`Sent ${$.length} file${$.length===1?"":"s"} to ${N.length} Client${N.length===1?"":"s"}`}),window.setTimeout(()=>{fs(Ie=>Ie?.id===R&&Ie.status==="queued"?null:Ie)},4500),{files:$.length,bytes:ae}}catch(Ie){throw fs({id:R,status:"failed",progress:100,message:Ie instanceof Error?Ie.message:String(Ie)}),Ie}},xu=async y=>{const N=$n.length>0?$n.map(L=>L.deviceId):$e?[$e.deviceId]:[];try{await bu(Lb(y),N)}catch(L){Ge(L instanceof Error?L.message:String(L))}},wu=async y=>{try{await bu(Lb(y),fu)}catch(N){Ge(N instanceof Error?N.message:String(N))}};u.useEffect(()=>{ff.current=!1},[]);const sn=y=>{y.preventDefault(),y.stopPropagation(),ql(!1),xu(y.dataTransfer.files)},gi=async(y="ltd")=>{if(!n){Ge("Sign in with Google before checkout.");return}if(T&&y===$t){Ge("LiveDesk license is already active.");return}if(T&&$t==="pro"){Ge("LiveDesk Pro is already active.");return}Ae("checkout");try{const{data:N,error:L}=await ft.functions.invoke("dodo-checkout",{body:{plan:y}});if(L)throw L;if(!N?.checkout_url)throw new Error("Checkout function did not return a checkout URL.");window.location.assign(N.checkout_url)}catch(N){Ge(N instanceof Error?N.message:String(N)),Ae("")}},ar=vT(),vi=yT(),cc=at.length,sr=pu.filter(y=>mi.has(y)).length,rr=na==="open"&&Ds.sampleMs>0?`${Ds.framesPerSecond.toFixed(1)} fps`:na,Oe=$e?ct?gl.get($e.deviceId):mi.get($e.deviceId):void 0,bl=$e?Zn(Mt[$e.deviceId],Qn($e)):0,Su=$e?wT($e):[],Cu=typeof Oe?.monitorIndex=="number"?Zn(Oe.monitorIndex,Math.max(1,Oe.monitorCount||1)):bl,xl=(Oe&&Cu===bl?Cw(Oe):null)||($e?Sw($e,bl):null);xl&&`${xl.width}${xl.height}`;const zr=$e?La(ct?"control":"wall",$e.deviceId):"",pn=zr?si[zr]:void 0,gn=zr?Fn[zr]:void 0,gt=gn?.lastInfo,oo=pn&&pn.sampleMs>0?`${pn.framesPerSecond.toFixed(1)} fps`:"waiting";pn&&`${pn.totalFrames}${oo}`,gn&&gn.sampleMs>0&&`${gn.framesPerSecond.toFixed(1)}`,gn&&gn.sampleMs>0&&`${gn.changedFramesPerSecond.toFixed(1)}`,gt&&(`${gt.frameSeq}${gt.decoderLabel}${gt.queueSize}${gt.renderQueueSize}${gt.droppedForLatency}${gt.decoderFlushCount}${gt.decoderTimestampFallbacks}${gt.decoderInputCount}${gt.decoderOutputCount}`,gt.visualChanged),gt&&`${Math.round(gt.queuedForMs)}${Math.round(gt.decodedForMs)}${Math.round(gt.scheduledForMs)}${gt.drawMs.toFixed(1)}`,gt?.targetPaintIntervalMs&&`${gt.targetPaintIntervalMs.toFixed(1)}${(1e3/gt.targetPaintIntervalMs).toFixed(1)}`,gn&&`${gn.decoderInputFps.toFixed(1)}${gn.decoderOutputFps.toFixed(1)}`,gt?.canvasPresentation,gt&&`${gt.interactiveBufferWaitCount}${Math.round(gt.interactiveBufferWaitMs)}${gt.interactiveQueueDrainCount}`,pn&&(Oe?.frameMode==="mode5-lzo-delta"?`${qc(pn.averageFrameBytes)}${Oe.deltaVisualTileCount||0}${Oe.deltaRefreshTileCount||0}${Oe.deltaTotalTiles||0}`:`${qc(pn.averageFrameBytes)}${Math.round(pn.tinyFrameRatio*100)}${Math.round(pn.repeatedFrameRatio*100)}`),pn&&pn.sourceSendSampleCount>0&&`${pn.sourceSendAverageMs.toFixed(1)}${pn.sourceSendP95Ms.toFixed(1)}`,Ab(pn),Ab(gn),pn&&gn&&`${Nb(pn)}${Nb(gn)}`,Oe?Oe.frameMode||Oe.mode||Oe.codec||Oe.mimeType:ct?kt.frameMode:ze.frameMode,ct?kt.frameMode:ze.frameMode,Oe?`${Oe.width}${Oe.height}${qc(Oe.byteLength)}`:ct?`${oi.maxWidth}${oi.maxHeight}`:`${ze.maxWidth}${ze.maxHeight}`,Oe&&`${Oe.isKeyFrame?"key":String(Oe.chunkType||"delta")}`,Oe&&Oe.monitorCount&&((Oe.monitorIndex??0)+1,`${Oe.monitorCount}`),Oe&&[`src ${Math.round(Oe.sourceGapMs||0)}ms`,`gap ${Math.round(Oe.agentSendGapMs||0)}ms`,`tx ${Math.round(Oe.agentSendDurationMs||0)}ms`,`pace ${Math.round(Oe.agentPaceMs||0)}ms`,`queue ${Math.round(Oe.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(Oe.agentFrameAgeMs||0)}ms`,Oe.hubPacketTransitAgeMs!==void 0?`sock ${Math.max(0,Math.round(Oe.hubPacketTransitAgeMs))}ms`:"",Oe.droppedByAgent?`drop ${Oe.droppedByAgent}`:"",Oe.hubIngressDropped?`ingress-drop ${Oe.hubIngressDropped}`:"",Oe.hubClientDropped?`ws-drop ${Oe.hubClientDropped}`:"",Oe.captureStageMs?`capture ${Math.round(Oe.captureStageMs)}ms`:"",Oe.requestedFps?`req ${Math.round(Oe.requestedFps)}fps`:"",Oe.effectiveFps?`eff ${Math.round(Oe.effectiveFps)}fps`:"",Oe.captureAverageMs?`avg ${Math.round(Oe.captureAverageMs)}ms`:"",Oe.captureP95Ms?`p95 ${Math.round(Oe.captureP95Ms)}ms`:"",Oe.slowFrameCount?`slow ${Math.round(Oe.slowFrameCount)}`:"",Oe.captureHelperRestarts?`helper ${Math.round(Oe.captureHelperRestarts)}`:"",Oe.convertMs?`rgb565 ${Math.round(Oe.convertMs)}ms`:"",Oe.compressMs?`lzo ${Math.round(Oe.compressMs)}ms`:"",Oe.captureSourceSerial?`cap #${Oe.captureSourceSerial}`:"",Oe.captureSourceSkipped?`cap skip ${Oe.captureSourceSkipped}`:"",Oe.frameMode==="mode5-lzo-delta"?`tiles ${Oe.deltaVisualTileCount||0}+${Oe.deltaRefreshTileCount||0}/${Oe.deltaTotalTiles||0}@${Oe.deltaTileSize||0}`:"",Oe.platformProfile||Oe.hardwareEncoder||"-",Oe.atlasComposeMs?`atlas ${Oe.atlasComposeMs.toFixed(1)}ms`:"",Oe.atlasPoolStarved?`pool ${Oe.atlasPoolStarved}`:"",Oe.atlasTileCount?`tiles ${Oe.atlasReadyTiles||0}/${Oe.atlasTileCount}`:"",Oe.atlasInputRevision?`input #${Oe.atlasInputRevision}`:"",Oe.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(Oe.atlasSourceMaxAgeMs)}ms`:"",gt?.inputFeedbackMs!==void 0&&gt.inputFeedbackAt!==void 0&&performance.now()-gt.inputFeedbackAt<=xb?`feedback ${Math.round(gt.inputFeedbackMs)}ms`:"",Oe.contentHash?`enc ${Oe.contentHash.slice(0,6)}`:"",gt?.visualHash?`pix ${gt.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "),eo==="open"&&[`${ja.sentPerSecond.toFixed(1)} hz`,ja.lastInputSeq>0?`rtt ${Math.round(ja.lastRoundTripMs)}ms`:"",ja.lastInputSeq>0?`apply ${ja.lastAgentApplyMs.toFixed(1)}ms`:"",ja.droppedPerSecond>0?`drop ${ja.droppedPerSecond.toFixed(1)}/s`:"",ja.bufferedAmount>0?`buf ${qc(ja.bufferedAmount)}`:"",ja.lastInputType||"ready"].filter(Boolean).join(" / "),gt?.inputFeedbackMs!==void 0&&gt.inputFeedbackAt!==void 0&&performance.now()-gt.inputFeedbackAt<=xb&&`${Math.round(gt.inputFeedbackMs)}${gt.inputFeedbackSeq||0}`,Be&&[bt,`context ${Ft.audioContextState}`,`queue ${Math.round(Ft.queuedMs)}ms`,`last ${Math.round(Ft.lastPacketAgeMs)}ms`,`accepted ${Math.round(Ft.lastAcceptedAgeMs)}ms`,`process ${Math.round(Ft.localProcessingAgeMs)}ms`,`remote ${Math.round(Ft.browserAgeMs)}/${Math.round(Ft.captureAgeMs)}ms`,`heartbeat ${Math.round(Ft.captureStatusAgeMs)}ms`,`capture ${Ft.captureAlive&&Ft.helperAlive?"alive":"down"}`,`drop ${Ft.drops}`,`resync ${Ft.resyncs}`,`restart ${Ft.automaticRestarts}`,Ft.pendingDecodes>0?`decode ${Ft.pendingDecodes}`:"",Is?`#${Is.frameSeq}`:"waiting"].filter(Boolean).join(" / "),Oe&&`${Oe.frameSeq}${Jb(Oe.receivedAt||Oe.capturedAt)}`;const Hs=Math.max(0,Ds.bytesPerSecond*8/1e6),wl=u.useCallback(()=>{it(!0),Nn(Date.now()),k(),Mn.current!==null&&window.clearTimeout(Mn.current),Mn.current=window.setTimeout(()=>{Mn.current=null,Nn(Date.now()),it(!1)},650)},[k]),uc=u.useCallback(()=>{if(rt){dt(!1);return}dt(!0),wl()},[wl,rt]),ir=u.useCallback(()=>{if(Re){An(!1);return}An(!0),wl()},[Re,wl]),Qa=new Map;if(rt||Re)for(const y of at){const N=y.deviceId,L=ct&&O===N,R=La(L?"control":"wall",N),ae=L?gl.get(N):mi.get(N),te=L?hn.current.get(N)||Vt.current.get(N)||null:Nt.current.get(N)||(pt?yr.current:null);Qa.set(N,AM({device:y,frame:ae,receiveStat:si[R],paintStat:Fn[R],codec:te?xy(te):{},selectedMonitorIndex:Zn(Mt[N],Qn(y)),control:L,controlInputReady:L&&Tt,controlBinding:L&&K?.deviceId===N?K:void 0,now:Date.now()}))}const ku=Re?NM({status:w||{},deviceDiagnostics:[...Qa.values()],codec:xy(),browser:{hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:Number(navigator.deviceMemory||0)},frameStats:Ds}):[],dc=Ga?.atlasReadyTiles??sr,lr=Ga?.atlasTileCount??sr,Sl=dc===lr?`${lr} tiles`:`${dc}/${lr} tiles`,co=ta.length>0;ct?`${rr}${Hs.toFixed(Hs>=10?0:1)}`:co?`${Sl}${rr}${Hs.toFixed(Hs>=10?0:1)}`:`${sr}${rr}${Hs.toFixed(Hs>=10?0:1)}`;const bi=j?"offline":w?.started?"online":"starting",xi=$n.length,ju=ct?$e?_a($e):"No Client":xi===0?"No Client":xi>1?`${xi} selected`:$e?_a($e):"No Client",Or=ct?[$e?.deviceId].filter(y=>!!y):$n.map(y=>y.deviceId),En=Oo[wn]||Oo.en,Za=En.sync||Oo.en.sync,uo=a||D?"checking":T?$t==="pro"?"Pro LTD active":`Plus LTD ${at.length}/${Uc}`:Kl?`Free ${at.length}/${$c}`:`Upgrade ${at.length}/${$c}`,fc=$t==="pro"?"Pro active":ge==="checkout"?"Opening":$t==="ltd"?"Pro $199":"Plus $79",or=T?$t==="pro"?"Pro active":"Upgrade to Pro LTD":n?ge==="checkout"?"Opening checkout":$t==="ltd"?"Buy Pro LTD":"Buy Plus LTD":ge==="auth"?"Opening Google":"Sign in to buy",Cl=$t==="pro"||ge==="checkout"||ge==="auth"||a||D,fo=n?.user?.user_metadata,wi=_b(fo,"avatar_url","picture"),Fs=_b(fo,"full_name","name")||n?.user?.email||"Google",Si=Fs.slice(0,1).toUpperCase(),Au=w?.started?"Local app ready":"Start LiveDesk",Nu=i?.active?"Published":n?"Not published":"Sign in required",Ci=/^\d{6}$/.test(w?.pairingPin||"")?w?.pairingPin:"------",ki=y=>{if(typeof window<"u"&&(y==="support"?window.history.pushState({},"","/support"):ve==="support"&&window.history.pushState({},"","/")),y==="control"){const N=Un||ms;if(N&&(va(!1),Q(N.deviceId)),Fe(y),!Qt){Ue(!1),Ge(ci);return}Ue(!0);return}y==="wall"&&Yt(N=>N+1),Fe(y),Ue(!1)},Fr=ge==="update"||De?.stage==="updating"||["dispatching","waiting-for-clients","hub-restart-requested"].includes(w?.update?.state||""),mc=!!(w?.update?.updateAvailable&&w.update.canApply||Fr||!w&&De),Bs=pC(wn),Vn=u.useCallback(y=>{if(!De?.targetIds.includes(y))return;if(De.stage==="updated")return{state:"updated",label:"Updated"};if(De.stage==="restored"||De.stage==="failed")return{state:"failed",label:De.stage==="restored"?"Update restored":"Update failed",error:De.error};const N=w?.update?.operationId===De.operationId?w.update.targets?.find(L=>L.deviceId===y):void 0;switch(N?.state){case"completed":return{state:"updated",label:"Updated"};case"failed":return{state:"failed",label:"Update failed",error:N.error||w?.update?.error};case"pending-offline":return{state:"offline",label:"Waiting for reconnect"};case"queued":return{state:"queued",label:"Queued"};case"waiting":return N.candidateSince?{state:"updating",label:"Verifying restart..."}:{state:"updating",label:"Restarting..."};default:return{state:"updating",label:"Verifying..."}}},[w?.update,De]);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(ex,{size:25})}),r.jsx("nav",{className:"rail-tools",children:$T.map(y=>{const N=y.icon,L=Gd(y.tooltip,wn);return r.jsxs("button",{className:`rail-tool ${y.id==="sync-server"?"sync-server hub-sync-trigger":""} ${ve===y.id?"active":""} accent-${y.accent}`,onClick:()=>y.id==="sync-server"?yl():ki(y.id),"data-tooltip":y.id==="sync-server"&&Ve?void 0:Ch(y.label,y.tooltip,wn),"aria-label":`${y.label}. ${L}`,type:"button",disabled:y.id==="sync-server"&&ge==="host","aria-busy":y.id==="sync-server"&&ge==="host","aria-expanded":y.id==="sync-server"?Ve:void 0,"aria-haspopup":y.id==="sync-server"?"dialog":void 0,"aria-controls":y.id==="sync-server"&&Ve?"hub-sync-popover":void 0,children:[y.id==="sync-server"&&ge==="host"?r.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):r.jsx(N,{size:19}),r.jsx("span",{children:y.id==="sync-server"&&ge==="host"?"Syncing…":y.label})]},y.id)})}),r.jsxs("div",{className:"rail-footer",children:[UT.map(y=>{const N=y.icon;return r.jsxs("button",{className:`rail-tool compact ${ve===y.id?"active":""} accent-${y.accent}`,onClick:()=>ki(y.id),title:y.label,type:"button",children:[r.jsx(N,{size:18}),r.jsx("span",{children:y.label})]},y.id)}),r.jsxs("button",{className:`rail-tool compact local-settings ${Wl?"active":""}`,onClick:()=>{Fe("settings"),typeof window<"u"&&window.history.pushState({},"","/"),zn(!1),Ue(!1),gr(!1)},title:"Settings",type:"button",children:[r.jsx(Ph,{size:18}),r.jsx("span",{children:"Settings"})]}),r.jsxs("button",{className:`rail-account ${n?"signed-in":""}`,onClick:()=>{zn(y=>!y)},disabled:a||ge==="auth","aria-expanded":rs,title:n?`Account: ${n.user?.email||Fs}`:"Sign in with Google",type:"button",children:[n?wi?r.jsx("img",{src:wi,alt:Fs,referrerPolicy:"no-referrer"}):r.jsx("span",{className:"avatar-fallback",children:Si}):r.jsx(Ol,{size:18}),r.jsx("span",{children:n?"Account":"Google"})]}),rs&&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&&wi?r.jsx("img",{src:wi,alt:Fs,referrerPolicy:"no-referrer"}):n?r.jsx("span",{children:Si}):r.jsx(Ol,{size:18})}),r.jsxs("div",{children:[r.jsx("strong",{children:n?Fs:"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:Au}),r.jsx("dt",{children:"Access"}),r.jsx("dd",{children:Nu}),r.jsx("dt",{children:"Plan"}),r.jsx("dd",{children:uo}),r.jsx("dt",{children:"Ads"}),r.jsx("dd",{children:$t==="free"?"Standard banner":"Removed"})]}),n?r.jsxs("button",{className:"account-popover-action",onClick:pi,disabled:ge==="auth",type:"button",children:[r.jsx(Fb,{size:16}),"Logout"]}):r.jsxs("button",{className:"account-popover-action primary",onClick:hi,disabled:ge==="auth",type:"button",children:[r.jsx(Ol,{size:16}),"Sign in with Google"]})]})]})]}),Ve&&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(mr,{size:19})}),r.jsx("span",{className:"client-hub-switch-eyebrow",children:Bs.eyebrow}),r.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>Lr(),"aria-label":Bs.closeLabel,children:r.jsx(la,{size:17})})]}),r.jsx("h2",{id:"hub-sync-title",children:Bs.title}),r.jsx("p",{id:"hub-sync-description",children:Bs.description}),r.jsxs("p",{id:"hub-sync-notice",className:"client-hub-switch-notice",children:[r.jsx(jn,{size:16,"aria-hidden":"true"}),r.jsx("span",{children:Bs.restartNotice})]}),r.jsxs("div",{className:"client-hub-switch-actions",children:[r.jsx("button",{type:"button",onClick:()=>Lr(),children:Bs.cancel}),r.jsxs("button",{ref:de,className:"primary",type:"button",onClick:oc,disabled:ge==="host",children:[r.jsx(mr,{size:16}),Bs.confirm]})]})]}),r.jsxs("section",{className:`desk-stage ${ll&&!Ha?"dock-open":""} ${ct?"control-stage":""} ${Wo?"agents-stage":""}`,children:[r.jsxs("header",{className:"topbar",children:[r.jsxs("div",{className:"brand",children:[r.jsx("span",{className:"brand-mark",children:r.jsx(Hl,{size:18})}),r.jsxs("div",{className:"brand-copy",children:[r.jsx("h1",{children:"LiveDesk"}),r.jsx("p",{children:"Control wall for local machines"})]}),mc?r.jsxs("button",{className:"topbar-update-button",onClick:()=>{_r()},title:De?.error||`Update LiveDesk to ${w?.update?.latestVersion||De?.targetManagerVersion||"latest"}`,"aria-label":Fr?"LiveDesk update in progress":`Update LiveDesk to ${w?.update?.latestVersion||De?.targetManagerVersion||"latest"}`,type:"button",disabled:Fr||!w?.update?.canApply,"aria-busy":Fr,children:[Fr?r.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):r.jsx(Bh,{size:19,"aria-hidden":"true"}),Fr&&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:[il&&!ct&&r.jsxs("div",{className:"file-share-top-route","aria-label":"File distribution route",children:[r.jsxs("div",{children:[r.jsx(_l,{size:17}),r.jsxs("span",{children:[r.jsx("small",{children:"Source"}),r.jsx("strong",{children:"LiveDesk Hub"})]})]}),r.jsx(Gh,{size:15}),r.jsx(h0,{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:[uu," Client",uu===1?"":"s"]}),r.jsx("em",{children:F.trim()||"Desktop/LiveDeskFiles"})]})]})]}),ll&&!ct&&r.jsxs("div",{className:"top-actions",children:[r.jsx(gb,{active:Re,refreshing:Re&&pa,onClick:ir}),r.jsx(pb,{active:rt,refreshing:rt&&pa,onClick:uc}),r.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),r.jsx(hb,{controller:ec,onError:Ge}),r.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),r.jsx("div",{className:"segmented-control","aria-label":"Wall view",children:PT.map(y=>r.jsx("button",{className:He===y.id?"active":"",onClick:()=>Me(y.id),type:"button",children:y.label},y.id))})]}),ct&&r.jsxs("div",{className:"top-actions",children:[r.jsx(gb,{active:Re,refreshing:Re&&pa,onClick:ir}),r.jsx(pb,{active:rt,refreshing:rt&&pa,onClick:uc}),r.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),r.jsx(hb,{controller:ec,onError:Ge})]})]})]}),Re&&ll&&r.jsx(xM,{items:ku,collectedAt:Xt,onClose:()=>An(!1)}),cu?r.jsxs("section",{className:"doc-page",lang:wn,dir:wn==="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(qd,{size:16}),En.eyebrow]}),r.jsx("h2",{children:En.title}),r.jsx("p",{children:En.intro})]}),r.jsxs("label",{className:"doc-language-picker",children:[r.jsxs("span",{children:[r.jsx(p0,{size:17}),En.languageLabel]}),r.jsx("select",{value:wn,onChange:y=>Cs(y.target.value),children:GT.map(y=>r.jsx("option",{value:y.id,children:y.label},y.id))})]})]}),r.jsx("section",{className:"doc-grid",children:En.sections.map((y,N)=>{const $=[mr,xh,_m,jn,ef][N]||qd;return r.jsxs("article",{className:"doc-card",children:[r.jsx("div",{className:"doc-card-icon",children:r.jsx($,{size:19})}),r.jsxs("div",{children:[r.jsx("h3",{children:y.title}),r.jsx("p",{children:y.body}),r.jsx("ul",{children:y.points.map(R=>r.jsx("li",{children:R},R))})]})]},y.title)})}),Za&&r.jsxs("section",{className:"doc-sync",children:[r.jsxs("div",{className:"doc-sync-head",children:[r.jsx(_m,{size:20}),r.jsxs("div",{children:[r.jsx("h3",{children:Za.title}),r.jsx("p",{children:Za.body})]})]}),r.jsx("ul",{children:Za.points.map(y=>r.jsx("li",{children:y},y))})]}),r.jsxs("section",{className:"doc-firewall",children:[r.jsxs("div",{className:"doc-firewall-head",children:[r.jsx(jn,{size:20}),r.jsxs("div",{children:[r.jsx("h3",{children:En.firewall.title}),r.jsx("p",{children:En.firewall.body})]})]}),r.jsx("ul",{children:En.firewall.points.map(y=>r.jsx("li",{children:y},y))})]}),r.jsxs("section",{className:"doc-command-panel",children:[r.jsxs("div",{className:"doc-command-head",children:[r.jsx(xh,{size:20}),r.jsxs("div",{children:[r.jsx("h3",{children:En.commands.title}),r.jsx("p",{children:En.commands.body})]})]}),r.jsxs("div",{className:"doc-command-list",children:[En.commands.manager&&r.jsxs("div",{className:"doc-command-row",children:[r.jsx("span",{children:En.commands.manager}),r.jsx("code",{children:vi}),r.jsx("button",{className:"icon-button",onClick:()=>Hd(vi),title:"Copy command",type:"button",children:r.jsx(Im,{size:16})})]}),r.jsxs("div",{className:"doc-command-row",children:[r.jsx("span",{children:En.commands.primary}),r.jsx("code",{children:ar}),r.jsx("button",{className:"icon-button",onClick:()=>Hd(ar),title:"Copy command",type:"button",children:r.jsx(Im,{size:16})})]}),r.jsxs("div",{className:"doc-command-row",children:[r.jsx("span",{children:En.commands.slot}),r.jsx("code",{children:`${ar} 3`}),r.jsx("button",{className:"icon-button",onClick:()=>Hd(`${ar} 3`),title:"Copy command",type:"button",children:r.jsx(Im,{size:16})})]})]})]})]}):Wo?r.jsx(db,{hubUrl:M,devices:C}):il?r.jsx(vN,{hubUrl:M,devices:at,localFeatureAccess:Qt,upgradeNotice:ci,remoteDirectory:F,onRemoteDirectoryChange:Je,targetMode:Sr,selectedTargetIds:ya,onTargetModeChange:ea,onTargetToggle:y=>ii(N=>N.includes(y)?N.filter(L=>L!==y):[...N,y]),filePickerRef:lu,folderPickerRef:df,onBrowserFileImport:y=>{wu(y)},onBrowserFolderImport:y=>{wu(y)},onNotice:Ge,onTransferChange:y=>{if(!y){fs(null);return}const N=y.state==="failed"||y.state==="partially-failed"||y.state==="cancelled"?"failed":y.state==="completed"?"queued":y.state==="sending"?"sending":"reading";fs({id:y.id,status:N,progress:y.progress,message:y.message}),["completed","partially-failed","failed","cancelled"].includes(y.state)&&window.setTimeout(()=>fs(L=>L?.id===y.id?null:L),4500)}}):Vo?r.jsx(Xb,{session:n,currentProductKey:"livedesk",appVersion:"",onSignIn:hi}):Wl?r.jsx(I1,{hubUrl:M,runtimeRole:w?.runtimeRole||"hub",runtimeDeviceId:w?.deviceId||"",sessionAccessToken:n?.access_token||"",pin:r.jsxs(z1,{children:[r.jsxs("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(oa,{size:20})]}),r.jsxs("div",{className:"settings-pin-display",children:[r.jsx("span",{children:"Hub PIN"}),r.jsx("strong",{children:Ci}),r.jsxs("button",{className:"text-button ghost compact",onClick:Os,disabled:!w?.started||ge==="pin",type:"button",children:[r.jsx(Zr,{size:15}),ge==="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:"Hub status"}),r.jsx("h3",{children:bi})]}),r.jsx("span",{className:`settings-status-dot state-${bi}`})]}),r.jsxs("dl",{className:"settings-facts",children:[r.jsx("dt",{children:"Address"}),r.jsx("dd",{children:M||"-"}),r.jsx("dt",{children:"Connected Clients"}),r.jsxs("dd",{children:[cc,"/",Yl]}),r.jsx("dt",{children:"Sync access"}),r.jsx("dd",{children:w?.started?"Local app ready":"Start Hub first"}),r.jsx("dt",{children:"Plan"}),r.jsx("dd",{children:uo})]}),r.jsxs("div",{className:"settings-action-row",children:[r.jsxs("button",{className:"text-button primary",onClick:()=>zs({takeover:!0,requestLocalAccess:!0}),disabled:!n||ge==="host",type:"button",children:[ge==="host"?r.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):r.jsx(_m,{size:16}),ge==="host"?"Syncing…":"Sync access"]}),r.jsxs("button",{className:"text-button buy",onClick:()=>gi($t==="ltd"?"pro":"ltd"),disabled:ge==="checkout"||$t==="pro",type:"button",children:[r.jsx(Do,{size:16}),fc]})]})]})]}),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(Lo,{size:20})]}),r.jsxs("label",{className:"settings-field",children:[r.jsx("span",{children:"Remote folder"}),r.jsx("input",{value:F,onChange:y=>Je(y.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),r.jsx("p",{className:"settings-help",children:"Blank uses Desktop/LiveDeskFiles on each Client."})]})]}),agent:r.jsx(H1,{hubUrl:M}),captureGallery:r.jsx(yM,{hubUrl:M,onToast:Ge})}):ou?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(yh,{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:()=>ki("wall"),title:"Close pricing",type:"button",children:r.jsx(la,{size:18})})]}),r.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[r.jsx("span",{children:"Current plan"}),r.jsx("strong",{children:Qo.name}),r.jsxs("small",{children:[at.length,"/",lT(Qs)," connected devices"]})]}),r.jsxs("div",{className:"pricing-cards","aria-label":"LiveDesk plans",children:[r.jsxs("article",{className:`pricing-plan-card ${$t==="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:Tl.free.audience}),r.jsx("h3",{children:"Monitor your local wall"}),r.jsx("p",{children:Tl.free.note}),r.jsxs("ul",{children:[r.jsxs("li",{children:[r.jsx(Dn,{size:16})," Up to ",$c," devices"]}),r.jsxs("li",{children:[r.jsx(Dn,{size:16})," Live view and local control"]}),r.jsxs("li",{children:[r.jsx(Dn,{size:16})," Standard ad-supported banner"]})]}),r.jsx("span",{className:"pricing-current-label",children:$t==="free"?"Current plan":"Included for everyone"})]}),r.jsxs("article",{className:`pricing-plan-card featured ${$t==="ltd"?"current":""}`,children:[r.jsxs("div",{className:"pricing-plan-topline",children:[r.jsxs("span",{className:"pricing-plan-badge plus",children:[r.jsx(g0,{size:14})," Plus"]}),r.jsx("strong",{children:"$5"})]}),r.jsx("p",{className:"pricing-plan-audience",children:Tl.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(Dn,{size:16})," Up to ",Uc," devices"]}),r.jsxs("li",{children:[r.jsx(Dn,{size:16})," No standard ad banner"]}),r.jsxs("li",{children:[r.jsx(Dn,{size:16})," ",Tl.ltd.ltd]})]}),r.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>gi("ltd"):hi,disabled:$t!=="free"||ge==="checkout"||ge==="auth"||a||D,type:"button",children:[r.jsx(Do,{size:16}),$t==="free"?n?"Choose Plus":"Sign in for Plus":"Plus active"]})]}),r.jsxs("article",{className:`pricing-plan-card pro ${$t==="pro"?"current":""}`,children:[r.jsxs("div",{className:"pricing-plan-topline",children:[r.jsxs("span",{className:"pricing-plan-badge pro",children:[r.jsx(jn,{size:14})," Pro"]}),r.jsx("strong",{children:"$15"})]}),r.jsx("p",{className:"pricing-plan-audience",children:Tl.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(Dn,{size:16})," 30+ Client walls"]}),r.jsxs("li",{children:[r.jsx(Dn,{size:16})," Commercial use included"]}),r.jsxs("li",{children:[r.jsx(Dn,{size:16})," ",Tl.pro.ltd]})]}),r.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>gi("pro"):hi,disabled:$t==="pro"||ge==="checkout"||ge==="auth"||a||D,type:"button",children:[r.jsx(Do,{size:16}),$t==="pro"?"Pro active":n?"Choose Pro":"Sign in for Pro"]})]})]}),r.jsxs("section",{className:"pricing-includes",children:[r.jsxs("div",{children:[r.jsx(oa,{size:17}),r.jsx("span",{children:"Screen wall"}),r.jsx("strong",{children:"120+ slots"})]}),r.jsxs("div",{children:[r.jsx(bh,{size:17}),r.jsx("span",{children:"Focused control"}),r.jsx("strong",{children:"Local-first"})]}),r.jsxs("div",{children:[r.jsx(Jv,{size:17}),r.jsx("span",{children:"Remote audio"}),r.jsx("strong",{children:"Available"})]}),r.jsxs("div",{children:[r.jsx(Lo,{size:17}),r.jsx("span",{children:"File transfer"}),r.jsx("strong",{children:"Included"})]})]}),r.jsxs("p",{className:"pricing-note",children:[r.jsx(Dn,{size:15})," Commercial use requires Pro. Plus LTD is for personal, creator, and homelab use."]}),r.jsxs("button",{className:"pricing-primary-cta",onClick:n?()=>gi($t==="ltd"?"pro":"ltd"):hi,disabled:Cl,type:"button",children:[r.jsx(Do,{size:18}),or]})]}):r.jsx(r.Fragment,{children:r.jsxs("section",{className:`monitor-layout ${Ha?"dock-collapsed":""}`,children:[r.jsxs("section",{ref:li,className:`screen-wall-panel ${Ul?"drop-active":""}`,onClick:y=>{y.currentTarget===y.target&&Ir()},onDragEnter:y=>{y.preventDefault(),ql(!0)},onDragOver:y=>{y.preventDefault(),y.dataTransfer.dropEffect="copy"},onDragLeave:y=>{y.currentTarget===y.target&&ql(!1)},onDrop:sn,children:[ta.length>0&&r.jsx("canvas",{ref:yu,className:"atlas-source-canvas",width:Rr?.width||1920,height:Rr?.height||1080,"aria-hidden":"true"}),ct?r.jsx("section",{className:"control-focus",children:r.jsxs("div",{className:"control-wall",children:[$e&&Su.length>1&&r.jsx("div",{className:"control-monitor-tabs","aria-label":"Select monitor",children:Su.map(y=>r.jsxs("button",{className:y.index===bl?"active":"",onClick:()=>ro($e.deviceId,y.index),title:CT(y),type:"button",children:[r.jsx("span",{children:y.name||`Display ${y.index+1}`}),y.width>0&&y.height>0&&r.jsxs("small",{children:[y.width,"x",y.height]})]},y.index))}),$e?r.jsx(ph,{device:$e,frame:Oe,selected:!1,controlEnabled:$a&&Ce&&Tt,showStatus:kt.showScreenStatus,monitorIndex:Zn(Mt[$e.deviceId],Qn($e)),monitorCount:Qn($e),onSelect:()=>{},onFocusDevice:()=>Q($e.deviceId),onOpenControl:()=>Xa($e.deviceId),onCycleMonitor:y=>nr($e.deviceId,y),onCanvasReady:Ar,sendInput:tn,presentationReady:$o,remoteDiagnostics:rt?Qa.get($e.deviceId):void 0},$e.deviceId):r.jsxs("div",{className:"control-empty",children:[r.jsx(oa,{size:30}),r.jsx("strong",{children:"No Client"}),r.jsx("span",{children:"Open a Client from the Wall."})]}),$e&&Xs&&r.jsxs("div",{className:"control-connection-overlay",role:"alert",children:[r.jsx(jn,{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."})]}),$e&&!Xs&&!$o&&r.jsxs("div",{className:"control-connection-overlay",role:"status","aria-live":"polite",children:[V!=="error"&&r.jsx("span",{className:"control-connection-spinner","aria-hidden":"true"}),r.jsx("strong",{children:V==="error"?"Connection failed":"Connecting"}),r.jsx("small",{children:V==="error"?"See the notification for details. Reopen Control to retry.":Va||z?"Control stream is recovering. See the notification for details.":na==="open"?"Preparing the first control frame":"Opening the Control stream"})]})]})}):He==="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"})]}),du.length>0?du.map(({device:y,slotNumber:N})=>r.jsx(YT,{device:y,slotNumber:N,selected:kr.has(y.deviceId),updateIndicator:Vn(y.deviceId),onSelect:()=>Ka(y.deviceId),onOpenControl:()=>Xa(y.deviceId)},y.deviceId)):r.jsxs("div",{className:"wall-device-list-empty",children:[r.jsx(oa,{size:24,"aria-hidden":"true"}),r.jsx("strong",{children:"No connected computers"})]})]}):pt?r.jsx("div",{className:`screen-wall atlas-slot-wall size-${He}`,onClick:y=>{y.currentTarget===y.target&&Ir()},children:Cr.map((y,N)=>y?r.jsx(ph,{device:y,frame:mi.get(y.deviceId),selected:kr.has(y.deviceId),controlEnabled:!1,showStatus:ze.showScreenStatus,monitorIndex:Zn(Mt[y.deviceId],Qn(y)),monitorCount:Qn(y),onSelect:()=>Ka(y.deviceId),onFocusDevice:()=>ys(y.deviceId),onOpenControl:()=>Xa(y.deviceId),onCycleMonitor:L=>nr(y.deviceId,L),onCanvasReady:Fc({mode4Enabled:pt,directMode4WallEnabled:gs,isMac:Qr(y.platform)})==="direct"?nc:sc,sendInput:tn,updateIndicator:Vn(y.deviceId),presentationReady:ze.autoStartLive&&Ua.includes(y.deviceId)?Gs.has(y.deviceId):void 0,showPresentationSpinner:ze.autoStartLive&&Ua.includes(y.deviceId),remoteDiagnostics:rt?Qa.get(y.deviceId):void 0},y.deviceId):r.jsx(zb,{index:N},`slot-${N}`))}):r.jsx("div",{className:`screen-wall size-${He}`,onClick:y=>{y.currentTarget===y.target&&Ir()},children:Cr.map((y,N)=>y?r.jsx(ph,{device:y,frame:mi.get(y.deviceId),selected:kr.has(y.deviceId),controlEnabled:$a&&Ce&&Tt&&$e?.deviceId===y.deviceId,showStatus:ze.showScreenStatus,monitorIndex:Zn(Mt[y.deviceId],Qn(y)),monitorCount:Qn(y),onSelect:()=>Ka(y.deviceId),onFocusDevice:()=>ys(y.deviceId),onOpenControl:()=>Xa(y.deviceId),onCycleMonitor:L=>nr(y.deviceId,L),onCanvasReady:nc,sendInput:tn,updateIndicator:Vn(y.deviceId),presentationReady:ze.autoStartLive&&Ua.includes(y.deviceId)?Gs.has(y.deviceId):void 0,showPresentationSpinner:ze.autoStartLive&&Ua.includes(y.deviceId),remoteDiagnostics:rt?Qa.get(y.deviceId):void 0},y.deviceId):r.jsx(zb,{index:N},`slot-${N}`))}),r.jsx(QT,{visible:Zo&&!ct})]}),!Wl&&r.jsxs("aside",{className:`right-dock actions-mode ${Ha?"collapsed":""}`,"aria-label":"LiveDesk tools",children:[r.jsx("button",{className:"dock-toggle",onClick:()=>gr(y=>!y),"aria-label":Ha?"Show control panel":"Hide control panel",title:Ha?"Show control panel":"Hide control panel",type:"button",children:Ha?r.jsx(Yb,{size:18}):r.jsx(Vh,{size:18})}),!Ha&&r.jsxs(r.Fragment,{children:[r.jsxs("section",{className:"action-dock",children:[r.jsx("input",{ref:al,className:"hidden-file-input",type:"file",multiple:!0,onChange:y=>{y.currentTarget.files&&xu(y.currentTarget.files),y.currentTarget.value=""}}),r.jsxs("div",{className:"manual-action-bar",role:"toolbar","aria-label":"Manual Client controls",children:[r.jsx(To,{label:"Control",tooltip:$e?Xs?"Allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client.":$a?Tt?"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($e){if(ct&&Ce){Ue(!1),Ge("Remote control paused. Screen viewing stays on.");return}Xa($e.deviceId)}},disabled:!$a||!!Le,active:Ce,pressed:ct&&Ce,children:r.jsx(bh,{size:17})}),r.jsx(To,{label:"Audio",tooltip:$e?cl?Be?"Stop hearing this Client":"Hear this Client":"Audio is not available on this Client":"Select a Client to use Audio",onClick:()=>{Cn()},disabled:!Jo||!!Le,active:Be,pressed:Be,children:Le==="audio"?r.jsx(Jr,{className:"spin",size:17}):r.jsx(Jv,{size:17})}),r.jsx(To,{label:"Send files",tooltip:$n.length===0&&!ct?"Select one or more Clients to send files":$e?"Choose files and send them to the selected Client":"Select a Client to send files",onClick:()=>{Ge(`Choose files to send to ${ju}.`),al.current?.click()},disabled:!!Le||!Qt||(ct?!$e:$n.length===0),children:r.jsx(Lo,{size:17})}),r.jsx(To,{label:"Restart",tooltip:$e?hu?"Restart Client":"Restart is not available on this Client":"Select a Client to restart",onClick:()=>{lo("restart")},disabled:!$e||!Qt||!!Le||!hu,children:Le==="restart"?r.jsx(Jr,{className:"spin",size:17}):r.jsx(Uh,{size:17})}),r.jsx(To,{label:"Sleep",tooltip:$e?"Put Client to sleep":"Select a Client to put to sleep",onClick:()=>{lo("sleep")},disabled:!$e||!Qt||!!Le,children:Le==="sleep"?r.jsx(Jr,{className:"spin",size:17}):r.jsx(v0,{size:17})}),r.jsx(To,{label:"Shut down",tooltip:$e?"Shut down Client":"Select a Client to shut down",onClick:()=>{lo("shutdown")},disabled:!$e||!Qt||!!Le,danger:!0,children:Le==="shutdown"?r.jsx(Jr,{className:"spin",size:17}):r.jsx(y0,{size:17})})]})]}),r.jsx(db,{hubUrl:M,devices:C,variant:"dock",selectedDeviceIds:Or})]})]})]})})]}),Jn&&r.jsxs("aside",{className:`transfer-bar state-${Jn.status}`,"aria-live":"polite",children:[r.jsx("span",{className:"transfer-bar-icon","aria-hidden":"true",children:Jn.status==="queued"?r.jsx(Dn,{size:18}):Jn.status==="failed"?r.jsx(la,{size:18}):r.jsx(qb,{size:18})}),r.jsxs("div",{className:"transfer-bar-copy",children:[r.jsx("p",{children:Jn.message}),r.jsx("div",{className:"transfer-bar-track",children:r.jsx("span",{style:{width:`${Math.max(0,Math.min(100,Jn.progress))}%`}})})]}),r.jsxs("strong",{children:[Math.max(0,Math.min(100,Jn.progress)),"%"]})]}),Ee&&r.jsxs("aside",{className:`livedesk-toast tone-${Ee.tone}`,role:Ee.tone==="error"?"alert":"status","aria-live":Ee.tone==="error"?"assertive":"polite","aria-busy":Ee.tone==="progress",children:[Ee.tone==="progress"&&r.jsx("span",{className:"livedesk-toast-spinner","aria-hidden":"true"}),r.jsx("span",{children:Ee.message}),r.jsx("button",{className:"livedesk-toast-close",onClick:()=>Ge(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:r.jsx(la,{size:15})})]})]})}function JT(){if(typeof window>"u")return[];const n=window.location.origin;return window.location.port==="5179"?[n]:["http://127.0.0.1:5179"]}function eE(){const[a,i]=u.useState(null);return u.useEffect(()=>{let l=!1,c=!1;const d=async()=>{for(const g of JT())try{const v=await fetch(`${g}/api/runtime`,{cache:"no-store"});if(!v.ok)continue;const b=(await v.json()).role==="hub"?"hub":"client";c=!0,l||i(b);return}catch{}};d();const m=window.setInterval(()=>{d()},1e3),p=window.setTimeout(()=>{!l&&!c&&i("client")},2500);return()=>{l=!0,window.clearInterval(m),window.clearTimeout(p)}},[null]),a?a==="client"?r.jsx(jC,{}):r.jsx(ZT,{}):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..."})]})}A0.createRoot(document.getElementById("root")).render(r.jsx(u.StrictMode,{children:r.jsx(eE,{})}));